text
stringlengths
15
59.8k
meta
dict
Q: How to use Diff function I'm doing an algorithm and at some point I have to calculate the derivative of a function, I tried to use diff but it didn't work. I have the function defined like this: function y = funcionF(x) y = x^3 - 3*x^2 -10; end I tried diff(funcionF) but I get this error: Not enough input arguments. Is there a way to make it work or is mandatory to use a Symbolic Function? A: https://au.mathworks.com/help/symbolic/differentiation.html You need to define the symbols using syms which requires the Symbolic Math Toolbox, which I don't have, but this should work (according to the documentation): >> syms x >> f = x^3 - 3*x^2 - 10; >> diff(f) should give you something like ans = 3*x^2-6*x
{ "language": "en", "url": "https://stackoverflow.com/questions/68387632", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Vuetify 2.6.12 - Problem with v-data-table inside v-dialog In my application, when inserting a v-data-table inside a v-dialog, it is losing part of its CSS style. Looking at the HTML, the class "v-application" and "v-application--is-ltr" are not being applied to v-dialog. I need the same classes that are applied to all components inside ("v-application" and "v-application--is-ltr"), inside . Without these classes the is without application of some CSS. I imagine that even inside a v-dialog I could use a v-data-table and it would work I've done several tests, like adding a v-row before the v-dialog, adding a v-container, putting v-col, removing v-col. A lot of tests and I couldn't find a solution. Has anyone gone through this problem? Thank you very much in advance A: Tables inside dialogs work just fine in Vuetify: var app = new Vue({ el: '#app', template: '#main', vuetify: new Vuetify(), data: { dlgVisible: false, header: [ { value: 'fname', text: 'First Name' , class: 'font-weight-bold text-subtitle-1', }, { value: 'lname', text: 'Last Name' , class: 'font-weight-bold text-subtitle-1', }, { value: 'salary', text: 'Salary' , class: 'font-weight-bold text-subtitle-1', }, ], rows: [ { fname: 'John', lname: 'Doe', salary: 1000 }, { fname: 'John', lname: 'Doe', salary: 1000 }, { fname: 'John', lname: 'Doe', salary: 1000 }, ], }, }); <link href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet"> <div id="app"> </div> <template id="main"> <v-app> <v-btn color="primary" @click="dlgVisible = true">Show dialog</v-btn> <v-dialog v-model="dlgVisible"> <v-card> <v-card-title class="primary white--text py-2">Dialog</v-card-title> <v-card-text> <v-data-table :items="rows" :headers="header"> </v-data-table> </v-card-text> <v-card-actions class="justify-center"> <v-btn color="primary" @click="dlgVisible = false">Close</v-btn> </v-card-actions> </v-card> </v-dialog> </v-app> </template> <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.js"></script>
{ "language": "en", "url": "https://stackoverflow.com/questions/74143450", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Can we make correlated queries with SQLAlchemy I'm trying to translate this SQL query into a Flask-SQLAlchemy call: SELECT * FROM "ENVOI" WHERE "ID_ENVOI" IN (SELECT d."ID_ENVOI" FROM "DECLANCHEMENT" d WHERE d."STATUS" = 0 AND d."DATE" = (SELECT max("DECLANCHEMENT"."DATE") FROM "DECLANCHEMENT" WHERE "DECLANCHEMENT"."ID_ENVOI" = d."ID_ENVOI")) As you can see, it uses subqueries and, most important part, one of the subqueries is a correlated query (it use d table defined in an outer query). I know how to use subqueries with subquery() function, but I can't find documentation about correlated queries with SQLAlchemy. Do you know a way to do it ? A: Yes, we can. Have a look at the following example (especially the correlate method call): from sqlalchemy import select, func, table, Column, Integer table1 = table('table1', Column('col', Integer)) table2 = table('table2', Column('col', Integer)) subquery = select( [func.if_(table1.c.col == 1, table2.c.col, None)] ).correlate(table1) query = ( select([table1.c.col, subquery.label('subquery')]) .select_from(table1) ) if __name__ == '__main__': print(query) will result in the following query SELECT table1.col, (SELECT if(table1.col = :col_1, table2.col, NULL) AS if_1 FROM table2) AS subquery FROM table1 As you can see, if you call correlate on a select, the given Table will not be added to it's FROM-clause. You have to do this even when you specify select_from directly, as SQLAlchemy will happily add any table it finds in the columns. A: Based on the link from univerio's comment, I've done this code for my request: Declch = db.aliased(Declanchement) maxdate_sub = db.select([db.func.max(Declanchement.date)])\ .where(Declanchement.id_envoi == Declch.id_envoi) decs_sub = db.session.query(Declch.id_envoi)\ .filter(Declch.status == SMS_EN_ATTENTE)\ .filter(Declch.date < since)\ .filter(Declch.date == maxdate_sub).subquery() envs = Envoi.query.filter(Envoi.id_envoi.in_(decs_sub)).all()
{ "language": "en", "url": "https://stackoverflow.com/questions/38127298", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: dotnet core web api running on built in Docker container and running on Kubernetes Get a better TTFB when calling a Docker Service I am running a Web API application using DotNet core 1.1, running it inside a Docker container deployed on Kubernetes. I have the exact same API deployed on IIS (VM on Azure) (IIS VM and Kubernestes master and agent have the same specs and both connecting to the same DB server) The request to the API deployed on IIS is fast as seen below in the image The request to the API deployed on Kubernetes inside Docker is slow here is my Dockerfile: FROM microsoft/aspnetcore:1.1 ENV ASPNETCORE_ENVIRONMENT Docker WORKDIR /app EXPOSE 80 COPY . /app/ ENTRYPOINT ["dotnet", "X.X.X.API.dll"] What could be causing this behavior? I have looked everywhere with no clear documentation related to DotNet core performance on Docker. A: I think there can be at least 2 reasons for that: * *Your Web API application depends on some DB/storage and for some reasons there bigger latency when you run it on k8s. *Probably you did not configure deployment limits/requests for CPU.
{ "language": "en", "url": "https://stackoverflow.com/questions/47697676", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Detect if user clicks inside a circle How can I detect when the user clicks inside the red bubble? It should not be like a square field. The mouse must be really inside the circle: Here's the code: <canvas id="canvas" width="1000" height="500"></canvas> <script> var canvas = document.getElementById("canvas") var ctx = canvas.getContext("2d") var w = canvas.width var h = canvas.height var bubble = { x: w / 2, y: h / 2, r: 30, } window.onmousedown = function(e) { x = e.pageX - canvas.getBoundingClientRect().left y = e.pageY - canvas.getBoundingClientRect().top if (MOUSE IS INSIDE BUBBLE) { alert("HELLO!") } } ctx.beginPath() ctx.fillStyle = "red" ctx.arc(bubble.x, bubble.y, bubble.r, 0, Math.PI*2, false) ctx.fill() ctx.closePath() </script> A: A circle, is the geometric position of all the points whose distance from a central point is equal to some number "R". You want to find the points whose distance is less than or equal to that "R", our radius. The distance equation in 2d euclidean space is d(p1,p2) = root((p1.x-p2.x)^2 + (p1.y-p2.y)^2). Check if the distance between your p and the center of the circle is less than the radius. Let's say I have a circle with radius r and center at position (x0,y0) and a point (x1,y1) and I want to check if that point is in the circle or not. I'd need to check if d((x0,y0),(x1,y1)) < r which translates to: Math.sqrt((x1-x0)*(x1-x0) + (y1-y0)*(y1-y0)) < r In JavaScript. Now you know all these values (x0,y0) being bubble.x and bubble.y and (x1,y1) being x and y. A: Just calculate the distance between the mouse pointer and the center of your circle, then decide whether it's inside: var dx = x - bubble.x, dy = y - bubble.y, dist = Math.sqrt(dx * dx + dy * dy); if (dist < bubble.r) { alert('hello'); } Demo As mentioned in the comments, to eliminate Math.sqrt() you can use: var distsq = dx * dx + dy * dy, rsq = bubble.r * bubble.r; if (distsq < rsq) { alert('HELLO'); } A: To test if a point is within a circle, you want to determine if the distance between the given point and the center of the circle is smaller than the radius of the circle. Instead of using the point-distance formula, which involves the use of a (slow) square root, you can compare the non-square-rooted (or still-squared) distance between the points. If that distance is less than the radius squared, then you're in! // x,y is the point to test // cx, cy is circle center, and radius is circle radius function pointInCircle(x, y, cx, cy, radius) { var distancesquared = (x - cx) * (x - cx) + (y - cy) * (y - cy); return distancesquared <= radius * radius; } (Not using your code because I want to keep the function general for onlookers who come to this question later) This is slightly more complicated to comprehend, but its also faster, and if you intend on ever checking point-in-circle in a drawing/animation/object moving loop, then you'll want to do it the fastest way possible. Related JS perf test: http://jsperf.com/no-square-root A: An alternative (not always useful meaning it will only work for the last path (re)defined, but I bring it up as an option): x = e.pageX - canvas.getBoundingClientRect().left y = e.pageY - canvas.getBoundingClientRect().top if (ctx.isPointInPath(x, y)) { alert("HELLO!") } Path can btw. be any shape. For more details: http://www.w3.org/TR/2dcontext/#dom-context-2d-ispointinpath
{ "language": "en", "url": "https://stackoverflow.com/questions/16792841", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "40" }
Q: Using tag breaks the material UI Grid I was trying to use <div> to wrap my element which is inside the <Grid> but i noticed that this will break my <Grid> !, i tried the same thing in bootstrap grid system but this issue did not occur, https://codesandbox.io/s/material-demo-6zet4?fontsize=14 The thing is i have to use div to give some style to my elements that are inside the Grid but as you can see in the Codesandbox, the Grid breaks after using the div, how can i handle this ?, should i use a replacement for div or is there some kind of props for Grid that can fix this? A: The problem is the flexbox, it breaks because your div doesnt have the properties it needs. .MuiGrid-grid-xs-12 { flex-grow: 0; max-width: 100%; flex-basis: 100%; } Adding this to the div will have the same result like giving the Grid the style property directly. But the left,right and top border will be outside of the view, because of the .MuiGrid-spacing-xs-3 class. .MuiGrid-spacing-xs-3 { width: calc(100% + 24px); margin: -12px; } Depending on your needs use a different spacing like 0 for normal 100% width without margin and at it yourself. A: I don't know what you expect as result, but you can do is add width:100% to your div. Another option would be to add the same classes a Grid has, that would be MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12 Result: option 1 <div style={{ border: "4px double black", width: '100%' }}> options 2 <div className="MuiGrid-root MuiGrid-item MuiGrid-grid-xs-12" style={{ border: "4px double black" }}> A: Just add your border styles to classes.paper It seems from your example that you can just add the border to the paper inside the grid element to get the desired style. paper: { padding: theme.spacing(2), textAlign: "center", color: theme.palette.text.secondary, border: "4px double black" } If you want multiple classes on an element, use string interpolation: <Paper className={`${classes.paper1} ${classes.paper2}`}>
{ "language": "en", "url": "https://stackoverflow.com/questions/57071229", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to compare SQLite datetime to C# string using Linq I'm trying to Compare the SQLITE table value GameDate with a C# string, tempDate using a Linq statement. I'm getting an error on the "var list = db.Table()" line. Since I can't get the Linq line to work. I have just selected all the rows of the table and use a for loop to match. (it doesn't work either) This is the Linq statement I'm trying to use. // var list = db.Table().Where(n => n.GameDate== Convert.ToDateTime(tempDate)).ToList(); Here is my code: int recCtr = 0; var root = Windows.Storage.ApplicationData.Current.LocalFolder.Path; var dbPath = Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "BaseBallOU.db"); List<string> myCollection = new List<string>(); foreach (Object obj in GameDateListBox.Items) { string tempDate= obj.ToString(); using (var db = new SQLite.SQLiteConnection(dbPath)) { try { // var list = db.Table<Results>().Where(DateTime.Compare(GameDate.Value.Date, tempDate) == 0); // var list = db.Table<Results>().Where(n => n.GameDate== Convert.ToDateTime(tempDate)).ToList(); var list = db.Table<Results>().ToList(); foreach (var item in list) { recCtr++; if (item.GameDate.ToString("d") == tempDate.ToString()) { myCollection.Add(item.GameDate.ToString()); } } } catch { } } } TIA, any help appreciated. A: EF can't parse Convert.ToDateTime to SQL. Instead of that, you can declare DateTime variable outside of the query. DateTime dt = Convert.ToDateTime(tempDate); var list = db.Table().Where(n => n.GameDate == dt).ToList(); Also, you may need to compare only Date() part of the DateTime. Then you need to use on of canonical functions like EntityFunctions.TruncateTime(): DateTime dt = Convert.ToDateTime(tempDate); var list = db.Table().Where(n => EntityFunctions.TruncateTime(n.GameDate) == dt.Date).ToList();
{ "language": "en", "url": "https://stackoverflow.com/questions/28995312", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: A pre-populated database does not work at API 28 throws "no such table" exception I use a pre-populated database in my project. I have a created .sql base and copy it at first start.The base is big 33mb. private void copyDataBase() throws IOException { InputStream externalDbStream = context.getAssets().open(DB_NAME); String outFileName = DB_PATH + DB_NAME; OutputStream localDbStream = new FileOutputStream(outFileName); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = externalDbStream.read(buffer)) > 0) { localDbStream.write(buffer, 0, bytesRead); } localDbStream.close(); externalDbStream.close(); } It works fine at different android versions except API 28. API 28 throws "Caused by: android.database.sqlite.SQLiteException: no such table: phrases" exception: Caused by: android.database.sqlite.SQLiteException: no such table: phrases (code 1 SQLITE_ERROR): , while compiling: select * from phrases where complexity > 1 and known is null or known == 1 order by complexity limit 10 at android.database.sqlite.SQLiteConnection.nativePrepareStatement(Native Method) at android.database.sqlite.SQLiteConnection.acquirePreparedStatement(SQLiteConnection.java:903) at android.database.sqlite.SQLiteConnection.prepare(SQLiteConnection.java:514) at android.database.sqlite.SQLiteSession.prepare(SQLiteSession.java:588) at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:58) at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:37) at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:46) Thank you in advance. A: The typical cause of an App, that uses SQLite and that copies a pre-existing database suddenly not working for API 28 is that to get around the issue of the database folder not existing (the copy would fail if the directory didn't exist) is to create an empty database and then overwrite the database. However, as by default, from API 28, the SDK uses WAL (Write-ahead logging) and that creating the empty database to be overwritten, results in the -shm and -wal files being created. It is the existence of these files that result in the database being empty after the copy. * *I believe that this is because once the copied database is opened, a mismach is detected and the SDK's methods create an empty usable database (this is conjecture and hasn't actually been shown to be). Quick Fix The quick, but not recommended fix, is to override the onConfigure method in the class that subclasses SQLiteOpenHelper to use the disableWriteAheadLogging method so that the database is opened in journal mode. * *the full code below (2nd piece of code) includes this, but the line has been commented out. Recommended Fix The recommended method, so as to gain from the benefits of WAL, is to check for the existence of the database directory and create the directory if it doesn't exist rather than create a database to be overwritten (and therefore the -shm and -wal file don't exist when the database is copied) The following is an example method where the directory is checked/created when checking to see if the database exists (obviously this would need to be tailored accordingly) :- private boolean checkDataBase() { /** * Does not open the database instead checks to see if the file exists * also creates the databases directory if it does not exists * (the real reason why the database is opened, which appears to result in issues) */ File db = new File(myContext.getDatabasePath(DB_NAME).getPath()); //Get the file name of the database if (db.exists()) return true; // If it exists then return doing nothing // Get the parent (directory in which the database file would be) File dbdir = db.getParentFile(); // If the directory does not exits then make the directory (and higher level directories) if (!dbdir.exists()) { db.getParentFile().mkdirs(); dbdir.mkdirs(); } return false; } * *Note that this relies upon the variable DB_NAME being the database name (file name of the database file) and that the final location of the database is the standard location (data/data/the_package/databases/). The above has been extracted from the following subclass of SQLiteOpenHelper :- public class DBHelper extends SQLiteOpenHelper { private static String DB_NAME = "db"; private SQLiteDatabase myDataBase; private final Context myContext; private int bytes_copied = 0; private static int buffer_size = 1024; private int blocks_copied = 0; public DBHelper(Context context) { super(context, DB_NAME, null, 1); this.myContext = context; // Check for and create (copy DB from assets) when constructing the DBHelper if (!checkDataBase()) { bytes_copied = 0; blocks_copied = 0; createDataBase(); } } /** * Creates an empty database on the system and rewrites it with your own database. * */ public void createDataBase() { boolean dbExist = checkDataBase(); // Double check if(dbExist){ //do nothing - database already exists } else { //By calling this method an empty database will be created into the default system path //of your application so we are gonna be able to overwrite that database with our database. //this.getReadableDatabase(); //<<<<<<<<<< Dimsiss the above comment //By calling this method an empty database IS NOT created nor are the related -shm and -wal files //The method that creates the database is flawed and was only used to resolve the issue //of the copy failing in the absence of the databases directory. //The dbExist method, now utilised, checks for and creates the database directory, so there //is then no need to create the database just to create the databases library. As a result //the -shm and -wal files will not exist and thus result in the error associated with //Android 9+ failing with due to tables not existining after an apparently successful //copy. try { copyDataBase(); } catch (IOException e) { File db = new File(myContext.getDatabasePath(DB_NAME).getPath()); if (db.exists()) { db.delete(); } e.printStackTrace(); throw new RuntimeException("Error copying database (see stack-trace above)"); } } } /** * Check if the database already exist to avoid re-copying the file each time you open the application. * @return true if it exists, false if it doesn't */ private boolean checkDataBase() { /** * Does not open the database instead checks to see if the file exists * also creates the databases directory if it does not exists * (the real reason why the database is opened, which appears to result in issues) */ File db = new File(myContext.getDatabasePath(DB_NAME).getPath()); //Get the file name of the database Log.d("DBPATH","DB Path is " + db.getPath()); //TODO remove for Live App if (db.exists()) return true; // If it exists then return doing nothing // Get the parent (directory in which the database file would be) File dbdir = db.getParentFile(); // If the directory does not exits then make the directory (and higher level directories) if (!dbdir.exists()) { db.getParentFile().mkdirs(); dbdir.mkdirs(); } return false; } /** * Copies your database from your local assets-folder to the just created empty database in the * system folder, from where it can be accessed and handled. * This is done by transfering bytestream. * */ private void copyDataBase() throws IOException { final String TAG = "COPYDATABASE"; //Open your local db as the input stream Log.d(TAG,"Initiated Copy of the database file " + DB_NAME + " from the assets folder."); //TODO remove for Live App InputStream myInput = myContext.getAssets().open(DB_NAME); // Open the Asset file String dbpath = myContext.getDatabasePath(DB_NAME).getPath(); Log.d(TAG,"Asset file " + DB_NAME + " found so attmepting to copy to " + dbpath); //TODO remove for Live App // Path to the just created empty db //String outFileName = DB_PATH + DB_NAME; //Open the empty db as the output stream File outfile = new File(myContext.getDatabasePath(DB_NAME).toString()); Log.d("DBPATH","path is " + outfile.getPath()); //TODO remove for Live App //outfile.setWritable(true); // NOT NEEDED as permission already applies //OutputStream myoutputx2 = new FileOutputStream(outfile); /* Note done in checkDatabase method if (!outfile.getParentFile().exists()) { outfile.getParentFile().mkdirs(); } */ OutputStream myOutput = new FileOutputStream(outfile); //transfer bytes from the inputfile to the outputfile byte[] buffer = new byte[buffer_size]; int length; while ((length = myInput.read(buffer))>0) { blocks_copied++; Log.d(TAG,"Ateempting copy of block " + String.valueOf(blocks_copied) + " which has " + String.valueOf(length) + " bytes."); //TODO remove for Live App myOutput.write(buffer, 0, length); bytes_copied += length; } Log.d(TAG, "Finished copying Database " + DB_NAME + " from the assets folder, to " + dbpath + String.valueOf(bytes_copied) + "were copied, in " + String.valueOf(blocks_copied) + " blocks of size " + String.valueOf(buffer_size) + "." ); //TODO remove for Live App //Close the streams myOutput.flush(); myOutput.close(); myInput.close(); Log.d(TAG,"All Streams have been flushed and closed."); //TODO remove for Live App } @Override public synchronized void close() { if(myDataBase != null) myDataBase.close(); super.close(); } @Override public void onCreate(SQLiteDatabase db) { } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { } @Override public void onConfigure(SQLiteDatabase db) { super.onConfigure(db); Log.d("DBCONFIGURE","Database has been configured "); //TODO remove for Live App //db.disableWriteAheadLogging(); //<<<<<<<<<< un-comment to force journal mode } @Override public void onOpen(SQLiteDatabase db) { super.onOpen(db); Log.d("DBOPENED","Database has been opened."); //TODO remove for live App } } * *Note the above code is/was intended for development/experimentation and thus includes code that could be removed.
{ "language": "en", "url": "https://stackoverflow.com/questions/55336900", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Gradient text is not working in safari browser.It is showing white color instead of gradient text Below is the code.Gradient not working in safari after using webkits also. .gradientText{ background: -webkit-linear-gradient(#862AA5, #CE3E81); background: -moz-linear-gradient(#862AA5, #CE3E81); background: -webkit-gradient(#862AA5, #CE3E81); background: -o-linear-gradient(#862AA5, #CE3E81); background: -ms-linear-gradient(#862AA5, #CE3E81); background: linear-gradient(#862AA5, #CE3E81); //-webkit-mask-image: linear-gradient(#862AA5, #CE3E81); -webkit-background-clip: text; -webkit-text-fill-color: transparent; display: flex; //border: 3px solid #fff; } <p class='gradientText'>text </p>
{ "language": "en", "url": "https://stackoverflow.com/questions/66602737", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to properly inline for static libraries I'm re-writing a small C math library of mine that will end up as a static library for the user and would like to benefit from inlining for my vector math interface. I have the following: [ mymath.h ] ... ... extern float clampf( float v, float min, float max ); ... ... [ mymath.c ] inline float clampf( float v, float min, float max ) { if( v < min ) v = min; if( v > max ) v = max; return v; } Since my library will be static and I'm only going to provide the .h (and the .lib) to the user, will the clampf function be inlined in their program when compiled? Am I doing the right thing but declaring the function extern in the .h and inline in the .c? A: You should define your function as static inline in the .h file: static inline float clampf( float v, float min, float max ) { if( v < min ) v = min; if( v > max ) v = max; return v; } The function must be absent in the .c file. The compiler may decide not to inline the function but make it a proper function call. So every generated .o file may contain a copy of the function. A: You have it almost correct. You actually have it backwards; for inline functions you must put the inline definition in the header file and the extern declaration in the C file. // mymath.h inline float clampf( float v, float min, float max ) { if( v < min ) v = min; if( v > max ) v = max; return v; } // mymath.c #include "mymath.h" extern float clampf( float v, float min, float max ); You have to put the definition (full body) in the header file, this will allow any file which includes the header file to be able to use the inline definition if the compiler chooses to do so. You have to put the extern declaration (prototype) in the source file to tell the compiler to emit an extern version of the function in the library. This provides one place in your library for the non-inline version, so the compiler can choose between inlining the function or using the common version. Note that this may not work well with the MSVC compiler, which has very poor support in general for C (and has almost zero support for C99). For GCC, you will have to enable C99 support for old versions. Modern C compilers support this syntax by default. Alternative: You can change the header to have a static inline version, // mymath.h static inline float clampf(float v, float min, float max) { ... } However, this doesn't provide a non-inline version of the function, so the compiler may be forced to create a copy of this function for each translation unit. Notes: * *The C99 inlining rules are not exactly intuitive. The article "Inline functions in C" (mirror) describes them in detail. In particular, skip to the bottom and look at "Strategies for using inline functions". I prefer method #3, since GCC has been defaulting to the C99 method for a while now. *Technically, you never need to put extern on a function declaration (or definition), since extern is the default. I put it there for emphasis.
{ "language": "en", "url": "https://stackoverflow.com/questions/10291581", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "18" }
Q: How to set order of the nodes in Sankey Diagram Plotly So i am traying to make a cycle that gives different sankey diagram the thing is due to the plotly optimization the node are in different positions. I will like to set the standard order to be [Formal, Informal, Unemployed, Inactive] import matplotlib.pyplot as plt import pandas as pd import plotly.graph_objects as go df = pd.read_csv(path, delimiter=",") Lista_Paises = df["code"].unique().tolist() Lista_DF = [] for x in Lista_Paises: DF_x = df[df["code"] == x] Lista_DF.append(DF_x) def grafico(df): df = df.astype({"Source": "category", "Value": "float", "Target": "category"}) def category(i): if i == "Formal": return 0 if i == "Informal": return 1 if i == "Unemployed": return 2 if i == "Inactive": return 3 def color(i): if i == "Formal": return "#9FB5D5" if i == "Informal": return "#E3EEF9" if i == "Unemployed": return "#E298AE" if i == "Inactive": return "#FCEFBC" df['Source_cat'] = df["Source"].apply(category).astype("int") df['Target_cat'] = df["Target"].apply(category).astype("int") # df['Source_cat'] = LabelEncoder().fit_transform(df.Source) # df['Target_cat'] = LabelEncoder().fit_transform(df.Target) df["Color"] = df["Source"].apply(color).astype("str") df = df.sort_values(by=["Source_cat", "Target_cat"]) Lista_Para_Sumar = df["Source_cat"].nunique() Lista_Para_Tags = df["Source"].unique().tolist() Suma = Lista_Para_Sumar df["out"] = df["Target_cat"] + Suma TAGS = Lista_Para_Tags + Lista_Para_Tags Origen = df['Source_cat'].tolist() Destino = df["out"].tolist() Valor = df["Value"].tolist() Color = df["Color"].tolist() return (TAGS, Origen, Destino, Valor, Color) def Sankey(TAGS: object, Origen: object, Destino: object, Valor: object, Color: object, titulo: str) -> object: label = TAGS source = Origen target = Destino value = Valor link = dict(source=source, target=target, value=value, color=Color) node = dict(x=[0, 0, 0, 0, 1, 1, 1, 1], y=[1, 0.75, 0.5, 0.25, 0, 1, 0.75, 0.5, 0.25, 0], label=label, pad=35, thickness=10, color=["#305CA3", "#C1DAF1", "#C9304E", "#F7DC70", "#305CA3", "#C1DAF1", "#C9304E", "#F7DC70"]) data = go.Sankey(link=link, node=node, arrangement='snap') fig = go.Figure(data) fig.update_layout(title_text=titulo + "-" + "Mujeres", font_size=10, ) plt.plot(alpha=0.01) titulo_guardar = (str(titulo) + ".png") fig.write_image("/Users/agudelo/Desktop/GRAFICOS PNUD/Graficas/MUJERES/" + titulo_guardar, engine="kaleido") for y in Lista_DF: TAGS, Origen, Destino, Valor, Color = grafico(y) titulo = str(y["code"].unique()) titulo = titulo.replace("[", "") titulo = titulo.replace("]", "") titulo = titulo.replace("'", "") Sankey(TAGS, Origen, Destino, Valor, Color, titulo) The expected result should be. The expected result due to the correct order: The real result i am getting is: A: I had a similar problem earlier. I hope this will work for you. As I did not have your data, I created some dummy data. Sorry about the looooong explanation. Here are the steps that should help you reach your goal... This is what I did: * *Order the data and sort it - used pd.Categorical to set the order and then df.sort to sort the data so that the input is sorted by source and then destination. *For the sankey node, you need to set the x and y positions. x=0, y=0 starts at top left. This is important as you are telling plotly the order you want the nodes. One weird thing is that it sometimes errors if x or y is at 0 or 1. Keep it very close, but not the same number... wish I knew why *For the other x and y entries, I used ratios as my total adds up to 285. For eg. Source-Informal starts at x = 0.001 and y = 75/285 as Source-Formal = 75 and this will start right after that *Based on step 1, the link -> source and destination should also be sorted. But, pls do check. Note: I didn't color the links, but think you already have achieved that... Hope this helps resolve your issue... My data - sankey.csv source,destination,value Formal,Formal,20 Formal,Informal, 10 Formal,Unemployed,30 Formal,Inactive,15 Informal,Formal,20 Informal,Informal,15 Informal,Unemployed,25 Informal,Inactive,25 Unemployed,Formal,5 Unemployed,Informal,10 Unemployed,Unemployed,10 Unemployed,Inactive,5 Inactive,Formal,30 Inactive,Informal,20 Inactive,Unemployed,20 Inactive,Inactive,25 The code import plotly.graph_objects as go import pandas as pd df = pd.read_csv('sankey.csv') #Read above CSV #Sort by Source and then Destination df['source'] = pd.Categorical(df['source'], ['Formal','Informal', 'Unemployed', 'Inactive']) df['destination'] = pd.Categorical(df['destination'], ['Formal','Informal', 'Unemployed', 'Inactive']) df.sort_values(['source', 'destination'], inplace = True) df.reset_index(drop=True) mynode = dict( pad = 15, thickness = 20, line = dict(color = "black", width = 0.5), label = ['Formal', 'Informal', 'Unemployed', 'Inactive', 'Formal', 'Informal', 'Unemployed', 'Inactive'], x = [0.001, 0.001, 0.001, 0.001, 0.999, 0.999, 0.999, 0.999], y = [0.001, 75/285, 160/285, 190/285, 0.001, 75/285, 130/285, 215/285], color = ["#305CA3", "#C1DAF1", "#C9304E", "#F7DC70", "#305CA3", "#C1DAF1", "#C9304E", "#F7DC70"]) mylink = dict( source = [ 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3 ], target = [ 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7 ], value = df.value.to_list()) fig = go.Figure(data=[go.Sankey( arrangement='snap', node = mynode, link = mylink )]) fig.update_layout(title_text="Basic Sankey Diagram", font_size=20) fig.show() The output
{ "language": "en", "url": "https://stackoverflow.com/questions/72749062", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Bug in VBA in MSProject how to check if sub project is loaded in master project? If I place watch on the tmp variable and stop on the line If Not tmp Then both show up as true, I.e. tmp is True and Not tmp is True. Dim subProj As Subproject For Each subProj In prj.Subprojects Dim tmp As Boolean tmp = subProj.IsLoaded If Not tmp Then ExportTaskToExcel subProj.SourceProject, StartDate, EndDate End If Next What should I do to check if the subproject is not loaded (not expanded) in master project? Look at image under this link which is showing that in the same time: True = not True A: There is a chance you have tmp declared somewhere else that can be seen from here causing this issue (i.e. it is declared public in another module). Try changing the name to isolate it, also, I've never declared a variable in a loop before, While I'm not sure of the implications, I would not recommend it. Dim subProj As Subproject Dim tmp10 As Boolean For Each subProj In prj.Subprojects tmp10 = subProj.IsLoaded If Not tmp10 Then ExportTaskToExcel subProj.SourceProject, StartDate, EndDate End If Next You may have done it for a specific reason but you could omit the variable altogether: - Dim subProj As Subproject For Each subProj In prj.Subprojects If Not subProj.IsLoaded Then ExportTaskToExcel subProj.SourceProject, StartDate, EndDate End If Next
{ "language": "en", "url": "https://stackoverflow.com/questions/37748054", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Porting QT application from Linux to Windows? Greetings all, We are developing a QT application (QT 4.6 LGPL version) in Linux platform.All the libraries we use are cross-platform. Now we want to port it into Windows and continue develop in Windows. My questions are: * *Which compiler should we use ,Can we use MinGW or Visual C++ compiler? 2.If its Visual C++ compiler, which Visual Studio version should be used ,can we use 'Visual C++ Studio 2010 express' ? thanks in advance. A: The easiest, by far, is to install QtCreator. it includes MinGW and simply opens the same project files as on linux. compile, and go! A huge advantage of MinGW over VC++ is that it doesn't make you chase circles around getting the right vcredist library for the exact version of the compiler, nor it cares too much about debug/release builds. To deploy, just be sure to copy the same one or two DLLs you have on the development machine. A few more for Qt, but these are well-documented on Qt docs. No hidden surprises.
{ "language": "en", "url": "https://stackoverflow.com/questions/2986754", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: sIFR 3 - sifr-config.js possibly not running? Not sure what's wrong I've been messing with this for a few hours, and I just can't get the text to be replaced at all. I really can't believe it's taking so long, especially because I did this a few months ago and got it to work in minutes. Anyway, here is my site I'm working on: http://www.moreheadplanetarium.org/regeneration/test/vision.php and I want to replace the h1 tag (Morehead's Vision). I don't know what's wrong, since I've done everything I know to do. I'm jumping back into web design and using Firebug, and when I check the scripts it only has sifr.js and sifr-debug.js in the list, so I'm assuming the config isn't loading but I have no idea what could be the hold up... How do you get the debug to work btw? thanks! A: There's a syntax error at the end of sifr-config.js.
{ "language": "en", "url": "https://stackoverflow.com/questions/1337401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Asp.net MVC binding ajax data to a submit button I have ajax code that gets data from a radio button. $("input[name='SelectedCG']").on('change', function () { $.ajax({ url: '@Url.Action("FilterReports", "Reports")', data: { cgName: $("input[name='SelectedCG']:checked").val() }, type: 'POST', success: function (data) { $('#reportTable').html(data); $('#reportTable').show(); }, error: function(xhr, status, error) { alert(xhr.responseText); } }) }); I want to bind this data to a submit button which can pass this information to a method in a controller. <input type="submit" value="Export" class="btn btn-primary btn-large" onclick="location.href='@Url.Action("Export", "Reports")'"> Any help would be appreciated! A: It is better to pass the value of the radioButton to the Export method and get the data again. In any case you might need to do some more work on that data before you export it any way. Also you might want to check the user's permissions to export such data. Also you might not want to transfer such data over the network back and forth. It is easier (faster) to send the value of a button than it is to send a collection of data which has to be exported. Not to mention that there are also security concerns depending on how you will handle the data you receive and if it is correct or not? What If a user changes it manually in the browser before hitting the export button? Would that hurt your application's logic in some way and would you want to protect yourself against that? Best is to use an HttpPost, to include AntiForgeryToken, to submit the radio button value and check the user's permissions.
{ "language": "en", "url": "https://stackoverflow.com/questions/37381133", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to read my String correctly in html and mvc? I'm using MVC, getting a certain message this way [HttpGet] public virtual ActionResult Message(int ID) { Models.Userr.Message model = new Models.User.Message(); String getMessage = userService.getMessage(ID); model.Message = getMessage; return View(model); } Then in the view I'm writting in the View: <label>@Model.Message</label> And it is writting in my screen, for example: Hello <a href="https://www.google.com">Google</a>. yet, it is being read as string. So my problem and question is: what can I use in either MVC (in the controller) or Html (in the View) in order to detect the link. Also I'm using the userservce.getMessage(int ID) to get a message related to a certain ID from a table of errors. A: I think what you're looking for is Raw <label>@Html.Raw(Model.Message)</label> This will write Model.Message's contents as html instead of text.
{ "language": "en", "url": "https://stackoverflow.com/questions/26513123", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: How to delete more than one relationship in neo4j using cypher? I want to remove more than one relationship but not all relationship for specific node, I can delete single relationship or every relationship but not more than one specific relationship match(n:Student{id:2), (n)-[r1:STUDENT_CLASS]->(b:Class), (n)-[r2:STUDENT_RANK]->(m:Rank) delete r1,r2 return n.name I connected Student node with 3 common nodes(School,Class,Rank) with different relationship. I want to delete 2 relationship(Class,Rank) for particular student in same query without affecting another node's(School) relationship with Student node. A: Your query is logically correct but syntactically wrong: match(n:Student{id:2), <--- missed a closing curly brace here (n)-[r1:STUDENT_CLASS]->(b:Class), (n)-[r2:STUDENT_RANK]->(m:Rank) delete r1,r2 return n.name Try this: match(n:Student{id:2}), (n)-[r1:STUDENT_CLASS]->(b:Class), (n)-[r2:STUDENT_RANK]->(m:Rank) delete r1,r2 return n.name A: The vertical stroke | acts as an OR operator when selecting relationships: match (n:Student {id:2})-[r:STUDENT_CLASS|STUDENT_RANK]->(b) where b:Class or b:Rank delete r
{ "language": "en", "url": "https://stackoverflow.com/questions/73702876", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Appgyver Steroids Simulator Build Submit to Facebook My app is nearing completion (HECK YEAH!) and we are needing some extended Facebook permissions. Following Facebook's instructions for submitting an app, it requires that I do a Simulator build. However, the Appgyver Facebook plugin doesn't work on the simulator so I have to use their build service to even test the Facebook functionality. Does anyone have any clue as to how to build an Appgyver Steroids app for iOS so that I can submit it to Facebook for review? Thanks! A: There's currently no support for custom simulator builds. That's something that we've considered but there has not been a real use case yet. Since Facebook now wants to review iOS builds using a Simulator build, we'll need to add support for that at some point soon. We can continue over email to get your application submitted for review before we can offer custom simulator builds from the Build Service. Edit: Custom Simulator builds have now been available since spring 2015.
{ "language": "en", "url": "https://stackoverflow.com/questions/26643650", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: how to set the required validator for an input field in jquery? I have a page which has a GridView placed in an update panel. Each row in the GridView has a update button, when clicked, a modal dialog will pop up, where you could edit the corresponding row and save the record to the database through a web service call. Following is the aspx and jquery code. My question is I want to make the txtName and txtDescription required. As you can see, the Save button in the modal dialog gets created in the jquery function. How should I add required field validator to those fields? And when the user clicking the Save button, if the txtName or txtDescription is empty, a red label with text “required!” will should next to it, the focus will set to the first field that is empty. <div id="dvMainContainer"> <asp:UpdatePanel ID="upMainPanel" runat="server" RenderMode="Inline" UpdateMode="Conditional"> <ContentTemplate> <table summary="content" id="Table3"> <tr> <td> <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="false" AutoGenerateColumns="False" PageSize="20" onpageindexchanging="GridView1_PageIndexChanging"> <Columns> <asp:TemplateField > <ItemTemplate> <div><input type="button" value="update" /></div> </ItemTemplate> </asp:TemplateField> <asp:TemplateField > <HeaderTemplate>Vendor<br /> <asp:DropDownList ID="ddlVendor" runat="server" AutoPostBack="true" AppendDataBoundItems="true" OnSelectedIndexChanged="OnVendorChanged"> <asp:ListItem Text="- Select a Vendor -" Value=""></asp:ListItem> </asp:DropDownList> </HeaderTemplate> <ItemTemplate><%#Eval("Vendor") %></ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Name" > <ItemTemplate><%#Eval("Name")%></ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Description" > <ItemTemplate><%#Eval("Description")%></ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> </td> </tr> </table> </ContentTemplate> </asp:UpdatePanel> </div> </div> <div id="dvUpdatePrompt" style="display: none;" runat="server"> <table> <tr> <td>Vendor:</td> <td><select name="VendorList" id="VendorList"></select></td> </tr> <tr> <td>Name:</td> <td><input type="text" id="txtName"/></td> </tr> <tr> <td>Description:</td> <td><input type="text" id="txtDescription"/></td> </tr> </table> </div> this.BindEvents = function () { var myself = this; $(myself.get_element()).find("input[value='update']").each( function () { var input = $(this); if (input.closest('tr').find('td')[1].innerText.replace('&nbsp;', '') != '') { input.click( function () { myself.UpdateButtonClicked(this); } ); } else { input.attr('disabled', 'disabled'); } } ); } this.UpdateButtonClicked = function (button) { var myself = this; var btns = {}; var Vendor = ""; var Name = ""; var Description = ""; … btns["Save"] = function () { myself.UpdateVendor(button); }; btns["Cancel"] = function () { $("#dvUpdatePrompt").dialog('close'); }; … $("#dvUpdatePrompt").dialog({ modal: true, buttons: btns, width: 500, height: 300 }); } this.UpdateVendor = function (button) { var myself = this; … var parmIn = "…"; myself.Utilities.CallWebService('WebService.asmx/UpateVendor', parmIn, function (result) { $("#dvUpdatePrompt").dialog('close'); ... } ); } Update: I added following code to the this.BindEvents function: But it is not working? $("#txtName").blur(function () { if (!$(this).val()) { $(this).parents('p').addClass('warning'); } });
{ "language": "en", "url": "https://stackoverflow.com/questions/20353718", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Making a copy of an own object instead of a reference (updated post, different Q) solution I am still getting the hang of it, and its probally logic for a lot of you. But I've updated the post with how I got it working, might some one come here by search. declare: var test=Element({"id" : 1, "name" : "wrapper"}). append(Element({"id" : 2, "name" : "elm A"}), Element({"id" : 3, "name" : "elm b"}) ); alert(test.getInfo("name")); alert(test.aArguments["children"][1].getInfo("name")); 'class': var Element = function ($aPassArguments) { aArguments: { "id" : false, "name" : false, "type" : false, "title" : false, "style" : false, "action" : [], "parent" : false, "children" : [] }; for (var prop in this.aArguments) if (prop in $aPassArguments) this.aArguments[prop] = $aPassArguments[prop]; return { append: function () { $argList = arguments; for ($i = 0; $i < $argList.length; $i++) if (typeof $argList[$i]=="string") this.setChild(this.importDB($argList[$i],true)); else this.setChild($argList[$i]); }, setChild: function($oChild) { this.aArguments["children"][this.aArguments["children"].length]=$oChild; } }; }; ............................................................. Previous edit I wasnt aware a new object instance in javascript is a reference instead of a copy. Now I want to have a copy of my own object Element. Apperantly (thanks @blurd) I want it to be a factory hybrid: http://javascript.info/tutorial/factory-constructor-pattern Thanks to the help of @blurd and me defining some problems, I came up with a sollution like the following: (but I am not happying with my usage declaration below) In which I finaly got copies of my Element object instead of references. The good answers below didnt completly solve my problem. But this is due to my poor clarification and understanding of the problems Sort of solution var Element = function (initialConfig) { return { aArguments: { "id" : false, "name" : false, "type" : false, "title" : false, "style" : false, "action" : [], "parent" : false, "children" : [], }, create:function ($aPassArguments) { for (var prop in this.aArguments) if (prop in $aPassArguments) this.aArguments[prop] = $aPassArguments[prop]; }, append: function () { $argList = arguments; for ($i = 0; $i < $argList.length; $i++) if (typeof $argList[$i]=="string") this.setChild(this.importDB($argList[$i],true)); else this.setChild($argList[$i]); }, setChild: function($oChild) { this.aArguments["children"][this.aArguments["children"].length]=$oChild; } }; }; usage var test=Element(); test.create({"id" : 1, "name" : "wrapper"}); var test2=Element(); test2.create({"id" : 2, "name" : "elm A"}); test3.create({"id" : 3, "name" : "elm B"}); test.append(test2,test3); alert(test.aArguments["name"]); alert(test.aArguments["children"][0].aArguments["name"]); Now I am very unhappy about the usage,I would like it be one line and use a constructor again. And this is probally possible, and... after some more selfschooling I will probally solve it. But for now I am done with it :P just updated my post with this. When I get to it again and have a beter declaration I will update it again. And perhaps someone might share a way (beter way) to do this. To eventually have something like this: var test=new Element({"id" : 3, "name" : "wrapper"}) .append( new Element{"id" : 3, "name" : "elm A"}), new Element({"id" : 3, "name" : "elm B"}) ); ............................................................................................. old post I am pulling my hair outs here, everything I search about javascript and objects tells me the same, which is not enough, because I cant figure out why the following code isnt working propaly: For example I am making an object like this: var Element = { aArguments: { //set Default arguments "id" : false, "name" : false, "type" : false, "title" : false, "style" : false, "action" : [], "parent" : false, "children" : {}, }, create:function ($aPassArguments) { for (var prop in this.aArguments) if (prop in $aPassArguments) this.aArguments[prop] = $aPassArguments[prop]; return this; }, append: function () { $argList = arguments; for ($i = 0; $i < $argList.length-1; $i++) if (typeof $argList[$i]=="string") this.setChild(this.importDB($argList[$i],true)); else this.setChild($argList[$i]); return this; }, setChild: function($oChild) { this.aArguments["children"][this.aArguments["children"].length-1]=$oChild; }, getInfo: function($sKey) { return this.aArguments[$sKey]; } }; Which merges $aPassArguments with this.Arguments on calling of .create() (I cant figureif its possible to use a '__constructor'). To replace given proparties in aArguments. And add passed object(s) with .append to aArguments["childeren"]. But when I call the object like this: $set=(Element.create({"id": 1, "name" : "wrapper"})). append(Element.create({"id" : 3, "name" : "elm A"})); alert($set.getInfo("name")); It will alert me "Elm A" and not "wrapper". I assume that this is because I am not creating a new object of Element, but are working on the same object. Now to me the logical solution and start would be to write: $set=(new Element.create({"id": 1, "name" : "wrapper"})). append(new Element.create({"id" : 3, "name" : "elm A"})); alert($set.getInfo("name")); but I get the error: TypeError: (intermediate value).append is not a function Why isnt my code not working as supposed by me? And is it possible and if so how do I add a constructor to an object? So I could skip calling .create and use: $set=new Element({"id": 1, "name" : "wrapper"}). append(new Element({"id" : 3, "name" : "elm A"})); A: You are right, you should be using the new operator. Aside from that, it looks like you're trying to make this some type of factory hybrid. I suggest the following. Use a Constructor Function Include an optional configuration that you can use when creating the object. var Element = function (initialConfig) { if (initialConfig) { this.create(initialConfig); } }; Add to the Prototype All your shared Element members should be part of the prototype. Element.prototype = { aArguments: { "id" : false, "name" : false, "type" : false, "title" : false, "style" : false, "action" : [], "parent" : false, "children" : {}, }, create:function ($aPassArguments) { for (var prop in this.aArguments) if (prop in $aPassArguments) this.aArguments[prop] = $aPassArguments[prop]; return this; }, append: function () { $argList = arguments; for ($i = 0; $i < $argList.length-1; $i++) if (typeof $argList[$i]=="string") this.setChild(this.importDB($argList[$i],true)); else this.setChild($argList[$i]); return this; }, setChild: function($oChild) { this.aArguments["children"][this.aArguments["children"].length-1]=$oChild; }, getInfo: function($sKey) { return this.aArguments[$sKey]; } }; Examples Your examples should now work as you expected. Notice that you can't call new Element.create() as that would treat Element.create as a constructor. Instead, pass your initial values into the constructor. $set = new Element({"id": 1, "name" : "wrapper"}). append(new Element({"id" : 3, "name" : "elm A"})); alert($set.getInfo("name")); Be Careful You're not checking for own properties in your loops, omitting {}, and I spotted at least one implied global. JavaScript will bite you if you're not careful. Consider using JSLint or JSHint to help you spot these problems. A: Your create function does not create any object, but rather changes on place the Element. aArguments object. Any strange thing might follow. Anyway, just go for a clean and simple prototypal inheritance scheme, do not use $, remember to always declare your vars, and keep things simple : function Element(initialValues) { this.id = this.prototype.id++; this.name = null; this.type = null; this.title = null; this.style = null; this.action = []; this.parent = null; this.children = []; for (var prop in initialValues) if (this[prop] != undefined) this[prop] = initialValues[prop]; } Element.prototype = { append: function () { for (var i = 0; i < arguments.length - 1; i++) { var thisElement = arguments[i]; if (typeof thisElement == "string") this.setChild(this.importDB(thisElement, true)); else this.setChild(thisElement); } return this; }, setChild: function (child) { this.children.push(child); return this; }, getInfo: function (key) { return this[Key]; }, id: 0 };
{ "language": "en", "url": "https://stackoverflow.com/questions/22095546", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to define n-th parent element by pure JavaScript? As in the title, how can i define nth parentElement in js in other way than: var theComment = e.target.parentElement.parentElement.parentElement.parentElement; A: You can write a loop for it: const n = 4 let elem = e.target for(let i = 0; i < n; i++) elem = elem.parentElement console.log(elem) However, as mentioned in the comments, if you're looking for a specific element, it might be better to just write a selector for the element you're looking for. This applies to your case even more, as event.target can return child nodes of the watched element (if the event bubbles), making your parent count shift around a bit. A: You might define a function which ascends up in the parent hierarchy with a loop, e.g.: function nthParent(n, el) { while (n--) { el = el.parentElement; if (!el) return null; } return el; }
{ "language": "en", "url": "https://stackoverflow.com/questions/67670507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Laravel 5.7 and ExtJS 5 app configuration I am trying for the first time to create an application with Laravel 5.7 and ExtJS 5. There is a lot of information for Laravel / Vue and Laravel / Angular applications, but for Laravel / ExtJS it is practically non-existent (unfortunately). I created an ExtJS app called extjs_app with cmd that I put in the public folder of the Laravel project. In the Laravel views folder I created a view named index_extjs.blade.php containing the index.html code of the ExtJS app with the following change: <script id="microloader" type="text/javascript" src="bootstrap.js"></script> replaced for <script id="microloader" type="text/javascript" src="extjs_app/bootstrap.js"></script> And in the bootstrap.js file (I probably should not edit this file): Ext.manifest = Ext.manifest || "bootstrap.json"; replaced for Ext.manifest = Ext.manifest || "extjs_app / bootstrap.json" And in the app.json file indexHtmlPath": "index.html" replaced for "indexHtmlPath": "../../../resources/views/index_extjs.php" However, despite several attempts, the files required for the ExtJS application are not loaded. How to properly configure Laravel and ExtJS to work together? A: You need to set the root route for the entire application to be served with your blade view, in your case index_extjs.blade.php. Why? Because when anyone opens up your site, you are loading up that page and hence, loading extjs too. After that page is loaded, you can handle page changes through extjs. So to achieve this, you need to declare your root route to server this index file: Route::get('/', function() { return view('index_extjs'); }); Also you need to revert all extjs config changes back to default, because everything will be relative to your extjs app inside public folder and not relative to the project itself. I hope this makes sense
{ "language": "en", "url": "https://stackoverflow.com/questions/52742928", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Hazelcast management center - Membres unable to communicate I have this config to connect: config.getManagementCenterConfig().setEnabled(true); config.getManagementCenterConfig().setUrl("http://localhost:8096/hazelcast-mancenter"); Error on management center console : 2019-05-29 12:44:27 [qtp873415566-15] WARN org.eclipse.jetty.server.HttpChannel - /hazelcast-mancenter/collector.do org.springframework.web.util.NestedServletException: Request processing failed; nested exception is com.hazelcast.webmonitor.model.DeserializationException: nodeState field is null at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:982) at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:872) at javax.servlet.http.HttpServlet.service(HttpServlet.java:707) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:865) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1655) at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:208) at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:177) at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:347) at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:263) at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1634) at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:533) at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:146) at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:548) at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:132) at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:257) at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:1595) at org.eclipse.jetty.server.handler.ScopedHandler.nextHandle(ScopedHandler.java:255) at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1317) Error on Client springboot app console: 2019-05-29 12:54:27.059 INFO [-,,,] 12068 --- [ main] c.h.i.m.ManagementCenterService : [10.1.204.138]:5701 [dev] [3.7.7] Hazelcast will connect to Hazelcast Management Center on address: http://localhost:8096/hazelcast-mancenter 2019-05-29 12:54:27.090 INFO [-,,,] 12068 --- [ main] com.hazelcast.core.LifecycleService : [10.1.204.138]:5701 [dev] [3.7.7] [10.1.204.138]:5701 is STARTED 2019-05-29 12:54:27.090 INFO [-,,,] 12068 --- [MC.State.Sender] c.h.i.p.impl.PartitionStateManager : [10.1.204.138]:5701 [dev] [3.7.7] Initializing cluster partition table arrangement... 2019-05-29 12:54:27.115 INFO [-,,,] 12068 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'hazelcastInstance' of type [com.hazelcast.instance.HazelcastInstanceProxy] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2019-05-29 12:54:27.197 INFO [-,,,] 12068 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'cacheManager' of type [com.hazelcast.spring.cache.HazelcastCacheManager] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2019-05-29 12:54:27.205 INFO [-,,,] 12068 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'cacheAutoConfigurationValidator' of type [org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration$CacheManagerValidator] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2019-05-29 12:54:27.292 INFO [-,,,] 12068 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration' of type [org.springframework.cloud.autoconfigure.ConfigurationPropertiesRebinderAutoConfiguration$$EnhancerBySpringCGLIB$$a3818d32] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2019-05-29 12:54:27.342 INFO [-,,,] 12068 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.sleuth.instrument.web.client.feign.TraceFeignClientAutoConfiguration$FeignBeanPostProcessorConfiguration' of type [org.springframework.cloud.sleuth.instrument.web.client.feign.TraceFeignClientAutoConfiguration$FeignBeanPostProcessorConfiguration$$EnhancerBySpringCGLIB$$c6f962fb] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2019-05-29 12:54:27.385 INFO [-,,,] 12068 --- [ main] trationDelegate$BeanPostProcessorChecker : Bean 'org.springframework.cloud.sleuth.instrument.async.AsyncDefaultAutoConfiguration' of type [org.springframework.cloud.sleuth.instrument.async.AsyncDefaultAutoConfiguration$$EnhancerBySpringCGLIB$$6f4b3654] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying) 2019-05-29 12:54:28.645 INFO [-,,,] 12068 --- [ main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat initialized with port(s): 8090 (http) 2019-05-29 12:54:28.667 INFO [-,,,] 12068 --- [ main] o.apache.catalina.core.StandardService : Starting service [Tomcat] 2019-05-29 12:54:28.669 INFO [-,,,] 12068 --- [ main] org.apache.catalina.core.StandardEngine : Starting Servlet Engine: Apache Tomcat/8.5.15 2019-05-29 12:54:28.799 WARN [-,,,] 12068 --- [MulticastThread] c.h.i.cluster.impl.MulticastService : [10.1.204.138]:5701 [dev] [3.7.7] Received a JoinRequest with a different packet version! This -> 4, Incoming -> -84, Sender -> /10.1.204.123 2019-05-29 12:54:29.260 INFO [-,,,] 12068 --- [ost-startStop-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext 2019-05-29 12:54:29.260 INFO [-,,,] 12068 --- [ost-startStop-1] o.s.web.context.ContextLoader : Root WebApplicationContext: initialization completed in 12542 ms 2019-05-29 12:54:30.158 WARN [-,,,] 12068 --- [MC.State.Sender] c.h.i.m.ManagementCenterService : [10.1.204.138]:5701 [dev] [3.7.7] Failed to send response, responseCode:405 url:http://localhost:8096/hazelcast-mancenter/collector.do I don't see any configuration to be made to set the nodeStatus as described in errorstack trace. Kindly let know what config to be made. Thanks! A: As stated by @emre in comments, there is official text about it: ... the Management Center is compatible with Hazelcast IMDG cluster members having the same or the previous minor version. For example, Hazelcast Management Center version 3.12.x works with Hazelcast IMDG cluster members having version 3.11.x or 3.12.x. from Hazelcast Management Center Documentation. The Exception message (DeserializationException: nodeState field is null) is not really helpful to realize that. The same happend to me, I was using Spring boot parent in version 1.5.9.RELEASE and therefore it had old the dependency of hazelcast (3.7.8). You can always check for versions of spring autoconfigured dependencies in spring-boot-dependencies projects's pom.xml file. There you can see hazelcast version in properties section defined like this: <hazelcast.version>3.7.8</hazelcast.version> You can * *change the spring-boot-starter-parent version to newer (e.g. 2.2.0.RELEASE) and the issue should dissapear or *overwrite only the properties in your own pom.xml with newer hazelcast version.
{ "language": "en", "url": "https://stackoverflow.com/questions/56355195", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: CS-CART Themeing I have been looking into using CS-CART as a shopping cart and started looking through the themes and it appears to me the only way to build a theme is to extend a default theme and use the theme editor and visual designer to construct themes. Is this the only way or is there a way to code custom themes without being limited to designing in the administration section? A: The theme editor is intended to be used as a customization tool for the site administrator, not for the theme developer. A theme may provide configuration for the theme editor - what colors can be changed, etc. For the deep customization of how the site looks you can create you own theme with your own CSS code. Check out this guide on how to create your custom theme - http://docs.cs-cart.com/4.3.x/designer_guide/theme_tutorial/index.html Also there is an official Bootstrap 3 theme for CS-Cart which can be easily customized - https://github.com/cscart/cscart-boilerplate#the-cs-cart-boilerplate-theme A: You are not limited, you have all the tools that you need to develop as you desire, the responsive theme is the base because this theme was tested enough so far and have good feedback and for somebody to start from scratch will take to much time and until you finish CS-Cart will do a big change and you will need to do another work ;) Please check https://www.ambientlounge.ie and let me know if you find any limitations here :D A: It's very easy modift cs-cart theme, cs-cart theme base on bootstrap and and smarty engine, firt you need looking for "index.tpl", "common/script.tpl", "common/style.tpl", "view/block_manager/render/grid.tpl || container.tpl || block.tpl || location.tpl. and you will understand cs-cart theme structure You need to know smarty engine syntax here http://www.smarty.net/documentation and cs-cart developer doc here http://docs.cs-cart.com/4.3.x/#designer-guide
{ "language": "en", "url": "https://stackoverflow.com/questions/35760989", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android Webview Javascript window.location and checked problems I am having 2 related problem with javascript in webview. The first is that when I check a checkbox in the html page it will sometimes but not always display the checkbox as checked. So, to help the user I also use a label and also set the onclick event to document.getElementById('checkbox')=checked and still it only sometimes works: <label><input type="checkbox" class="big" id="checkbox' + (i-1) +'" name="activities" value="' + (i-1) + '"><a onclick="document.getElementById(checkbox' + (i-1) +')=checked">' + questionsTexts[i-1] + '</a></label> The second is that when I try to open a new page i use function clickNextPage(url) { //write to cookies here //end write to cookies var HtmlStr = "ict4d_198_19815d.html?num_questions="+num_questions+"&"; for(i=1; i<=num_questions; i++) { if (document.getElementById("checkbox" + (i-1)).checked)HtmlStr+="arrId"+(i-1)+"="+(i-1)+"&"; } window.location=""+HtmlStr; return false; } Originally I passed it to the activity and used loadUrl(url) but this did not work as i could not get the webview to loadUrl. I tried this.loadUrl webview.loadUrl super.loadUrl but nothing would work so I went back to doing it in the javascript code with window.location. Again, it only works sometimes. Tried window.location.href also to no avail. All these issues don't exist in the HTC Desire but do in the Samsung Galaxy S. Does anyone have a workaround that is foolproof? Thanks.
{ "language": "en", "url": "https://stackoverflow.com/questions/7498507", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Sort-Object - differences when using console vs .ps1 file When running .ps1 file the sizes are sorted alphabetically (mixing MB and KB). But when running in the console directly, it correctly sorts by folder size. Both running on the same server. Get-MailboxFolderStatistics -identity [email protected] | Sort-Object Foldersize -Descending | Format-Table folderpath, foldersize Solution: turns out it had to do with using a Remote shell. Remote shell returns FolderSize as System.String rather than Microsoft.Exchange.Data.ByteQuantifiedSize
{ "language": "en", "url": "https://stackoverflow.com/questions/46806810", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Authorize to Apple Music via Facebook Messenger In-App Browser We're using https://developer.apple.com/documentation/musickitjs to authorize Apple music, on Desktop it opens a new window to authorize to apple. But It's NOT working on mobile In-App Browser (both iOS & Android), probably because on mobile messenger, it's not possible to allow the opening of multiple windows. Are we missing something here? Any workaround for it? Has anyone done that? Ref: https://developer.apple.com/forums/thread/117058
{ "language": "en", "url": "https://stackoverflow.com/questions/66254870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: HTML/Javascript/CSS GUI for the development of desktop applications with python? I wonder if there's a python GUI like pyqt etc. which works purely with html and javascript for layouting desktop applications... Do you know if there are projects like this? Does this make sense at all ;-) Or it it just me finding that a nice tool... A: Since you mention PyQt yourself, you could perhaps just create a simple GUI using these tools, with your entire application made up of a QtWebKit module. Then just point to some files you created locally, and browse them using your appliction? But, this would not be any different compared to using a normal browser, so there's not really any point in doing this in my opinion... A: If it were Python-based but had nothing to do with Python, would you really care if it wasn't Python based? Anyways, yes, a project exists. A pretty big one too. It's called XULRunner. The project is maintained by Mozilla and is used for the GUI of every Mozilla program. It features an XML-based syntax (XUL): <?xml version="1.0"?> <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> <window id="main" title="My App" width="300" height="300" xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <script type="application/javascript" src="chrome://myapp/content/main.js"/> <caption label="Hello World"/> <separator/> <button label="More >>" oncommand="showMore();"/> <separator/> <description id="more-text" hidden="true">This is a simple XULRunner application. XUL is simple to use and quite powerful and can even be used on mobile devices.</description> </window> And JavaScript: function showMore() { document.getElementById("more-text").hidden = false; } You can even embed Python scripts, it seems, into your code: http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xulrunner_about.html A: you could always use django, django templates support html, js, css, php etc.
{ "language": "en", "url": "https://stackoverflow.com/questions/7967575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Best way to make object hash in Ruby? So I have a class wherein I need to override the equality operators. This is not so hard. But the custom equality operators aren't used unless my_obj.hash is equal for two objects being compared. so we need to override hash() I'm kind of stuck on the best way to do this. My object embeds three other object instances. I see by example that for simple instance vars you can just take a hash of the vars themselves: [var1, var2, var3].hash More specifically, my class has instance vars for three embedded objects, let's call them: A B1 B2 Two instances of my object are equal if object1.B1 == object2.B1 && object1.B2 == object2.B2 || object1.B1 == object2.B2 && object1.B2 == object2.B1 In other words, the collection of B1 and B2 has the same two objects in it, regardless of which specific vars they're assigned to. B1 and B2 have a custom equality mechanism as well. I'm just not clear on the best strategy for overriding hash() here. Sorry if the example is abstract, I'm trying to avoid posting a lot of code. A: Try using a Set instead of an array so the order doesn't matter. You have to have this line at the top: require 'set' Then make a Set containing both objects and use it to help implement the equality operator and hash method. I assume Set#hash behaves correctly and your can use it in your hash method. Set#== can be used to simplify your equality operator. http://www.ruby-doc.org/stdlib-2.1.4/libdoc/set/rdoc/Set.html A: Are your B1 and B2 objects sortable? If so, here's an easy implementation of your hash method: class MyClass def hash return [self.B1, self.B2].sort.hash end end If they aren't currently sortable and it makes no sense to sort them by any inherent value, you could always just sort by object_id: class BClass include Comparable def <=> (other) case other when BClass then return (self.object_id <=> other.object_id) else return nil end end end This enables your B1 and B2 objects to sort themselves versus each other, while throwing "ArgumentError: comparison of X with Y failed" versus instances of any other class. If you're going the route of using object_id, though, it may just be easier to implement your hash method using that to begin with: class MyClass def hash return [self.B1.object_id, self.B2.object_id].sort.hash end end but this will mean only self-same objects will correctly turn up as equal, and not just objects that "look" alike. To understand what I mean, compare the following: # Comparison of look-alike objects "a".object_id == "a".object_id # => false # Comparison of self-same objects a = "a" a.object_id == a.object_id # => true A: I assume the hash value can be any object as long as it is unique in each object in your case. If that assumption is correct, how about defining the object hash() method returns as an array, for example? I am not 100% clear what you are trying to achieve. But I have interpreted the order of self.B1 and self.B2 does not matter. Then this is a possibility: def hash [self.B1.hash, self.B2.hash].sort end Then you can compare hash() of two objects with (my_obj1.hash == my_obj2.hash)
{ "language": "en", "url": "https://stackoverflow.com/questions/26694760", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How would it be possible that adaptive cards in Microsoft Teams for Android never be cropped (using c#)? In Microsoft Teams for Windows the Adaptive Cards look like this: And in Microsoft Teams for Android the same Adaptive Cards look this way: I'm using LG-files (Microsoft Language Generation files) and Microsoft.Bot.Builder.Dialogs. Is there a solution to prevent that adaptive cards were being cropped in Microsoft Teams for Android? Here is the code of the first part: { "type": "AdaptiveCard", "body": [ { "type": "ColumnSet", "columns": [ { "type": "Column", "width": "auto", "items": [ { "type": "ActionSet", "actions": [ { "type": "Action.Submit", "title": "Ja, einverstanden.", "data": { "msteams": { "type": "messageBack", "text": "Ja, einverstanden.", "displayText": "Ja, einverstanden." } } } ] } ] }, { "type": "Column", "width": "auto", "items": [ { "type": "ActionSet", "actions": [ { "type": "Action.Submit", "title": "Nein", "data": { "msteams": { "type": "messageBack", "text": "Nein", "displayText": "Nein" } } } ] } ] }, { "type": "Column", "width": "auto", "items": [ { "type": "ActionSet", "actions": [ { "type": "Action.Submit", "title": "Weitere Infos", "data": { "msteams": { "type": "messageBack", "text": "Weitere Infos", "displayText": "Weitere Infos" } } } ] } ] } ] } ], "$schema": "http://adaptivecards.io/schemas/adaptive-card.json", "version": "1.0" } Thank you Tim Cadenbach. Your example looks like this on Android: This means that only the first button was displayed and it was cropped. On Windows, it Looks like this: The first and second buttons have been cropped. All buttons are located one above the other and not side by side. I considered adding a case distinction and programming other adaptive cards for mobile devices. How can I find out what device it is? With channels from Microsoft.Bot.Connector I can find out that the channel is MS Teams. But how the device? A: This is the default behaviour of Mobile adaptive card actions. Adaptive card renders the buttons according to the width of the screens and provides you a scroll bar below to scroll through the buttons. A: Updated Answer: This is a known issue in the MS Teams Mobile App already raised with the team here: https://github.com/microsoft/AdaptiveCards/issues/3919 Someone is working on it and it should be solved in the next month.
{ "language": "en", "url": "https://stackoverflow.com/questions/62470617", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: flask-sqlalchemy - change lazy in different situations Take the example in document class User(db.Model): id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(50), nullable=False) addresses = db.relationship('Address', lazy='dynamic', backref=db.backref('person', lazy='select')) We can only set the lazy parameter to relationship when we build the models. But I found no document show how to change it after instantiated it. In most of my situation like user = User.query.first() addresses = user.addresses.filter(is_del=0).all() which is One-to-Many or wallet = user.wallet which is One-to-One Model, I just set the lazy to dynamic or select to let the model only get data what I need. However recently I want to export the data in database using Admin Front-end page. user_list = UserModel.query.all() for x in user_list: item = { "ID": x.id if x.id else '' } if 'basic' in fields or is_all_field == 1: ex_item = { "Email": x.base.account, "Full Name": x.base.full_name, "Display Name": x.display_name if x.display_name else '', "Phone Number": x.base.phone_number if x.base.phone_number else '', "Status": status_map(x.is_sharer,x.is_block,x.status_id) "Register Time": x.create_date.strftime('%Y-%m-%d %H:%M:%S') if x.create_date else '' } item = {**item, **ex_item} if ...... ........ If I continue to use select and dynamic as lazy. It will be very very slow cause every loop the parent query will access database every time when it use subquery. I test the speed between select and joined using single field like "Full Name": x.base.full_name to export all user data. Select got 53s and joined got 0.02s. Is there a way to change the lazy parameter based on not changing the original Model? A: According to the documentation you can use options to define the type of loading you want. I believe it will override your default value defined in your relationship Useful links Joined Loads Select Loads Lazy Load A: So, basically, if you are using lazy=' select', lazy load, and want to switch to joinedload to optimize your query, use the following: from sqlalchemy.orm import joinedload # import the joinedload user_list = db.session.query(UserModel).options(joinedload("person")) # running a joinedload which will give you access to all attributes in parent and child class for x in user_list: # now use x.account directly
{ "language": "en", "url": "https://stackoverflow.com/questions/52249870", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: "binding" between factory and controller I'm trying to return a scope for binding from a factory to a controller. it would be ideal if i could pass the name so it could be dynamic. Here's what I have so far .factory('urlWatch', function (urlFactory) { var _this = this; return { listenToUrl: function (scope, moduleName, stateName) { scope.$on('$locationChangeSuccess', function (event) { console.log(scope.bind); scope = urlFactory.parseState(moduleName, stateName); }); } }; return _this; }); and in the controller I have $scope.mod1m3 = urlWatch.listenToUrl($scope, "module1", "mod1"); So this does not work but if I change the factory to look like this listenToUrl: function (scope, moduleName, stateName) { scope.$on('$locationChangeSuccess', function (event) { console.log(scope.bind); scope.mod1m3 = urlFactory.parseState(moduleName, stateName); }); } What i was trying to do is change it to listenToUrl: function (scope, moduleName, stateName, bind) { scope.$on('$locationChangeSuccess', function (event) { scope.bind = urlFactory.parseState(moduleName, stateName); }); } and $scope.mod1m3 = urlWatch.listenToUrl($scope, "module1", "mod1", "mod1m3"); however it doesn't seem to want to connect the 2, I'm getting : TypeError: Cannot read property '$on' of undefined Unsure how i can get it to connect to get it to work as intended. Thanks! A: As the $scope attributre should be dynamic and saved in variable bind use: listenToUrl: function (scope, moduleName, stateName, bind) { scope.$on('$locationChangeSuccess', function (event) { // use scope like an associative array scope[bind] = urlFactory.parseState(moduleName, stateName); }); } In the controller it is sufficient, if you use. urlWatch.listenToUrl($scope, "module1", "mod1", "mod1m3"); $scope.mod1m3 will then be whatever parseState returns
{ "language": "en", "url": "https://stackoverflow.com/questions/28954163", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to hide and show an object on scene in three.js I have an object which is composed of spheres on my scene. And I have a hide and show button. The flow of my program is like that. For example, when I select one of the spheres (I used raycasting for select a sphere) then click the hide button, this sphere will be hidden. And after then click the show button it will be shown. But I don't know how can I do it. I used three.js for creating my scene. And I don't find any example for my question. How can I do it? Thanks for your help. A: Try this: object.visible = false; //Invisible object.visible = true; //Visible A: simply use the object traverse method to hide the mesh in three.js. In my code hide the object based on its name object.traverse ( function (child) { if (child instanceof THREE.Mesh) { child.visible = true; } }); Here is the working sample for Object show/hide option http://jsfiddle.net/ddbTy/287/ I think it should be helpful,..
{ "language": "en", "url": "https://stackoverflow.com/questions/42609602", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "8" }
Q: Ms dynamics crm 2013 subgrid overlap with its add button In Ms dynamics crm 2013 when we hide and show a subgrid using JavaScript visible function then subgrid's add button overlap with subgrid. Is there any way to resolve this issue. A: You want to find the schema name of the sub grid. You can do this by opening the form editor and then double clicking on the specific sub-grid. To hide the sub-grid, you want to make sure to use supported JavaScript. To hide: Xrm.Page.ui.controls.get('ProjectRisks').setVisible(false); To show: Xrm.Page.ui.controls.get('ProjectRisks').setVisible(false); When testing, these worked fine for me.
{ "language": "en", "url": "https://stackoverflow.com/questions/21714002", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: What are these GCC/G++ parameters? I've been using the UVa Online Judge to solve some programming challenges, and, when submitting my solutions, I'm told the judge will compile my code using the following parameters to GCC/G++ that I don't know: -lm -lcrypt -pipe -DONLINE_JUDGE. What do they do? Thank you very much in advance! A: "-lm -lcrypt" specifies to link with the math and cryptography libraries - useful if you're going to use the functions defined in math.h and crypt.h. "-pipe" just means it won't create intermediate files but will use pipes instead. "-DONLINE_JUDGE" defines a macro called "ONLINE_JUDGE", just as if you'd put a "#define" in your code. I guess that's so you can put something specific to the judging in your code in an "#ifdef"/"#endif" block.
{ "language": "en", "url": "https://stackoverflow.com/questions/1512476", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "12" }
Q: What is the default working directory for a jar launched from Windows Explorer? I have created a jar file of my application so that users can run it from Windows Explorer. It loads a JSON file in its own working directory for some settings (using the path ".\config.json"). However, when I run it from the jar file from Windows Explorer, it cannot find the config file, while running the same jar from the command line works. I'm assuming this is because explorer sets the working directory to something other than the jar's folder. What does it set it to? (And how can I find the jar's own folder?) A: Why not try printing out System.getProperty("user.dir"); and finding out what the application thinks? user.dir User's current working directory use the following to get the PARENT of where you .jar is loading from, which is what it sounds like you want import java.io.*; public class Main { public static void main(final String[] args) throws IOException { final File file = new File("."); System.out.println("file = " + file.getAbsoluteFile().getParent()); } } The output when I run it from the command line or double clicking from Windows Explorer is: file = c:\Users\Jarrod Roberson\Projects\SwingJarFinder A: Looks like a duplicate of: How to get the path of a running JAR file? If your jar file is in your file system start here to get the current path: ClassLoader.getSystemClassLoader().getResource(".").getPath();
{ "language": "en", "url": "https://stackoverflow.com/questions/8188408", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Extjs Set dirty false for form after saving I need to reset the form's dirty status to false after saving the form. Form is configured for trackresetonload so that not set dirty for setvalue function. I tried calling reset() but it resets the data in the form fields to its previous state(ie initial value). Is there a way to do this, Thanks. A: formpanel.setValues(formpanel.getValues()); Aafter you call this, the form has not longer the dirty status
{ "language": "en", "url": "https://stackoverflow.com/questions/24931119", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: TypeScript: add more data to enum In TypeScript, is it possible to add more stuff (properties, methods, etc.) to enum constants, like in Java? Java example demonstrating adding of fields, methods and constructor: public enum Planet { MERCURY (3.303e+23, 2.4397e6), VENUS (4.869e+24, 6.0518e6), EARTH (5.976e+24, 6.37814e6), MARS (6.421e+23, 3.3972e6), JUPITER (1.9e+27, 7.1492e7), SATURN (5.688e+26, 6.0268e7), URANUS (8.686e+25, 2.5559e7), NEPTUNE (1.024e+26, 2.4746e7); private final double mass; // in kilograms private final double radius; // in meters Planet(double mass, double radius) { this.mass = mass; this.radius = radius; } private double mass() { return mass; } private double radius() { return radius; } // universal gravitational constant (m3 kg-1 s-2) public static final double G = 6.67300E-11; double surfaceGravity() { return G * mass / (radius * radius); } double surfaceWeight(double otherMass) { return otherMass * surfaceGravity(); } // ... } A: Not using an enum, but you can get the same exact thing using a class and a few static members: class Planet { public static MERCURY = new Planet(3.303e+23, 2.4397e6); public static VENUS = new Planet(4.869e+24, 6.0518e6); public static EARTH = new Planet(5.976e+24, 6.37814e6); public static MARS = new Planet(6.421e+23, 3.3972e6); public static JUPITER = new Planet(1.9e+27, 7.1492e7); public static SATURN = new Planet(5.688e+26, 6.0268e7); public static URANUS = new Planet(8.686e+25, 2.5559e7); public static NEPTUNE = new Planet(1.024e+26, 2.4746e7); private mass: number; private radius: number; private constructor(mass: number, radius: number) { this.mass = mass; this.radius = radius; } public static G = 6.67300E-11; public surfaceGravity(): number { return Planet.G * this.mass / (this.radius * this.radius); } public surfaceWeight(otherMass: number) { return otherMass * this.surfaceGravity(); } } console.log(Planet.MERCURY.surfaceGravity()); (code in playground) In java for each item in the enum a static instance is created, which means that this indeed does the same thing, it's just that java has a nicer syntax for defining enums. Edit Here's a version with the equivalent Planet.values() which java will generate: class Planet { public static MERCURY = new Planet(3.303e+23, 2.4397e6); public static VENUS = new Planet(4.869e+24, 6.0518e6); ... private static VALUES: Planet[] = []; private mass: number; private radius: number; private constructor(mass: number, radius: number) { this.mass = mass; this.radius = radius; Planet.VALUES.push(this); } public static values() { return Planet.VALUES; } ... } 2nd edit Here's a way to implement the valueOf: public static valueOf(name: string): Planet | null { const names = Object.keys(this); for (let i = 0; i < names.length; i++) { if (this[names[i]] instanceof Planet && name.toLowerCase() === names[i].toLowerCase()) { return this[names[i]]; } } return null; } A: Unfortunately it's not possible. You can just assign property names See this reference for the TypeScript spec https://github.com/microsoft/TypeScript/blob/30cb20434a6b117e007a4959b2a7c16489f86069/doc/spec-ARCHIVED.md#a7-enums A: You can get the 'same thing' using a const. Obviously this solution isn't exactly like enumerations, it's just a different use of the keys of a const object instead of an actual enumeration value. export const OrderStateEnum = { WAITING_SCORING: { key: 1, value: "WAITING for SCORING" }, WAITING_ACCEPTANCE: { key: 2, value: "Waiting for acceptance" }, ORDER_ACCEPTED: { key: 3, value: "Order accepted" }, } as const export type OrderStateEnum = keyof typeof OrderStateEnum export function valueOf(value: string): OrderStateEnum{ for(var key in OrderStateEnum) { if(value.toLowerCase()=== OrderStateEnum[key].value.toLowerCase()){ return OrderStateEnum[key]; } } } To receive all the values of the false enum: states = OrderStateEnum; To receive a certain value of the false enum: OrderStateEnum.WAITING_SCORING.value; Below is a usage via *ngFor <select formControlName="statoOrdine" [(ngModel)]="stato"> <option *ngFor="let item of states | keyvalue" [value]="item.value.key"> {{item.value.value}}</option> </select>
{ "language": "en", "url": "https://stackoverflow.com/questions/43376040", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: Many-to-many relationship using @EmbeddedId produces null id generated for:class I have two tables that have a many to many relationship between them: * *Table one: Competition *Relationship table: Entry *Table two: User The entry table is using an @EmbeddedId: @Getter @Setter @AllArgsConstructor @NoArgsConstructor public class Entry { @EmbeddedId EntryKey id; @ManyToOne @MapsId("competition_id") @JoinColumn(name = "competition_id") private Competition competition; @ManyToOne @MapsId("user_id") @JoinColumn(name = "user_id") private User user; private Integer number; } where EntryKey is implemented as: @EqualsAndHashCode @Getter @Setter @AllArgsConstructor @NoArgsConstructor public class EntryKey implements Serializable { @Column(name = "competition_id") Integer competitionId; @Column(name = "user_id") Integer userId; } The Competition and User entities also contain the inverse references: Competition @OneToMany(mappedBy = "competition") private Set<Entry> entries; User @OneToMany(mappedBy = "user") private Set<Entry> entries; The issue is when executing the following post request (maybe this is wrong?): { "user_id": 1, "competition_id": 2, "number": 1 } ...which is being picked up in this controller: @PostMapping public Entry create(@RequestBody Entry entry) { return entryRepo.save(entry); } A IdentifierGenerationException is thrown: org.hibernate.id.IdentifierGenerationException: null id generated for:class com.mw.API.Entities.Entry. I'm not sure where I'm going wrong here. There is a very similar question here however none of the answers seemed to help. A: It seems that the EntryKey is not getting bound by the request.Sending this { "competition":{ "competitionId":6 }, "user":{ "userId":5 }, "number": 1 } instead of this { "user_id": 1, "competition_id": 2, "number": 1 } Should bind the values properly.
{ "language": "en", "url": "https://stackoverflow.com/questions/59592921", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mysql order by field with given values which has NULL in between I'm trying to sort a query by given values like this: ORDER BY FIELD(items.stock_id, 1, 5, NULL, 3, 6) But it seems it doesn't work and null comes first or last depending on it being descending or not. The order is not always the same hence [1,5,NULL,3,6] changes every time and is dynamic. A: FIELD-function does not match the NULL-stock_id as NULL value (NULL does not have any value). You could use a magic number: ORDER BY FIELD(IFNULL(items.stock_id,-1), 1, 5, -1, 3, 6)
{ "language": "en", "url": "https://stackoverflow.com/questions/67806575", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: ksh: How to pass arguments containing white space between scripts? I have two scripts (one ksh and other Perl) and one calls the other. I have to handle a scenario when someone accidentally enters a white space in file name and report it as an error (only when the file does not exist). It looks like p.sh which uses $* to pass/forward all arguments to p.pl doesn't handle quoted arguments the way they should be? Any ideas how to fix this? Let's just say one could enter multiple spaces in the filename too. p.sh: #!/usr/bin/env ksh /tmp/p.pl $* 1>/tmp/chk.out 2>&1 print "Script exited with value $?" print "P.PL OUTPUT:" cat /tmp/chk.out exit 0 p.pl: #!/usr/bin/perl -w use Getopt::Std; getopts ("i:", \ %options); if ($options{i} && -e $options{i}) { print "File $options{i} Exists!\n"; } else { print "File $options{i} DOES NOT exist!\n"; } Test cases (when there is an actual file '/tmp/a b.txt' (with a space in it) on the system): [test] /tmp $ p.pl -i /tmp/a b.txt File /tmp/a DOES NOT exist! [test] /tmp $ p.pl -i "/tmp/a b.txt" File /tmp/a b.txt Exists! [test] /tmp $ ./p.sh -i "/tmp/a b.txt" Script exited with value 0 P.PL Check OUTPUT: File /tmp/a DOES NOT exist! [test] /tmp $ ./p.sh -i "/tmp/ a b.txt" Script exited with value 0 P.PL Check OUTPUT: File /tmp/ Exists! It's the last two scenarios I'm trying to fix. Thank you. A: To preserve whitespace that was passed into the script, use the $@ parameter: /tmp/p.pl "$@" 1>/tmp/chk.out 2>&1 The quotation marks are necessary to make sure that quoted whitespace is seen by p.pl.
{ "language": "en", "url": "https://stackoverflow.com/questions/15233177", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: cannot find protocol declaration custom protocol delegate iphone Slowly but surely getting this delegation and protocol stuff on iphone but I cannot understand this error. I have declared my protocol in my first viewcontroller. In the second viewcontroller i try to add it at the top after i have imported it into the header file and it cannot find it. see my code below. //SendSMS #import <UIKit/UIKit.h> #import "LoginPage.h" #import "MessageOptions.h" @protocol SMSProtocol <NSObject> -(NSString *)postbackType; @end @interface SendSMS : UIViewController <UITextViewDelegate, UITextFieldDelegate> { id<SMSProtocol> delegate; MessageOptions *messageOptions; LoginPage *loginPage; IBOutlet UITextField *phonenumber; IBOutlet UITextView *smsBody; IBOutlet UIScrollView *scrollview; } @property (nonatomic, retain) id<SMSProtocol> delegate; -(IBAction)LoadMessageOptions; @end Then my second view #import <UIKit/UIKit.h> #import "SendSMS.h" @interface ScheduledSMS : UIViewController <SMSProtocol>{ } -(IBAction)popBack; @end A: That is surely strange. Have you tried restarting Xcode? Xcode has a habit of not indexing symbols for me when I add new files. You should also look into how your naming conventions. SendSMS is not really a good class name, more of a action method name. I would go for SendSMSViewController, since that is what it is. By that it would follow that SMSProtocol should be named SendSMSViewControllerDelegate, since that is what it is. Methods in a delegate protocol should contain the sender and one of the three words will, did, or should. If not at the very least it should name what it expects to return. -(NSString *)postbackType; should probably be -(NSString *)postbackTypeForSendSMSViewController:(SendSMSViewController*)controller;.
{ "language": "en", "url": "https://stackoverflow.com/questions/6954895", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Powershell command SCCM 2012 - Get all Resource Names from device collection? I'm still learning about PowerShell and SCCM. At the moment i'm trying to get all resource names of a device collection into an array variable. I don't know if this is possible? Example: Computers: Win7, Win8, CM02,.... into a variable like: $computers = COMPUTERNAMEWIN7.local.domain.lo, COMPUTERNAMEWIN8.local.domain.lo, COMPUTERNAMECM02.local.domain.lo This is what i'm trying to achieve: I'm trying to deploy LibreOffice to all computers i have under my control in SCCM 2012. So i have a Device Collection: "All Systems" with all these computers in it. and then use aForeach-Object command to copy and install the .Msi file of LibreOffice. Is there a PowerShell command to get these into an array like the example, when specifying the device collection name ? thank you :)
{ "language": "en", "url": "https://stackoverflow.com/questions/47911918", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Calling JS function from external file give error in yii2 I'm trying to call a JS function in a yii2 project but got function not define, the JS function is inside a file named main.js which is included to the layout of the homepage, and in site/index in have another internal JS code that calls the function in main.js file. if i put this function in site/index everything works fine as expected but if i separate it to call it from outside it says function not define. My action page site/index: <?php $getcatUrl = Yii::$app->UrlManager->createUrl(['site/getcategories']); $script = <<< JS $(document).ready(function(){ $(".sideBarNav").mouseenter(function(){ id = $(this).attr('href'); getCategories(id); $('.cat-container').css('display', 'block'); }); }); JS; $this->registerJs($script); ?> Now in my main JS file i have the following: function getCategories(id){ $.ajax({ url: '{$getcatUrl}', type: 'POST', data: {category_id: id}, success: function (data) { data = jQuery.parseJSON(data); //console.log(data); return; if (data.length > 0) { $("#dl-cat").html(""); var content = $("#dl-cat"); firstdata = data[0]; secdata = data[1]; for (var i = 0; i < firstdata.length; i++) { // var d = $( document.createElement('dl') ); var dl = $("<dl></dl>"); dl.append("<a href='"+firstdata[i].id+"'><dt>"+firstdata[i].name+"</dt></a>"); for (var j = 0; j < secdata.length; j++) { if (secdata[i][j] !== undefined) { dl.append("<dd><a href = '"+secdata[i][j].id+"'>"+secdata[i][j].name+"</a></dd>"); } } content.append(dl); } } else { console.log('no item for this categories'); } }, error: function(jqXHR, errMsg) { // handle error console.log(errMsg); } }); } Note other codes from the JS file works expect from functions that needed to be called from external source This how do i solve this problem any help will be appreciated thanks A: I bet, the script is before the jquery all, so the function "disappears". Try placing the script in a external file and making sure that try «I hope it helps» $this->registerJsFile( '@web/js/your_file.js', ['depends' => [\yii\web\JqueryAsset::class]] ); If it's not exactly this, but probably the function is being placed after the call, so it will be undefined, so try to be sure that the function gets rendered before the call.
{ "language": "en", "url": "https://stackoverflow.com/questions/50966013", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to use CircleImageView with Volley's NetworkImageView? I need to get circle images from rectangular/square images taken from network. In my application I get images with Volley's NetworkImageView. I found that fantastic library https://github.com/hdodenhof/CircleImageView but I don't understand how I can use it with NetworkImageView. Can someone help me? A: Check this Class public class CirculaireNetworkImageView extends NetworkImageView { private int borderWidth; private int canvasSize; private Bitmap image; private Paint paint; private Paint paintBorder; public CirculaireNetworkImageView(final Context context) { this(context, null); } public CirculaireNetworkImageView(Context context, AttributeSet attrs) { this(context, attrs, R.attr.actionButtonStyle); } public CirculaireNetworkImageView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); paint = new Paint(); paint.setAntiAlias(true); paintBorder = new Paint(); paintBorder.setAntiAlias(true); } public void setBorderWidth(int borderWidth) { this.borderWidth = borderWidth; this.requestLayout(); this.invalidate(); } public void setBorderColor(int borderColor) { if (paintBorder != null) paintBorder.setColor(borderColor); this.invalidate(); } public void addShadow() { setLayerType(LAYER_TYPE_SOFTWARE, paintBorder); paintBorder.setShadowLayer(4.0f, 0.0f, 2.0f, Color.BLACK); } @SuppressLint("DrawAllocation") @Override public void onDraw(Canvas canvas) { // load the bitmap image = drawableToBitmap(getDrawable()); // init shader if (image != null) { canvasSize = canvas.getWidth(); if(canvas.getHeight()<canvasSize) canvasSize = canvas.getHeight(); BitmapShader shader = new BitmapShader(Bitmap.createScaledBitmap(image, canvasSize, canvasSize, false), Shader.TileMode.CLAMP, Shader.TileMode.CLAMP); paint.setShader(shader); // circleCenter is the x or y of the view's center // radius is the radius in pixels of the cirle to be drawn // paint contains the shader that will texture the shape int circleCenter = (canvasSize - (borderWidth * 2)) / 2; canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, ((canvasSize - (borderWidth * 2)) / 2) + borderWidth - 4.0f, paintBorder); canvas.drawCircle(circleCenter + borderWidth, circleCenter + borderWidth, ((canvasSize - (borderWidth * 2)) / 2) - 4.0f, paint); } } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { int width = measureWidth(widthMeasureSpec); int height = measureHeight(heightMeasureSpec); setMeasuredDimension(width, height); } private int measureWidth(int measureSpec) { int result = 0; int specMode = MeasureSpec.getMode(measureSpec); int specSize = MeasureSpec.getSize(measureSpec); if (specMode == MeasureSpec.EXACTLY) { // The parent has determined an exact size for the child. result = specSize; } else if (specMode == MeasureSpec.AT_MOST) { // The child can be as large as it wants up to the specified size. result = specSize; } else { // The parent has not imposed any constraint on the child. result = canvasSize; } return result; } private int measureHeight(int measureSpecHeight) { int result = 0; int specMode = MeasureSpec.getMode(measureSpecHeight); int specSize = MeasureSpec.getSize(measureSpecHeight); if (specMode == MeasureSpec.EXACTLY) { // We were told how big to be result = specSize; } else if (specMode == MeasureSpec.AT_MOST) { // The child can be as large as it wants up to the specified size. result = specSize; } else { // Measure the text (beware: ascent is a negative number) result = canvasSize; } return (result + 2); } public Bitmap drawableToBitmap(Drawable drawable) { if (drawable == null) { return null; } else if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; } } A: Check the source code of the NetworkImageView here. Modify it to extend your "CircleImageView" instead of the normal ImageView and you are done.
{ "language": "en", "url": "https://stackoverflow.com/questions/30571034", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: how to jump from the if state without executing else.? for(....) if(condition) printf(_); else printf(); what code will come here.... A: If I understand you correctly, you want to jump out of the if and the enclosing for loop when condition is true. You can achieve this using break: for(....) { if(condition) { printf(_); break; } else printf(); } Note: I added proper indentation and angle brackets to make the code cleaner. Update after OP's comment int isPrime = 0; for (i = 0; i < 10 && !isPrime; i++) { isPrime = (16 / i == i); } if (isPrime) printf("its a prime no"); else printf("not a prime no."); Disclaimer: th condition above is hardly the proper way to detect whether a given number is prime, but still this code snippet illustrates the general idiom of saving the result of an expression from a loop and inspecting it later. A: The else code is never executed if condition is true: if (condition) // If this condition evaluates to true { printf("Hello"); // Then this code is executed } else { printf("World"); // If it is false then this code is executed. } Edit: Wrapping it in a for loop makes no difference (unless you mean want to actually exit the for loop as well?)
{ "language": "en", "url": "https://stackoverflow.com/questions/4990884", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Odd Chap Timeline Date Issue - Items Rendered in the Future on All Browsers Apart from FireFox I've got an odd situation going on here. I've got the following JSON being passed to the time line control: [ { "UserId": 2, "ItemId": 3, "ItemText": null, "ItemDate": "2014-06-09T18:51:37", "ItemDateEnd": null, "OutcomeScore": null }, ... ] This is a simple of array of items that I pass to the control to render. In Firefox this renders perfectly, no problems whatsoever. However, Every other browser I've tried it on shows the items +1 hour. I've tried it in Opera, Chrome and IE9 and they are all showing the same problem apart from Firefox. The now time displays as expected on all browsers. Interestingly I'm in GMT summer time at the moment which is +1h ... but why would this selectively effect browsers differently? Each browser is running exactly the same query and getting exactly the same JSON. I'm very confused and not even sure where to start looking. I'm running v2.5.0 of the time line. I've tried updating to the latest version and the same thing occured so I rolled back to 2.5.0 to get the solved before working on getting the latest version integrated into the page. Anyone seen this and have a solution? A: Creating Date objects from strings is unreliable, as you have observed. You should manually parse those strings into Date objects, like this: // assumes date string is in the format "yyyy-MM-ddTHH:mm:ss" var dateMatch = dataItem.ItemDate.match(/(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})/); var year = parseInt(dateMatch[1], 10); var month = parseInt(dateMatch[2], 10) - 1; // convert to javascript's 0-indexed months var day = parseInt(dateMatch[3], 10); var hours = parseInt(dateMatch[4], 10); var minutes = parseInt(dateMatch[5], 10); var seconds = parseInt(dateMatch[6], 10); var date = new Date(year, month, day, hours, minutes, seconds); A: First, note that the Timeline of the CHAP Links library does not support strings as Date, you should provided Dates or a timestamp with a Number (note that the successor of the Timeline, vis.js, does support strings as date). Strings as Date work nowadays because most browsers now support creating dates from an ISO date string. The issue you have is because you provide an ISO Date String without time zone information. Apparently not all browsers have the same default behavior in that case. Enter the following in a JavaScript console in both Firefox and an other browser: new Date("2014-06-09T18:51:37").toISOString() // output is ambiguous, time zone information missing and you will see them adding timezone information in different ways. To prevent these kind of ambiguities, you should provide timezone information yourself. To specify the time in UTC, add a Z to the end of the string: new Date("2014-06-09T18:51:37Z").toISOString() // output is unambiguous
{ "language": "en", "url": "https://stackoverflow.com/questions/24126987", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MYSQL Duplicate Data and Show Only One Data I have data like this emp_id| name | log | 16646 | bella | 2023-01-30 07:28:54 | 9050 | mark | 2023-01-30 07:22:12 | 8612 | nandya | 2023-01-30 07:20:35 | 7965 | arya | 2023-01-30 06:21:39 | 7965 | arya | 2023-01-30 06:21:40 | My query SELECT h.emp_id, p.name, h.log FROM presence.history h JOIN employee p on p.emp_id = h.emp_id and h.log >= '2023-01-30 05:00:00' and h.log <= '2023-01-30 07:45:00' I want the duplicate data only show one data and for the 'log' field show the early data. the result I expected emp_id| name | log | 16646 | bella | 2023-01-30 07:28:54 | 9050 | mark | 2023-01-30 07:22:12 | 8612 | nandya | 2023-01-30 07:20:35 | 7965 | arya | 2023-01-30 06:21:39 | A: SELECT emp_id, name, MIN(log) as log FROM table_name GROUP BY emp_id, name;
{ "language": "en", "url": "https://stackoverflow.com/questions/75280010", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Mixin won't accept @content block with libsass The error I get: DEPRECATION WARNING: Passing white, a non-string value, to unquote() will be an error in future versions of Sass. on line 56 of src/scss/_library.scss events.js:85 throw er; // Unhandled 'error' event ^ Error: src\scss\_library.scss Error: Mixin "media" does not accept a content block. Backtrace: src/scss/_library.scss:27, in mixin `media-above` src/scss/_layout.scss:16 on line 27 of src/scss/_library.scss >> @include media($min-query, null) { @content; -----------^ This is on windows 10 with all other gulpfile configs/tools working fine. I've tried npm update, npm rebuild node-sass, npm reinstall to cheack this. The mixin is loaded before the component styles. It works fine with ruby-sass, this error appears when I'm using the libsass complier. Any ideas on why the content block cant be accpeted in the mixin?
{ "language": "en", "url": "https://stackoverflow.com/questions/33669953", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Flash movie not visible in ie 6 I have a flash movie and I use this code to embed it crossbrowser '<object id="adFoxMovie" classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=9,0,0,0" width="100%" height="100%" align="left"> <param name="bgcolor" value="#faa"> <param name="allowScriptAccess" value="always" /> <param name="allowFullScreen" value="false" /> <param name="movie" value="'+this.mainSwfUrl+'" /> <param name="flashvars" value="'+this.flashParameters+'&'+this.events+'" /> <param name="quality" value="high" /> <param name="wmode" value="transparent" /> <embed name="adFoxMovie" src="'+this.mainSwfUrl+'" quality="high" width="100%" height="100%" align="left" allowScriptAccess="always" allowFullScreen="false" bgcolor="#cccccc" wmode="transparent" flashvars="'+this.flashParameters+'&'+this.events+'" type="application/x-shockwave-flash" pluginspage="http://www.macromedia.com/go/getflashplayer" /> </object>' And I use this string as innerHTML for a div present on the page. Now in all browsers except IE 6 this works fine. The curious thing is that I have two movies and one works in this embed and the other doesn't. I can't seem to find any apparent difference. Of course the two movies have slightly different flashvars passed. Now I've tried taking the movie link and just opening it in the browser window. The movie seems to work on its own. PS. Can't use SWF object A: Resolution: It seems that this embed way had nothing to do with the problem. Comment: This question didn't get an answer for a quite a long time. Anyway I hope IE6 mixed with flash is not a problem nowadays.
{ "language": "en", "url": "https://stackoverflow.com/questions/9362428", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Unique constraint violation on insertion after server restart I am running a JBoss EAP 7 server with an Oracle 11g DB, and Hibernate for JPA. I have noticed something weird. When I first create the database and start the server, everything works fine. I send requests from the client and the server persists the data in the DB. If I restart the server and try to do the same, I get a unique constraint violation exception for every request: java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint (SCHEMA.SYS_C0010299) violated at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:447) at oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:396) at oracle.jdbc.driver.T4C8Oall.processError(T4C8Oall.java:951) at oracle.jdbc.driver.T4CTTIfun.receive(T4CTTIfun.java:513) at oracle.jdbc.driver.T4CTTIfun.doRPC(T4CTTIfun.java:227) at oracle.jdbc.driver.T4C8Oall.doOALL(T4C8Oall.java:531) at oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:208) at oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:1046) at oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1336) at oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3613) at oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3694) at oracle.jdbc.driver.OraclePreparedStatementWrapper.executeUpdate(OraclePreparedStatementWrapper.java:1354) at org.jboss.jca.adapters.jdbc.WrappedPreparedStatement.executeUpdate(WrappedPreparedStatement.java:537) at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:204) I checked the constraint in sqlplus with the query below. (I ran the query as the system user, not the same user as the server, if that matters). SELECT A.TABLE_NAME,C.TABLE_NAME,COLUMN_NAME FROM ALL_CONS_COLUMNS A JOIN ALL_CONSTRAINTS C ON A.CONSTRAINT_NAME = C.CONSTRAINT_NAME WHERE C.CONSTRAINT_NAME = 'SYS_C0010299'; It seems to happen on the primary key of one of my tables. That primary key is generated with a sequence. @Id @Column(name="ID_COL") @GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "SEQ_NAME_GEN") @SequenceGenerator(name = "SEQ_NAME_GEN", sequenceName = "SEQ_NAME") private Long id; If I create a fresh new DB, the application again works fine at first, until I restart the server. Why does this happen? This is the relation of the entity class to another entity class: // other class @OneToMany(cascade=CascadeType.ALL, mappedBy="otherClass") @MapKey(name = "mapKey") private Map<MapKey, ConstraintViolationEntityClass> map; // problematic class (ConstraintViolationEntityClass) @Column(name = "MAP_KEY") @Enumerated(EnumType.ORDINAL) private EnumType enumType; @ManyToOne @JoinColumn(name = "OTHER_CLASS_ID", nullable = false) private OtherClass otherClass; And this is the SQL code I used to create the table for the ConstraintViolationEntityClass: create table schema.ConstraintViolationEntityTable ( id_col number(10) not null primary key, map_key number(2) not null, other_class_id number(10) not null, constraint other_class_fk foreign key (other_class_id) references schema.other_class(id) ); This is my persistence.xml: <persistence-unit name="unit1" transaction-type="JTA"> <jta-data-source>java:jboss/OracleDS</jta-data-source> <exclude-unlisted-classes>false</exclude-unlisted-classes> <properties> <property name="hibernate.transaction.jta.platform" value="org.hibernate.service.jta.platform.internal.JBossStandAloneJtaPlatform"/> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.format_sql" value="true" /> <property name="hibernate.hbm2ddl.auto" value="validate" /> </properties> </persistence-unit> For some reason, some of the primary keys of the rows inserted by the successful requests are negative. And checking dba_sequences, the last_number of the sequence is 43, even though the table only has 24 rows in it (12 rows added per client request) A: As stated in the answer that PeterM linked to, the default allocation size for sequence generators is 50, which is the root cause of the problem, since you defined the sequence with an increment of 1. I'll just comment on the negative values issue. An allocation size of 50 (set in SequenceGenerator.allocationSize) means that Hibernate will: * *create the sequence with INCREMENT BY 50 (if you let it) *grab the next value n from the sequence *start allocating ids from n-50 till n *repeat the two steps above once it runs out of numbers Since you've made the sequence increment by 1, it's easy to see where the negative values come from (and why constraint violations will follow). If you tried inserting more than 50 rows, you'd run into constraint violations without having to restart the server.
{ "language": "en", "url": "https://stackoverflow.com/questions/49739772", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: Invalid byte sequence for encoding when reading NpgsqlDataReader I am counting all the rows from a data reader, for that I am doing this: connection = new NpgsqlConnection(CS); connection.Open(); command = new NpgsqlCommand(cmd, connection); dataReader = command.ExecuteReader(); while (dataReader.Read()) { res++; } Where CS is my connection string, with the format Server=server_here;Port=port_here;User Id=username_here;Password=password_here;Database=database_here;. After a certain number of records, I get an exception with the following message: ERROR: 22021: invalid byte sequence for encoding \"UTF8\": 0xbb I am using postgres 9.4, and the Npgsql version (downloaded from nuget) is 3.2.2. My database encoding is SQL_ASCII, is there any way for me to successfully read the full data reader without changing the data base encoding? A: By default, Npgsql will set the client encoding to UTF8, which means that it is PostgreSQL's responsibility to provide valid UTF8 data, performing server-side conversions in case the database isn't in UTF8. However, the SQL_ASCII is special, in that it means "we don't know anything about characters beyond 127" (see the PG docs). So PostgreSQL performs no conversions on those. If you know that your database is in some specific non-UTF8 encoding (say, ISO 8859-1), you can pass the Client Encoding parameter on the connection string with the name of a valid .NET encoding. This will make Npgsql correctly interpret characters beyond 127 coming from PostgreSQL. If you really don't know what encoding your database uses, well, there's nothing much you can do... For more info, see this issue. A: AFAIK is not possible to enable postgres's built-in conversion from SQL_ASCII. Probably you should do it manually, using a tool like iconv ou recode. If the client character set is defined as SQL_ASCII, encoding conversion is disabled, regardless of the server's character set. Just as for the server, use of SQL_ASCII is unwise unless you are working with all-ASCII data. Quote from PostgreSQL documentation.
{ "language": "en", "url": "https://stackoverflow.com/questions/43899024", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Get Microphone Input Level Naudio I've been looking for a simple way to determine the volume/level of sound being inputted into the microphone, as soon as the data is available. I've not been able to find a simple answer. Is there no simple way to do this, or am I just missing it? A: What I've been using for a peak meter (a progress bar) is the following, passing in the device from my IWaveIn.DataAvailable MMDevice.AudioMeterInformation.MasterPeakValue * 100
{ "language": "en", "url": "https://stackoverflow.com/questions/26834223", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "4" }
Q: How to get members of facebook group which are only my friends I need to fetch groups & friends from facebook. Also in group members I need only those who are my friends. This gives me list of friends FBRequestConnection startWithGraphPath:@"me/friends" parameters:nil HTTPMethod:@"GET" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) { } This gives me list of groups FBRequestConnection startWithGraphPath:@"me/groups" parameters:nil HTTPMethod:@"GET" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) { } This gives me list of group members FBRequestConnection startWithGraphPath:@"me/groups?fields=members" parameters:nil HTTPMethod:@"GET" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) { } Where I get number of members which I cant draw a for loop to find my friends. Any other way to achieve that? A: Edit 0 - FQL Solution SELECT uid,first_name,pic FROM user WHERE uid IN (SELECT uid2 FROM friend WHERE uid1 = me()) AND uid IN (SELECT uid FROM group_member WHERE gid=GROUP_ID) Wouldn't the below provide you with a list of members that you could loop through to find your friends? Applications can get the list of members that belong to a group by issuing a GET request to /GROUP_ID/members with an app access_token. If the action is successful, the response will contain: Name Description Type ID The id of the user. string Name The name of the user. string administrator The user is administrator of the group. boolean via https://developers.facebook.com/docs/reference/api/app-game-groups/#read_group_members
{ "language": "en", "url": "https://stackoverflow.com/questions/20344787", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How to use multiple postDelayed handlers Hi I am new to android delveloping and I am curently making a simple game that tests your reflection when a certain color changes, to test what I have learned so far but I cant solve a problem that came up. Alright, first I will explain how the game works: When you tap the screen there is a random delay and after that you need to tap the screen again as quick as possilbe to get the best score, and if you tap earlier than when the delay is over the game stops and tells you to try again. My problem is that when I tap for the second time no matter if that is after or erlier the delay it repeats a part of a code and I cant figure out why.I posted my code that is relevant to this below.Also if you need any decleration let me know! P.S I thing that it has somenthing to do with the handlers but i'm not sure. final Random random = new Random(); final int randomNumber = random.nextInt(10) + 1; bestScoreView.setText("best score " + bestTime + " ms"); mainThing.setText("Tap to start"); mainThing.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { randomTimeDelay = randomNumber * 1000; if (previousTapDetected){ mainThing.setText("You taped too fast"); mainThing.setBackgroundColor(ContextCompat .getColor(getApplicationContext(), R.color.red)); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { mainThing.setText("Try again"); } }, 750); }else if (previousTapDetected = true){ mainThing.setText("Wait for the color to change"); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { previousTapDetected=false; mainThing.setText("Tap now"); startTime = System.currentTimeMillis(); mainThing.setBackgroundColor(ContextCompat .getColor(getApplicationContext(), R.color.red)); Handler handler = new Handler(); handler.postDelayed(new Runnable() { @Override public void run() { mainThing.setText("You scored " + score + " ms"); mainThing.setEnabled(false); } }, 500); } }, randomTimeDelay); endTime = System.currentTimeMillis(); score = endTime - startTime; if (bestTime > score) { bestScoreView.setText("Best score: " + score + " ms"); bestTime = score; } else if (bestTime < score){ bestScoreView.setText("Best score " + bestTime + " ms"); } } } }); A: As per the docs When you create a new Handler, it is bound to the thread / message queue of the thread that is creating it -- from that point on, it will deliver messages and runnables to that message queue and execute them as they come out of the message queue. And, in your code, you are trying to manipulate the UI elements, so the Handler should be created on the UI Thread Handler handler = new Handler(); mainThing.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { randomTimeDelay = randomNumber * 1000; if (previousTapDetected){ mainThing.setText("You taped too fast"); mainThing.setBackgroundColor(ContextCompat .getColor(getApplicationContext(), R.color.red)); handler.postDelayed(new Runnable() { @Override public void run() { mainThing.setText("Try again"); } }, 750);
{ "language": "en", "url": "https://stackoverflow.com/questions/47242283", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-3" }
Q: Unable to instantiate Action, signupFormAction, defined for 'signupForm' in namespace '/'signupFormAction. ClassNotFoundException: signupFormAction Been trying to setup a Struts2 + Sprint + Hibernate basic framework and was working on creating a sample application. Everything configured and the stack doesnt through any error/exception while starting tomcat. Even when I run the action it doesnt throw any Exception, but on the browser it throws the following stack Unable to instantiate Action, signupFormAction, defined for 'signupForm' in namespace '/'signupFormAction com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:318) com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:399) com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:198) org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:61) org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39) com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:475) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) root cause java.lang.ClassNotFoundException: signupFormAction org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645) org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1491) com.opensymphony.xwork2.util.ClassLoaderUtil.loadClass(ClassLoaderUtil.java:157) com.opensymphony.xwork2.ObjectFactory.getClassInstance(ObjectFactory.java:107) com.opensymphony.xwork2.spring.SpringObjectFactory.getClassInstance(SpringObjectFactory.java:223) com.opensymphony.xwork2.spring.SpringObjectFactory.buildBean(SpringObjectFactory.java:143) com.opensymphony.xwork2.ObjectFactory.buildBean(ObjectFactory.java:150) com.opensymphony.xwork2.ObjectFactory.buildAction(ObjectFactory.java:120) com.opensymphony.xwork2.DefaultActionInvocation.createAction(DefaultActionInvocation.java:299) com.opensymphony.xwork2.DefaultActionInvocation.init(DefaultActionInvocation.java:399) com.opensymphony.xwork2.DefaultActionProxy.prepare(DefaultActionProxy.java:198) org.apache.struts2.impl.StrutsActionProxy.prepare(StrutsActionProxy.java:61) org.apache.struts2.impl.StrutsActionProxyFactory.createActionProxy(StrutsActionProxyFactory.java:39) com.opensymphony.xwork2.DefaultActionProxyFactory.createActionProxy(DefaultActionProxyFactory.java:58) org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:475) org.apache.struts2.dispatcher.ng.ExecuteOperations.executeAction(ExecuteOperations.java:77) org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:91) My struts.xml <struts> <!-- <constant name="struts.enable.DynamicMethodInvocation" value="false" />--> <constant name="struts.devMode" value="false" /> <constant name="struts.custom.i18n.resources" value="ApplicationResources" /> <package name="default" extends="struts-default" namespace="/"> <action name="login" class="loginAction"> <result name="success">welcome.jsp</result> <result name="error">login.jsp</result> </action> <action name="signup" class="registerAction" method="add"> <result name="success">welcome.jsp</result> <result name="error">login.jsp</result> </action> <action name="signupForm" class="signupFormAction"> <result name="input">registerForm.jsp</result> <result name="error">login.jsp</result> </action> </package> </struts> My SpringBeans.xml <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- Database Configuration --> <import resource="config/spring/DataSource.xml" /> <import resource="config/spring/HibernateSessionFactory.xml" /> <!-- Beans Declaration --> <import resource="com/srisris/khiraya/spring/register.xml" /> <import resource="com/srisris/khiraya/spring/login.xml" /> </beans> My register.xml <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!-- <bean id="ownerService" class="com.srisris.khiraya.service.OwnerServiceImpl">--> <!-- <property name="ownerDAO" ref="ownerDAO" />--> <!-- </bean>--> <bean id="signupForm" class="com.srisris.khiraya.action.RegisterAction"/> <!-- <bean id="registerAction" class="com.srisris.khiraya.action.RegisterAction">--> <!-- <property name="ownerService" ref="ownerService" /> --> <!-- </bean>--> <!-- <bean id="ownerDAO" class="com.srisris.khiraya.dao.OwnerDAOImpl" >--> <!-- <property name="sessionFactory" ref="sessionFactory" />--> <!-- </bean>--> </beans> My Action Class package com.srisris.khiraya.action; import com.opensymphony.xwork2.ActionSupport; import com.opensymphony.xwork2.ModelDriven; import com.srisris.khiraya.dao.hibernate.Owner; import com.srisris.khiraya.service.OwnerService; @SuppressWarnings("rawtypes") public class RegisterAction extends ActionSupport implements ModelDriven{ private static final long serialVersionUID = 6521996078347478542L; private String ownerFirstName; private String ownerLastName; private String username; private String password; private String ownerPhone; private String ownerEmail; private OwnerService ownerService; Owner owner = new Owner(); public void setOwnerService(OwnerService ownerService) { this.ownerService = ownerService; } public String add() { owner.setOwnerFirstName(ownerFirstName); owner.setOwnerLastName(ownerLastName); owner.setOwnerPassword(password); owner.setOwnerPhone(ownerPhone); owner.setOwnerEmail(ownerEmail); ownerService.save(owner); return SUCCESS; } public String execute() { return INPUT; } public String getOwnerFirstName() { return ownerFirstName; } public void setOwnerFirstName(String ownerFirstName) { this.ownerFirstName = ownerFirstName; } public String getOwnerLastName() { return ownerLastName; } public void setOwnerLastName(String ownerLastName) { this.ownerLastName = ownerLastName; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getOwnerPhone() { return ownerPhone; } public void setOwnerPhone(String ownerPhone) { this.ownerPhone = ownerPhone; } public String getOwnerEmail() { return ownerEmail; } public void setOwnerEmail(String ownerEmail) { this.ownerEmail = ownerEmail; } public Object getModel() { return owner; } } A: I made a trivial mistake which costed me hours of pain. Silly me the problem was that my class name in struts.xml and id in register.xml were not matching and hence the issue.
{ "language": "en", "url": "https://stackoverflow.com/questions/5184516", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Can't install Compare plugin in notepad++ I am trying to install compare plugin in notepad++ v7.6.2 32bit following this tutorial https://www.youtube.com/watch?v=qvEOX6mSbpo I did exact same steps, except I realized when I tried to place the DLL in the plugins folder, I didn't find a plugins folder! so I created one myself and placed the DLL. restarted notepad++ and I can't see the compare plugin at all in plugins I found this thread here https://notepad-plus-plus.org/community/topic/17492/plugins-gone/2 apparently, plugins in the new version have to be placed in a subfolder of the plugin name due to organization so I did that, and still, I can't see the compare plugin finally, I tried installing from PluginsAdmin (apparently that's what plugin manager is replaced within new notepad++ versions), and it restarts automatically during installation, but i still cannot see compare plugin listed... what is going on? Update: i discovered, thanks to this thread (last post) that based on initial installation selection (which i think i just did default installation whatever options are selected automatically), i found the plugins folder in %APPDATA% still, placing the dll there didn't help. the plugin won't show up still! A: Or another fix is to disconnect from your company intranet, connect to the internet via wifi or using your mobile phone usb tethering. Then try to install the plugin, it will work. It's because np++ domain is blocked by your network administrator A: Finally! I figured out why thanks to this post here: https://notepad-plus-plus.org/community/topic/17276/cannot-install-plugins-at-all/11 because my machine is company machine, it appears the proxy must be set Do this in elevated mode (i.e. open notepad++ as administrator) after that, from pluginAdmin, install compare plugin, restarted notepad++, and wala! the plugin is showing up finally!!
{ "language": "en", "url": "https://stackoverflow.com/questions/56839880", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Efficient way of computing Kullback–Leibler divergence in Python I have to compute the Kullback-Leibler Divergence (KLD) between thousands of discrete probability vectors. Currently I am using the following code but it's way too slow for my purposes. I was wondering if there is any faster way to compute KL Divergence? import numpy as np import scipy.stats as sc #n is the number of data points kld = np.zeros(n, n) for i in range(0, n): for j in range(0, n): if(i != j): kld[i, j] = sc.entropy(distributions[i, :], distributions[j, :]) A: Scipy's stats.entropy in its default sense invites inputs as 1D arrays giving us a scalar, which is being done in the listed question. Internally this function also allows broadcasting, which we can abuse in here for a vectorized solution. From the docs - scipy.stats.entropy(pk, qk=None, base=None) If only probabilities pk are given, the entropy is calculated as S = -sum(pk * log(pk), axis=0). If qk is not None, then compute the Kullback-Leibler divergence S = sum(pk * log(pk / qk), axis=0). In our case, we are doing these entropy calculations for each row against all rows, performing sum reductions to have a scalar at each iteration with those two nested loops. Thus, the output array would be of shape (M,M), where M is the number of rows in input array. Now, the catch here is that stats.entropy() would sum along axis=0, so we will feed it two versions of distributions, both of whom would have the rowth-dimension brought to axis=0 for reduction along it and the other two axes interleaved - (M,1) & (1,M) to give us a (M,M) shaped output array using broadcasting. Thus, a vectorized and much more efficient way to solve our case would be - from scipy import stats kld = stats.entropy(distributions.T[:,:,None], distributions.T[:,None,:]) Runtime tests and verify - In [15]: def entropy_loopy(distrib): ...: n = distrib.shape[0] #n is the number of data points ...: kld = np.zeros((n, n)) ...: for i in range(0, n): ...: for j in range(0, n): ...: if(i != j): ...: kld[i, j] = stats.entropy(distrib[i, :], distrib[j, :]) ...: return kld ...: In [16]: distrib = np.random.randint(0,9,(100,100)) # Setup input In [17]: out = stats.entropy(distrib.T[:,:,None], distrib.T[:,None,:]) In [18]: np.allclose(entropy_loopy(distrib),out) # Verify Out[18]: True In [19]: %timeit entropy_loopy(distrib) 1 loops, best of 3: 800 ms per loop In [20]: %timeit stats.entropy(distrib.T[:,:,None], distrib.T[:,None,:]) 10 loops, best of 3: 104 ms per loop
{ "language": "en", "url": "https://stackoverflow.com/questions/34007028", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "5" }
Q: Fieldsets & legends vs sections & headings in .net Is there any real difference between these when used in an aspx web form? A: They have semantic differences. A fieldset is designed to encapsulate a group of fields, inputs or controls. Sections and headings are more designed for actual text content (your actual copy in the literary sense).
{ "language": "en", "url": "https://stackoverflow.com/questions/6930113", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to print a fixed length memory area which contains multiple \0? I have a memory area with fixed length. char *p = malloc(100); memset(p, 0 ,100); I have some strings in this memory area, along with some \0, for example memcpy(p, "asdf", 4); memcpy(p + 10, "ghi", 3); memcpy(p + 20, "1234", 3); So, there are \0 between asdf and ghi I want to print this memory are and the output is asdfghi1234 How can I do that? Note that above code is just an example, where are these \0 is not fixed. A: Assuming you know the size of the block of memory (hard coded to 100 here): for (int i = 0; i < 100; i++) { char c = p[i]; if (c != 0) printf("%c", c); } Minor nit but in your sample above, the string will be "asdfghi123", because the memcpy for "1234" is only copying 3 bytes. A: Since the NUL bytes don’t mess up the way the text appears (I think) and that’s all you’re looking for, you should be able to write all of the bytes directly to stdout: fwrite(p, sizeof(char), 100, stdout);
{ "language": "en", "url": "https://stackoverflow.com/questions/56352106", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: jQuery Shake broke position:fixed In a web site I want to shake a div which includes an image, it is fixed at the bottom of the page. I try to add shake function to it, it is shaking but position changes to left side. How can I fix it ? Let me write the code. var css_shake={ right: '225px', left: 'auto', position: 'fixed', bottom:'50px' } jQuery.fn.shake = function() { this.each(function(i) { jQuery(this).css(css_shake); for (var x = 1; x <= 3; x++) { jQuery(this).animate({ left: -25 }, 10).animate({ left: 0 }, 50).animate({ left: 25 }, 10).animate({ left: 0 }, 50); } }); return this; } when write $(div).shake() it works but not I want to do. <div id="affix_sepet"> <img src="img/sepet_yeni.png" height="226" width="163"> </div> This div also have bootstrap affix : jQuery("#affix_sepet").affix() A: var css_shake={ right: '225px', left: 'auto', position: 'fixed', bottom:'50px' } jQuery.fn.shake = function() { this.each(function(i) { jQuery(this).css(css_shake); jQuery(this).animate({ left: -25 }, 10).animate({ left: 0 }, 50).animate({ left: 25 }, 10).animate({ left: 0 }, 50); jQuery(this).animate({ top: -25 }, 10).animate({ top: 0 }, 50).animate({ top: 25 }, 10).animate({ top: 0 }, 50); jQuery(this).animate({ left: -25 }, 10).animate({ left: 0 }, 50).animate({ left: 25 }, 10).animate({ left: 0 }, 50); jQuery(this).animate({ top: -25 }, 10).animate({ top: 0 }, 50).animate({ top: 25 }, 10).animate({ top: 0 }, 50); jQuery(this).animate({ left: -25 }, 10).animate({ left: 0 }, 50).animate({ left: 25 }, 10).animate({ left: 0 }, 50); jQuery(this).animate({ top: -25 }, 10).animate({ top: 0 }, 50).animate({ top: 25 }, 10).animate({ top: 0 }, 50); }); return this; } A: You are using absolute left values for your animation rather than relative values. Try using this syntax: jQuery(this).animate({ left : '+=25px' }, 10).animate({ left : '-=25px' }, 10) ; currently you are bouncing the element around absolute position -25 to 25, and leaving it up against the left border.
{ "language": "en", "url": "https://stackoverflow.com/questions/17388260", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to make function with forEach loop check 2 files, if exists return with string if not return file name I have application can download and save file in LocalFileSystem and i need run 2 file in same time , before start i need to check if those file exist or not . i made somthing like this but i thing its stupid function ,it works with console but dosent work as return string function fileExist(songName,vocalName){ // i change it a bit for this example var downloadedFolder = 'filesystem:http://192.168.1.20:3000/persistent/downloaded/'; var fileName = []; storedFiles = []; misingFiles = []; fileName[0] = ({'value':'Song','name':musicName}); fileName[1] = ({'value':'Vocal','name':vocalName}); fileName.forEach(function(item) { let path = downloadedFolder + item.name; const fName = item.value; window.resolveLocalFileSystemURL(path, function(){ storedFiles.push( fName ) if ( misingFiles.length == 0 && storedFiles.length == 2) { return 'All'; } }, function(){ misingFiles.push( fName ) if ( misingFiles.length == 2 ){ return 'Nothing'; } else if ( misingFiles.length == 1 && storedFiles.length == 1){ return misingFiles[0]; } }) })} i want this function to use it somthing like this : if ( fileExist(songName,vocalName) == 'Nothing' ) thanks A: If you're using NodeJS, you can use fs to check if a file exists or not. if (!fs.existsSync(path)) { // file doens't exists } else { // file does exists } If you're not using NodeJS you can setup a simple localhost server and send a request to that to check if it does exists with fs. If you're using electron (idk which framework you're using) you can use the Electron ipc to send messages from the main process to the renderer process. A: You could check if the file exists using the FileReader object from phonegap. You could check the following: var reader = new FileReader(); var fileSource = <here is your file path> reader.onloadend = function(evt) { if(evt.target.result == null) { // If you receive a null value the file doesn't exists } else { // Otherwise the file exists } }; // We are going to check if the file exists reader.readAsDataURL(fileSource); If that one does work check the comments of this post: How to check a file's existence in phone directory with phonegap (This is were I got this answer from)
{ "language": "en", "url": "https://stackoverflow.com/questions/61205030", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: .htaccess redirect if url ends with certain extension I'm trying to do a redirect if the url ends in .asp to just 301 to the same url but with just / So for example I would like domain.com/category/thingy.asp to redirect to domain.com/category/thingy/ Some urls have .asp others don't. I understand this part of it RewriteCond %{REQUEST_URI} .asp but not sure what to do next? A: You can use this redirect rule in your site root .htaccess: RedirectMatch 301 ^/(.+)\.asp$ /$1/ A: I'm not sure that works on wordpress, you can make it using PHP like $currentUrl = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . $_SERVER[HTTP_HOST] . $_SERVER[REQUEST_URI]; if(strpos($currentUrl, ".asp")) { header("HTTP/1.1 301 Moved Permanently"); $currentUrl = str_replace(".asp", "/", $currentUrl); header("Location:". $currentUrl); die(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/41248314", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to download specific labels/images from tensorflow-datasets I'm currently using the coco/2017 dataset for some use in tf.keras transferred learning I am aware that you can download the full dataset using the code bellow: (raw_train, raw_validation, raw_test), metadata = tfds.load( 'coco/2017', split=list(splits), with_info=True, as_supervised=True) How would I do this if I only wanted to extract the 'persons' images and labels. Instead of the full dataset?
{ "language": "en", "url": "https://stackoverflow.com/questions/57507455", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: how to make audios copy right like gaana app I have been developing an app which contains audios and now I want users to download those audio and can play only through my app. By doing this we can restrict user from copying audios from one device to another because of security concerns. I have searched a lot but only found DRM(Digiatal Right management) is used to restrict the user. As per early study Digital rights management (DRM) is a systematic approach to copyright protection for digital media. But I am not able to find any real practical example of DRM nor there is any kind of documentation. I would really appreciate if somebody tell me how to start with such technologies.
{ "language": "en", "url": "https://stackoverflow.com/questions/37246595", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Does a version control database storage engine exist? I was just wondering if a storage engine type existed that allowed you to do version control on row level contents. For instance, if I have a simple table with ID, name, value, and ID is the PK, I could see that row 354 started as (354, "zak", "test")v1 then was updated to be (354, "zak", "this is version 2 of the value")v2 , and could see a change history on the row with something like select history (value) where ID = 354. It's kind of an esoteric thing, but it would beat having to keep writing these separate history tables and functions every time a change is made... A: It seems you are looking more for auditing features. Oracle and several other DBMS have full auditing features. But many DBAs still end up implementing trigger based row auditing. It all depends on your needs. Oracle supports several granularities of auditing that are easy to configure from the command line. I see you tagged as MySQL, but asked about any storage engine. Anyway, other answers are saying the same thing, so I'm going delete this post as originally it was about the flashback features. A: Obviously you are really after a MySQL solution, so this probably won't help you much, but Oracle has a feature called Total Recall (more formally Flashback Archive) which automates the process you are currently hand-rolling. The Archive is a set of compressed tables which are populated with changes automatically, and queryable with a simple AS OF syntax. Naturally being Oracle they charge for it: it needs an additional license on top of the Enterprise Edition, alas. Find out more (PDF). A: You can achieve similar behavior with triggers (search for "triggers to catch all database changes") - particularly if they implement SQL92 INFORMATION_SCHEMA. Otherwise I'd agree with mrjoltcola Edit: The only gotcha I'd mention with MySQL and triggers is that (as of the latest community version I downloaded) it requires the user account have the SUPER privilege, which can make things a little ugly A: Oracle and Sql Server both call this feature Change Data Capture. There is no equivalent for MySql at this time. A: I think Big table, the Google DB engine, does something like that : it associate a timestamp with every update of a row. Maybe you can try Google App Engine. There is a Google paper explaining how Big Table works. A: CouchDB has full versioning for every change made, but it is part of the NOSQL world, so would probably be a pretty crazy shift from what you are currently doing. A: The wikipedia article on google's bigtable mentions that it allows versioning by adding a time dimension to the tables: Each table has multiple dimensions (one of which is a field for time, allowing versioning). There are also links there to several non-google implementations of a bigtable-type dbms. A: The book Refactoring Databases has some insights on the matter. But it also points out there is no real solution currently, other then carefully making changes and managing them manually. A: One approximation to this is a temporal database - which allows you to see the status of the whole database at different times in the past. I'm not sure that wholly answers your question though; it would not allow you to see the contents of Row 1 at time t1 while simultaneously letting you look at the contents of Row 2 at a separate time t2. A: "It's kind of an esoteric thing, but it would beat having to keep writing these separate history tables and functions every time a change is made..." I wouldn't call audit trails (which is obviously what you're talking of) an "esoteric thing" ... And : there is still a difference between the history of database updates, and the history of reality. Historical database tables should really be used to reflect the history of reality, NOT the history of database updates. The history of database updates is already kept by the DBMS in its logs and journals. If someone needs to inquire the history of database upates, then he/she should really resort to the logs and journals, not to any kind of application-level construct that can NEVER provide sufficient guarantee that it reflects ALL updates.
{ "language": "en", "url": "https://stackoverflow.com/questions/2503510", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "14" }
Q: SocketError at / getaddrinfo: nodename nor servname provided, or not known padrino I am trying to use padrino to build a dashboard for my amazon environment. But when I try the following piece of code in the controller: get :index, :map => "/" do AWS.config(access_key_id: 'ACCESS_KEY', secret_access_key: 'secret_access_key', region: 'ap-southeast-2') ec2 = AWS::EC2.new response = ec2.client.describe_instances(:instance_ids => ['instance_id']) @instance = response[:reservation_set].first[:instances_set].first render 'index' end I got the following errors: SocketError - getaddrinfo: nodename nor servname provided, or not known: /Users/mymac/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/net/http.rb:877:in initialize' /Users/mymac/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/net/http.rb:877:inopen' /Users/mymac/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/net/http.rb:877:in block in connect' /Users/mymac/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/timeout.rb:66:intimeout' /Users/mymac/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/net/http.rb:876:in connect' /Users/mymac/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/net/http.rb:862:indo_start' /Users/mymac/.rvm/rubies/ruby-2.0.0-p247/lib/ruby/2.0.0/net/http.rb:857:in start' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/aws-sdk-1.37.0/lib/aws/core/http/connection_pool.rb:309:instart_session' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/aws-sdk-1.37.0/lib/aws/core/http/connection_pool.rb:125:in session_for' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/aws-sdk-1.37.0/lib/aws/core/http/net_http_handler.rb:55:inhandle' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/aws-sdk-1.37.0/lib/aws/core/client.rb:252:in block in make_sync_request' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/aws-sdk-1.37.0/lib/aws/core/client.rb:288:inretry_server_errors' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/aws-sdk-1.37.0/lib/aws/core/client.rb:248:in make_sync_request' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/aws-sdk-1.37.0/lib/aws/core/client.rb:510:inblock (2 levels) in client_request' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/aws-sdk-1.37.0/lib/aws/core/client.rb:390:in log_client_request' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/aws-sdk-1.37.0/lib/aws/core/client.rb:476:inblock in client_request' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/aws-sdk-1.37.0/lib/aws/core/client.rb:372:in return_or_raise' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/aws-sdk-1.37.0/lib/aws/core/client.rb:475:inclient_request' (eval):3:in describe_instances' /Users/mymac/dev/padrino_workspace/aem_dashboard/app/controllers/aem.rb:24:inblock (2 levels) in ' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/padrino-core-0.12.0/lib/padrino-core/application/routing.rb:699:in call' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/padrino-core-0.12.0/lib/padrino-core/application/routing.rb:699:inblock in route' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/padrino-core-0.12.0/lib/padrino-core/application/routing.rb:62:in []' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/padrino-core-0.12.0/lib/padrino-core/application/routing.rb:62:inblock (3 levels) in process_destination_path' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-1.4.4/lib/sinatra/base.rb:976:in route_eval' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/padrino-core-0.12.0/lib/padrino-core/application/routing.rb:62:inblock (2 levels) in process_destination_path' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/padrino-core-0.12.0/lib/padrino-core/application/routing.rb:62:in catch' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/padrino-core-0.12.0/lib/padrino-core/application/routing.rb:62:inblock in process_destination_path' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/padrino-core-0.12.0/lib/padrino-core/application/routing.rb:37:in instance_eval' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/padrino-core-0.12.0/lib/padrino-core/application/routing.rb:37:inprocess_destination_path' (eval):20:in block in call' (eval):9:incatch' (eval):9:in call' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/http_router-0.11.1/lib/http_router.rb:288:inraw_call' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/http_router-0.11.1/lib/http_router.rb:142:in call' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/padrino-core-0.12.0/lib/padrino-core/application/routing.rb:1101:inroute!' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/padrino-core-0.12.0/lib/padrino-core/application/routing.rb:1086:in block in dispatch!' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-1.4.4/lib/sinatra/base.rb:1049:inblock in invoke' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-1.4.4/lib/sinatra/base.rb:1049:in catch' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-1.4.4/lib/sinatra/base.rb:1049:ininvoke' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/padrino-core-0.12.0/lib/padrino-core/application/routing.rb:1084:in dispatch!' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-1.4.4/lib/sinatra/base.rb:889:inblock in call!' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-1.4.4/lib/sinatra/base.rb:1049:in block in invoke' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-1.4.4/lib/sinatra/base.rb:1049:incatch' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-1.4.4/lib/sinatra/base.rb:1049:in invoke' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-1.4.4/lib/sinatra/base.rb:889:incall!' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-1.4.4/lib/sinatra/base.rb:877:in call' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/sass-3.3.3/lib/sass/plugin/rack.rb:54:incall' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/rack-protection-1.5.2/lib/rack/protection/base.rb:50:in call' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/rack-protection-1.5.2/lib/rack/protection/xss_header.rb:18:incall' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/rack-protection-1.5.2/lib/rack/protection/base.rb:50:in call' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/rack-protection-1.5.2/lib/rack/protection/base.rb:50:incall' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/rack-protection-1.5.2/lib/rack/protection/json_csrf.rb:18:in call' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/rack-protection-1.5.2/lib/rack/protection/base.rb:50:incall' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/rack-protection-1.5.2/lib/rack/protection/base.rb:50:in call' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/rack-protection-1.5.2/lib/rack/protection/frame_options.rb:31:incall' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/rack-1.5.2/lib/rack/head.rb:11:in call' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/rack-1.5.2/lib/rack/methodoverride.rb:21:incall' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/padrino-core-0.12.0/lib/padrino-core/reloader/rack.rb:22:in call' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/padrino-core-0.12.0/lib/padrino-core/logger.rb:398:incall' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-1.4.4/lib/sinatra/show_exceptions.rb:21:in call' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/rack-1.5.2/lib/rack/session/abstract/id.rb:225:incontext' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/rack-1.5.2/lib/rack/session/abstract/id.rb:220:in call' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-1.4.4/lib/sinatra/base.rb:2004:incall' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-1.4.4/lib/sinatra/base.rb:1469:in block in call' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-1.4.4/lib/sinatra/base.rb:1778:insynchronize' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/sinatra-1.4.4/lib/sinatra/base.rb:1469:in call' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/padrino-core-0.12.0/lib/padrino-core/router.rb:82:inblock in call' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/padrino-core-0.12.0/lib/padrino-core/router.rb:75:in each' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/padrino-core-0.12.0/lib/padrino-core/router.rb:75:incall' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/thin-1.6.2/lib/thin/connection.rb:86:in block in pre_process' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/thin-1.6.2/lib/thin/connection.rb:84:incatch' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/thin-1.6.2/lib/thin/connection.rb:84:in pre_process' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/thin-1.6.2/lib/thin/connection.rb:53:inprocess' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/thin-1.6.2/lib/thin/connection.rb:39:in receive_data' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/eventmachine-1.0.3/lib/eventmachine.rb:187:inrun_machine' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/eventmachine-1.0.3/lib/eventmachine.rb:187:in run' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/thin-1.6.2/lib/thin/backends/base.rb:73:instart' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/thin-1.6.2/lib/thin/server.rb:162:in start' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/rack-1.5.2/lib/rack/handler/thin.rb:16:inrun' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/rack-1.5.2/lib/rack/server.rb:264:in start' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/padrino-core-0.12.0/lib/padrino-core/server.rb:50:instart' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/padrino-core-0.12.0/lib/padrino-core/server.rb:39:in start' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/padrino-core-0.12.0/lib/padrino-core/server.rb:12:inrun!' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/padrino-core-0.12.0/lib/padrino-core/cli/adapter.rb:7:in start' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/padrino-core-0.12.0/lib/padrino-core/cli/base.rb:32:instart' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.17.0/lib/thor/task.rb:27:in run' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.17.0/lib/thor/invocation.rb:120:ininvoke_task' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.17.0/lib/thor.rb:344:in dispatch' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/thor-0.17.0/lib/thor/base.rb:434:instart' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/gems/padrino-core-0.12.0/bin/padrino:9:in <top (required)>' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/bin/padrino:23:inload' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/bin/padrino:23:in <main>' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/bin/ruby_executable_hooks:15:ineval' /Users/mymac/.rvm/gems/ruby-2.0.0-p247/bin/ruby_executable_hooks:15:in `' Here is my gem file: ruby '2.0.0' gem 'rake' gem 'thin' gem 'bcrypt-ruby', :require => 'bcrypt' gem 'sass' gem 'haml' gem 'mongoid', '~>3.0.0' gem 'mocha', :group => 'test', :require => false gem 'shoulda', :group => 'test' gem 'rack-test', :require => 'rack/test', :group => 'test' gem 'padrino', '0.12.0' gem "bootstrap-sass", "~> 3.1.1.0" gem 'aws-sdk', '~> 1.37.0' gem 'rest-client', '~> 1.6.7' gem 'net-ping', '~> 1.7.2' If I try the following code in irb, sinatra and rails, it works well: AWS.config(access_key_id: 'ACCESS_KEY', secret_access_key: 'secret_access_key', region: 'ap-southeast-2') ec2 = AWS::EC2.new response = ec2.client.describe_instances(:instance_ids => ['instance_id']) @instance = response[:reservation_set].first[:instances_set].first Can anyone please help me out. Thank you. I am using ruby 2.0.0, padrino 0.12.0 and OS X 10.8.2. Regards Johnny A: Your region configuration may be wrong. I ran into the same error when trying to access an S3 bucket. Since my bucket was on us-standard, aka 'us-east-1', this configuration ended up working: AWS.config(access_key_id: 'xxx', secret_access_key: 'xxx', region: 'us-west-1', s3: { region: 'us-east-1' })
{ "language": "en", "url": "https://stackoverflow.com/questions/22588089", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: Get HTML Source of WebElement in Selenium WebDriverJS There is a similar question out there (an older one in Python) but this one has to do with JS. Testing using Selenium in a NodeJS, Mocha environment. What I'd like to do is click on a Bootstrap dropdown and check the HTML to look for changes. I've tried the following: test.it('should click on all header links', function() { var elem = driver.findElement(By.id('Profile')); console.log(elem.getAttribute('innerHTML')); console.log(elem.getInnerHtml()); }); Both calls return the same thing. { then: [Function: then], cancel: [Function: cancel], isPending: [Function: isPending] } I plan to feed the HTML into cheerio so i can check for structure changes. Appreciate any help on this. A: I was able to retrieve the HTML as a string by doing the following. driver.findElement(By.id('Profile')).getAttribute("innerHTML").then(function(profile) { console.log(profile); }); A: I got the inner HTML with: element.getAttribute('innerHTML').then(function (html) { console.log(html) })
{ "language": "en", "url": "https://stackoverflow.com/questions/24293189", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "3" }
Q: figures and plotting in Matlab I have an application in Matlab where I'll be creating lots of plots. Generally, I want each new plot to appear in a a separate figure and also save the handle to the figure, so I do: h = figure('NextPlot','new'); plot(1:13); The above however creates one empty figure and one with the plot(1:13). Why is this? A: To store the handle you could run something like: for i=1:4 h(i)=figure(i); plot(1:13); end A: AFAIK you are good to go with h = figure plot(1:13) I tested it in R2010a before posting. The figure('NextPlot','new') instructs MATLAB to create a new window (other than being opened) for next plot. That is why you get an empty window + the plot window. By defaut NextPlot has the value add, and it is for Use the current figure to display graphics (the default)
{ "language": "en", "url": "https://stackoverflow.com/questions/37220565", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Outlook push notification subscription error, ErrorInvalidParameter , verification failed The operation has timed out https://learn.microsoft.com/en-us/previous-versions/office/office-365-api/api/version-2.0/notify-rest-operations#compare-streaming-and-push-notifications I am trying to subscribe push notification for user calendar events (create, update). I am stuck on point. (ref: above doc url) Heading:- Subscription process Point# 3 Implementation in PHP (Laravel). I successfully hit the api to subscribe push notification. but on my endpoint when I try to validate url it always retuning me bellow error. My php (Laravel) code to validate url:- return response($request->validationtoken, 200) ->header('Content-Type', 'text/plain'); Error Response:- Array ( [error] => Array ( [code] => ErrorInvalidParameter [message] => Notification URL 'https://fe6e2bee141e.ngrok.io/outlook-calendar/webhook?validationtoken=YmE1ODdiMzItODVmYy00YmI5LWJiZDgtMzViZGM0MGJkYzBj' verification failed 'System.Net.WebException: The operation has timed out at System.Net.HttpWebRequest.GetResponse() at Microsoft.Exchange.OData.Model.Notifications.PushNotification.PushSubscriptionCallbackUrlValidationHelper.SendRequestAndVerifyResponse(Uri callbackUrl, PushSubscription pushSubscription)'. ) ) Anyone can guide me what is wrong and how to do it in proper way? (If you can able to provide me php code reference that will be great.)
{ "language": "en", "url": "https://stackoverflow.com/questions/62828937", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Displaying members in teams Im trying to display the number of users in each team. I have an department object that has departmentId and with it i would want to display users. Im displaying my users in a modal with this function. async selectTeam(index: any) { this.selectedTeam = this.teams[index]; this.usersToShow = this.tenantUsers.filter(item => !this.teams.find(team => team.id == this.selectedTeam.id).users.map(x => x.id).includes(item.id)); } <a click.delegate="selectTeam($index)" class="rounded-circle" data-toggle="modal" href="#modal-form3"> If i have 2 teams each in his own row, how would i display length of the each team?
{ "language": "en", "url": "https://stackoverflow.com/questions/67735899", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to find out that keyboard down arrow key pressed, programmatically I know that when down arrow key is pressed on keyboard then we can get Keyboard Hide notification but the problem is, we get Keyboard Hide notification also when we rotate the device and keyboard hides, now how to differentiate that keyboard is hiding because of key pressed not because of rotation. A: In your AppDelegate.m - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide) name:UIKeyboardWillHideNotification object:nil]; return YES; } -(void) keyboardWillHide { NSLog(@"Bye"); } A: Following Delegate method of textfield is called automatically when we clicked on the return or arrow button of keyboard. - (BOOL)textFieldShouldReturn:(UITextField *)textField
{ "language": "en", "url": "https://stackoverflow.com/questions/15629418", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Jtable adding rows with strings and doubles Hi there i'm studing Java and i have some questions. I'm trying to populate a Jtable and sorting it: i'm creating a model of an existing Jtable and adding it some data: ArrayList<Cliente> lista = new ArrayList<Cliente>(); lista = FachadaLogica.cargarTablaClientes(); DefaultTableModel modelo = new DefaultTableModel(); modelo.addColumn("Cédula"); modelo.addColumn("Nombre"); modelo.addColumn("Dirección"); modelo.addColumn("Departamento"); modelo.addColumn("Código Postal"); modelo.addColumn("Monto Total"); this.tabla.setModel(modelo); tabla.setAutoCreateRowSorter(Boolean.TRUE); Object clientes[]=new Object[6]; String ci; String departamento = ""; for (int i = 0; i < lista.size(); i++) { clientes[0] = lista.get(i).getCedula(); clientes[1] = lista.get(i).getNombre(); clientes[2] = lista.get(i).getDireccion(); departamento = FachadaLogica.obtenerDepartamento(lista.get(i).getDepartamento()); clientes[3] = departamento; clientes[4] = lista.get(i).getCodigoPostal(); ci = lista.get(i).getCedula(); clientes[5] = FachadaLogica.obtenerMontoCliente(ci); modelo.addRow(clientes); } Result: My problem is when i try to sort it by "monto total" translated to english it is the money that the client must to pay, the method "obtenerMontoCliente" returns a Double but it sorts like a String. public static Double obtenerMontoCliente(String ci){ Double resultado= 0.0; TrabajoPersistencia pers = new TrabajoPersistencia(); try { resultado=pers.montoTotalCliente(ci); } catch (TrabajoExcepcion ex) { } i don't know what i am doing wrong.
{ "language": "en", "url": "https://stackoverflow.com/questions/68539386", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Splunk: 'net stop splunk' only works *sometimes* I'm trying to manage Splunk with Chef and ran across a problem when using Chef to programmatically start/stop/restart the Splunkforwarder service: The request did not respond to the start or control request in a timely fashion. - ControlService: The service did not respond to the start or control request in a timely fashion. Once the Chef run fails, I'm able to start the service with net start splunkforwarder. I decided to try going through the restart (stop/start) process manually in Powershell, and now when I try to stop the service with net stop splunkfowarder I get an error: The service is not responding to the control function. Somtimes stopping the service works, but rarely. At this point I have no idea what's going on because I'm not used to working on Windows (or with Splunk), and am not sure if the error from Chef and the net stop splunkforwarder errors are related. I've also found if I interact with splunk directly through the executable file in C:\Program Files\SplunkUniversalForwarder\bin\splunk.exe that everything works fine. I can cd to that directory and run ./splunk restart without problems. Anyone know what's going on or have advice on next-steps for troubleshooting? A: This does belong on ServerFault. However. Stopping a service with net.exe actually does two things: * *Sends the stop command to the service. *Wait an amount of time (either 30s or 60s, IIRC) to see if the service has stopped. If it has, report success. Else, error. My guess it that net.exe stop splunk is hitting whatever timeout that net.exe uses sometimes. What you can do instead is: sc.exe stop splunk The sc.exe command will only do step 1. It sends the stop command and immediately returns. The PowerShell cmdlet Stop-Service will do the same thing, IIRC. Note that net.exe and sc.exe are not native PowerShell commands or cmdlets. They're standard programs. You can also do this to wait, say, 5 seconds: $svc = Get-Service splunk; $svc.Stop(); $svc.WaitForStatus('Stopped','00:00:05'); And then you can look at $svc.Status to see what it's doing. Or you can tell it to wait indefinitely: $svc = Get-Service splunk; $svc.Stop(); $svc.WaitForStatus('Stopped'); Get-Service returns an object of type System.ServiceProcess.ServiceController. You can take a look at $svc | Get-Member or $svc | Format-List to get more information about the object and what you can do with it. If you want your script to be able to kill the process, you'll probably need to get the PID. That's somewhat more complex because the above class doesn't expose the PID for some stupid reason. The typical method is WMI: $wmisvc_pid = (Get-WmiObject -Class Win32_Service -Filter "Name = 'splunk'").ProcessId; Stop-Process $wmisvc_pid -Force; WMI also exposes it's own Start() and Stop() methods, and is particularly useful because Start-Service and Stop-Service don't work remotely, but WMI does.
{ "language": "en", "url": "https://stackoverflow.com/questions/39355584", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: How can I use SFINAE to disable a function inside a class based on template type I have a template class template<typename TLoader, typename TCreator> class ManagerGroup { public: uint32_t loadFromPath(const Path &path) { return mLoader.load(path); } void createFile(uint32_t handle) { return mCreator.create(handle); } private: TLoader mLoader; TCreator mCreator; }; For the loadFromPath and createFile functions, I want to disable them if the provided typename is std::nullptr_t; so, I can do something like this: ManagerGroup<FontLoader, std::nullptr_t> fontManager; // No issues fontManager.loadFromPath("/test"); // Compilation error fontManager.createFile(10); ManagerGroup<std::nullptr_t, MeshCreator> meshManager; // NO issues meshManager.createFile(20); // Throws error meshManager.loadFromFile("/test"); Is this possible with SFINAE? I tried the following but could not get it working (based on example #5 in https://en.cppreference.com/w/cpp/types/enable_if): template<typename = std::enable_if_t<!std::same<TCreator, std::nullptr_t>::value>> void createFile(uint32_t handle) { return mCreator.create(handle); } A: In order for SFINAE to work you need to use a parameter that is being deduced. In your case TCreator is already known so you can't use it. You can instead get around the problem by adding your own parameter and defaulting it to TCreator like template<typename T = TCreator, std::enable_if_t<!std::is_same_v<T, std::nullptr_t>, bool> = true> void createFile(uint32_t handle) { return mCreator.create(handle); }
{ "language": "en", "url": "https://stackoverflow.com/questions/73115436", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Calendar iframe being scrolled to when page laoded When my html page loads, the screen is automatically moved to a Calendar iframe I have installed I've already tried scrolling="no" and it didn't work Any way to work around this? A: add some js to your page document.addEventListener('DOMContentLoaded', ()=>{document.body.scrollIntoView()});
{ "language": "en", "url": "https://stackoverflow.com/questions/71989749", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: In-class struct, how does "this" work? As stated, how does the this pointer act when called in a struct defined in a class ? Let's say I have the following piece of code: class A { public: struct { void bar() { std::cout << this << std::endl; } } foo; }; int main() { A a; a.foo.bar(); std::cout << &a << std::endl; std::cout << &a.foo << std::endl; } That generate this output: 0x62fe9f 0x62fe9f 0x62fe9f a.foo share the same address with a, how could one access to the this pointer of foo ? Using this->foo raise an error: test.cpp:20:23: error: 'struct A::<anonymous>' has no member named 'foo' A: The address is mostly just where the memory if the object "starts". How much to offset is needed members is then defined by the class definition. So class A "starts" at 0x62fe9f. At the beginning of class A is the member foo so because there is nothing in front of it it has also address 0x62fe9f etc. When you change the class to class A { public: int i; struct { void bar() { std::cout << this << std::endl; } } foo; }; You shloud see &a.i and &a having the same address and &a.foo should be &a + sizeof(int) (Note: It may be more than sizeof(int) and in other cases also different because how padding is set. This is just a simple example. You should not rely on this in real code) A: Possibly this modified version of your program, and its output, will be enlightening. #include <iostream> using std::cout; class A { public: int data; struct { int data; void bar() { cout << this << '\n'; cout << &this->data << '\n'; } } foo; void bar() { cout << this << '\n'; cout << &this->data << '\n'; cout << &this->foo << '\n'; } }; int main(void) { A a; cout << &a << '\n'; a.bar(); a.foo.bar(); }
{ "language": "en", "url": "https://stackoverflow.com/questions/40288073", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Android Device Monitor "data" folder is empty I have tested creating, inserting and retrieving data into my apps db, and know it works through usage of Log statements. However, I wish to expedite testing and use the Android Device Monitor. However, though the db exists and data is stored, when accessing below, the data folder is empty: Why would this be the case? How can this be configured to show the db file and contents? A: It isn't empty....you just don't have permission to view that folder on a device. Try it in a simulator and it will work for you since you have root access. A: There are two ways if you want to browse your device data (data/data) folder. * *You need to have a phone with root access in order to browse the data folder using ADM(Android Device Monitor). ADM location - (YOUR_SDK_PATH\Android\sdk\tools) *You need to be running ADB in root mode, do this by executing: adb root If you just want to see your DB & Tables then the esiest way is to use Stetho. Pretty cool tool for every Android developer who uses SQLite buit by Facobook developed. Steps to use the tool * *Add below dependeccy in your application`s gradle file (Module: app) 'compile 'com.facebook.stetho:stetho:1.4.2' *Add below lines of code in your Activity onCreate() method @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Stetho.initializeWithDefaults(this); setContentView(R.layout.activity_main); } Now, build your application & When the app is running, you can browse your app database, by opening chrome in the url: chrome://inspect/#devices Screenshots of the same are as below_ ChromeInspact Your DB Hope this will help all! :) A: It may be easier to store the database in a public folder during development. Or you can see this post : How to access data/data folder in Android device? A: Solving the issue using an emulator The folder /data can be empty because you are missing the proper permissions. To solve it, I had to execute the following commands. adb shell su Those commands starts a shell in the emulator and grant you root rights. The command adb is located in the folder platform-tools of the Android SDK, typically installed in ~/Library/Android/sdk/ on MacOS. chmod -R 777 /data Modify the permissions of the folder (and subfolders recursively) /data in order to make them appear in the tool Android Device Monitor. adb root Finally, this command restarts adb as root. Be careful, it only works on development builds (typically emulators builds). Afterwards, you can see the content of the folder /data and transfer the data located in. You can do it in console as well, using adb pull <remote> <locale>, such as: adb pull /data/data/<app name>/databases/<database> . A: In cmd GoTo: C:\Users\UserName\android-sdks\platform-tools Execute: adb root Done A: In addition to @Steven K's answers: If you want to gain access to your data without having to root your real device you need to run your app in an emulator with API 23 (or lower). It is a known problem that APIs above 23 can cause problems when deploying Android Device Monitor. A: If anyone is having the stated problem, follow below steps in terminal window: * *Navigate to /Users/Username/Library/Android/sdk/platform-tools *Execute ./adb root That's it. Problem solved. A: I had same problem with API_25, it didn't work for me. Configure an API_23 emulator, it will work on API_23. A: If you are on Windows follow these instructions step by step: * *Launch your app in android emulator. *Then open command prompt as an administrator and navigate to the sdk path for example cd C:\Android\sdk\platform-tools *Type adb root *Then type adb pull /data/data/ name-of-your-package /databases/name-of-your-database *You'll find your database located in the folder called platform-tools. Then you can install Sqlite Manager extension in Google Chrome via chrome webstore and use it to view and manage your exported database. In case you have a rooted phone you can follow the same instructions as above.
{ "language": "en", "url": "https://stackoverflow.com/questions/34603355", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "45" }
Q: Arduino IDE is able to use avrdude to flash hex file, but command line on ubuntu is unable to Good day all, I have an arduino pro micro (Chinese knock off version) with which I am able to flash to with the arduino IDE but I am unable to recreate the same effect with avrdude in the terminal on Ubuntu 16.04 This is what I have observed from the verbose output on the arduino IDE: Forcing reset using 1200bps open/close on port /dev/ttyACM0 PORTS {/dev/ttyACM0, } / {} => {} PORTS {} / {/dev/ttyACM0, } => {/dev/ttyACM0, } Found upload port: /dev/ttyACM0 /home/philip/Desktop/arduino-1.8.5/hardware/tools/avr/bin/avrdude -C/home/philip/Desktop/arduino-1.8.5/hardware/tools/avr/etc/avrdude.conf -v -patmega32u4 -cavr109 -P/dev/ttyACM0 -b57600 -D -Uflash:w:/tmp/arduino_build_182426/strandtest.ino.hex:i avrdude: Version 6.3, compiled on Jan 17 2017 at 11:00:16 Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/ Copyright (c) 2007-2014 Joerg Wunsch System wide configuration file is "/home/philip/Desktop/arduino-1.8.5/hardware/tools/avr/etc/avrdude.conf" User configuration file is "/home/philip/.avrduderc" User configuration file does not exist or is not a regular file, skipping Using Port : /dev/ttyACM0 Using Programmer : avr109 Overriding Baud Rate : 57600 AVR Part : ATmega32U4 Chip Erase delay : 9000 us PAGEL : PD7 BS2 : PA0 RESET disposition : dedicated RETRY pulse : SCK serial program mode : yes parallel program mode : yes Timeout : 200 StabDelay : 100 CmdexeDelay : 25 SyncLoops : 32 ByteDelay : 0 PollIndex : 3 PollValue : 0x53 Memory Detail : Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW MaxW ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- --------- eeprom 65 20 4 0 no 1024 4 0 9000 9000 0x00 0x00 flash 65 6 128 0 yes 32768 128 256 4500 4500 0x00 0x00 lfuse 0 0 0 0 no 1 0 0 9000 9000 0x00 0x00 hfuse 0 0 0 0 no 1 0 0 9000 9000 0x00 0x00 efuse 0 0 0 0 no 1 0 0 9000 9000 0x00 0x00 lock 0 0 0 0 no 1 0 0 9000 9000 0x00 0x00 calibration 0 0 0 0 no 1 0 0 0 0 0x00 0x00 signature 0 0 0 0 no 3 0 0 0 0 0x00 0x00 Programmer Type : butterfly Description : Atmel AppNote AVR109 Boot Loader Connecting to programmer: . Found programmer: Id = "CATERIN"; type = S Software Version = 1.0; No Hardware Version given. Programmer supports auto addr increment. Programmer supports buffered memory access with buffersize=128 bytes. Programmer supports the following devices: Device code: 0x44 avrdude: devcode selected: 0x44 avrdude: AVR device initialized and ready to accept instructions Reading | ################################################## | 100% 0.00s avrdude: Device signature = 0x1e9587 (probably m32u4) avrdude: reading input file "/tmp/arduino_build_182426/strandtest.ino.hex" avrdude: writing flash (5918 bytes): Writing | ################################################## | 100% 0.45s avrdude: 5918 bytes of flash written avrdude: verifying flash memory against /tmp/arduino_build_182426/strandtest.ino.hex: avrdude: load data flash data from input file /tmp/arduino_build_182426/strandtest.ino.hex: avrdude: input file /tmp/arduino_build_182426/strandtest.ino.hex contains 5918 bytes avrdude: reading on-chip flash data: Reading | ################################################## | 100% 0.05s avrdude: verifying ... avrdude: 5918 bytes of flash verified avrdude done. Thank you. Which I have done my best to replicate by using this code: stty -F /dev/ttyACM0 speed 1200 stty -F /dev/ttyACM0 speed 57600 /home/philip/Desktop/arduino-1.8.5/hardware/tools/avr/bin/avrdude -v -p m32u4 -C /home/philip/Desktop/arduino-1.8.5/hardware/tools/avr/etc/avrdude.conf -c avr109 -P /dev/ttyACM0 -b 57600 -D -U flash:w:layout.hex To the extent of using the same avrdude file and configuration as the IDE However, when I do it this way, I face the following error: /home/philip/Desktop/arduino-1.8.5/hardware/tools/avr/bin/avrdude -v -p m32u4 -C /home/philip/Desktop/arduino-1.8.5/hardware/tools/avr/etc/avrdude.conf -c avr109 -P /dev/ttyACM0 -b 57600 -D -U flash:w:layout.hex avrdude: Version 6.3, compiled on Jan 17 2017 at 11:00:16 Copyright (c) 2000-2005 Brian Dean, http://www.bdmicro.com/ Copyright (c) 2007-2014 Joerg Wunsch System wide configuration file is "/home/philip/Desktop/arduino-1.8.5/hardware/tools/avr/etc/avrdude.conf" User configuration file is "/home/philip/.avrduderc" User configuration file does not exist or is not a regular file, skipping Using Port : /dev/ttyACM0 Using Programmer : avr109 Overriding Baud Rate : 57600 AVR Part : ATmega32U4 Chip Erase delay : 9000 us PAGEL : PD7 BS2 : PA0 RESET disposition : dedicated RETRY pulse : SCK serial program mode : yes parallel program mode : yes Timeout : 200 StabDelay : 100 CmdexeDelay : 25 SyncLoops : 32 ByteDelay : 0 PollIndex : 3 PollValue : 0x53 Memory Detail : Block Poll Page Polled Memory Type Mode Delay Size Indx Paged Size Size #Pages MinW MaxW ReadBack ----------- ---- ----- ----- ---- ------ ------ ---- ------ ----- ----- --------- eeprom 65 20 4 0 no 1024 4 0 9000 9000 0x00 0x00 flash 65 6 128 0 yes 32768 128 256 4500 4500 0x00 0x00 lfuse 0 0 0 0 no 1 0 0 9000 9000 0x00 0x00 hfuse 0 0 0 0 no 1 0 0 9000 9000 0x00 0x00 efuse 0 0 0 0 no 1 0 0 9000 9000 0x00 0x00 lock 0 0 0 0 no 1 0 0 9000 9000 0x00 0x00 calibration 0 0 0 0 no 1 0 0 0 0 0x00 0x00 signature 0 0 0 0 no 3 0 0 0 0 0x00 0x00 Programmer Type : butterfly Description : Atmel AppNote AVR109 Boot Loader **Connecting to programmer: .avrdude: butterfly_recv(): programmer is not responding avrdude: butterfly_recv(): programmer is not responding avrdude: butterfly_recv(): programmer is not responding avrdude: butterfly_recv(): programmer is not responding avrdude: butterfly_recv(): programmer is not responding avrdude: butterfly_recv(): programmer is not responding Found programmer: Id = ""; type = Software Version = .; Hardware Version = . avrdude: butterfly_recv(): programmer is not responding avrdude: butterfly_recv(): programmer is not responding avrdude: error: buffered memory access not supported. Maybe it isn't a butterfly/AVR109 but a AVR910 device?** avrdude: initialization failed, rc=-1 Double check connections and try again, or use -F to override this check. avrdude: butterfly_recv(): programmer is not responding avrdude: error: programmer did not respond to command: leave prog mode avrdude: butterfly_recv(): programmer is not responding avrdude: error: programmer did not respond to command: exit bootloader So my question is, why is the Arduino IDE able to detect the type of programmer when the exact same avrdude executable is run through the terminal and yet is unable to flash the hex file? My best bet is that it has something to do with the forced reset using the baud rate and that the arduino IDE is doing it differently from me, but I am unsure of what I need to change Any help is greatly appreciated! Thank you. A: Darn I fixed it within 5 seconds of posting the question, heres how I did it Instead of using the baud rate to reset it I pressed the reset switch and run the exact same code So the error is here stty -F /dev/ttyACM0 speed 1200 stty -F /dev/ttyACM0 speed 57600 But I am not sure what exactly about it is wrong, and clarification would be appreciated anyway :)
{ "language": "en", "url": "https://stackoverflow.com/questions/51466401", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Is search speed achieved with fast data access or fast index access? From MySQL doc: CREATE [TEMPORARY] TABLE [IF NOT EXISTS] tbl_name (create_definition,...) {DATA|INDEX} DIRECTORY [=] 'absolute path to directory' My table is for search only and takes 8G of disk space (4G data + 4G index) with 80M rows I can't use ENGINE = Memory to store the whole table into memory but I can store either the data or the index in a RAM drive through the DIRECTORY table options From a theorical knoledge, is it better to store the data or the index in RAM? A: MySQL's default storage engine is InnoDB. As you run queries against an InnoDB table, the portion of that table or indexes that it reads are copied into the InnoDB Buffer Pool in memory. This is done automatically. So if you query the same table later, chances are it's already in memory. If you run queries against other tables, it load those into memory too. If the buffer pool is full, it will evicting some data that belongs to your first table. This is not a problem, since it was only a copy of what's on disk. There's no way to specifically "lock" a table on an index in memory. InnoDB will load either data or index if it needs to. InnoDB is smart enough not to evict data you used a thousand times, just for one other table requested one time. Over time, this tends to balance out, using memory for your most-frequently queried subset of each table and index. So if you have system memory available, allocate more of it to your InnoDB Buffer Pool. The more memory the Buffer Pool has, the more able it is to store all the frequently-queried tables and indexes. Up to the size of your data + indexes, of course. The content copied from the data + indexes is stored only once in memory. So if you have only 8G of data + indexes, there's no need to give the buffer pool more and more memory. Don't allocate more system memory to the buffer pool than your server can afford. Overallocating memory leads to swapping memory for disk, and that will be bad for performance. Don't bother with the {DATA|INDEX} DIRECTORY options. Those are for when you need to locate a table on another disk volume, because you're running out of space. It's not likely to help performance. Allocating more system memory to the buffer pool will accomplish that much more reliably. A: but I can store either the data or the index in a RAM drive through the DIRECTORY table options... Short answer: let the database and OS do it. Using a RAM disk might have made sense 10-20 years ago, but these days the software manages caching disk to RAM for you. The disk itself has its own RAM cache, especially if it's a hybrid drive. The OS will cache file system access in RAM. And then MySQL itself will do its own caching. And if it's an SSD that's already extremely fast, so a RAM cache is unlikely to show much improvement. So making your own RAM disk isn't likely to do anything that isn't already happening. What you will do is pull resources away from the OS and MySQL that they could have managed smarter themselves likely slowing everything on that machine down. What you're describing a micro-optimization. This is attempting to make individual operations faster. They tend to add complexity and degrade the system as a whole. And there are limits to how much optimizing you can do with micro-optimizations. For example, if you have to search 1,000,000 rows, and it takes 1ms per row, that's 1,000,000 ms. If you make it 0.9ms per row then it's 900,000 ms. What you want to focus on is algorithmic optimization, improvements to the algorithm. These tend to make the code simpler and less complex, though often the data structures need to be more thought out, because you're doing less work. Take those same 1,000,000 rows and add an index. Instead of looking at 1,000,000 rows you'll spend, say, 100 ms to look at the index. The numbers are made up, but I hope you get the point. If "what you want is speed", algorithmic optimizations will take you where no micro-optimization will. There's also the performance of the code using the database to consider, it is often the real bottleneck using unoptimized queries, poor patterns for fetching related data, and not taking advantage of caching. Micro-optimizations, with their complexities and special configurations, tend to make algorithmic optimizations more difficult. So you might be slowing yourself down in the long run by worrying about micro-optimizations now. Furthermore, you're doing this at the very start when you only have fuzzy ideas about how this thing will be used or perform or where the bottlenecks will be. Spend your time optimizing your data structures and indexes, not minute details of your database storage. Once you've done that, if it still isn't fast enough, then look at tweaking settings. As a side note, there is one possible benefit to playing with DIRECTORY. You can put the data and index on separate physical drives. Then both can be accessed simultaneously with the full I/O throughput of each drive. Though you've just made it twice as likely to have a disk failure, and complicated backups. You're probably better off with an SSD and/or RAID. And consider whether a cloud database might actually out-perform any hardware you might be able to afford.
{ "language": "en", "url": "https://stackoverflow.com/questions/48695597", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: In a Rails 3 model, DateTime attributes are falsly "dirty" In my Rails 3 application, I only want to write an entry in a certain log if changes are actually made to a model. So if a user doesn't change any of the fields and clicks 'Submit', then there should not be a log entry. But it seems that no matter what, Rails always seems to think that the DateTime attributes of the model have been changed. When I debug, I run the following lines during my update and they both return true, which I would think would be a contradiction. @request.begin_date == @request.begin_date_was # Returns true @request.begin_date_changed? # Returns true I'm wondering if it has something to do with changing the default date format in an initializer (to '%m/%d/%Y') or possibly something with time zones. I'm stumped, so any help would be greatly appreciated. A: You can change default date and time format in your en.yml locale file like this: (this is example for french format in one of my projects) date: formats: default: "%d/%m/%Y" short: "%e %b" long: "%e %B %Y" long_ordinal: "%e %B %Y" only_day: "%e" time: formats: default: "%d %B %Y %H:%M" time: "%H:%M" short: "%d %b %H:%M" long: "%A %d %B %Y %H:%M:%S %Z" long_ordinal: "%A %d %B %Y %H:%M:%S %Z" only_second: "%S" am: 'am' pm: 'pm' Or you can simply convert your datetime instances to: @request.begin_date.strftime("%m/%d/%Y") == @request.begin_date_was.strftime("%m/%d/%Y") or even: l(@request.begin_date, :format => your_format_in_locale_file) == l(@request.begin_date_was, :format => your_format_in_locale_file) Hope it will help you A: I realize when you asked, you were probably using a different Rails version, but I just stumbled upon this myself with Rails 3.2.5. Apparently its a regression in 3.2.5, too: https://github.com/rails/rails/issues/6591 A: I arrived here from a google search for a similar problem. It wasn't related to the Rails version, but I found out after some debugging that I was assigning a Time object with milliseconds. When calling changed, I got back and array of seemingly identical objects, since it got converted to DateTime's. Not sure if this can be considered a bug in Rails or not, but in case you end up with the same problem, check that you aren't assigning datetime's with milliseconds in them.
{ "language": "en", "url": "https://stackoverflow.com/questions/5845798", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "6" }
Q: Accessing the DOM representation of a template instance that is calling a helper I am trying to access a DOM element corresponding to the particular template instance that is calling a helper function. As I read the Meteor documentation, Template.instance() should return the template instance object that called the helper, and something like Template.instance().$() would allow me to grab DOM elements within that instance. However, the following code (and similar variations) is not working for me: * HTML * <template name="input_container"> <div class="small-12 medium-12 large-6 columns empty {{isActive}}"></div> </template> * JS * Template.input_container.helpers({ isActive: function() { if (Template.instance().$('.empty') && [some Session variable logic] { return 'active'; } } }); When I do something like: if (some Session logic) { console.log(Template.instance()) } I get the helper properly logging multiple versions of: Blaze.TemplateInstance {view: Blaze.View, data: 7, firstNode: div.small-12.medium-12.large-6.columns.empty.active-container, lastNode: div.small-12.medium-12.large-6.columns.empty.active-container, $: function…} (With data: values going from 1-12 appropriately, but otherwise each seems to be the same) How do I get from this to being able to used the template methods such as template.$ or template.find? EDIT: While not a perfect solution, I did manage to work around some of these issues by using Template.currentData() and setting an identifier on each instance of the input. Template.create_form.helpers( # Create 12 input containers inputContainer: () -> [0..11] And then: Template.input_container.helpers( isActive: () -> # Get which template instance we are working with, will return the number 0-11 that was used to create it current = Template.currentData() # Now I can do $(".input-container").eq(current) to grab the correct DOM element ) But it seems a little dirty to need to use so much jQuery. A: I'm not sure if I've interpreted the question correctly, but if you're trying to access another DOM element on the page - I was able to use a jquery selector. For example, given html of <input type="textfield" id="initials" value=" "> and a simple meteor template of <template name="demo"> <input type="button" div id="s0"> </template> I can successfully access the initials field when the s0 button is clicked as follows Template.demo.events({ 'click .cell': function(event, template) { if ($('#initials').val().trim().length > 0) { console.log($('#initials').val().trim() + ' - you clicked button '+$(event.target).attr('id')); } },
{ "language": "en", "url": "https://stackoverflow.com/questions/26749652", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: SSO with Classic Asp I am in the process of trying to implement Single Sign On for our classic asp parts of our site that run on a separate server. I have already implemented the php SSO on our other server using simpleSAMLphp. I am attempting to use shibboleth right now for the classic asp / IIS side of things. I have made it as far as getting to the login page of our Identity Provider, but once I authenticate I get stuck at /SAML2/POST and a webpage saying that the ip address of my server cannot be found. I have tried implementing fixes I found in forums but still have not made any progress. I am wondering if there is another tool that I could try to implement SSO with classic asp with? I am open to any suggestions at this point. A: Shibboleth supports IIS using "native module" package (iis7_shib.dll). Check this https://wiki.shibboleth.net/confluence/display/SP3/IIS for further information.
{ "language": "en", "url": "https://stackoverflow.com/questions/51070145", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "2" }
Q: Google Analytics referral exclusions do not seem to work when using the Google Tag Manager script Two days ago I added 'paypal.com' to the referral exclusions on the google analytics account for my website. My website is submitting its data to GA via google tag manager. So far, yesterday's visits are not excluding paypal as referral. Do you know if the process of setting the referral exclusions with google tag manager is different than it is for google analytics? do you know how long do the referral exclusions settings take to have any effect? A: I sorted this out by implementing the referral exclusion in javascript, right before the gtm tag: var previousReferrer = Cookies.get("previous_referrer") if(document.referrer.match(/paypal\.com/)) Object.defineProperty(document, "referrer", {get : function(){ return previousReferrer; }}); Cookies.set("previous_referrer", document.URL); please notice that as it is hard to change the document.referrer variable we need to use defineProperty and that this only works in modern browsers (safari <=5, Firefox < 4, Chrome < 5 and Internet Explorer < 9 ): How to manually set REFERER header in Javascript?
{ "language": "en", "url": "https://stackoverflow.com/questions/32614542", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Why is my relation-object reinitialized each time it is accessed? I use Realm Swift 0.95.3. In my project I'm working with a contact (not with contacts AddressBook), which contain information about the name, last name, middle name, email, … and photograph. I have created a subclass of Object called Contact. I understand that the image, or any other binary data, should not be stored in the Realm. Especially as my images could be large enough ~5 Mb. In any case, I wanted to store the image in the file system, and Realm stores only a link to this image. I thought that in the future I may need to attach other files (audio, PDF, …) to subclasses of Object. So I decided to create a separate class File, which is inherited from Object. The whole structure looks like. class File: Object { dynamic var objectID = NSUUID().UUIDString private var filePath: String { let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) let documentsDirectory = paths[0] as NSString return documentsDirectory.stringByAppendingPathComponent(objectID) } lazy var fileData: NSData? = { return self.readFile() }() override static func primaryKey() -> String? { return "objectID" } override static func ignoredProperties() -> [String] { return ["fileData"] } override func copy() -> AnyObject { let result = File(value: self) result.objectID = NSUUID().UUIDString result.fileData = fileData?.copy() as? NSData return result } } extension File { //MARK:- private func readFile() -> NSData? { let lFilePath = filePath print("Try to read file \(lFilePath)") return NSData(contentsOfFile: lFilePath) } private func writeFileWithFileData() { if let lFileData = fileData { lFileData.writeToFile(filePath, atomically: true) print("File \(filePath) was created") } else { removeFile() } } private func removeFile() { do { try NSFileManager.defaultManager().removeItemAtPath(filePath) print("File \(filePath) was removed") } catch { print(error) } } } As you can see, when trying to get the property fileData, data is received from the file system. Moreover fileData is declared with the keyword lazy, that is, I wish that the data is requested from disk to cache in this property. If this property is changed, the File object before saving to the database, I call writeFileWithFileData (), and data on the disk is overwritten. This system works as I need to, I to experiment. Then I created a Contact. class Contact: Object { dynamic var objectID = NSUUID().UUIDString dynamic var firstName = "" dynamic var lastName = "" ... private dynamic var avatarFile: File? var avatar: UIImage? { get { guard let imageData = avatarFile?.fileData else { return nil } return UIImage(data: imageData) } set { avatarFile = File() guard let imageData = newValue else { avatarFile?.fileData = nil return } avatarFile?.fileData = UIImagePNGRepresentation(imageData) } } override static func primaryKey() -> String? { return "objectID" } override static func ignoredProperties() -> [String] { return ["image"] } } The problem is that when I choose a contact from the database, and am trying to get the avatar, then access to the file system occurs every time you access this property. That is, property fileData does not operate as lazy - as I thought at first. But then I looked at the memory address properties avatarFile, each time it is received, the address has changed. From this I can conclude that the object avatarFile is constantly requested from the database again, with any reference to this property. As a consequence, all its ignoredProperties are reset. * *Why is the relation-object reinitialized each time it is accessed? *Share your opinion about my arch A: * *It should be fine. Realm Objects are live links to their parent Realm object, not static copies, so their addresses do periodically change. This is normal, and the objects aren't getting re-allocated so you shouldn't see any memory issues here. As far as I'm aware, NSData itself is lazy, so the data won't actually be read until you explicitly request it. *Your architecture looks good! You're right in that it's usually not the best form to store file data directly inside a Realm file, but you've done a good job at making the Realm Object manage the external file data as if it was. :)
{ "language": "en", "url": "https://stackoverflow.com/questions/33586433", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How to retain specific parts of an element in a column and eliminate everything else in R? I have a column containing the brand and model of cars. How to keep only the brand and remove the model? In the original dataset, the brand and the mode were separated by a space. So I tried this: carprice$CarName=gsub(pattern = " *", replacement = "",carprice$CarName) What happened was the space got eliminated and now the brand and the model names are concatenated. I am not able to even undo it.
{ "language": "en", "url": "https://stackoverflow.com/questions/47445403", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: How do I reverse a string in java by creating a new temporary string? What's the error in the following code? I am not able to identify it shows the index 0 out of bounds exception. public class stringBuilders{ public static void main(String[] args) { StringBuilder str = new StringBuilder("Shubham"); StringBuilder str2= new StringBuilder(); int j=0; for(int i = str.length()-1; i>=0 ; i--) { str2.setCharAt(j++,str.charAt(i)); } System.out.print(str2); } } A: As you are already iterating from end to start you can just append the characters to the fresh and empty string builder. setChar() is only intended to replace existing characters. public class StringBuilders { public static void main(String[] args) { String str = "Shubham"; StringBuilder str2 = new StringBuilder(); for (int i = str.length() - 1; i >= 0; i--) { str2.append(str.charAt(i)); } System.out.println(str2.toString()); } } gives $ java StringBuilders.java mahbuhS A: You haven't declared a value to the str2 string. The for loop is trying to find a character at index j=0 in str2 to set value i of str2, which it cannot find. Hence the error. For this to work, you need declare a value of str2 to a length >= str1. i.e., if str1 = "0123456", str2 should be at least 0123456 or more. Instead of using StringBuilder to set the char, you can use String to just append to it. String str1 = new String("Shubham"); String str2 = new String(); int iter = str1.length() -1; for(int i=iter; i>=0; i--) { str2 += str1.charAt(i); } System.out.println(str2)
{ "language": "en", "url": "https://stackoverflow.com/questions/72087427", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Exporting Result Set to Another Table? How can you export a result set given by a query to another table using SQL Server 2005? I'd like to accomplish this without exporting to CSV? A: INSERT INTO TargetTable(Col1, Col2, Col3) SELECT Col1, Col2, Col3 FROM SourceTable A: insert into table(column1, columns, etc) select columns from sourcetable You can omit column list in insert if columns returned by select matches table definition. Column names in select are ignored, but recommended for readability. Select into is possible too, but it creates new table. It is sometimes useful for selecting into temporary table, but be aware of tempdb locking by select into. A: SELECT col1, col2, ... INTO dbo.newtable FROM (SELECT ...query...) AS x;
{ "language": "en", "url": "https://stackoverflow.com/questions/7391075", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Handling pagination with Blogger Api I understand the documentation regarding the nextPageToken and retrieving subsequent pages. My question-- what is the best practice to implement a way to go to the PREVIOUS page?
{ "language": "en", "url": "https://stackoverflow.com/questions/44121387", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to get parent id with jQuery? $('td').click(function() { myId = $(this).parent().attr("id"); myItem = $(this).text(); alert('u clicked ' + myId); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <table> <tr> <td>Computer</td> </tr> <tr> <td>maths</td> </tr> <tr> <td>physics</td></div> </tr> </table> When I click on table item I want to get alert 'u clicked science' but I get undefined. Any help would be appreciated! A: There are no id attributes in your markup. All you are dealing with is innerText $('td').click(function() { var myItem = $(this).text(); alert('u clicked ' + myItem); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <table> <tr> <td>Computer</td> </tr> <tr> <td>maths</td> </tr> <tr> <td>physics</td> </tr> </table> A: You have invalid markup. extra closing div is added after last tr closing markup. you need to remove it. what you need to alert is text of element and not parent id. use .text() along with clicked td elements jquery context: $('td').click(function(){ myItem=$(this).text(); alert('u clicked ' +myItem); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script> <table> <tr><td>Computer</td></tr> <tr><td>maths</td></tr> <tr><td>physics</td></tr> </table> A: try this: $('td').click(function () { alert('u clicked ' + $(this).text()); }); A: As I have already commented, you are missing ID in tr. I have added few more tds for demo. $('td').click(function() { var myId = $(this).parent().attr("id"); var myItem = $(this).text(); alert('u clicked ' + myId); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <table> <tr id="IT"> <td>Computer</td> </tr> <tr id="General"> <td>maths</td> <td>History</td> </tr> <tr id="Science"> <td>physics</td> <td>Chemistry</td> <td>Biology</td> </tr> </table>
{ "language": "en", "url": "https://stackoverflow.com/questions/34765497", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "-1" }
Q: Pyinstaller - ModuleNotFoundError: No module named 'cpuinfo' I'm trying to package this script but I keep getting this error message Traceback (most recent call last): File "systeminfo.py", line 1, in <module> ModuleNotFoundError: No module named 'cpuinfo' [6308] Failed to execute script systeminfo I tried this into cmd pyinstaller -F --hidden-import="cpuinfo" systeminfo.py I'm on the latest version of pyinstaller and pip. This is the import section of my file: import psutil, platform, GPUtil, cpuinfo, os, sys, wmi, winreg, getpass from tabulate import tabulate from datetime import datetime When I run it, it just opens up and closes out. But when I run it through CMD, that's when I get that error message. How do I fix this? I want to include all the modules so I can run this script on different computers that don't have python installed. EDIT: I fixed this issue by using this thread: Pyinstaller 'failed to execute' script I use pycharm so this worked for me. The only issue is whenever the CMD opens up, nothing happens. The only thing that can printed is if I hardcode a print(). Functions aren't working at all. A: fix it with : pip install py-cpuinfo
{ "language": "en", "url": "https://stackoverflow.com/questions/66034639", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: What should I learn first? (For web programming) Should I learn PHP or JQuery.I have some knowledge in HTML CSS and JavaScript. A: Modern web development is now actually divided in to two major parts * *Frontend (JavaScript and related things) *Backend (PHP, NodeJS or others) Now if you are more interested in designing the User Interface and what shows on the screen, then go forward to HTML and then JavaScipt and then JQuery (which is an opensource library in JavaScript) and then CSS. However if you are interested in Backend (means server side coding, databases and business logics etc) then you should target PHP or any other suitable server side language. Bonus: If you are interested in starting things quickly, I would recommend that start learning JavaScript first, because there is a server side technology named NodeJS (which does almost all the work PHP does) and it uses JavaScript. So in that case, you only will have to learn JavaScript and CSS. A: They are for different purposes. JQuery is for Front End, that means, what will run on users's browsers. The same goes for HTML and CSS. PHP is what will run on the server. If you are extremely newbie, just as I was a few years ago, you might want to learn them all at the same time. Also, SQL, as it is the language for databases. This site is for beginners: http://www.w3schools.com/
{ "language": "en", "url": "https://stackoverflow.com/questions/35777107", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Unity custom UI Messagebox I am trying to make a custom messagebox to display text that characters say throughout my game. I tried to achieve this through this code: [SerializeField] public Text PresetText; [SerializeField] public GameObject PresetBorder; [SerializeField] public GameObject Canvas; private Text UIText; private Text _tempText; private GameObject _tempBorder; public static bool TEXT_INPUT; public string text = "Placeholder."; void Start () { _tempBorder = Instantiate(PresetBorder as GameObject); _tempBorder.transform.SetParent(Canvas.gameObject.transform, false); _tempText = Instantiate(PresetText) as Text; _tempText.transform.SetParent(Canvas.gameObject.transform, false); UIText = _tempText; UIText.text = text; } public void SetText ( string _text ) { text = "Speech: " + _text; } void Update () { UIText.text = text; } ... and I am calling the SetText () function through this in a dummy file: public MessageShell m; void Start () { m.SetText("Test!"); } (MessageShell because my code file is named MessageShell.cs) The problem is if I call this, an empty border with no text appears. How do I fix this and could I improve this script? A: First thing that I would do is to figure out where the problem lies. Is the text created? Where does it actually appear? Run the game, and look at the game object view to see what is happening for these objects. My second observation is that you probably want the text to be parented to the border. This allows the border to adequately manage the text, and how it laid out. They should go together. Lastly, take a look at LayoutGroups. If your border has a layout group, then it should adjust it's size (Or adjust the size of it's children) to match the text as you want it to be.
{ "language": "en", "url": "https://stackoverflow.com/questions/34725537", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: VS2008 keeps hanging busy when clicking design view VS2008 express web developer keeps hanging whenever I try to go to design mode. this just started a couple days ago for some reason, was fine before. whenever i click design mode, the whole thing freezes, any clicks anywhere on the program give me a 'ding' sound until i end task in task manager. usually there's no error to see, though sometimes i'll see some error in the status update about jquery intellisense problems loading, the thing is that this happens even on a brand new project and default.aspx with no jquery attached. any ideas? this is very frustrating, i can no longer work. multiple uninstalls and fresh installs have done nothing to help. A: VS gets hang many times when we click on its design page (aspx) and it dies. This issue can be solved by following these steps – 1. Go to control Panel 2. Add or Remove programs 3. Find Microsoft Visual Studio Web Authoring Component. 4. Click on change and then click Repair. 5. Restart your system and hopefully your problem will get solved.  A: It might be the ToolBox refreshing itself. Try this tip: http://weblogs.asp.net/stevewellens/archive/2009/07/23/speed-up-the-visual-studio-toolbox.aspx A: There is a good resolution on MSDN blog. Follow the link below: Troubleshooting "Visual Studio 2008 Design view hangs" issues A: This link fixed my hang problem: https://blogs.msdn.microsoft.com/amol/2009/07/23/visual-studio-2008-hangs-on-switching-to-design-view/ Run regedit.exe and look for HKEY_LOCAL_MACHINE\Software\Microsoft\Office\12.0\Common\ProductVersion key. If key is missing, add it and set “LastProduct” value to 12.0.4518.1066. Restart the machine after this step. Also, you can try repair "Microsoft Visual Studio Web Authoring Component" in programs and features.
{ "language": "en", "url": "https://stackoverflow.com/questions/4870020", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: Twig: mapping array to table I need to have such output -------------------------------- | | id1 | id2 | id ... | -------------------------------- | m1 | x1,x2 | x3 | x5 | -------------------------------- | m2 | x4 | x6,x7 | ... | -------------------------------- |m...| ... | ... | ... | -------------------------------- where "x" is unique, "m" and "id" are not unique; each row in object array returns m,x,id values how can I map such array using other array to have above result? main problem is to map first row as header and then make x'es to sort based on column header. I know how to use nested loop in Twig but have no idea how to prepare array with data. results from database can be sorted by any of this values if needed.
{ "language": "en", "url": "https://stackoverflow.com/questions/21919149", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "1" }
Q: How to uninstall an older PHP version from centOS7 My project is on Laravel 5.2. and as per guide it required php >= 5.5.6 but there was php 5.4 intalled and I had to upgrade php version through YUM, But now it is giving error "PDO driver not found" and I tried YUM install php-pdo but it's giving error that "there is conflict between php56w-common and php-comon-5.4.16". I am stuck on this point A: yum -y remove php* to remove all php packages then you can install the 5.6 ones. A: Subscribing to the IUS Community Project Repository cd ~ curl 'https://setup.ius.io/' -o setup-ius.sh Run the script: sudo bash setup-ius.sh Upgrading mod_php with Apache This section describes the upgrade process for a system using Apache as the web server and mod_php to execute PHP code. If, instead, you are running Nginx and PHP-FPM, skip ahead to the next section. Begin by removing existing PHP packages. Press y and hit Enter to continue when prompted. sudo yum remove php-cli mod_php php-common Install the new PHP 7 packages from IUS. Again, press y and Enter when prompted. sudo yum install mod_php70u php70u-cli php70u-mysqlnd Finally, restart Apache to load the new version of mod_php: sudo apachectl restart You can check on the status of Apache, which is managed by the httpd systemd unit, using systemctl: systemctl status httpd
{ "language": "en", "url": "https://stackoverflow.com/questions/43537523", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "21" }
Q: Implementing a second battleship into a one dimensional game "River Battleship" Would anybody be able to offer me a simple way to implement a second enemy battleship into a game I have designed to only have one enemy, this is my code currently : import java.util.*; //Scanner that reads user input public static void main(String[] arg) { int riverLength = promptForInt("Select Length for River ") ; //Variable that stores the user input when prompted int [] shipArray = new int[riverLength] ; //User input is used to create an Array, i.e. River Size int battleshipCoordinates = new Random().nextInt(riverLength) ; //Random number is found within the Array (Where the enemy ship will hide) shipArray[battleshipCoordinates] = 1 ; boolean hit = false ; //Statement created for ship hit and default to false int playerSelection; //int Variable declared do { displayRiver (shipArray, false); playerSelection = promptForInt(String.format("Select location to launch torpedo (1 - %d) ", riverLength)); playerSelection = playerSelection -1 ; if(shipArray[playerSelection] == 1 ) //if a user strikes the Enemy (Case 1) correctly they system informs them of a strike { System.out.println("Battleship Sunk!"); hit = true; displayRiver(shipArray, true); } else if(shipArray[playerSelection] == -1) { System.out.println("Location already Hit! Try again."); } else if(shipArray[playerSelection] == 0) { System.out.println("Miss!"); shipArray[playerSelection] = -1 ; } } while(!hit); } } A: Step 0 - Create a new battleship and place them on the array just like the first one. Step 1- Change your boolean hit to an int equaling 2. Step 2- Instead of toggling hit, reduce it by 1 when you hit a ship and then set that position on the array to a 0. Step 3- Adjust your logic so that you do not win unless hit < 1
{ "language": "en", "url": "https://stackoverflow.com/questions/58920194", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: React Native: GiftedChat only updating chat message if I scroll to top of screen? I'm using Gifted Chat for a chat app using React Native. When I send either a text message or an image, the code executes, but the new message does not appear on the screen unless I scroll to the top of the chat screen. If I scroll to the bottom, nope, and if I only scroll halfway up, still nope. Only when I scroll to the top of the screen does it update. Anyone understand why this could be happening? Here is my code. import React, { useState } from 'react'; import { Image, StyleSheet, Text, View, Button, FlatList, TouchableOpacity, Alert } from 'react-native'; import { GiftedChat } from 'react-native-gifted-chat'; const Conversation = (props) => { const chatId = props.chatId || "12345"; const userId = props.userId || "6789"; const [messages, setMessages] = useState([ { _id: 1, text: 'My message', createdAt: new Date(Date.UTC(2016, 5, 11, 17, 20, 0)), user: { _id: userId, name: 'Jane', avatar: 'https://randomuser.me/api/portraits/women/79.jpg', } }, { _id: 3, text: 'My next message', createdAt: new Date(Date.UTC(2016, 5, 11, 17, 21, 0)), user: { _id: 4, name: 'Gerry', avatar: 'https://randomuser.me/api/portraits/women/4.jpg', }, image: 'https://media1.giphy.com/media/3oEjHI8WJv4x6UPDB6/100w.gif', } ]); const d = Date.now(); const onSend = (msg) => { console.log("msg : ", msg); const message = { _id: msg[0]._id, text: msg[0].text, createdAt: new Date(), user: { _id: userId, avatar: "https://randomuser.me/api/portraits/women/79.jpg", name: "Jane" } } const arr = messages; arr.unshift(message); setMessages(arr); } return ( <GiftedChat messages={messages} onSend={newMessage => onSend(newMessage)} user={{ _id: userId, name: "Jane", avatar: "https://randomuser.me/api/portraits/women/79.jpg" }} /> ) } export default Conversation; A: Figured it out. GiftedChat requires that you use one of its own methods called append. const onSend = (msg) => { console.log("msg : ", msg); // first, make sure message is an object within an array const message = [{ _id: msg[0]._id, text: msg[0].text, createdAt: new Date(), user: { _id: userId, avatar: "https://randomuser.me/api/portraits/women/79.jpg", name: "Jane" } }] // then, use the GiftedChat method .append to add it to state setMessages(previousArr => GiftedChat.append(previousArr, message)); }
{ "language": "en", "url": "https://stackoverflow.com/questions/62379571", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: MixPanel: Should all property names be denoted with dollar signs? The built-in default properties of MixPanel such as $browser or $city all start with dollar signs. Does this have any purpose? Should we denote custom properties with dollar signs as well or is the dollar sign meant to be the marker for a default property? A: It would not be recommended to start all of your custom properties with the same dollar convention. The dollar sign convention is meant to denote properties that the Mixpanel SDKs track automatically or properties that have some special meaning within Mixpanel itself. That link you shared is great for the default properties and there is also documentation for the reserved user profile properties and reserved event properties if you were curious about those.
{ "language": "en", "url": "https://stackoverflow.com/questions/74391084", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }
Q: Google Sheets importxml() scraping doesn't work with xpath copied from console I am trying to scrape content from tradingview website. Specifically the Industry of a particular ticker given in the description. I have the xpath which I copied from the element inspector of the browser. But it doesn't seem to work and the output I get is "#N/A". The formula I have used is =IMPORTXML("https://www.tradingview.com/symbols/NSE-FINPIPE/", "//div[3]/div[3]/div/div[2]/div/div/div[1]/div[3]/div/div[2]/div/div[1]/div[2]/div[2]/a") A: IMPORTXML as well as IMPORTHMTL they can only see the source code, not the DOM shown on the web browser developer console. If the the content that you want to scrape is added to the DOM by client-side JavaScript or the web browser engine, it can't be scraped by using IMPORTXML.
{ "language": "en", "url": "https://stackoverflow.com/questions/49814399", "timestamp": "2023-03-29T00:00:00", "source": "stackexchange", "question_score": "0" }