id
stringlengths
5
11
text
stringlengths
0
146k
title
stringclasses
1 value
doc_23537500
struct dirent **Entries; DIR *Dir = opendir("/path/to/directory"); How would I record each entry into the Entries list, without calling realloc each iteration with a while loop. I need a faster way to record a list of items in a directory. Is there a faster way other than: struct dirent **Entries; DIR *Dir = opendir("/path/to/directory"); struct dirent *Entry; unsigned int Count = 0; while ((Entry = readdir(Dir))) { Count++; } Entries = malloc(Count*sizeof(char*)); closedir(Dir); Dir = opendir("Some dir path"); //Also, is there a better way to reset it, other than closing it and reopening? for (int i = 0; (Entry = readdir(Dir); i++) { Entries[i] = Entry; } Or struct dirent **Entries; DIR *Dir = opendir("/path/to/directory"); Dir = opendir("Some dir path"); struct dirent *Entry; for (int i = 0; (Entry = readdir(Dir); i++) { Entries = realloc(Entries, i*sizeof(struct dirent*)); Entries[i] = Entry; } closedir(Dir); Like, is there a direct way to get all the contents of a directory at once, or a better way to handle a growing buffer of entries? Help? Please?
doc_23537501
error_log off - doesnt works, just creates filename "off", really, not joke. error_log dev/null doesnt supports. OS freebsd. I need disable logging for subdomain. A: http://wiki.nginx.org/CoreModule#error_log From wiki Note that error_log off does not disable logging - the log will be written to a file named "off". To disable logging, you may use: error_log /dev/null crit; A: Set the logging to stderr (the redirect to /dev/null does not work reliably since from version 0.7.53 /var/log/nginx/error.log) is hardcoded to be used until the config file has been read (http://wiki.nginx.org/CoreModule#error_log). error_log stderr crit; Using /dev/null on systems where /var/log/nginx/* doesn't exist will cause nginx to quit. A: To disable NGINX access and error log for all latest NGINX version http { access_log off; error_log off; }
doc_23537502
VkResult (*vkCreateDebugUtilsMessengerEXT_NE)( VkInstance, const VkDebugUtilsMessengerCreateInfoEXT*, const VkAllocationCallbacks*, VkDebugUtilsMessengerEXT*); VkResult vkCreateDebugUtilsMessengerEXT(VkInstance instance, const VkDebugUtilsMessengerCreateInfoEXT* info, const VkAllocationCallbacks* callbacks, VkDebugUtilsMessengerEXT* messenger) { return vkCreateDebugUtilsMessengerEXT_NE(instance, info, callbacks, messenger); } void LoadeFunctions() { vkCreateDebugUtilsMessengerEXT_NE = (PFN_vkCreateDebugUtilsMessengerEXT) instance.getProcAddr( "vkCreateDebugUtilsMessengerEXT"); Assert(vkCreateDebugUtilsMessengerEXT_NE, "Failed to find extension function: vkCreateDebugUtilsMessengerEXT"); } I am wondering how to accomplish the same in rust using the ash bindings. A: Each extension supported by ash is provided by a struct in the ash::extensions module. For instance, VK_EXT_debug_utils is provided by ash::extensions::ext::DebugUtils. use ash::{extensions::ext::DebugUtils, Entry, Instance}; unsafe { let entry = ash::Entry::load().unwrap(); let instance = entry.create_instance(/* ... */).unwrap(); // Load `VK_EXT_debug_utils` extension. let debug_utils = DebugUtils::new(&entry, &instance); // Create a debug messenger. let debug_messenger = debug_utils .create_debug_utils_messenger(/* ... */) .unwrap(); } Loading an extension loads all the functions associated with that extension. You still need to enumerate the available extensions ahead of time, as loading an unsupported extension will not return an error. Instead, calling any functions of that extension will result in a panic at runtime.
doc_23537503
Duplicates are allowed, but there needs to be at least one. I am able to write the algorithm to go through all possibilities but the minimum of at least one of each of Z is the part I'm having trouble with. Looking to do this algorithm in java. Can someone help?
doc_23537504
Click here is you want to view the higher resolution of frame 5 or frame 0 Frame 0 means there is no rotation while frame 5 means it's rotated 5 degrees from frame 0. In each frame, there is a list of edge (2D) from delaunay triangulation (which is displayed as a mesh as you see). I also have list of edge (2D) from delaunay triangulation for frame 1 (rotate 1 degree from frame 0), frame 2, frame 3, frame 4. With these parameter, could anyone tell me how to generate image (bitmap) of frame 1, 2, 3,4 so that when scroll from frame 0 to frame 5, it looks smooth. Any help would be appreciated. -- A: I already answered your question on Google+ but I think it is a good idea to also post the answer right here for other people who will come up with a similar problem. The thing which is needed here is called 'optical flow'. There is a huge amount of information on the web about this topic but I want you to refere you to one lecture I visited in university: http://www.gris.tu-darmstadt.de/teaching/courses/ss11/cv1/index.en.htm The slides 'motion estimation' will give you a quick starting point about this topic but you definitely have to read additional literature. One of the literature mentioned on the course's website is available as free pdf and covers most of the basic understandings of computer vision. What you are trying to achieve will be difficult but absolutely possible. A: You can use a linear transformation from the mesh. You can take the start and endpoint and use straight lines and multiple from the frames for the transformation. It uses in simple 3d animations and morphing.
doc_23537505
I'd like the compression to be enabled for: * */api/endpoint/123, */api/endpoint/456 but not for * *api/endpoint2/12, *api/endpoint/123/action, *api/endpoint/test I am sure that mod_deflate is enabled. My idea was to first disable gzip with no-gzip variable, and then remove the variable when URI matches a regular expression. My full .htaccess looks like this: <IfModule mod_deflate.c> SetOutputFilter DEFLATE SetEnv no-gzip 1 SetEnvIf Request_URI "/api/endpoint/\d+$" !no-gzip </IfModule> <IfModule mod_rewrite.c> <IfModule mod_negotiation.c> Options -MultiViews -Indexes </IfModule> RewriteEngine On # Handle Authorization Header RewriteCond %{HTTP:Authorization} . RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}] # Redirect Trailing Slashes If Not A Folder... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} (.+)/$ RewriteRule ^ %1 [L,R=301] # Send Requests To Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] </IfModule> Another idea was to add a new RewriteRule (before the last one): RewriteCond %{REQUEST_URI} !^/api/endpoint/\d+$ RewriteRule ^ - [E=no-gzip:1] Unfortunately none of this work and no response is compressed... A: SetEnv no-gzip 1 SetEnvIf Request_URI "/api/endpoint/\d+$" !no-gzip SetEnv and SetEnvIf belong to separate Apache modules (mod_env and mod_setenvif respectively). mod_setenvif is processed before mod_env, despite the apparent order of the directives in the config file, so the above will always set no-gzip to 1. Try using mod_setenvif instead to initialise the no-gzip env var: SetEnvIf ^ ^ no-gzip This sets no-gzip to 1 (default) essentially unconditionally (for any request header). (Unfortunately, I think this is the most minimal way to unconditionally set an env var using mod_setenvif.) Aside: You should perhaps anchor the regex at the start of the URL-path: "^/api/endpoint/\d+$" UPDATE: # Send Requests To Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [L] Since you are using mod_rewrite to rewrite the URL, the rewriting process starts over and the no-gzip env var would get renamed to REDIRECT_no-gzip. You can prevent the rewrite engine starting over by using the END flag instead of L in the last rule (requires Apache 2.4).
doc_23537506
What i've done so far , is check if there are Points on the Plane, that is created by 2 Vectors of the Triangle. The Problem is now to check, if the Point is inside the Triangle.I use barycentric Coordinates Vec3 AB = b_-a_; Vec3 AC = c_-a_; double areaABC = vec_normal_triangle.dot(AB.cross(AC)); Vec3 PB = b_-intersection.pos; Vec3 PC = c_-intersection.pos; double alpha = vec_normal_triangle.dot(PB.cross(PC)); Vec3 PA = a_-position.pos; double beta = vec_normal_triangle.dot(PC.cross(PA)); double gamma = 1-alpha-beta; if((beta+gamma) < 1 && beta > 0 && gamma > 0) { return true; } Actually its not even a triangle, just about random Points. Can someone explain me or knows how i compute the barycentric Coordinates for 3 given Vectors? A: Assuming vec_normal_triangle is the vector computed as AB.cross(AC) normalized (in other words, the triangle's normal), you should divide alpha and beta by areaABC to get the barycentric coordinates of the intersecton point. double alpha = vec_normal_triangle.dot(PB.cross(PC)) / areaABC; and double beta = vec_normal_triangle.dot(PC.cross(PA)) / areaABC; This normalizes alpha and beta so that your computation of gamma and comparison against 1 make sense. I'd also like to make a suggestion. To avoid recomputation and make the code a bit cleaner you could replace your test with the following. if(alpha > 0 && beta > 0 && gamma > 0) { return true; } Aside from that, I see that you first use intersection.pos and then position.pos. Is this intentional? My guess is that you need to use intersection.pos both times.
doc_23537507
Console.WriteLine("Enter Employee name"); string inputName = Console.ReadLine(); Employee [ inputName ] = new Employee(); A: If you have the following class: public class Employee { public string FirstName { get; set; } public string LastName { get; set; } } You can create a new instance of the class and assign the FirstName property like this: Employee newEmployee = new Employee() { FirstName = "Joe" }; or like this: Employee newEmployee = new Employee(); newEmployee.FirstName = "Joe"; or... if there's a rule that you shouldn't be able to make an instance of the employee class without supplying the first name, then you add a constructor to your class: public class Employee { private string firstName; public Employee(string FName) //constructor { firstName = FName; } public string FirstName { get { return firstName; } set { firstName = value; } } public string LastName { get; set; } } A: use dictionnary, inputname as key and Employee as value Dictionnary<String,Employee> employees = new Dictionnary<String,Employee>(); string inputname=Console.ReadLine(); employees[inputname]=new Employee();
doc_23537508
I looked at the component's documentation and did not find anything related, in my case i need to show the file only on client-side operation (i already got the file on server-side) Looking at the component's library i notice that when we click on "add file", the component uses the following syntax to create file on list: $(<component_name>).component.add(this) But i've tried create a class of object with the atributes "fileName", "state" etc (just like the documentation says) and insert when click on js script, but still didn't work. Anyone has any ideia of how to solve my problem? Thank's. PS: I'm using richfaces 3.3. A: To everyone interested, I could not find a way to insert default file on the component, but i found a workaround for this problem. I just remove the native list with "listHeight=0" and develop my own list using datatables.
doc_23537509
NavController (in MainActivity.java) // set up navigation navController = Navigation.findNavController(this, R.id.nav_host_fragment); NavigationUI.setupWithNavController(binding.navView, navController); // top level dest Set<Integer> topLevelDest = new HashSet<>(); topLevelDest.add(R.id.nav_foo); topLevelDest.add(R.id.nav_bar); appBarConfiguration = new AppBarConfiguration.Builder(topLevelDest).setDrawerLayout(binding.drawerLayout) .build(); NavigationUI.setupWithNavController(binding.toolbar.toolbar, navController, appBarConfiguration); Here is my MainActivity.xml which includes a Drawerlayout, NavHostFragment, and CustomToolbar: <androidx.drawerlayout.widget.DrawerLayout android:id="@+id/drawer_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:fitsSystemWindows="true" tools:openDrawer="start"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <include android:id="@+id/toolbar" layout="@layout/toolbar" /> <fragment android:id="@+id/nav_host_fragment" android:name="androidx.navigation.fragment.NavHostFragment" android:layout_width="match_parent" android:layout_height="match_parent" app:defaultNavHost="true" app:navGraph="@navigation/drawer_navigation" /> </LinearLayout> <com.google.android.material.navigation.NavigationView android:id="@+id/nav_view" android:layout_width="wrap_content" android:layout_height="match_parent" android:layout_gravity="start" android:fitsSystemWindows="true" app:menu="@menu/drawer_menu" /> </androidx.drawerlayout.widget.DrawerLayout> And here is my Navigationgraph: <navigation xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/drawer_navigation" app:startDestination="@id/nav_foo"> <fragment android:id="@id/nav_foo" android:name="FooFragment" tools:layout="@layout/fragment_foo"/> <fragment android:id="@id/nav_bar" android:name="BarFragment"> </fragment> <fragment android:id="@+id/nav_A" android:name="AFragment" tools:layout="@layout/fragment_A" /> </navigation> I can acces the spinner in MainActivity via binding.toolbar.spinner Now I would like to pass the selection of the spinner (int) in the toolbar to the fragment_A, which is also a DrawerNav-Entry but no toplevel destination. Is this even possible? I temporarly solved it over shared-preferences Regards
doc_23537510
This is the error I am seeing: npm ERR! Windows_NT 6.1.7601 npm ERR! argv "C:\\Program Files\\nodejs\\node.exe" "C:\\Program Files\\nodejs\\node_modules\\npm\\bin\\npm-cli.js" "insta ll" "-g" "protractor" npm ERR! node v6.11.1 npm ERR! npm v3.10.10 npm ERR! code E404 npm ERR! 404 Registry returned 404 for GET on https://registry.npmjs.org/@types%2fnode npm ERR! 404 npm ERR! 404 '@types/node' is not in the npm registry. npm ERR! 404 You should bug the author to publish it (or use the name yourself!) npm ERR! 404 It was specified as a dependency of 'protractor' npm ERR! 404 npm ERR! 404 Note that you can also install from a npm ERR! 404 tarball, folder, http url, or git url. npm ERR! Please include the following file with any support request: npm ERR! C:\protractor\npm-debug.log I've tried installing @type/node directly, but that fails with the same error. I've tried downloading Typescript directly (and successfully), but that does not seem to satisfy the protractor installation. What am I missing here? Is this package just not available right now (i.e. broken), it was updated 3 days ago, according to npm. https://www.npmjs.com/package/@types/node A: In my previous company we were using Nexus 2 with the private NPM repo as an option. All npm traffic went through Nexus, but it couldn't handle @types because is was supported Inna newer version / update. It gave the same error. Are you also using a setup for a Private repo? A: I had the same problem while installing native scripts. Try using the following commands: * *set http *set http_proxy= This will help you.
doc_23537511
Basically I have a webreference that I send an XDocument to System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); Byte[] baXml = encoding.GetBytes(xdoc.ToString()); object o = MEF_Test.NewSubmission("*********", "*********", baXml); The transmission is successful and I get back what I assume is the xml document and I am trying to go back to an XDocument. I convert my object to a byte array Byte[] baResponse = ObjectToByteArray(o); I put this function in at the bottom but it may be where there error is at The object I get back is 10492 characters but gets bigger by 28 bytes to the size of 10520 after conversion string ss = Encoding.UTF8.GetString(baResponse); string ss1 = ss.Substring(28); XDocument xSubmissionResponse = XDocument.Parse(ss1); In the screenshot you can see the extra characters and I attempt to get past them by getting the substring past them. The string then looks good but then throws an exception about a hexadecimal value 0x0B further ahead in the string. Can anyone give this a look? Thanks. --Screenshot with as much info as possible I don't have the reputation to stick the image in I hope the link works. private static byte[] ObjectToByteArray(Object obj) { if (obj == null) return null; BinaryFormatter bf = new BinaryFormatter(); MemoryStream ms = new MemoryStream(); bf.Serialize(ms, obj); return ms.ToArray(); } A: o is already an array of bytes (as seen in the debugger). Deserializing it again makes no sense. Just cast object o to byte[] and then run the Encoding.GetString method on it.
doc_23537512
There are three classes. FirstWindow class: import javax.swing.JFrame; import javax.swing.JButton; public class FirstWindow extends JFrame { public static final int WIDTH = 300; public static final int HEIGHT = 200; public FirstWindow() { super(); setSize(WIDTH, HEIGHT); setTitle("First Window Class"); setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE); JButton endButton = new JButton("Click to end program."); endButton.addActionListener(new EndingListener()); add(endButton); } } EndingListener class: import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class EndingListener implements ActionListener { public void actionPerformed(ActionEvent e) { System.exit(0); } } DemoWindow class (the one with the main method): public class DemoWindow { public static void main(String[] args) { FirstWindow w = new FirstWindow(); w.setVisible(true); } } When I try to compile DemoWindow, I get: DemoWindow.java:5: error cannot find symbol FirstWindow w = new FirstWindow(); ^ symbol: class FirstWindow location: class DemoWindow DemoWindow.java:5: error cannot find symbol FirstWindow w = new FirstWindow(); ^ symbol: class FirstWindow location: class DemoWindow 2 errors When I try to compile FirstWindow specifically, I get: FirstWindow.java:18: error: cannot find symbol endButton.addActionListener(new EndingListener()); ^ symbol: class EndingListener location: class FirstWindow 1 error When looking around for a solution, the only issue I saw answered was something along the lines of an improper import statement (import java.awt.* or the likes). Can someone help me figure out what exactly went wrong? The compiling issue has been solved. I had to compile all classes in bulk. My new issue is that after compiling, I get an error when I try to run DemoWindow. Error: Could not find or load main class DemoWindow All files are in one directory.
doc_23537513
I will be using NUnit to do this testing. Is it as simple as creating a test project, adding the service to it and then create a test class and instance of that service..then start creating your test methods? I need to test both the .asmx and .asmx.cs methods (unit test the methods) so that I know if I pass this to a teammate that it's going to work. Maybe it's not possible to test an .asmx.cs directly and I'll just have to test via integration tests. I guess what I really would need is to mock my .asmx. Probably not possible. A: The best practice of a Unit test is not to test the asmx file, but the parts (units) behind the asmx file. If you can split up your code in small and separate pieces, then you can unit test those pieces. If you want to test the asmx file itself, you're talking about an integration test. You can use NUnit for that in the way you described, but that's not really unit testing. A: You might be missing the point of what other people are saying. The .asmx file should have no logic worth testing. If it truly is just a wrapper around business layer calls, then it adds nothing and doesn't need to be tested. If it does add something, extract that until the .asmx contains nothing but a pass-through call. What does your .asmx file contain that cannot be extracted into separate, testable classes? A: Unfortunately this is a problem with .asmx web services, they are dependent on ASP.net, you're best approach would be to keep the .asmx web service as a stub and extract your web service logic into a clean dependency-free class and unit test that instead. The other alternative is to run Integration tests as well. In the long run, if unit testing is important to you, you may be better off developing using a web service framework that was designed with unit testing from the start. A: Like Lodewijk stated, it is best practice to not unit test the asmx file. Instead, extract the logic from that file into class files which handle the behavior you are after. That way you can then unit test those classes in isolation from the UI. You may find that the real problem you have is that there is too much business logic in your UI layer. If you want to test the asmx file itself you'll either want to consider manual testing, integration testing, or acceptance testing...but if you can move your logic to the business layer you'll probably find it much easier to test.
doc_23537514
var userSchema = new mongoose.Schema({ name: {type: String,required: true,lowercase: true, trim: true}, email: {type: String, required : true, validate: validateEmail }, createdOn: { type: Date, default: Date.now }, lastLogin: { type: Date, default: Date.now } }); and this are my validation "rules" var isNotTooShort = function(string) { return string && string.length >= 5; }; var onlyLettersAllow = function(string) { var myRegxp = /^[a-zA-Z]+$/i; return myRegxp.test(string); }; To validate my name field I tried this: userSchema.path('name').validate(isNotTooShort, 'Is too short'); userSchema.path('name').validate(onlyLettersAllow, 'Only Letters'); and it works. Can I add multiple validation on a field in Schema? Something like: validate:[onlyLettersAllow,isNotTooShort] A: You can add more than one validation like this: var manyValidators = [ { validator: isNotTooShort, msg: 'Is too short' }, { validator: onlyLettersAllow, msg: 'Only Letters' } ]; var userSchema = new Schema({ name: { type: String, validate: manyValidators }, email: {type: String, required : true, validate: validateEmail }, createdOn: { type: Date, default: Date.now }, lastLogin: { type: Date, default: Date.now } }); A: answer: var isNotTooShort = function(string) { return string && string.length >= 5; }; var onlyLettersAllow = function(string) { var myRegxp = /^[a-zA-Z]+$/i; return myRegxp.test(string); }; var manyValidators = [ { validator: isNotTooShort, msg: 'Is too short' }, { validator: onlyLettersAllow, msg: 'Only Letters' } ]; var userSchema = new Schema({ name: { type: String, validate: manyValidators }, email: {type: String, required : true, validate: validateEmail }, createdOn: { type: Date, default: Date.now }, lastLogin: { type: Date, default: Date.now } }); another example : You can add more than one validation in mongoose like tags and use mongoose default validation like the name: const Course = mongoose.model('Course', mongoose.Schema({ name: { minLength: 5, maxLength: 50, type: String, required: true, }, tags: { type: Array, required: true, validate: [ { validator: function (v) { return v && v.length > 0 }, message: 'tags is required ...' }, { validator: function (v) { return v && v.length < 2 }, message: 'tags are too much ...' } ] }, date: { type: Date, default: Date.now } }))
doc_23537515
It seems that it doesn't dispatch DoubleClick-Events. For better understanding look at the following code: <s:VideoDisplay [..] doubleClickEnabled="true" doubleClick="{trace('VideoDisplay_DoubleClick')}" click="{trace('VideoDisplay_Click')}" /> <s:Panel [..] doubleClickEnabled="true" doubleClick="{trace('Panel_DoubleClick')}" click="{trace('Panel_Click')}" /> The Click-Event works for both components. But the DoubleClick-Event is only handled by the Panel-Component. Do you guys have any idea why? A: The documentation is here: http://www.adobe.com/livedocs/flex/3/langref/mx/controls/VideoDisplay.html#eventSummary In the events section. doubleClick "Dispatched when a user presses and releases the main button of a pointing device twice in rapid succession over the same InteractiveObject when that object's doubleClickEnabled flag is set to true. from InteractiveObject" If it doesn't work, then it's a bug. But, have you set your object's "doubleClickEnabled" flag to true? Oz 4dtext - website enhancement tools
doc_23537516
Here is the code: import com.jogamp.common.nio.Buffers; import com.jogamp.opengl.*; import com.jogamp.opengl.awt.GLCanvas; import com.jogamp.opengl.util.Animator; import org.joml.Matrix4f; import org.joml.Vector2f; import org.joml.Vector3f; import javax.swing.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.nio.FloatBuffer; import java.util.ArrayList; import java.util.List; import static com.jogamp.opengl.GL.*; public class WalkingTour extends JFrame implements GLEventListener, KeyListener { private static final int windowWidth = 800, windowHeight = 600; private static final String windowTitle = "Walking Tour"; private static final String vertexShaderFile = "src/walkingtour-vertex.glsl", fragmentShaderFile = "src/walkingtour-fragment.glsl"; private final GLCanvas glCanvas; private int renderingProgram; private final int[] vao = new int[1]; private final int[] vbo = new int[6]; private final FloatBuffer values = Buffers.newDirectFloatBuffer(16); private final Matrix4f pMat = new Matrix4f(); // perspective matrix private final Matrix4f vMat = new Matrix4f(); // view matrix private final Matrix4f mMat = new Matrix4f(); // model matrix private final Matrix4f mvMat = new Matrix4f(); // model-view matrix private int gTexture; private ImportedModel myModel; private int numObjVertices; private boolean keyPressedForward = false, keyPressedBackward = false, keyPressedMoveRight = false, keyPressedMoveLeft = false, keyPressedTurnRight = false, keyPressedTurnLeft = false, keyPressedSpace = false, keyPressedControl = false, keyPressedShift = false; private final ArrayList<Float> vertexValues = new ArrayList<>(); private final ArrayList<Float> stVals = new ArrayList<>(); private final ArrayList<Float> normalValues = new ArrayList<>(); private final ArrayList<Float> triangleVerts = new ArrayList<>(); private final ArrayList<Float> textureCoordinates = new ArrayList<>(); private final ArrayList<Float> normals = new ArrayList<>(); private List<float[]> vertices = new ArrayList<float[]>(); private List<int[]> faces =new ArrayList<int[]>(); public WalkingTour() { setTitle(windowTitle); setSize(windowWidth, windowHeight); glCanvas = new GLCanvas(new GLCapabilities(GLProfile.getMaxProgrammableCore(true))); glCanvas.addGLEventListener(this); this.add(glCanvas); this.setVisible(true); Animator animator = new Animator(glCanvas); animator.start(); } public static void main(String[] args) { new WalkingTour(); } @Override public void init(GLAutoDrawable glAutoDrawable) { myModel = new ImportedModel("hwk5Model.obj"); GL4 gl = (GL4) GLContext.getCurrentGL(); numObjVertices = myModel.getNumVertices(); Vector3f[ ] vertices = myModel.getVertices(); Vector2f[ ] texCoords = myModel.getTexCoords(); Vector3f[ ] normals = myModel.getNormals(); float[ ] pvalues = new float[numObjVertices*3]; // vertex positions float[ ] tvalues = new float[numObjVertices*2]; // texture coordinates float[ ] nvalues = new float[numObjVertices*3]; // normal vectors for (int i=0; i<numObjVertices; i++) { pvalues[i*3] = (float) (vertices[i]).x(); pvalues[i*3+1] = (float) (vertices[i]).y(); pvalues[i*3+2] = (float) (vertices[i]).z(); tvalues[i*2] = (float) (texCoords[i]).x(); tvalues[i*2+1] = (float) (texCoords[i]).y(); nvalues[i*3] = (float) (normals[i]).x(); nvalues[i*3+1] = (float) (normals[i]).y(); nvalues[i*3+2] = (float) (normals[i]).z(); } // VBO for vertex locations gl.glBindBuffer(GL_ARRAY_BUFFER, vbo[2]); FloatBuffer vertBuf = Buffers.newDirectFloatBuffer(pvalues); gl.glBufferData(GL_ARRAY_BUFFER, vertBuf.limit()*4, vertBuf, GL_STATIC_DRAW); // VBO for texture coordinates gl.glBindBuffer(GL_ARRAY_BUFFER, vbo[3]); FloatBuffer texBuf = Buffers.newDirectFloatBuffer(tvalues); gl.glBufferData(GL_ARRAY_BUFFER, texBuf.limit()*4, texBuf, GL_STATIC_DRAW); // VBO for normal vectors gl.glBindBuffer(GL_ARRAY_BUFFER, vbo[4]); FloatBuffer norBuf = Buffers.newDirectFloatBuffer(nvalues); gl.glBufferData(GL_ARRAY_BUFFER, norBuf.limit()*4,norBuf, GL_STATIC_DRAW); renderingProgram = Utils.createShaderProgram(vertexShaderFile, fragmentShaderFile); gTexture = Utils.loadTexture("groundTexture.jpeg"); gl.glActiveTexture(GL_TEXTURE0); gl.glBindTexture(GL_TEXTURE_2D, gTexture); float[] floor = { -2000.0f, -50.0f, -2000.0f, -2000.0f, -50.0f, 2000.0f, 2000.0f, -50.0f, 2000.0f, -2000.0f, -50.0f, -2000.0f, 2000.0f, -50.0f, -2000.0f, 2000.0f, -50.0f, 2000.0f, }; gl.glGenVertexArrays(vao.length, vao, 0); gl.glBindVertexArray(vao[0]); gl.glGenBuffers(vbo.length, vbo, 0); FloatBuffer corBuf = Buffers.newDirectFloatBuffer(floor); gl.glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); gl.glBufferData(GL_ARRAY_BUFFER, corBuf.limit() * 4L, corBuf, GL_STATIC_DRAW); float[] textureCoords = { 0f, 1f, 0f, 0f, 1f, 0f, 0f, 1f, 1f, 1f, 1f, 0f }; FloatBuffer textureBuffer = Buffers.newDirectFloatBuffer(textureCoords); gl.glBindBuffer(GL_ARRAY_BUFFER, vbo[1]); gl.glBufferData(GL_ARRAY_BUFFER, textureBuffer.limit() * 4L, textureBuffer, GL_STATIC_DRAW); this.addKeyListener(this); } @Override public void dispose(GLAutoDrawable glAutoDrawable) { this.removeKeyListener(this); } @Override public void display(GLAutoDrawable glAutoDrawable) { GL4 gl = (GL4) GLContext.getCurrentGL(); gl.glClear(GL_COLOR_BUFFER_BIT); gl.glClear(GL_DEPTH_BUFFER_BIT); gl.glUseProgram(renderingProgram); int mvLoc = gl.glGetUniformLocation(renderingProgram, "mv_matrix"); int pLoc = gl.glGetUniformLocation(renderingProgram, "p_matrix"); float aspect = (float) glCanvas.getWidth() / (float) glCanvas.getHeight(); pMat.identity().setPerspective((float) Math.toRadians(60.0f), aspect, 0.1f, 5000.0f); gl.glUniformMatrix4fv(pLoc, 1, false, pMat.get(values)); vMat.translate(0f,0f,0f); mvMat.identity(); mvMat.mul(vMat); mvMat.mul(mMat); gl.glUniformMatrix4fv(mvLoc, 1, false, mvMat.get(values)); gl.glBindBuffer(GL_ARRAY_BUFFER, vbo[0]); gl.glVertexAttribPointer(0, 3, GL_FLOAT, false, 0, 0); gl.glEnableVertexAttribArray(0); gl.glEnable(GL_DEPTH_TEST); gl.glDepthFunc(GL_LEQUAL); gl.glBindBuffer(GL_ARRAY_BUFFER, vbo[1]); gl.glVertexAttribPointer(1, 2, GL_FLOAT, false, 0, 0); gl.glEnableVertexAttribArray(1); gl.glBindTexture(GL_TEXTURE_2D, gTexture); gl.glDrawArrays(GL_TRIANGLES, 0, 6); gl.glDrawArrays(GL_TRIANGLES, 0, myModel.getNumVertices()); if (keyPressedForward) { vMat.translateLocal(0f, 0f, 0.1f); } if (keyPressedBackward) { vMat.translateLocal(0f,0f,-0.1f); } if (keyPressedMoveLeft) { vMat.translateLocal(0.1f,0f,0f); } if (keyPressedMoveRight) { vMat.translateLocal(-0.1f,0f,0f); } if (keyPressedTurnLeft) { vMat.rotateLocalY(-0.001f); } if (keyPressedTurnRight) { vMat.rotateLocalY(0.001f); } if (keyPressedSpace) { vMat.translateLocal(0f,-0.1f,0f); } if (keyPressedControl) { vMat.translateLocal(0f,0.1f,0f); } if (keyPressedForward && keyPressedShift){ vMat.translateLocal(0f,0f,0.2f); } } @Override public void reshape(GLAutoDrawable glAutoDrawable, int i, int i1, int i2, int i3) { } @Override public void keyTyped(KeyEvent e) { //do nothing } @Override public void keyPressed(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_W) { // Move camera forward keyPressedForward = true; } else if (keyCode == KeyEvent.VK_DOWN || keyCode == KeyEvent.VK_S) { // Move camera backward keyPressedBackward = true; } else if (keyCode == KeyEvent.VK_LEFT || keyCode == KeyEvent.VK_A) { // Move camera to the left keyPressedMoveLeft = true; } else if (keyCode == KeyEvent.VK_RIGHT || keyCode == KeyEvent.VK_D) { // Move camera to the right keyPressedMoveRight = true; } else if (keyCode == KeyEvent.VK_HOME || keyCode == KeyEvent.VK_Q) { // Turn camera to the left keyPressedTurnLeft = true; } else if (keyCode == KeyEvent.VK_PAGE_UP || keyCode == KeyEvent.VK_E) { // Turn camera to the right keyPressedTurnRight = true; } else if (keyCode == KeyEvent.VK_SPACE) { // Move camera up keyPressedSpace = true; } else if (keyCode == KeyEvent.VK_CONTROL) { // Move camera down keyPressedControl = true; } else if (keyCode == KeyEvent.VK_SHIFT) { //hold shift to "sprint" //can only sprint while forward buttons are pressed keyPressedShift = true; } } @Override public void keyReleased(KeyEvent e) { int keyCode = e.getKeyCode(); if (keyCode == KeyEvent.VK_UP || keyCode == KeyEvent.VK_W) { // Move camera forward keyPressedForward = false; } else if (keyCode == KeyEvent.VK_DOWN || keyCode == KeyEvent.VK_S) { // Move camera backward keyPressedBackward = false; } else if (keyCode == KeyEvent.VK_LEFT || keyCode == KeyEvent.VK_A) { // Move camera to the left keyPressedMoveLeft = false; } else if (keyCode == KeyEvent.VK_RIGHT || keyCode == KeyEvent.VK_D) { // Move camera to the right keyPressedMoveRight = false; } else if (keyCode == KeyEvent.VK_HOME || keyCode == KeyEvent.VK_Q) { // Turn camera to the left keyPressedTurnLeft = false; } else if (keyCode == KeyEvent.VK_PAGE_UP || keyCode == KeyEvent.VK_E) { // Turn camera to the right keyPressedTurnRight = false; } else if (keyCode == KeyEvent.VK_SPACE) { // Move camera up keyPressedSpace = false; } else if (keyCode == KeyEvent.VK_CONTROL) { // Move Camera down keyPressedControl = false; } else if (keyCode == KeyEvent.VK_SHIFT) { //hold shift to "sprint" keyPressedShift = false; } } } import org.joml.Vector2f; import org.joml.Vector3f; import java.io.*; import java.nio.file.Files; import java.util.ArrayList; public class ImportedModel { private Vector3f[ ] vertices; private Vector2f[ ] texCoords; private Vector3f[] normals; private int numVertices; public ImportedModel(String filename) { ModelImporter modelImporter = new ModelImporter(); try { modelImporter.parseOBJ(filename); // uses modelImporter to get vertex information numVertices = modelImporter.getNumVertices(); float[ ] verts = modelImporter.getVertices(); float[ ] tcs = modelImporter.getTextureCoordinates(); float[ ] norm = modelImporter.getNormals(); this.vertices = new Vector3f[numVertices]; this.texCoords = new Vector2f[numVertices]; this.normals = new Vector3f[numVertices]; for(int i=0; i<vertices.length; i++) { vertices[i] = new Vector3f(); vertices[i].set(verts[i*3], verts[i*3+1], verts[i*3+2]); texCoords[i] = new Vector2f(); texCoords[i].set(tcs[i*2], tcs[i*2+1]); this.normals[i] = new Vector3f(); this.normals[i].set(norm[i*3], norm[i*3+1], norm[i*3+2]); } } catch (IOException e) { e.printStackTrace(); } } public int getNumVertices() { return numVertices; } // accessors public Vector3f[ ] getVertices() { return vertices; } public Vector2f[ ] getTexCoords() { return texCoords; } public Vector3f[ ] getNormals() { return normals; } private static class ModelImporter { // values as read in from OBJ file private final ArrayList<Float> vertVals = new ArrayList<>(); private final ArrayList<Float> stVals = new ArrayList<>(); private final ArrayList<Float> normVals = new ArrayList<>(); // values stored for later use as vertex attributes private final ArrayList<Float> triangleVerts = new ArrayList<>(); private final ArrayList<Float> textureCoords = new ArrayList<>(); private final ArrayList<Float> normals = new ArrayList<>(); public void parseOBJ(String filename) throws IOException { InputStream input = Files.newInputStream(new File(filename).toPath()); BufferedReader br = new BufferedReader(new InputStreamReader(input)); String line; while ((line = br.readLine()) != null) { if(line.startsWith("v")) // vertex position ("v" case) { for(String s : (line.substring(2)).split(" ")) { vertVals.add(Float.valueOf(s)); // extract the vertex position values } } else if(line.startsWith("vt")) // texture coordinates ("vt" case) { for(String s : (line.substring(3)).split(" ")) { stVals.add(Float.valueOf(s)); // extract the texture coordinate values } } else if(line.startsWith("vn")) // vertex normals ("vn" case) { for(String s : (line.substring(3)).split(" ")) { normVals.add(Float.valueOf(s)); // extract the normal vector values } } else if(line.startsWith("f")) // triangle faces ("f" case) { for(String s : (line.substring(2)).split(" ")) { String v = s.split("/")[0]; // extract triangle face references String vt = s.split("/")[1]; String vn = s.split("/")[2]; int vertRef = (Integer.parseInt(v)-1)*3; int tcRef = (Integer.parseInt(vt)-1)*2; int normRef = (Integer.parseInt(vn)-1)*3; triangleVerts.add(vertVals.get(vertRef)); // build array of vertices triangleVerts.add(vertVals.get(vertRef+1)); triangleVerts.add(vertVals.get(vertRef+2)); textureCoords.add(stVals.get(tcRef)); // build array of textureCoords.add(stVals.get(tcRef+1)); // texture coordinates. normals.add(normVals.get(normRef)); //… and normals normals.add(normVals.get(normRef+1)); normals.add(normVals.get(normRef+2)); } }} System.out.println(vertVals); System.out.println(stVals); System.out.println(normVals); input.close(); } // accessors for retrieving the number of vertices, the vertices themselves, // and the corresponding texture coordinates and normals (only called once per model) public int getNumVertices() { return (triangleVerts.size()/3); } public float[ ] getVertices() { float[ ] p = new float[triangleVerts.size()]; for(int i = 0; i < triangleVerts.size(); i++) { p[i] = triangleVerts.get(i); } return p; } public float[] getTextureCoordinates() { float[] p = new float[textureCoords.size()]; for (int i = 0; i < textureCoords.size(); i++) { p[i] = textureCoords.get(i); } return p; } public float[] getNormals() { float[ ] p = new float[normals.size()]; for(int i = 0; i < normals.size(); i++) { p[i] = normals.get(i); } return p; } // similar accessors for texture coordinates and normal vectors go here } } Here are the errors I am getting: Exception in thread "main-AWTAnimator#00" com.jogamp.opengl.util.AnimatorBase$UncaughtAnimatorException: java.lang.RuntimeException: com.jogamp.opengl.GLException: Caught NumberFormatException: empty String on thread AWT-EventQueue-0 at com.jogamp.opengl.util.AWTAnimatorImpl.display(AWTAnimatorImpl.java:92) at com.jogamp.opengl.util.AnimatorBase.display(AnimatorBase.java:452) at com.jogamp.opengl.util.Animator$MainLoop.run(Animator.java:204) at java.lang.Thread.run(Thread.java:748) Caused by: java.lang.RuntimeException: com.jogamp.opengl.GLException: Caught NumberFormatException: empty String on thread AWT-EventQueue-0 at com.jogamp.common.util.awt.AWTEDTExecutor.invoke(AWTEDTExecutor.java:58) at jogamp.opengl.awt.AWTThreadingPlugin.invokeOnOpenGLThread(AWTThreadingPlugin.java:103) at jogamp.opengl.ThreadingImpl.invokeOnOpenGLThread(ThreadingImpl.java:201) at com.jogamp.opengl.Threading.invokeOnOpenGLThread(Threading.java:202) at com.jogamp.opengl.Threading.invoke(Threading.java:221) at com.jogamp.opengl.awt.GLCanvas.display(GLCanvas.java:505) at com.jogamp.opengl.util.AWTAnimatorImpl.display(AWTAnimatorImpl.java:81) ... 3 more Caused by: com.jogamp.opengl.GLException: Caught NumberFormatException: empty String on thread AWT-EventQueue-0 at com.jogamp.opengl.GLException.newGLException(GLException.java:76) at jogamp.opengl.GLDrawableHelper.invokeGLImpl(GLDrawableHelper.java:1327) at jogamp.opengl.GLDrawableHelper.invokeGL(GLDrawableHelper.java:1147) at com.jogamp.opengl.awt.GLCanvas$12.run(GLCanvas.java:1438) at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:301) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756) at java.awt.EventQueue.access$500(EventQueue.java:97) at java.awt.EventQueue$3.run(EventQueue.java:709) at java.awt.EventQueue$3.run(EventQueue.java:703) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80) at java.awt.EventQueue.dispatchEvent(EventQueue.java:726) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93) at java.awt.EventDispatchThread.run(EventDispatchThread.java:82) Caused by: java.lang.NumberFormatException: empty String at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1842) at sun.misc.FloatingDecimal.parseFloat(FloatingDecimal.java:122) at java.lang.Float.parseFloat(Float.java:451) at java.lang.Float.valueOf(Float.java:416) at ImportedModel$ModelImporter.parseOBJ(ImportedModel.java:60) at ImportedModel.<init>(ImportedModel.java:18) at WalkingTour.init(WalkingTour.java:83) at jogamp.opengl.GLDrawableHelper.init(GLDrawableHelper.java:644) at jogamp.opengl.GLDrawableHelper.init(GLDrawableHelper.java:667) at com.jogamp.opengl.awt.GLCanvas$10.run(GLCanvas.java:1407) at jogamp.opengl.GLDrawableHelper.invokeGLImpl(GLDrawableHelper.java:1291) ... 16 more Exception in thread "AWT-EventQueue-0" com.jogamp.opengl.GLException: Caught GLException: array vertex_buffer_object must be bound to call this method on thread AWT-EventQueue-0 at com.jogamp.opengl.GLException.newGLException(GLException.java:76) at jogamp.opengl.GLDrawableHelper.invokeGLImpl(GLDrawableHelper.java:1327) at jogamp.opengl.GLDrawableHelper.invokeGL(GLDrawableHelper.java:1147) at com.jogamp.opengl.awt.GLCanvas$12.run(GLCanvas.java:1438) at com.jogamp.opengl.Threading.invoke(Threading.java:223) at com.jogamp.opengl.awt.GLCanvas.display(GLCanvas.java:505) at com.jogamp.opengl.awt.GLCanvas.paint(GLCanvas.java:559) at sun.awt.RepaintArea.paintComponent(RepaintArea.java:264) at sun.lwawt.LWRepaintArea.paintComponent(LWRepaintArea.java:59) at sun.awt.RepaintArea.paint(RepaintArea.java:240) at sun.lwawt.LWComponentPeer.handleJavaPaintEvent(LWComponentPeer.java:1314) at sun.lwawt.LWComponentPeer.handleEvent(LWComponentPeer.java:1198) at java.awt.Component.dispatchEventImpl(Component.java:4965) at java.awt.Component.dispatchEvent(Component.java:4711) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758) at java.awt.EventQueue.access$500(EventQueue.java:97) at java.awt.EventQueue$3.run(EventQueue.java:709) at java.awt.EventQueue$3.run(EventQueue.java:703) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90) at java.awt.EventQueue$4.run(EventQueue.java:731) at java.awt.EventQueue$4.run(EventQueue.java:729) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80) at java.awt.EventQueue.dispatchEvent(EventQueue.java:728) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93) at java.awt.EventDispatchThread.run(EventDispatchThread.java:82) Caused by: com.jogamp.opengl.GLException: array vertex_buffer_object must be bound to call this method at jogamp.opengl.gl4.GL4bcImpl.checkBufferObject(GL4bcImpl.java:40621) at jogamp.opengl.gl4.GL4bcImpl.checkArrayVBOBound(GL4bcImpl.java:40653) at jogamp.opengl.gl4.GL4bcImpl.glVertexAttribPointer(GL4bcImpl.java:12429) at WalkingTour.display(WalkingTour.java:180) at jogamp.opengl.GLDrawableHelper.displayImpl(GLDrawableHelper.java:692) at jogamp.opengl.GLDrawableHelper.display(GLDrawableHelper.java:674) at com.jogamp.opengl.awt.GLCanvas$11.run(GLCanvas.java:1424) at jogamp.opengl.GLDrawableHelper.invokeGLImpl(GLDrawableHelper.java:1293) ... 30 more Exception in thread "AWT-EventQueue-0" com.jogamp.opengl.GLException: Caught GLException: array vertex_buffer_object must be bound to call this method on thread AWT-EventQueue-0 at com.jogamp.opengl.GLException.newGLException(GLException.java:76) at jogamp.opengl.GLDrawableHelper.invokeGLImpl(GLDrawableHelper.java:1327) at jogamp.opengl.GLDrawableHelper.invokeGL(GLDrawableHelper.java:1147) at com.jogamp.opengl.awt.GLCanvas$12.run(GLCanvas.java:1438) at com.jogamp.opengl.Threading.invoke(Threading.java:223) at com.jogamp.opengl.awt.GLCanvas.display(GLCanvas.java:505) at com.jogamp.opengl.awt.GLCanvas.paint(GLCanvas.java:559) at com.jogamp.opengl.awt.GLCanvas.update(GLCanvas.java:866) at sun.awt.RepaintArea.updateComponent(RepaintArea.java:255) at sun.lwawt.LWRepaintArea.updateComponent(LWRepaintArea.java:47) at sun.awt.RepaintArea.paint(RepaintArea.java:232) at sun.lwawt.LWComponentPeer.handleJavaPaintEvent(LWComponentPeer.java:1314) at sun.lwawt.LWComponentPeer.handleEvent(LWComponentPeer.java:1198) at java.awt.Component.dispatchEventImpl(Component.java:4965) at java.awt.Component.dispatchEvent(Component.java:4711) at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758) at java.awt.EventQueue.access$500(EventQueue.java:97) at java.awt.EventQueue$3.run(EventQueue.java:709) at java.awt.EventQueue$3.run(EventQueue.java:703) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:90) at java.awt.EventQueue$4.run(EventQueue.java:731) at java.awt.EventQueue$4.run(EventQueue.java:729) at java.security.AccessController.doPrivileged(Native Method) at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80) at java.awt.EventQueue.dispatchEvent(EventQueue.java:728) at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201) at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116) at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101) at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93) at java.awt.EventDispatchThread.run(EventDispatchThread.java:82) Caused by: com.jogamp.opengl.GLException: array vertex_buffer_object must be bound to call this method at jogamp.opengl.gl4.GL4bcImpl.checkBufferObject(GL4bcImpl.java:40621) at jogamp.opengl.gl4.GL4bcImpl.checkArrayVBOBound(GL4bcImpl.java:40653) at jogamp.opengl.gl4.GL4bcImpl.glVertexAttribPointer(GL4bcImpl.java:12429) at WalkingTour.display(WalkingTour.java:180) at jogamp.opengl.GLDrawableHelper.displayImpl(GLDrawableHelper.java:692) at jogamp.opengl.GLDrawableHelper.display(GLDrawableHelper.java:674) at com.jogamp.opengl.awt.GLCanvas$11.run(GLCanvas.java:1424) at jogamp.opengl.GLDrawableHelper.invokeGLImpl(GLDrawableHelper.java:1293) ... 31 more Any help would be appreciated. Trying to parse a .obj model and use the extracted information to load my model into a JOGL program.
doc_23537517
use AAA exec BBB.dbo.ap_MyProc The procedure being called which is in database BBB:- use BBB create procedure ap_MyProc as print 'We want a way to return the database name AAA' Any advice would be appreciated. A: Can your stored procedure be edited? If yes, I think you can edit the stored procedures and add one more parameter for the database name. And during calling the stored procedure, you should pass the db_name() into the new parameter, so that your stored procedure could know which database is calling it DECLARE @ServerName varchar(50) = db_name() EXEC [dbo].[SP] @newParams = @ServerName A: Well i can now answer my own question. We can exploit syslockinfo... declare @db_name varchar(255) select @db_name = db_name(rsc_dbid) from master.dbo.syslockinfo where req_spid = @@SPID and req_ownertype = 4 --"exSession" and rsc_dbid <> db_id() select @db_name = isnull(@db_name, db_name()) print @db_name Works in SQL 2008 as well. :)
doc_23537518
Through further investigations and by looking up how this thing is already handled in the wild I came across YouTube and saw they're using meta tags within a div-block to describe their videos and found it to be weird since I never used meta tags beside within the head-section of a document. The div-block had an itemtype to declare the scheme it's using so I checked the given page (schema.org) and found by digging in their docs the following part: 3c. Missing/implicit information: use the meta tag with content Sometimes, a web page has information that would be valuable to mark up, but the information can't be marked up because of the way it appears on the page. [...] In these cases, use the meta tag along with the content attribute to specify the information. Consider this example—the image shows users a 4 out of 5 star rating: <div itemscope itemtype="http://schema.org/Offer"> <span itemprop="name">Blend-O-Matic</span> <span itemprop="price">$19.95</span> <img src="four-stars.jpg" /> Based on 25 user ratings </div> Here is the example again with the rating information marked up. <div itemscope itemtype="http://schema.org/Offer"> <span itemprop="name">Blend-O-Matic</span> <span itemprop="price">$19.95</span> <div itemprop="reviews" itemscope itemtype="http://schema.org/AggregateRating"> <img src="four-stars.jpg" /> <meta itemprop="ratingValue" content="4" /> <meta itemprop="bestRating" content="5" /> Based on <span itemprop="ratingCount">25</span> user ratings </div> </div> Source: http://schema.org/docs/gs.html#advanced_missing Now it seems like best practise to (sometimes) add microdata that way but it still felt strange to me to use meta out of the head-block so I checked the w3 about meta tags and realized where that feeling came from. 4.2.5 The meta element ... Contexts in which this element can be used: * *If the charset attribute is present, or if the element's http-equiv attribute is in the Encoding declaration state: in a head element. *If the http-equiv attribute is present but not in the Encoding declaration state: in a head element. *If the http-equiv attribute is present but not in the Encoding declaration state: in a noscript element that is a child of a head element. *If the name attribute is present: where metadata content is expected. ... Exactly one of the name, http-equiv, charset attributes must be specified. If either name or http-equiv is specified, then the content attribute must also be specified. Otherwise, it must be omitted. Source: http://www.w3.org/TR/html5/document-metadata.html#the-meta-element Now I don't know what to think about that since the documentation given by schema.org practically ignores the w3 recommendation. So I'm asking the more experienced guys for an answer to this before I actually start doing it wrong. Greets JD. A: Yeah. This is a bit complicated. Are you sitting comfortably? Then I'll begin... Microdata first appeared in what's now called the HTML Living standard as an integral chapter of that. This is the HTML spec produced by WHATWG. At the time the W3C HTML5 draft automatically took the same changes, so Microdata appeared in that standard too. However the people at the W3C felt that it conflicted and competed with their own existing standard RDFa on which they had been working for some time. They felt that having Microdata in the main HTML5 standard document, while RDFa was separate was unfair, and so Microdata was moved at the W3C to a separate standard Both the HTML living standard (still) and the W3C Microdata standard (until recently) specifically state that the <meta> element is valid in <body> if and only if it contains a itemprop attribute and a content attribute, and none of the other <meta> element specific attributes. (e.g. it must not contain http-equiv or name attributes, but id and class are OK.) More recently however, it has been decided that the validity requirement would be better in the main W3C HTML spec rather that the microdata spec. So the actual requirements have been removed from the microdata spec, although there are still a couple of examples of <meta> elements being used in <body>. This all happened after the HTML5 spec was fixed - effectively only clarifications and bug fixes can be made now - so the validity information was moved to the W3C HTML5.1 spec That describes the validity requirement that make <meta> in <body> valid. It says (see the last bullet point): 4.2.5 The meta element Contexts in which this element can be used: * *If the charset attribute is present, or if the element's http-equiv attribute is in the Encoding declaration state: in a head element. *If the http-equiv attribute is present but not in the Encoding declaration state: in a head element. *If the http-equiv attribute is present but not in the Encoding declaration state: in a noscript element that is a child of a head element. *If the name attribute is present: where metadata content is expected. *If the itemprop attribute is present: where metadata content is expected. *If the itemprop attribute is present: where phrasing content is expected. Note that the <link> element is also extended in a similar way. UPDATE: As unor notes in the comments, the changes to the "Contexts in which this element can be used:" for the meta element didn't make into the HTML 5.1 Recommendation, and they weren't restored to 5.2 or 5.3 either. They now appear in the separate W3C Microdata Spec under Section 7.2 Content Models where point 4 says: If the itemprop attribute is present on a link or meta element, that element is flow content and phrasing content, and may be used where phrasing content is expected.
doc_23537519
*One vector containing variables (names1); *One list that contains two variables (some vars1 and the values); *And the end product should a data.frame with "names1" that contains as many lines as cases that match. *If there is no match between a specific list and a the vector, it should be NA. *The values can also be factors or strings. names1 <- c("a", "b", "c") dat1 <- data.frame(names1 =c("a", "b", "c", "f"),values= c("val1", 13, 11, 0)) dat1$values <- as.factor(dat1$values) dat2 <- data.frame(names1 =c("a", "b", "x"),values= c(12, 10, 2)) dat2$values <- as.factor(dat2$values) list1 <- list(dat1, dat2) The results should be a new data frame with the variables "names" and all values that match of each of list parts: a b c val1 13 11 12 10 NA A: One option would be to loop through the list ('list1'), filter the 'names' column based on the 'names' vector, convert it to a single dataset while creating an identification column with .id, spread from 'long' to 'wide' and remove the 'grp' column library(tidyverse) map_df(list1, ~ .x %>% filter(names %in% !! names), .id = 'grp') %>% spread(names, values) %>% select(-grp) # a b c #1 25 13 11 #2 12 10 NA Or another option is to bind the datasets together with bind_rows, created a grouping id 'grp' to specify the list element, filter the rows by selecting only 'names' column that match with the 'names' vector and spread from 'long' to 'wide' bind_rows(list1, .id = 'grp') %>% filter(names %in% !! names) %>% spread(names, values) NOTE: It is better not to use reserved keywords for specifying object names (names). Also, to avoid confusions, the object should be different from the column names of the dataframe object. It can be also done with only base R. Create a group identifier with Map, rbind the list elements to single dataset, subset the rows by keeping only the values from the 'names' vector, and reshape from 'long' to 'wide' df1 <- subset(do.call(rbind, Map(cbind, list1, ind = seq_along(list1))), names %in% .GlobalEnv$names) reshape(df1, idvar = 'ind', direction = 'wide', timevar = 'names')[-1] A: A mix of base R and dplyr. For every list element we create a dataframe with 1 row. Using dplyr's rbind_list row bind them together and then subset only those columns which we need using names. library(dplyr) rbind_list(lapply(list1, function(x) setNames(data.frame(t(x$values)), x$names)))[names] # a b c # <dbl> <dbl> <dbl> #1 25 13 11 #2 12 10 NA Output without subset looks like this rbind_list(lapply(list1, function(x) setNames(data.frame(t(x$values)), x$names))) # a b c x # <dbl> <dbl> <dbl> <dbl> #1 25 13 11 NA #2 12 10 NA 2 A: Using base R only body <- do.call('rbind', lapply(list1, function(list.element){ element.vals <- list.element[['values']] element.names <- list.element[['names']] names(element.vals) <- element.names return.vals <- element.vals[names] if(all(is.na(return.vals))) NULL else return.vals })) df <- as.data.frame(body) names(df) <- names df A: In base R t(sapply(list1, function(x) setNames(x$values, names)[match(names, x$names)])) # a b c # [1,] 25 13 11 # [2,] 12 10 NA A: For the sake of completeness, here is a data.table approach using dcast() and rowid(): library(data.table) nam <- names1 # avoid name conflict with column name rbindlist(list1)[names1 %in% nam, dcast(.SD, rowid(names1) ~ names1)][, names1 := NULL][] a b c 1: val1 13 11 2: 12 10 <NA> Or, more concisely, pick columns after reshaping: library(data.table) rbindlist(list1)[, dcast(.SD, rowid(names1) ~ names1)][, .SD, .SDcols = names1]
doc_23537520
A: There are two ways... First, you can do it in php with strtotime()... $time = strtotime('2010-05-05 05:05:05'); echo date('F j, Y', $time); Or, you can convert it to unix time in MySQL with UNIX_TIMESTAMP(): SELECT UNIX_TIMESTAMP(`your timestamp column`) FROM blahblah.... You'd then need to format it with date() in php after fetching it. Or, you can do the entire thing right in MySQL with DATE_FORMAT(): SELECT DATE_FORMAT(`your timestamp column`, '%M %e, %Y') FROM ... A: You can have MySQL return it as an Epoch timestamp which php's date function can handle or use the following function: $epoch = strtotime('YYYY-MM-DD HH:MM:SS'); php Manual: strtotime A: Third option: use MySQL's DATE_FORMAT() function (although I prefer ircmaxell's way) A: See date and strtotime. For manipulations in other time zones, see date_default_timezone_set and the DateTime class.
doc_23537521
MBA-Anton:llvm-34-xcode-build asmirnov$ cmake -G Xcode ../llvm_34 -- The C compiler identification is Clang 5.1.0 -- The CXX compiler identification is Clang 5.1.0 -- Looking for C++ include cxxabi.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCXXInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for C++ include cxxabi.h - not found -- Looking for dirent.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for dirent.h - not found -- Looking for dlfcn.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for dlfcn.h - not found -- Looking for errno.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for errno.h - not found -- Looking for execinfo.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for execinfo.h - not found -- Looking for fcntl.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for fcntl.h - not found -- Looking for inttypes.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for inttypes.h - not found -- Looking for limits.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for limits.h - not found -- Looking for malloc.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for malloc.h - not found -- Looking for malloc/malloc.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for malloc/malloc.h - not found -- Looking for ndir.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for ndir.h - not found -- Looking for pthread.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for pthread.h - not found -- Looking for sanitizer/msan_interface.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for sanitizer/msan_interface.h - not found -- Looking for signal.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for signal.h - not found -- Looking for stdint.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for stdint.h - not found -- Looking for sys/dir.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for sys/dir.h - not found -- Looking for sys/ioctl.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for sys/ioctl.h - not found -- Looking for sys/mman.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for sys/mman.h - not found -- Looking for sys/ndir.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for sys/ndir.h - not found -- Looking for sys/param.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for sys/param.h - not found -- Looking for sys/resource.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for sys/resource.h - not found -- Looking for sys/stat.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for sys/stat.h - not found -- Looking for sys/time.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for sys/time.h - not found -- Looking for sys/uio.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for sys/uio.h - not found -- Looking for sys/wait.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for sys/wait.h - not found -- Looking for termios.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for termios.h - not found -- Looking for unistd.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for unistd.h - not found -- Looking for utime.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for utime.h - not found -- Looking for valgrind/valgrind.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for valgrind/valgrind.h - not found -- Looking for zlib.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for zlib.h - not found -- Looking for fenv.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for fenv.h - not found -- Looking for FE_ALL_EXCEPT CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for FE_ALL_EXCEPT - not found -- Looking for FE_INEXACT CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for FE_INEXACT - not found -- Looking for mach/mach.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for mach/mach.h - not found -- Looking for mach-o/dyld.h CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for mach-o/dyld.h - not found -- Looking for pthread_create in pthread CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for pthread_create in pthread - not found -- Looking for pthread_create in c CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for pthread_create in c - not found -- Looking for dlopen in dl CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for dlopen in dl - not found -- Looking for clock_gettime in rt CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for clock_gettime in rt - not found -- Looking for compress2 in z CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for compress2 in z - not found -- Looking for setupterm in tinfo CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for setupterm in tinfo - not found -- Looking for setupterm in terminfo CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for setupterm in terminfo - not found -- Looking for setupterm in curses CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for setupterm in curses - not found -- Looking for setupterm in ncurses CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for setupterm in ncurses - not found -- Looking for setupterm in ncursesw CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) ... CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for strtoll - not found -- Looking for strtoq CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for strtoq - not found -- Looking for strerror CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for strerror - not found -- Looking for strerror_r CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for strerror_r - not found -- Looking for strerror_s CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for strerror_s - not found -- Looking for setenv CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for setenv - not found -- Looking for __GLIBC__ CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for __GLIBC__ - not found -- Performing Test HAVE_INT64_T CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCXXInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Performing Test HAVE_INT64_T - Failed -- Performing Test HAVE_UINT64_T CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCXXInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Performing Test HAVE_UINT64_T - Failed -- Performing Test HAVE_U_INT64_T CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCXXInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Performing Test HAVE_U_INT64_T - Failed -- Performing Test LLVM_HAS_ATOMICS CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCXXInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Performing Test LLVM_HAS_ATOMICS - Failed -- Warning: LLVM will be built thread-unsafe because atomic builtins are missing -- Could NOT find LibXml2 (missing: LIBXML2_INCLUDE_DIR) -- Performing Test SUPPORTS_NO_VARIADIC_MACROS_FLAG CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCXXInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Performing Test SUPPORTS_NO_VARIADIC_MACROS_FLAG - Failed -- Target triple: x86_64-apple-darwin13.2.0 -- Native target architecture is X86 -- Looking for _strtoi64 CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Looking for _strtoi64 - not found -- Threads disabled. -- Doxygen disabled. CMake Warning at cmake/modules/HandleLLVMOptions.cmake:109 (message): -fPIC not supported with Xcode. Call Stack (most recent call first): CMakeLists.txt:272 (include) -- Performing Test CXX_SUPPORTS_MISSING_FIELD_INITIALIZERS_FLAG CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCXXInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Performing Test CXX_SUPPORTS_MISSING_FIELD_INITIALIZERS_FLAG - Failed -- Performing Test CXX_SUPPORTS_COVERED_SWITCH_DEFAULT_FLAG CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCXXInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Performing Test CXX_SUPPORTS_COVERED_SWITCH_DEFAULT_FLAG - Failed -- Performing Test C_SUPPORTS_COVERED_SWITCH_DEFAULT_FLAG CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Performing Test C_SUPPORTS_COVERED_SWITCH_DEFAULT_FLAG - Failed -- Performing Test CXX_SUPPORTS_NON_VIRTUAL_DTOR_FLAG CMake Error at /usr/local/Cellar/cmake/2.8.11.1/share/cmake/Modules/CMakeCXXInformation.cmake:37 (get_filename_component): get_filename_component called with incorrect number of arguments Call Stack (most recent call first): CMakeLists.txt:3 (PROJECT) CMake Error: Internal CMake error, TryCompile configure of cmake failed -- Performing Test CXX_SUPPORTS_NON_VIRTUAL_DTOR_FLAG - Failed -- Found PythonInterp: /usr/bin/python (found version "2.7.5") -- Constructing LLVMBuild project information -- Targeting AArch64 -- Targeting ARM -- Targeting CppBackend -- Targeting Hexagon -- Targeting Mips -- Targeting MSP430 -- Targeting NVPTX -- Targeting PowerPC -- Targeting R600 -- Targeting Sparc -- Targeting SystemZ -- Targeting X86 -- Targeting XCore CMake Error at projects/compiler-rt/CMakeLists.txt:52 (message): Please use architecture with 4 or 8 byte pointers. -- Configuring incomplete, errors occurred! MBA-Anton:llvm-34-xcode-build asmirnov$ A: cmake 2.8.11 bug. Works in cmake 2.8.12.12
doc_23537522
2011-10-27 21:41:21.575 bugtitanium[15903:207] nested push animation can result in corrupted navigation bar 2011-10-27 21:41:21.945 bugtitanium[15903:207] Finishing up a navigation transition in an unexpected state. Navigation Bar subview tree might get corrupted. 2011-10-27 21:41:21.946 bugtitanium[15903:207] Finishing up a navigation transition in an unexpected state. Navigation Bar subview tree might get corrupted. Attaching the code to reproduce ; on the first load, everything is ok, hit 1 time reload , click on one row and click the back button Do the same and reload 2 times, you will have to hit the back button 2 times, and so on .... Can someone provide me with a workaround or a fix please ? I need to load and populate the table as async processes the code is Titanium.UI.setBackgroundColor('#000'); var tabGroup = Titanium.UI.createTabGroup(); var win1 = Titanium.UI.createWindow({ title:'Tab 1', backgroundColor:'#fff' }); var mytasks_helping_button = Ti.UI.createButton({ title : 'Reload', top:0, color:'black', width:200, height:30, style:Ti.UI.iPhone.SystemButtonStyle.BORDERED }); win1.add(mytasks_helping_button); var mytasks_helping_tableview = Titanium.UI.createTableView({ top:100 }); win1.add(mytasks_helping_tableview); var tab1 = Titanium.UI.createTab({ icon:'KS_nav_views.png', title:'Tab 1', window:win1 }); function populateData(datasourcetmp,tabletmp){ var data = []; for( i = 0; i < datasourcetmp.length; i++) { var row = Titanium.UI.createTableViewRow({ height : 120, backgroundColor:'#fff', borderWidth : 0, borderColor : 'transparent' }); var my_tasks_table_top_label = Titanium.UI.createLabel({ text : 'test row:'+i+' date:'+new Date(), width : "100%", font : { fontSize : 12, fontFamily : 'Helvetica' }, color : "black", top : 30, height : 20, left : 5 }); row.add(my_tasks_table_top_label); data.push(row); }; mytasks_helping_tableview.addEventListener('click', function(e) { //view a task screen var viewTask = Titanium.UI.createWindow({ height : "100%", width : "100%", title : "Helping with", barColor : 'lightGray' }); var viewTask_top_label = Titanium.UI.createLabel({ text : 'nested view '+ e.index, width : "80%", font : { fontSize : 15, fontFamily : 'Helvetica' }, color : "gray", top : 10, height : 20, left : 60 }); viewTask.add(viewTask_top_label); tab1.open(viewTask); }); tabletmp.setData(data); } var datasource = ['1','2','3','4','5','6','7']; populateData(datasource,mytasks_helping_tableview); mytasks_helping_button.addEventListener('click', function(e) { populateData(datasource,mytasks_helping_tableview); }); tabGroup.addTab(tab1); tabGroup.open(); A: In the code above, you are adding an event listener every time you call populateData. mytasks_helping_tableview.addEventListener('click', function.... Adding a event listener does NOT 'replace' the existing event listener so it is firing multiple time after the first 'load' and opening multiple windows. Just move the mytasks_helping_tableview.addEventListener call to outside the populateData function. A: Actually a more flexible way to fix that enable the code to by used by different table comp is to create a map of table instances and every time delete the previous instance and rebuild Titanium.UI.setBackgroundColor('#000'); var tabGroup = Titanium.UI.createTabGroup(); var win1 = Titanium.UI.createWindow({ title:'Tab 1', backgroundColor:'#fff' }); var mytasks_helping_button = Ti.UI.createButton({ title : 'Reload', top:0, color:'black', width:200, height:30, style:Ti.UI.iPhone.SystemButtonStyle.BORDERED }); win1.add(mytasks_helping_button); var tab1 = Titanium.UI.createTab({ icon:'KS_nav_views.png', title:'Tab 1', window:win1 }); var tableView={}; function populateData(datasourcetmp,tableName){ if(tableView[tableName]){ win1.remove(tableView[tableName]); delete tableView[tableName]; } var tabletmp = Titanium.UI.createTableView({ top:100 }); win1.add(tabletmp); tableView[tableName] = tabletmp; var data = []; for( i = 0; i < datasourcetmp.length; i++) { var row = Titanium.UI.createTableViewRow({ height : 120, backgroundColor:'#fff', borderWidth : 0, borderColor : 'transparent' }); var my_tasks_table_top_label = Titanium.UI.createLabel({ text : 'test row:'+datasourcetmp[i]+' date:'+new Date(), width : "100%", font : { fontSize : 12, fontFamily : 'Helvetica' }, color : "black", top : 30, height : 20, left : 5 }); row.add(my_tasks_table_top_label); data.push(row); }; tabletmp.addEventListener('click', function(e) { //view a task screen var viewTask = Titanium.UI.createWindow({ height : "100%", width : "100%", title : "Helping with", barColor : 'lightGray' }); var viewTask_top_label = Titanium.UI.createLabel({ text : 'nested view '+ e.index, width : "80%", font : { fontSize : 15, fontFamily : 'Helvetica' }, color : "gray", top : 10, height : 20, left : 60 }); viewTask.add(viewTask_top_label); tab1.open(viewTask); }); tabletmp.setData(data); } var datasource = ['1','2','3']; populateData(datasource,'mytasks'); mytasks_helping_button.addEventListener('click', function(e) { datasource = ['4','5','6','7']; populateData(datasource,'mytasks'); }); tabGroup.addTab(tab1); // open tab group tabGroup.open();
doc_23537523
public void simpleShare(String toShare, Uri uriImage) { Log.d(TAG,"simpleShare, toShare: " + toShare + ", uri: " + uriImage); ShareDialog shareDialog = new ShareDialog(getActivity()); ShareLinkContent linkContent = new ShareLinkContent.Builder() .setImageUrl(uriImage) .setContentUrl(Uri.parse(toShare)) .build(); shareDialog.show(linkContent); } This code is inside a class that extends DialogFragment. The facebook dialog is showing correctly if called from an Activity, but it's not working if called from a Fragment. This is happening only on Android 4, not on Android 5 (i.e. on Android 5 is working fine even from the fragment). Any idea why is it happening? I can assure that the call from activity or fragment are exact the same, I used the log to compare them. Thanks! A: try with the code: instead of getActivity use the class, and remove the imageurl parse into contentur first ShareLinkContent content = new ShareLinkContent.Builder() .setContentUrl(Uri.parse(url)) .setQuote(msg) .build(); if (ShareDialog.canShow(ShareLinkContent.class)) { ShareDialog.show(activity, content); result.success("success"); } the new facebook SDK change some ways to make the dialog share run, and they dont give us many documentation about and how
doc_23537524
Example of expected behaviour (for a given id and window size=3): A mov_ave_A NULL NULL 1 NULL 1 NULL 1 1 4 2 The first 3 rows of the moving average are NULL, because the first value (which is included in the first 3 windows) is NULL. Row 4 of mov_ave_A is equal to 1 because it's the average of rows 2 to 4 of A, and so on. I tried: CASE WHEN SUM(CASE WHEN a IS NULL THEN 1 ELSE 0 END) = 0 THEN AVG(a) ELSE NULL END OVER ( PARTITION BY id ORDER BY date_month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) AS mov_ave_A but I get "Sliding window frame unsupported for function CASE". Also, I'd really like the solution to be short and simple as I need to create 6 such columns. So, I'll have to repeat the logic 6 times. A: The issue with your query is the OVER clause is after the END. I believe this should work. You need to have the OVER clause for each window function so once for COUNT and once for AVG. COUNT is a easier to way to check for NULL's then using SUM SELECT * ,CASE /*Check for 3 values in a, if so return the rolling AVG value. Implicit ELSE NULL*/ WHEN COUNT(a) OVER (PARTITION BY ID ORDER BY date_month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) = 3 THEN AVG(a) OVER (PARTITION BY ID ORDER BY date_month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW) END AS mov_ave_A FROM YourTable A: Use the following case expression: CASE WHEN COUNT(a) OVER ( PARTITION BY id ORDER BY date_month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW ) = 3 THEN AVG(a) OVER ( PARTITION BY id ORDER BY date_month ROWS BETWEEN 2 PRECEDING AND CURRENT ROW ) END AS mov_avg
doc_23537525
Here's a piece of code where that Fill value is used: <Canvas x:Key="IconStartExportThumb" Width="17.458" Height="56.000" x:Shared="False"> <Path Data="F1 M 13.000,26.021 C 13.000,29.611 10.089,32.521 6.500,32.521 C 2.910,32.521 0.000,29.611 0.000,26.021 C 0.000,22.431 2.910,19.521 6.500,19.521 C 10.089,19.521 13.000,22.431 13.000,26.021 Z" Fill="#ffa9e1bf" /> <Path Data="F1 M 10.000,26.021 C 10.000,27.954 8.433,29.521 6.500,29.521 C 4.567,29.521 3.000,27.954 3.000,26.021 C 3.000,24.088 4.567,22.521 6.500,22.521 C 8.433,22.521 10.000,24.088 10.000,26.021 Z" Fill="#ff00ad41" /> <Path Data="F1 M 5.458,0.000 L 5.458,56.000 L 7.458,56.000 L 7.458,2.000 L 17.458,2.000 L 17.458,0.000 L 5.458,0.000 Z" Fill="#ff00ad41" /> </Canvas> For this exception I cannot even debug using live visual tree. Any advice is appreciated.
doc_23537526
I recall reading a JS book by Nick Zakas that described techniques for maintaining UI responsiveness during intensive operations (using timers). I'm wondering if there is a similar technique for dealing with my situation? *I'm trying to avoid combining the AJAX calls for a number of reasons $(".report").each(function(){ var container = $(this) var stat = $(this).attr('id') var cache = db.getItem(stat) if(cache != null && cacheOn) { container.find(".value").html(cache) } else { $.ajax({ url: "/admin/" + stat, cache: false, success: function(value){ container.find(".value").html(value.stat) db.setItem(stat, value.stat); db.setItem("lastUpdate", new Date().getTime()) } }); } }) A: If you have access to jQuery, you can utilize the $.Deferred object to make multiple async calls simultaneously and perform a callback when they all resolve. http://api.jquery.com/category/deferred-object/ http://api.jquery.com/deferred.promise/ If each of these callbacks are making modifications to the DOM, you should store the changes in some temporary location (such as in-memory DOM objects) and then append them all at once. DOM manipulation calls are very time consuming. A: I've had similar problems working heavily with SharePoint web services - you often need to pull data from multiple sources to generate input for a single process. To solve it I embedded this kind of functionality into my AJAX abstraction library. You can easily define a request which will trigger a set of handlers when complete. However each request can be defined with multiple http calls. Here's the component (and detailed documentation): DPAJAX at DepressedPress.com This simple example creates one request with three calls and then passes that information, in the call order, to a single handler: // The handler function function AddUp(Nums) { alert(Nums[1] + Nums[2] + Nums[3]) }; // Create the pool myPool = DP_AJAX.createPool(); // Create the request myRequest = DP_AJAX.createRequest(AddUp); // Add the calls to the request myRequest.addCall("GET", "http://www.mysite.com/Add.htm", [5,10]); myRequest.addCall("GET", "http://www.mysite.com/Add.htm", [4,6]); myRequest.addCall("GET", "http://www.mysite.com/Add.htm", [7,13]); // Add the request to the pool myPool.addRequest(myRequest); Note that unlike many of the other solutions provided this method does not force single threading of the calls being made - each will still run as quickly (or as slowly) as the environment allows but the single handler will only be called when all are complete. It also supports the setting of timeout values and retry attempts if your service is a little flakey. In your case you could make a single request (or group related requests - for example a quick "most needed" request and a longer-running "nice to have" request) to call all your data and display it all at the same time (or in chunks if multiple requests) when complete. You can also specifically set the number of background objects/threads to utilize which might help with your performance issues. I've found it insanely useful (and incredibly simple to understand from a code perspective). No more chaining, no more counting calls and saving output. Just "set it and forget it". Oh - concerning your lockups - are you, by any chance, testing this on a local development platform (running the requests against a server on the same machine as the browser)? If so it may simply be that the machine itself is working on your requests and not at all indicative of an actual browser issue.
doc_23537527
log('Cotaylitcs: Script loaded successfully.'); outputs to the console. I'm just not able to call my functions. I have included the JS code as well. Custom Template Code (Sandboxed Javascript) // Enter your template code here. const log = require('logToConsole'); const injectScript = require('injectScript'); const copyFromWindow = require('copyFromWindow'); const callInWindow = require('callInWindow'); const callLater = require('callLater'); const setInWindow = require('setInWindow'); const key = "testing"; const value = "test2"; const url = 'https://api.deve/cotalytics/cotalytics.js'; // If the script loaded successfully, log a message and signal success const onSuccess = () => { log('Cotaylitcs: Script loaded successfully.'); const cotalytics = copyFromWindow('cotalytics'); log(cotalytics); callInWindow('cotalytics.addEvent',"testing12" ,{key: value}, "{{DL - cottageCode}}"); callInWindow('cotalytics.logEvents()'); data.gtmOnSuccess(); }; // If the script fails to load, log a message and signal failure const onFailure = () => { log('Cotaylitcs: Script load failed.'); data.gtmOnFailure(); }; injectScript(url, onSuccess, onFailure, 'cotalytics'); My Javascript code that is injected by Sandboxed Js: let Cotalytics = function(){ this.init(); }; // Init Cotalytics.prototype = { init: function () { var cotalytics = this; // Argument Assignment //cotalytics.endpoint = 'https://localhost:44301/api/events/', //cotalytics.async = true, //cotalytics.debug = true, //cotalytics.events = {} //creat cookie here return cotalytics; }, // Add Interaction Object Triggered By Events to Records Array addEvent: function (eventType, data, cottageCode, brandid) { data = data || {}; cottageCode = cottageCode || null; data.Browser = window.navigator.appVersion; var cotalytics = this; // cotalytics Object cotalytics.events = { timestamp : new Date(), cottagecode : cottageCode, type : eventType, ipaddress : "127.0.0.1", requesturl : window.location.href, sessionid : "1234567", brandid : brandid, eventData : Object.keys(data).map(function(key) { return {"key": key, "value": data[key]}}) }; // Log Interaction if Debugging //cotalytics.logEvents(); //console.log("Session:\n", interactor.interaction); //var data =JSON.stringify(interactor) console.log("JSON:\n", JSON.stringify(cotalytics)); return cotalytics; }, // Gather Additional Data and Send Interaction(s) to Server logEvents: function () { var cotalytics = this, // Initialize Cross Header Request xhr = new XMLHttpRequest(); // Post Session Data Serialized as JSON xhr.open('POST', 'https://localhost:44301/api/events/', true); xhr.setRequestHeader('Content-Type', 'application/json; charset=UTF-8'); var data = JSON.stringify(cotalytics.events); xhr.send(data); return cotalytics; } }; window.cotalytics = new Cotalytics(); A: Okay, so it looks like you're mostly there, but there are a few things that aren't quite right. * *The use of {key: value} in the addEvent call. Whilst the value will be populated with your constant, the key won't be. I'm imagining that these will be dynamic variables, so why don't you have something like: const kvp= {}; const key = "yourKey"; const value = "yourValue"; kvp[key] = value; That will create the object with the key you want and not just "key". *This line here won't work. you can't use container variables in a custom template. callInWindow('cotalytics.addEvent',"testing12" ,{key: value}, "{{DL - cottageCode}}"); It looks like a dataLayer variable, so why don't you use the copyFromDataLayer API and try this? const copyFromDataLayer = require('copyFromDataLayer'); const cottageCode = copyFromDataLayer('cottageCode'); *The logEvents callInWindow callInWindow('cotalytics.logEvents()'); doesn't need the brackets, it's just callInWindow('cotalytics.logEvents');. The final code that I got working was: const log = require('logToConsole'); const injectScript = require('injectScript'); const callInWindow = require('callInWindow'); const makeTableMap = require('makeTableMap'); const copyFromDataLayer = require('copyFromDataLayer'); const cottageCode = copyFromDataLayer('cottageCode'); //Create the Key Value Pair const kvp = {}; const key = "testing"; const value = "test2"; kvp[key]=value; const url = "https://api.deve/cotalytics/cotalytics.js"; // If the script loaded successfully, log a message and signal success const onSuccess = () => { log('Cotaylitcs: Script loaded successfully.'); callInWindow('cotalytics.addEvent',"testing12" ,kvp,cottageCode); callInWindow('cotalytics.logEvents'); data.gtmOnSuccess(); }; // If the script fails to load, log a message and signal failure const onFailure = () => { log('Cotaylitcs: Script load failed.'); data.gtmOnFailure(); }; injectScript(url, onSuccess, onFailure, 'cotalytics'); Hopefully that helps, ask if you have any other questions! A: I've managed to resolve this now. I am still using the Custom template but I needed to add a new custom HTML tag that injected my .JS script into all pages after doing this my custom template tag worked.
doc_23537528
Code: #Import all necessary scapy functionality from ethernet Api from Lib.IHR_EthApi import * from Lib.IHR_GeneralApi import GeneralApi as SYS from scapy.all import * FullTrafficList = [] #show_interfaces() scapy.all.sniff(lfilter=None, iface="Realtek PCIe GBE Family Controller", store=True, prn = lambda x: FullTrafficList.append(x), count=10, timeout= None) SYS.IHR_print(str(FullTrafficList)) Error describtion: > Traceback (most recent call last): File > "c:\Users\Evgenij\Desktop\Desktop\Eth_Test_Dev\Code\Test.py", line 8, > in <module> > scapy.all.sniff(lfilter=None, iface="Realtek PCIe GBE Family Controller", store=True, prn = lambda x: FullTrafficList.append(x), > count=10, timeout= None) File > "C:\Python27\Lib\site-packages\scapy\sendrecv.py", line 708, in sniff > *arg, **karg)] = iface File "C:\Python27\Lib\site-packages\scapy\arch\pcapdnet.py", line 198, in > __init__ > self.ins = open_pcap(iface, 1600, self.promisc, 100, monitor=monitor) File > "C:\Python27\Lib\site-packages\scapy\arch\windows\__init__.py", line > 856, in open_pcap > if iface.ismonitor(): AttributeError: 'str' object has no attribute 'ismonitor' A: I had this same issue for hours. Here's what I did to solve it. Be sure you have the latest version of scapy and the latest version of npcap. When you install npcap click the option to turn monitor mode on. I also found this on the scapy documentation site Winpcap/Npcap conflicts As Winpcap is becoming old, it’s recommended to use Npcap instead. Npcap is part of the Nmap project. If you get the message ‘Winpcap is installed over Npcap.’ it means that you >have installed both winpcap and npcap versions, which isn’t recommended. You may uninstall winpcap from your Program Files, then you will need to remove: C:/Windows/System32/wpcap.dll C:/Windows/System32/Packet.dll And if you are on a x64 machine: C:/Windows/SysWOW64/wpcap.dll C:/Windows/SysWOW64/Packet.dll To use npcap instead. Those files are not removed by the Winpcap un-installer. after I did that I listed the interfaces using show_interfaces() iface = raw_input("Enter the interface to sniff on: ") copy and paste the interface into the input A: My problem is solved by downgrading the Wireshark version. But i guess the real problem is the compatibility between npcap(v0.98) and Python(v2.7.14). Unfortunately i dont understand the usage of the "ismonitor=True" parameter, but if it should be a compatibility problem, we will read soon more about it:)
doc_23537529
dotnet add package Twilio All went well, no errors. It adds version 5.1.1 of Twilio packages. But building the app now gives me The type or namespace name 'Twilio' could not be found I'm running .Net core version 1.1 with the equivalent 1.0.1 SDK. Any ideas? A: Did you restore? The following works for me. dotnet new console dotnet add package Twilio dotnet restore <---- We need to restore after adding a package. dotnet build Program.cs using Twilio; class Program { static void Main(string[] args) { TwilioClient.SetUsername("foo"); } } DotNetCoreTwilio.csproj <Project Sdk="Microsoft.NET.Sdk"> <PropertyGroup> <OutputType>Exe</OutputType> <TargetFramework>netcoreapp1.1</TargetFramework> </PropertyGroup> <ItemGroup> <PackageReference Include="Twilio" Version="5.1.1" /> </ItemGroup> </Project> A: Ive just had this problem with a core 2.2 project. It turns out i needed an additional using statement of: using Twilio.Types; Visual studio wasnt providing any suggestions when it was referenced as follows: twilio.Types.PhoneNumber("xx"); Changing the reference to the below prompted a new using suggestion from Visual Studio: PhoneNumber("xx"); Hope this helps someone
doc_23537530
I want change mode column with respect of tour column as the following mood== car if there exist at least one trip in the tour with mode car mood==non-car if non of trips in a tour has mode=car example: household. person. trip. tour. mode 1 1 1 1 car 1 1 2 1 walk 1 1 4 1 bus 1 1 1 2 bus 1 1 2 2 walk 1 2 1 1 walk 1 2 2 1 bus 1 2 3 1 walk 2 1 1 1 walk 2 1 1 1 car output household. person. trip. tour. mode 1 1 1 1 car 1 1 2 1 car 1 1 4 1 car 1 1 1 2 non-car 1 1 2 2 non-car 1 2 1 1 non-car 1 2 2 1 non-car 1 2 3 1 non-car 2 1 1 1 car 2 1 1 1 car A: We can group by 'household.', 'person.', 'tour.' and change the 'mode' to two values by checking if there are any 'car' in the column. In that case, convert it to a numeric index by adding 1 (TRUE -> 2, FALSE ->1) and based on this index, we pass a vector of strings to replace the index library(dplyr) df1 %>% group_by(household., person., tour.) %>% mutate(mode = c('non-car', 'car')[1+any(mode == "car")]) # A tibble: 10 x 5 # Groups: household., person., tour. [4] # household. person. trip. tour. mode # <int> <int> <int> <int> <chr> # 1 1 1 1 1 car # 2 1 1 2 1 car # 3 1 1 4 1 car # 4 1 1 1 2 non-car # 5 1 1 2 2 non-car # 6 1 2 1 1 non-car # 7 1 2 2 1 non-car # 8 1 2 3 1 non-car # 9 2 1 1 1 car #10 2 1 1 1 car data df1 <- structure(list(household. = c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L), person. = c(1L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 1L), trip. = c(1L, 2L, 4L, 1L, 2L, 1L, 2L, 3L, 1L, 1L), tour. = c(1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 1L), mode = c("car", "walk", "bus", "bus", "walk", "walk", "bus", "walk", "walk", "car" )), class = "data.frame", row.names = c(NA, -10L))
doc_23537531
Currently I'm designing a new database which will store a lot of data for different web applications and other systems with different data access approaches (ORM, stored procedures) and I want to implement general rules on the lowest level as possible (database). (So not to worry about this rules later in applications). To give you an example let's say that I have a table of users User with foreign key column for his nationality NationalityID which is a primary key CountryID for table Country. Now I have two/three options: A: I allow NationalityID column (and all other similar foreign key columns in database) to be null and just stick with common approach of checking always and everywhere for null (applying rules in application) or B: I assign a default value for every foreign key to be let's say "-1" and put in every relation table additional column with "-1" as a key and all other data as "No data" (for this example in Country table I put column with CountryID of "-1" and for CountryName I set "No data"). So every time I will want to know users nationality I will always get result without additional code rules (no need for me to check if it's null or not). or C: I can disallow null value for foreign keys. But this is really something what I want to avoid. (I need to have an option to store at least basic data (users name) if not the additional data (users nationality)) So is B good approach or not? What am I missing here? Do I lose more that I gain with this approach? Which problems could I have (in addition to be careful to always have additional column in relational tables with ID value of "-1" which says there is "No data")? What is your good/bad experience with foreign key default values? thank you A: If you normalize this won't be an issue. Instead of putting nationality in the USER table, make a User_Nationality table that links users to Country_ID in the other table. If they have an entry in that lookup table, great. If not, you don't need to store a NULL or default value for it. You need to enforce FK relationships, and allowing NULL goes against that. You also don't want to make up information that may not be accurate just to populate a field, which negates the point of requiring the field in the first place. Use lookup tables and you can bypass that entirely. This will also allow you to change your mind and choose one of your options down the road. If you use views, you can choose to treat missing data as a NULL or a default value without needing to alter the underlying data. A: Personally, I would feel that even if you have a non-entry entry in your database with a key of -1, you would still be performing a check to see whether you want to display 'No Data' or not for each individual field. I would stick to NULLs. NULL is meant to mean the absence of data, which is the case here. A: I like your B solution. Maybe it will be possible to map the values into other entities, so you have Country, and NullCountry that extends Country and is mapped to row with id=-1 and have special code in its methods to make it easy to handle special cases. One problem is probably that it will be harder to do outer joins on that foreign key. EDIT: no, there should be no problem with outer joins, because there would be no need to do outer joins. A: B is a terrible approach. It is easier to remeber to handle nulls than to have to figure out what magic number you used and then you still have to handle them. Use number 1. But I like JNKs idea best. A: I suggest option D. If not all users have a defined nationality then that information doesn't belong in the user table. Create a table called UserNationality keyed on UserId.
doc_23537532
I scrolled down to "Creating a Date Picker" and copy pasted this code in a file called DatePickerFragment.java: public static class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener { @Override public Dialog onCreateDialog(Bundle savedInstanceState) { // Use the current date as the default date in the picker final Calendar c = Calendar.getInstance(); int year = c.get(Calendar.YEAR); int month = c.get(Calendar.MONTH); int day = c.get(Calendar.DAY_OF_MONTH); // Create a new instance of DatePickerDialog and return it return new DatePickerDialog(getActivity(), this, year, month, day); } public void onDateSet(DatePicker view, int year, int month, int day) { // Do something with the date chosen by the user } } I then created this button in activity_front_page.xml: <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/pick_date" android:onClick="showDatePickerDialog" /> and added this code to the DatePickerFramegent class: public void showDatePickerDialog(View v) { DialogFragment newFragment = new DatePickerFragment(); newFragment.show(getSupportFragmentManager(), "datePicker"); } But it is saying that getSupportFrammentManager() is not defined? I'm new to using Android studio and developing for Andriod. What I want is the date picker (a picture of it is shown near the top of the screen if you access the link provided above). Any idea how to fix this issue? A: As you're using android.support.v4.app.DialogFragment, you should pass to show() an instance of android.support.v4.app.FragmentManager which can be queried using an getSupportFragmentManager() call A: Try the below code and see if it helps: Activity activity = getActivity; DatePickerDialog datePickerDialog = new DatePickerDialog(activity, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() { @Override public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) { }, year, mm, dd); datePickerDialog.show(); A: You need FragmentTransaction not getSupportFragmentManager() public void showDatePickerDialog(View v) { FragmentTransaction ft = getSupportFragmentManager().beginTransaction(); DialogFragment newFragment = new DatePickerFragment(); newFragment.show(ft, "datePicker"); }
doc_23537533
private String buildQueryString(String url, List<NameValuePair> params) throws IOException { StringBuilder sb = new StringBuilder(); if (params == null) return url; for (NameValuePair param : params) { sb.append(urlEncode(param.getName())); sb.append("="); sb.append(urlEncode(param.getValue())); sb.append("&"); } return url + "?" + sb.substring(0, sb.length() - 1); } If I update my gradle to compileSdkVersion 23, the import org.apache.http.NameValuePair no longer exists. I was curious to know what the replacement is? Thanks in advance! EDIT -posting gradle- Also, I am using gradle-2.4 buildscript { repositories { maven { url 'https://maven.fabric.io/public' } maven { url 'https://zendesk.artifactoryonline.com/zendesk/repo' } } dependencies { classpath 'io.fabric.tools:gradle:1.+' } } apply plugin: 'com.android.application' apply plugin: 'io.fabric' repositories { maven { url 'https://maven.fabric.io/public' } } android { signingConfigs { debug { storeFile file('keystore/debug/debug.keystore') } } compileSdkVersion 23 buildToolsVersion "21.1.2" useLibrary 'org.apache.http.legacy' // jenkins setup def versionPropsFile = file('version.properties') def code = 1; if (versionPropsFile.canRead() && versionPropsFile.exists()) { def Properties versionProps = new Properties() versionProps.load(new FileInputStream(versionPropsFile)) List<String> runTasks = gradle.startParameter.getTaskNames(); def value = 0 for (String item : runTasks) { if (item.contains("assembleRelease")) { value = 1; } } code = Integer.parseInt(versionProps['VERSION_CODE']).intValue() + value versionProps['VERSION_CODE'] = code.toString() versionProps.store(versionPropsFile.newWriter(), null) } else { throw new GradleException("Could not read version.properties!") } // construct version name def versionMajor = 2 def versionMinor = 3 def versionPatch = 9 defaultConfig { minSdkVersion 16 targetSdkVersion 22 versionName "${versionMajor}.${versionMinor}.${versionPatch}" versionCode code signingConfig signingConfigs.debug // enabling multidex support multiDexEnabled true } buildTypes { stage { <content removed> } debug { <content removed> } release { <content removed> } } packagingOptions { exclude 'META-INF/LICENSE.txt' } dependencies { <bunch of dependencies> compile 'com.android.support:support-v4:23.0.1' } A: To elaborate on this issue, there are two ways to fix this for those that face the same conflict. As @Michele pointed out, useLibrary 'org.apache.http.legacy' can be used, but you have to remember to also update gradle. For API 23: Top level build.gradle - /build.gradle buildscript { ... dependencies { classpath 'com.android.tools.build:gradle:1.3.1' } } ... Module specific build.gradle - /app/build.gradle android { compileSdkVersion 23 buildToolsVersion "23.0.0" useLibrary 'org.apache.http.legacy' ... } Official doc: https://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-apache-http-client Latest android gradle plugin changelog: http://tools.android.com/tech-docs/new-build-system The second way of resolving this is by adding the following to dependencies dependencies { compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2' } A: Add this on your build.gradle android { useLibrary 'org.apache.http.legacy' } org.apache library was deprecated from api 22 and it was eliminated on api 23. change buildToolsVersion '21.1.2' with buildToolsVersion '23.0.1' Or you should add this on your dependencies: compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.cli‌​ent:4.1.2' Be careful to use the Gradle 1.3.+
doc_23537534
when i use that dll it give error Could not load file or assembly 'MySql.Data, Version=6.2.2.0..... blah blah So please where can i download this version of dll... A: Try here: ftp://mysql.sh.cvut.cz/mysqlDownloads/Connector-Net/
doc_23537535
thing.js - angular factory .factory( 'Things', ['$resource', function ( $resource ) { return $resource('/api/things/:name', { name: '@name' }, { update: { method: 'PUT', isArray: true }, get: { method: 'GET', isArray: true } }); }]) app.js - angular routes .config( function ( $routeProvider, $locationProvider, $httpProvider ) { $locationProvider.html5Mode(true); $routeProvider .when('/', { templateUrl: 'thing/view', controller: 'ThingCtrl' }); routes.js - express routes app.route( '/api/thing/:name' ) .get( things.all ) .put( things.update ); app.route( '/things/*' ) .get( index.partials ); app.param( 'name', things.load ); index.js - express controller exports.partials = function( req, res ) { var stripped = req.url.split('.')[0]; var requestedView = path.join('./', stripped); res.render( requestedView, function( err, html ) { if( err ) { console.log( "Error rendering partial '" + requestedView + "'\n", err ); res.status( 404 ); res.send( 404 ); } else { res.send( html ); } }); }; Error message Error rendering partial 'things/nameOfThing' { [Error: Failed to lookup view "things/nameOfThing" in views directory "/Users/johnsmith/projects/theProject/app/views"] view: { name: 'things/nameOfThing', root: '/Users/johnsmith/projects/theProject/app/views', defaultEngine: 'html', ext: '.html', engine: [Function], path: undefined } } I'd expect the refresh to use things/view.html template, but it seems to want to use the passed parameter. A: If I understand your problem correctly, you must have enabled html5 mode for location provider in app config like below $locationProvider.html5Mode(true); which sets the base path of your application to '/'. You can change it to false to use hash based location. $locationProvider.html5Mode(false);
doc_23537536
any suggestion is welcomed. A: Essentially, you need to have some unique identifier in the data you pull from the source database. Maybe it is whatever has already been defined as the primary key. Or, maybe the table has some timestamp field. Or, maybe some combination of fields will be unique. Once you identify that, when you are putting the data into the target, reject any key that is already in the target. You could use Camel's "idempotency" features, but if you are able to check for the key in the target database, you probably won't need anything else. If you have to make the decision about what to send, but do not have access to your remote database from App #1, you'll need to keep a record on the other side of the firewall. You would need to do this, even if the connection did not break every 15 minutes...because you could have failures for other reasons. If you can have an Idempotency database for App#1, another approach could be to transfer data from the local database to some other local table, and read from this. Then you poll this other table, and delete whenever the send is successful. Example: It looks like you're using MySql. If both databases are on MySql, you could look into MySql data-replication, rather than using your own app, with Camel.
doc_23537537
Look at this code: #include <iostream> #include <mutex> #include <vector> #include <initializer_list> using namespace std; class Data { public: void write_data(vector<float>& data) { datav = move(data); } vector<float>* read_data() { return(&datav); } Data(vector<float> in) : datav{ in } {}; private: vector<float> datav{}; }; void f1(vector<Data>& in) { for (Data& tupel : in) { vector<float>& in{ *(tupel.read_data()) }; for (float& f : in) { f += (float)1.0; }; }; } void f2(vector<Data>& in) { for (Data& tupel : in) { vector<float>& in{ *(tupel.read_data()) }; for (float& f : in) { cout << f << ","; }; }; } int main() { vector<Data> datastore{}; datastore.emplace_back(initializer_list<float>{ 0.2, 0.4 }); datastore.emplace_back(initializer_list<float>{ 0.6, 0.8 }); vector<float> bigfv(50, 0.3); Data demo{ bigfv }; datastore.push_back(demo); thread t1(f1, ref(datastore)); thread t2(f2, ref(datastore)); t1.join(); t2.join(); }; In my expectancy, I would have guessed that I will get a wild mixture of output values depending on which thread first got to the vector value, so in the third "demo" vector with 50x0.3f, I would have expected a mixture of 0.3 (t2 got there first) and 1.3 (t1 got it first) as output. Even as I tried to use as much pass-by-reference, direct pointers, etc as possible to avoid copying (the original project uses quite large data amounts), the code behaves defined (always t2, then t1 access). Why? Don't I access the floats directly by reference in both thread functions? How would you make this vector access well-defined? The only possible solutions I found in the other thread were: -define a similar sized array of unique_ptr to mutexes (feels bad because I need to be able to add data containers to the datastore, so that would mean clearing the array and rebuilding it every time I change size of the datastore?), or -make the access to the vector atomic (which as a thought makes my operation as I want it threadsafe, but there is no atomic invariant for a vector, or is there in some non-STL-lib?), or -write a wrapper for a mutex in the data class? It's for my project not important which thread accesses first, it's only important that I can definitifly read/write the whole vector into the data tupel by a thread without another thread manipulating the dataset at the same time. A: I believe I did this now with reference to Sam's comments, and it seems to work, is this correct? #include <iostream> #include <mutex> #include <vector> #include <initializer_list> using namespace std; class Data { public: unique_ptr<mutex> lockptr{ new mutex }; void write_data(vector<float>& data) { datav = move(data); } vector<float>* read_data() { return(&datav); } Data(vector<float> in) : datav{ in } { }; Data(const Data&) = delete; Data& operator=(const Data&) = delete; Data(Data&& old) { datav = move(old.datav); unique_ptr<mutex> lockptr{ new mutex }; } Data& operator=(Data&& old) { datav = move(old.datav); unique_ptr<mutex> lockptr{ new mutex }; } private: vector<float> datav{}; //mutex lock{}; }; void f1(vector<Data>& in) { for (Data& tupel : in) { unique_lock<mutex> lock(*(tupel.lockptr)); vector<float>& in{ *(tupel.read_data()) }; for (float& f : in) { f += (float)1.0; }; }; } void f2(vector<Data>& in) { for (Data& tupel : in) { (*(tupel.lockptr)).try_lock(); vector<float>& in{ *(tupel.read_data()) }; for (float& f : in) { cout << f << ","; }; (*(tupel.lockptr)).unlock(); }; } int main() { vector<Data> datastore{}; datastore.emplace_back(initializer_list<float>{ 0.2, 0.4 }); datastore.emplace_back(initializer_list<float>{ 0.6, 0.8 }); vector<float> bigfv(50, 0.3); Data demo{ bigfv }; datastore.push_back(move(demo)); thread t1(f1, ref(datastore)); thread t2(f2, ref(datastore)); t1.join(); t2.join(); }; By usage of the unique_ptr, I should leave no memory leaks when I move the instance, right?
doc_23537538
A: Yes, a sem_t can take on a value of more than 1. You can use sem_init to initialise your semaphore to an abitrary value. Quoting from this link: To initialize a semaphore, use sem_init(): int sem_init(sem_t *sem, int pshared, unsigned int value); * *sem points to a semaphore object to initialize *pshared is a flag indicating whether or not the semaphore should be shared with fork()ed processes. LinuxThreads does not currently support shared semaphores *value is an initial value to set the semaphore to Example of use: sem_init(&sem_name, 0, 10); I'm not aware of any function that can increment a sem_t by an arbitrary value.
doc_23537539
HTML Tag, which i am using <span ng-click="LoadFieldData()">{{name.An}}</span><input type="text" style="width:515px;" ng-value="{{name.An}}" ng-model="name.An" id="topmost[0]" /></div> Also,Please find the directive which i use. angularform.directive("formChange",function($compile){ return{ restrict:"EA", terminal:true, priority:1000, scope:{}, transclude:true, templateUrl:"../../app/Pages/dpang.html", css:"../../Common/Styles/style.css" } }) Also the controller function is $scope.LoadFieldData = function () { debugger; alert('function called.') $scope.name.An = 'An is my name'; } I am calling the directive like this in a div on master page.master. <form-change/> but when i am trying to access the variable {{name.An}}, only {{name.an}} is displayed on the html screen, instead of the value of variable "An is my name". Can anybody please help. A: Not sure if it will work with iFrame like you are trying in the plnkr. You should use the directive tag like this: <teen-internal></teen-internal> Also in your directive you dont need the empty scope: myApp.directive('teenInternal', function() { return { restrict: 'AE', templateUrl: 'teen-external.html' }; }); This is should work. Plunker Cheers,
doc_23537540
I have searched many forums for my question without a good enough answer. I have the following situation: Imagine that I have a list1 with user IDs and list2 with their names. I have also list3 with some of the user IDs(from list1) and I want to create list4 with the names from list2. I know that I can easily find their names with a for loop searching ID by ID in list3 and lookup the name of the user from list2, but I need speed because I am working with millions of rows. Here is my code snippet: for userID in list3: index = [i for i, x in enumerate(list1) if x == userID] list4.append(list2[index]) So, my question is if there is a faster approach to that problem? Thank you! A: Let's say list1, ..., list4 have lengths n1, ..., n4. Linear scan for ids in list3 has complexity of O(n1*n3). Alternative approach is to create a lookup dictionary from list1 and list2. In this case the complexity will be the dictionary creation + lookups, i.e. O(n1) + O(n3). id2name = dict(zip(list1, list2)) list4 = [id2name[id] for id in list3] In most cases (except very short list3, 0- or 1-length) it will be faster than linear scan A: You can use index() function of list. for userID in list3: list4.append(list2[list1.index(userID)) I hope this will make your code faster
doc_23537541
I have to execute some script after completion of all ajax calls but I am unable to do that. I tried the below, also deferred way noting seems working for me. The function "sangeetha" never fires. What am I doing wrong? $("#pnlEmail1").ready(function () { YR.printGraphs(); }).sangeetha(); function sangeetha() { var s = 0.0; $(".printgraphs").each(function () { s += parseFloat($(this).height()); }); s = s - parseFloat($("#pnlEmail1").height()); $(".fulldtls").css({ "top": s + "px", "position": "relative" }); } printGraphs: function () { ///<summary>Loop through the email metrics available for this customer and makes ajax calls to get the email graph data.</summary> $(".printgraphs").each(function () { //Every div id is generated with its respective tab name in printreport.cs to distingush graphs. // So, check if the div belongs to Email tab, Phone tab or Grades and send the respective tab name to controller to get the correct graph data. if ($(this).attr("id").toLowerCase().indexOf("email") >= 0) { YAHOO.Report.changeGraph("Email", $(this), true); } else if ($(this).attr("id").toLowerCase().indexOf("grade") >= 0) { YAHOO.Report.changeGraph("Grades", $(this), true); } else { YAHOO.Report.changeGraph("Phone", $(this), true); } }); } Every YAHOO.Report.changeGraph makes an ajax call. I heard of function chaining in jQuery but not sure how to apply it in this scenario.
doc_23537542
Do you have any advices of how to build that kind of view? Unfortunately It can't be simple horizontal ScrollView, because I need to show a lot of images, so I guess It can't be done without any view recycler. Shoud I build my own implementation of AdapterView or extend any existing? Perfect solution for me, would be Android implementation of UICollectionView from iOS, but I guess that it not exists. A: i too have faced similar situation , i solved it by using Grid Layout (not gridview) in a horizontal-scroll-view , i agree that its not the optimized solution , but worth implementing, one thing in my case was i just have to show the text no images were there. here is the view i created :- you have to span your rows and column carefully for this you can refer following questions How to make a GridLayout fit screen size Set rowSpan or colSpan of a child of a GridLayout programmatically? and use view tag to identify the view if you are implementing any click or touch listener , as i have not found any other way to locate the view other than using its tag !! hope it helps !! A: There is a component called StaggeredGridView that allows you to make uneven tiles while keeping recycling opitimizations. There is a port of it somewhere on github, though I had some trouble with it and just took implementation directly from android sources (the component isn't public yet). The last time I used it it wasn't quite ready, so some functionality I had to add myself, but nothing too criminal there, just some minor things
doc_23537543
I have linked my dll to the exact version of C++ runtime found in the manifest files installed with the Citrix Client. Now, my DLL is pure win32 code with no MFC calls, yet I am getting 'error generating activation context for MFC80.dll' Msg Activation context generation failed for "C:\Program Files (x86)\Citrix\ICA Client\MFC80.DLL".Error in manifest or policy file "C:\Program Files (x86)\Citrix\ICA Client\Microsoft.VC80.MFCLOC.MANIFEST" on line 5. Component identity found in manifest does not match the identity of the component requested. Reference is Microsoft.VC80.MFCLOC,processorArchitecture="x86",publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="8.0.50608.0". Definition is Microsoft.VC80.MFCLOC,processorArchitecture="x86",publicKeyToken="1fc8b3b9a1e18e3b",type="win32",version="8.0.50727.762". Please use sxstrace.exe for detailed diagnosis. A: 1) Installing the runtime listed in the SxSTrace, solved the problem.
doc_23537544
I'd like to its Expenses sheet to pull and fill data from my detailed "Expense Breakdown" sheet automatically to avoid me filling the data twice. Here is my table I need to fill in(there are many tables like that) Here is my detailed expenses list And here is a test spreadsheet https://docs.google.com/spreadsheets/d/1rk03JI6-JRkaH5eixWJaOU5xwcOl2sVE_fMInOIBZhA/edit?usp=sharing I tried pivot tables to aggregate dates into month and sum expenses, but for some reason, Google doesn't know how to do it. So the way I see it, I need to place a formula into each cell in D46 to O53 range, where each cell will query expenses list, aggregate data(sum by category and date) there, then match and pull by date(from D2:O2 cella)and category (in C col). Does that make sense? Can somebody help me to create a formula for that? A: first, you need to fix your logic... every category (column A) needs to have unique sub-category (column C) meaning you cant have sub-category called Other for every category because you would output exact same values of Other sub-category for all categories then use in D46, D4, D15, D24, etc... =ARRAYFORMULA(IFNA(VLOOKUP( INDIRECT(ADDRESS(ROW(), 3)&":"&ADDRESS(IFERROR(MATCH("Monthly totals:", INDIRECT(ADDRESS(ROW(), 3)&":C"), 0)+ROW()-4, ROWS(A:A)), 3)), QUERY({'Expenses Breakdown'!B:F; {VALUE(TEXT(SEQUENCE(12, 1, 0, 29), "m/d/yyy")), SEQUENCE(12, 3, 0, 0)&"♀", SEQUENCE(12, 1, 0, 0)}}, "select Col3,sum(Col5) where Col3 matches '"&TEXTJOIN("|", 1, "0♀", INDIRECT(ADDRESS(ROW(), 3)&":"&ADDRESS(IFERROR(MATCH("Monthly totals:", INDIRECT(ADDRESS(ROW(), 3)&":C"), 0)+ROW()-4, ROWS(A:A)), 3)))&"' group by Col3 pivot month(Col1)+1"), COLUMN(B:M), 0))) also, you may want to disable rounding:
doc_23537545
variable is defined as : variable create 0 , ; Is alloting more cells to the variable not guaranteed to extend the block of memory contiguously because create can only be called once per word? Example: create test 1 , 2 , test 3 , 4 , 5 , <<<< This won't necessarily extend the array contiguously, correct? Are my assumptions correct? A: * *The wording in the standard gives VARIABLE and CREATE freedom to put the data in different memory regions. If they do, obviously CREATE or ALLOT can't extend the region created by VARIABLE. *CREATE can be called many times from any word. *Your example may not quite do what you think. The second line calls test, leaving its address on the stack. Then it lays down three cells which do extend the region allocated for test. *Your assumption about the definition of VARIABLE is not correct for all implementations.
doc_23537546
I actually ask because if a CFG is given and there is a question like: "Find the language of the grammar.Prove/Justify your answer." , then how can someone prove/justify his/her answer otherwise? A: In general, no. For example, for an arbitrary context free grammar, the question of whether the language is equivalent to Sigma* is undecidable -- and that's about the simplest description of a CFL one might imagine. Another undecidable question is whether two context free grammars A and B define the same language, which doesn't bode well for the more general question of whether a grammar and some other alternate presentation define the same language. In specific cases, such questions may be decidable -- fortunately for formal language theory students! But in light of the above decidability results, you're not going to find a simple algorithm that gets you from a grammar, to a concise description of the sort usually presented in language theory textbooks. It's more of a trial and error process, where you use some intuition to think up a candidate description, then apply the more formal methods like building parse trees, or using closure properties or pumping lemmas, to prove or disprove the equivalence.
doc_23537547
public class SomeObject { private String id; private String parentId; private String type; //constructor,getters,setters } And the following use case: The field values are not unique. I have a List of SomeObject. First I want to know which SomeOjects share the same parentId and secondly which of those share the same type. First I wanted to group them into the following structure: Map<String, Map<String, List<String>>> The key of the first map is the parentId and the value is another map. The key of the second map is the type and the value of the second map is a list of ids from the SomeObjects. I was able to do this as follows: Map<String, Map<String, List<String>>> firstTry = SomeObjects.stream() .collect( groupingBy( SomeObject::getParentId, groupingBy( SomeObject::getType, mapping(SomeObject::getId, toList())))); And now comes the part where I need some help: I now want to filter this created map as follows: Lets assume I have 3 parentId keys which each then have a map with two keys: type1 and type2. (and 2 lists of ids as values) If the list of ids from type2 contains more/less/different ids than the list of ids from type1, then I want to delete/filter out their parentId entry. And I want to do that for each parentId. Is there any way with streams to cleanly achieve this? A: Some points I would use to improve the code before the answere: * *I would leave the SomeObject pointer instead of the String literal in the map. Not only they are gonna be more memory efficient most of the time (8 bytes fixed vs 2*character bytes String) but also much more convenient to access the data. *I would also make the type String an enum type. But getting to the core of the question, i'm sorry. Lets assume I have 3 parentId keys which each then have a map with two keys: type1 and type2. (and 2 lists of ids as values) { 'p1': { 'type1':['1','2','uuid-random-whatever'], 'type2':['asdsad'] }, 'p2': { 'type1':['1','2'], 'type2':['asdsad','i','want','more','power'] }, 'p3': { 'type1':['2'], 'type2':['2'] } } Something like this So for the filtering itself Map<String, Map<String, List<String>>> theMap = buildMapExample(); Predicate<Map.Entry<String, Map<String, List<String>>>> filterType2LessElementsType1 = (Map.Entry<String, Map<String, List<String>>> entry) -> entry.getValue().get("type2").size() < entry.getValue().get("type1").size(); Predicate<Map.Entry<String, Map<String, List<String>>>> filterType2MoreElementsType1 = (Map.Entry<String, Map<String, List<String>>> entry) -> entry.getValue().get("type2").size() > entry.getValue().get("type1").size(); Predicate<Map.Entry<String, Map<String, List<String>>>> filterType2SameElementsType1 = (Map.Entry<String, Map<String, List<String>>> entry) -> (new HashSet<>(entry.getValue().get("type2"))) .equals(new HashSet<>(entry.getValue().get("type1"))); theMap = theMap.entrySet().stream() .filter( // Choose your lambda for more/less/different. for example filterType2LessElementsType1 ) .collect( Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue) ); printMap(theMap); This code would work. I left out the building/printing to not make this larger as it should. Try it out A: If you need to retain only those parentId which have the same ids per type, it can be done by converting lists of ids into set and checking the set size: List<SomeObject> list = Arrays.asList( new SomeObject("id1", "p1", "type1"), new SomeObject("id1", "p1", "type2"), new SomeObject("id2", "p2", "type1"), new SomeObject("id3", "p2", "type1"), new SomeObject("id2", "p2", "type2"), new SomeObject("id4", "p3", "type1"), new SomeObject("id4", "p3", "type2"), new SomeObject("id5", "p3", "type2") ); //.. building firstTry as in the initial code snippet System.out.println(firstTry); firstTry.entrySet().stream() .filter(e -> new HashSet(e.getValue().values()).size() == 1) .forEach(System.out::println); Output: {p1={type2=[id1], type1=[id1]}, p2={type2=[id2], type1=[id2, id3]}, p3={type2=[id4, id5], type1=[id4]}} p1={type2=[id1], type1=[id1]}
doc_23537548
SELECT ST_Clip(rast, the_geom)FROM raster, polygons that is very fast to process. the_geom has 50 geometries while raster is a 400x400 tiled 5-band raster layer (about 3GB in size). While the above query works fine, SELECT ST_Union(ST_Clip(rast, the_geom)) FROM raster, polygons takes forever to process. I created spatial index st_convexthull(rast) while loading the raster to PostGIS. What would I have missed? Thank you in advance.
doc_23537549
By duplicate/newI mean the following: Container 1 contains: [1, 2, 4, 8, 16] Container 2 contains: [1, 2, 4, 16, 32] After running the algorithm, the new container (or modified container 2) should contain: Container 3 contains: [32] Notice that I do NOT want '8' to be in the new container (or modified container) as I only want to find the 'new' values. I could easily implement a naive and slow program to do this myself, however I'm looking for the most elegant and efficient way to achieve this (Boost is fine if the STL does not provide all the necessary tools/algos without rolling your own, otherwise rolling your own is fine too). So... What would be the 'best' (read: most elegant and efficient) way to do this? Thanks in advance. P.S. If it is at all relevant, I'm using this to write a 'diffing' tool for exported functions from a DLL. I have a number of very large DLLs and I want to find the 'new' exports in the latest builds of those DLLs. A: Looks like STL set_difference might be right for you. Example from here: // set_difference example #include <iostream> #include <algorithm> #include <vector> using namespace std; int main () { int first[] = {5,10,15,20,25}; int second[] = {50,40,30,20,10}; vector<int> v(10); // 0 0 0 0 0 0 0 0 0 0 vector<int>::iterator it; sort (first,first+5); // 5 10 15 20 25 sort (second,second+5); // 10 20 30 40 50 it=set_difference (first, first+5, second, second+5, v.begin()); // 5 15 25 0 0 0 0 0 0 0 cout << "difference has " << int(it - v.begin()) << " elements.\n"; return 0; } A: The simplest method would likely be to sort and then iterate. As the two containers are both sorted, you can simply directly compare each index (or de-referenced iterator) for equality, and insert into new (or remove from existing) only if not equal. This is O(n logn) and depends on operator< and operator==. A: hash_table in STL can solve this problem. * *Insert all the elements in container one into the hash_table. *For every element in container two, check whether it's in the hash_table or not; if not, push it into container three. The overall time complexity is O(n). The sort and compare method have time complexity O(nlogn).
doc_23537550
Currently, I am trying {{ float|floatformat:2|rjust }}, but it keeps throwing up a TemplateSyntaxError. Is it even possible to do this via the template system, or will I just have to use some CSS styling for this? A: According to the docs: "{{ value|rjust:"10" }}" If value is Django, the output will be "____Django". EDIT: If you do use this solution, be sure to surround the element with a <pre> tag because extra spaces are removed by your browser. Or look here for info. A: {{ value|rjust:"10" }} didn't work for me so I had to format the string before being passed to the HTML page. I first right aligned the string with an arbitrary character: amount.rjust(12, '$') And then replace the character with "&nbsp;" amount.replace('$', '&nbsp;')
doc_23537551
however nowhere in the DOCS does it mention anything about low-power mode on IOS. This is a big issue because The message handler never fires. My app relies on notifications to trigger foreground data refresh... A: Low power mode on iOS disables a number of device features. One of those is the receipt of push notification as the push notification service requires that the device keeps a persistent connection to Apple's servers. This consumes battery. Firebase relies on push notifications to receive updates. There is nothing you can do about this. Generally you can expect pending push notifications to be delivered once the device exits low power mode, but there is no guarantee that push notifications will always be delivered and your app should have other mechanisms for checking for updated data.
doc_23537552
library(doSNOW) library(foreach) cl<- makeCluster(4, type = "SOCK") registerDoSNOW(cl) min_subid <- c() max_subid <- c() p_typ <- c() p_nm <- c() st_tm<-c() end_tm <- c() supp <- c() chart_type <- c() foreach(j =1:noOfPhases) %dopar% { start_time <-phases[j, colnames(phases)=="StartTime"] end_time <-phases[j, colnames(phases)=="StopTime"] phase_type <-phases[j, colnames(phases)=="Phase_Type_Id"] phase_name <-phases[j, colnames(phases)=="Phase_Name"] suppress <-phases[j, colnames(phases)=="Suppression_Time"] chart_typ <-phases[j, colnames(phases)=="chartType"] conft<-(masterData$Time.Subgroup>=start_time & masterData$Time.Subgroup<=end_time) masterData[which(conft), colnames(masterData)=="Phase_Type"]<-phase_type masterData[which(conft), colnames(masterData)=="Phase_Name"]<-phase_name min_subid <- rbind(min_subid, min(which(conft))) max_subid <- rbind(max_subid, max(which(conft))) p_typ <- rbind( p_typ, masterData$Phase_Type[min(which(conft))]) p_nm <- rbind( p_nm, masterData$Phase_Name[min(which(conft))]) st_tm <- rbind( st_tm, as.character(start_time)) end_tm <- rbind( end_tm, as.character(end_time)) supp <- rbind(supp,as.character(suppress)) chart_type <- rbind(chart_type,as.character(chart_typ)) phase_info <- data.frame(Subgrp_No_Start=min_subid, Subgrp_No_End=max_subid, Phase_Type=p_typ, Phase_Name=p_nm, Start_Time=st_tm, Stop_Time=end_tm, Suppression_Time=supp,ChartType=chart_type) } phase_output<-merge(phase_info, phases, by.x=c("Start_Time", "Stop_Time","ChartType"), by.y=c("StartTime", "StopTime","chartType")) The above code executes successfully when %do% is included instead of %dopar%. can anyone help me in understanding why I get the following error when it runs parallel (%dopar%) and runs successfully on sequential (%do%) Error in merge(phase_info, phases, by.x = c("Start_Time", "Stop_Time", : object 'phase_info' not found A: The solution is really simple, but I start off with an explanation of what is happening when you execute the code to explain the error. What happens in your foreach block is that the one data frame (phase_info) is created for each value of j and they are returned together in a list. However, since your assignment phase_info <- data.frame(...) is located inside the foreach rather than outside, the list is not stored anywhere and gets discarded. The cause for confusion is that when using %do% you create all the data frames sequentially on the master node and when using %dopar% the frames are being created in parallel on the worker nodes. The following merge command is executed on the master node causing an error if you used %dopar% since phase_info does not exist in its workspace. Also note that when using %do% like above, each iterations of foreach overwrites the result of the previous ones (i.e. you get only the result of the last iteration). This minor change fixes it: phase_info <- foreach(...) %dopar% { ... data.frame(Subgrp_No_Start=min_subid, Subgrp_No_End=max_subid, Phase_Type=p_typ, Phase_Name=p_nm, Start_Time=st_tm, Stop_Time=end_tm, Suppression_Time=supp,ChartType=chart_type) # No need to give it a name as it will be returned and the name forgotten } phase_output <- merge(phase_info, ...) As I mentioned above, phase_info will now be a list where each element is a data frame. I am just guessing now but you probably want to execute the merge elementwise then, like this: phase_output <- lapply(phase_info, merge, phases, by.x=c("Start_Time", "Stop_Time","ChartType"), by.y=c("StartTime", "StopTime","chartType"))
doc_23537553
A: Use strip_tags to avoid any html / js / php. It has some options to allow any tags you want like this: strip_tags($text, '<p><a>'); A: strip_tags, as stated in the documentation will not remove inline javascript or sanitise so it isn't a good idea. A common solution is to use bbcode instead for which many libraries exist, or you can make your own and then use preg_replace to substitute in your own markup safely. Here's a quick sample: $safe_output = htmlspecialchars($output); $find = array("'\[b\](.*?)\[/b\]'is"); $replace = array("<strong>\\1</strong>"); $result = preg_replace($find, $replace, nl2br($safe_output)); A: * *User posts data *Data is escaped for mysql, written to DB *User makes request for data *Data is encoded for display (aggressively with htmlentities or htmlspecialchars, or some subset of allowed characters. You could do this with str_replace, but there are better utilities).
doc_23537554
personalInfo[] pers = new personalInfo[3]; Scanner input = new Scanner(System.in); String inName; String inAddress; int inAge; long inPhoneNumber; for(int i=0; i<3; i++){ pers[i] = new personalInfo(); System.out.printf("Please input the name for person %d: ", i ); inName = input.nextLine(); pers[i].setName(inName); System.out.printf("Please input the address for person %d: ", i ); inAddress = input.nextLine(); pers[i].setAddress(inAddress); System.out.printf("Please input the age for person %d: ", i ); inAge = input.nextInt(); pers[i].setAge(inAge); System.out.printf("Please input the phone number for person %d, without dashes included (ex. 1112223333): ", i ); inPhoneNumber = input.nextLong(); pers[i].setPhoneNumber(inPhoneNumber); } I get this output: Please input the name for person 0: name Please input the address for person 0: address Please input the age for person 0: 18 Please input the phone number for person 0, without dashes included (ex. 1112223333): 1289308439 Please input the name for person 1: Please input the address for person 1: You can see that on the first iteration of the loop it prompts for name, waits for input, then prompts for address. However, on the second iteration of the loop it prompts for name and address on the same line, then waits for input. This doesn't make sense to me. Can anyone please explain this for me?
doc_23537555
$subject = "Become a Member of Room"; $message = "Hi Zeeshan"; $message.= "<a href='http://iqra.com.hk/sms/Member/activate/sdskdksn2n23kan92nns29/12'>Clickhere</a>"; $message.= "Room Invite is here"; $message.= "Regards,<br><br>"; $message.= "Demo School"; $this->sendEmail('myemail@gmail.com', $subject, $message,'Demo School'); Defination of sendEmail() Function function sendEmail($email,$subject,$message,$school){ $this->load->library('email'); $config['protocol'] = 'sendmail'; $config['mailtype'] = 'html'; $config['mailpath'] = '/usr/sbin/sendmail'; $config['charset'] = 'iso-8859-1'; $config['wordwrap'] = TRUE; $this->email->initialize($config); $this->email->from('no-reply@example.com',$school); $this->email->to($email); $this->email->subject($subject); $this->email->message($message); $this->email->send(); } Now i am facing issue is that when i send email,email doesn't received.I tracked this issue and i find that http://iqra.com.hk/sms/ in Link is creating issue.When i remove http://iqra.com.hk/sms/ from $message.= "<a href='http://iqra.com.hk/sms/Member/activate/sdskdksn2n23kan92nns29/12'>Clickhere</a>"; and make it like this $message.= "<a href='Member/activate/sdskdksn2n23kan92nns29/12'>Clickhere</a>"; then email receives.So i am wondering Why email is not receiving by adding my domain name in Link?Please suggest me.
doc_23537556
make A method named withdraw that withdraws a specified amount from the account and then add the transaction to the ArrayList of transactions.  A method named deposit that deposits a specified amount to the account and then then add the transaction to the ArrayList of transactions. package hw1josezaragoza; import java.util.Date; import java.util.ArrayList; /** * * @author jose */ public class Hw1josezaragoza { /** * @param args the command line arguments */ public static void main(String[] args) { // TODO code application logic here Account acc = new Account(1122, "George", 1000); acc.deposit(3000); acc.withdraw(2500); acc.setInterestRate(1.5); acc.getMonthlyInterestRate(); System.out.print("The account holder's name: " + acc.getName() + ".\nThe annual interest rate: " + acc.getInterestRate() + ".\nThe balance: " + acc.getBalance() + ".\nThe monthly interest: " + acc.getMonthlyInterest() + "\nAccount created on " + acc.getDate()); } } Transaction Class: class Transaction { private Date dateOfTrans; private char typeOfTrans; char WithDraw = 'W'; char Deposit = 'D'; private double amount; private double balance; private String description; public Transaction(char Type, double newAmount, double newBalance, String newDescription, Date date) { typeOfTrans = Type; amount = newAmount; balance = newBalance; description = newDescription; dateOfTrans = date; } public Date getDate() { return dateOfTrans; } public char getType() { return typeOfTrans; } public double getAmount() { return amount; } public String getDescription() { return description; } public double getBalance() { return balance; } } Account Class: class Account { private int Id = 0; private String name; private double balance = 0; private double annualRate = 0.0; private Date dateCreated = new Date(); private ArrayList Transaction = new ArrayList(); Account() { Id = 0; balance = 0.0; annualRate = 0.0; } Account(int newId, double newBalance) { Id = newId; balance = newBalance; } Account(int newId, String newName, double newBalance) { Id = newId; name = newName; balance = newBalance; } public int getId() { return Id; } public void setId(int newId) { Id = newId; } public double getBalance() { return balance; } public void setBalance(double newBalance) { balance = newBalance; } public String getName() { return name; } public void setName(String newName) { name = newName; } public double getInterestRate() { return annualRate; } public void setInterestRate(double annualRate) { this.annualRate = annualRate/100; } public Date getDate() { return dateCreated; } public void setDate(Date newDate) { dateCreated = newDate; } double monthlyInterestRate; double monthlyInterest; public double getMonthlyInterestRate( ) { monthlyInterestRate = annualRate / 12; return monthlyInterestRate; } public double getMonthlyInterest() { monthlyInterest =balance * monthlyInterestRate; return monthlyInterest; } double withdraw(double amount) { balance -= amount; return balance; } double deposit(double amount) { balance += amount; return balance; } } A: First of all, you can't name your arraylist the same as one of your classes. Assuming you change the arraylist's name to transaction, insert the following code at the end of the withdraw method. transaction.add(new Transaction("W", amount, balance, "Withdrawal", new Date())); And this into the deposit method. transaction.add(new Transaction("D", amount, balance, "Deposit", new Date())); Additionally, it's recommended to change your arraylist declaration statement to the following: private ArrayList<Transaction> transaction = new ArrayList<Transaction>();
doc_23537557
import pyodbc cnxn = pyodbc.connect("DRIVER={SQL Server};" +"SERVER=somesqlserver2008.example.com;" +"DATABASE=exampledatabase;") cursor = cnxn.cursor() #do stuff... The above code runs just fine. I have reason to believe, though, that this code is actually passing some form of credentials 'behind my back' (so to speak). For example, this code: cnxn = pyodbc.connect("DRIVER={SQL Server};" +"SERVER=someOTHERsqlserver2008.example.com;" +"DATABASE=exampledatabase;") cursor = cnxn.cursor() returns: Traceback (most recent call last): File "C:\Users\<my username>\Documents\sql_connect_test1.py", line 27, in <module> +"SERVER=someOTHERsqlserver2008.example.com;") Error: ('28000', "[28000] [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user '<user name appears here>'. (18456) (SQLDriverConnect); [28000] [Microsoft][ODBC SQL Server Driver][SQL Server]Login failed for user '<user name appears here>'. (18456)") Even though I didn't specify a username/password in the second connection string, it appears that a username and password were used by pyodbc. How can I find out what username and password were used? A: It must be passing your WINDOWS domain credentials for you, if you don't specify. On the server where it fails, your Windows account does not have access (or the other machine is in a different, untrusted domain). Your program probably shouldn't rely on Windows auth if this is a common scenario - a different domain or different users with different rights will try to run it. You should consider using SQL authentication and putting the connection string in a config file (not inside the code). A: This is quite an old answer, but ranks highly for modern searches along these lines so I thought I'd add a few thoughts that arrive here and wonder what still applies. Aaron Bertrand's post is an excellent summary. I discovered a similar issue a while back when I shared a utility I wrote originally for myself. When run by another user the utility would silently fail in the background as their domain account had no access to the database. Below is some simplified sample code that works for for talking to an SQL Server instance. The following code prompts the user for the password at runtime, far from an ideal way to do it in production, but still better than putting the credential in your code directly. db_user_auth = input("Please enter the db password:") conn_str = "Driver={SQL Server Native Client 11.0}" conn_str = f'{conn_str};Server={db_svr_name}' conn_str = f'{conn_str};Database={db_name}' conn_str = f'{conn_str};UID={db_user_name}' conn_str = f'{conn_str};PWD={db_user_auth}' db_conn = pyodbc.connect(conn_str) FWIW I use a very similar technique for connecting to a some legacy Microsoft Access databases.
doc_23537558
""" Create from metadata on MSSQL and Oracle """ import urllib from sqlalchemy import * # pylint: disable=wildcard-import, unused-wildcard-import params = urllib.parse.quote_plus( "Driver={ODBC Driver 17 for SQL Server};Server=xxx\\xxx;Database=xxx;Trusted_Connection=yes" ) print("mssql+pyodbc:///?odbc_connect=%s" % params) mssqle = create_engine("mssql+pyodbc:///?odbc_connect=%s" % params, echo=True) oraclee = create_engine("oracle+cx_oracle://@xxx", echo=True) metadata = MetaData() t1 = Table( "TableNumberOne", metadata, Column("id", Integer(), primary_key=True), Column("ColumnNumberOne", String(50), index=True) ) metadata.create_all(mssqle) metadata.create_all(oraclee) I can get away with this. I am not sure it covers every possible situation. for _tab in metadata.sorted_tables: _tab.name = _tab.name.lower() for _col in _tab.columns: _col.name = _col.name.lower() for _con in _tab.constraints: if _con.name is not None: _con.name = _con.name.lower() for _idx in _tab.indexes: if _idx.name is not None: _idx.name = _idx.name.lower()
doc_23537559
A: I found right clicking on Git Bash->Properties->tab Shrotcut-> edit-field "Start In" is set as %HOMEDRIVE%%HOMEPATH% or alternatively when Git Bash starts you can write pwd Then you can just add to that path file with magic name .bashrc Then you can put all the goodies you want there like: alias ll="ls -all" alias proj="cd /d/Data/vbe/ghd_josh"
doc_23537560
My Entites: Person @Entity public class Person { //... @OneToMany(fetch = FetchType.LAZY,mappedBy = "personWithMail") @JsonIgnoreProperties(value = "personWithMail") private List<MyMail> mailList; @OneToMany(mappedBy = "employee") @JsonIgnoreProperties(value = "employee") private List<Deploy> deploys; } MyMail: @Entity public class MyMail{ //... @ManyToOne(fetch = FetchType.EAGER, optional = true) private Person personWithMail; } Deploy @Entity public class Deploy{ //... @ManyToOne(fetch = FetchType.EAGER) @JsonIgnoreProperties(value = "deploys") private Person employee; JSON Input: This is the json data I try to send to the server and deserialize: The output object should be an object containing a person and deploys. { "aPersonOutsideDeploy":{ //... "mailList":[] //No Error here }, "deploys": [ { //... "mailList":[] //ERROR. When I delete this line then the problem will be solved }, //... ] } This is the error : trace org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: (was java.lang.NullPointerException); nested exception is com.fasterxml.jackson.databind.JsonMappingException: (was java.lang.NullPointerException) (through reference chain: my.com.tool.model.MYMODEL["deploys"]->java.util.ArrayList[0]->my.com.tool.model.Deploy["employee"]->my.com.tool.model.Person["mailList"]) What I have done so far: On the stack trace you can find out that the error comes from this line in the library Caused by: java.lang.NullPointerException at com.fasterxml.jackson.databind.deser.std.CollectionDeserializer._deserializeFromArray(CollectionDeserializer.java:341) The problem is still there when you serialize an object and try to use the same json data to test deserialization. So the json input is not wrong. Line 341: if (valueDes.getObjectIdReader() != null) and when you debug the app, valueDes is here null so it throws Nullpointerexception. I thought maybe the problem is with the library. I've created a custom deserializer, and inside, I return empty list when the input is [] and it works but I don't know it's the correct way to face this problem. Do you have any suggestion how I can solve this problem? A: Which class instance is expected to be created as a result of the deserialization operation? Is it a Person? If so, the input JSON appears incorrect. Shouldn't the deploys attribute appear a level further down i.e., under employee? { "mailList":[...], "deploys":[{ "employee": { "mailList":[...], "deploys": [...] } }] } I suggest creating an instance of the structure in code and logging the serialized output to the console. Whatever JSON gets generated should deserialize to the intended class.
doc_23537561
Thanks in advance. A: The best way you can achieve what you want is to use SSIS parkage to move the data from excel to access DB. if however, you do not have SSIS you can import all rows and delete the one you do not need. A: You can use SQL for import data from file as from table: INSERT INTO Table1 (MyColumn1, MyColumn2, MyColumn3, MyColumn4) SELECT * FROM [Sheet1$D3:E24] IN "C:\Temp\Test.xls" [Excel 8.0;HDR=YES;IMEX=0] WHERE MyColumn1 > 0; If HDR=YES, You can use names from header row as column names. If IMEX=0, Access determines column data type, if IMEX=1, considers all data as text, which may be very useful for complex data.
doc_23537562
Currently, I am using the following RegEx: var dateReg = /^(0[1-9]|1[012])[- //.](0[1-9]|[12][0-9]|3[01])[- //.](19|20)\d\d$/; This validates in the mm/dd/yyyy format, but only validates for anything under 31 days. Is it possible to do the day validation on a per-month basis? Would it be recommended to go another route with this? A: As @Wooble explained, a regexp won't be able to suit your needs. What about this: if(typeof String.prototype.isValidDate === "undefined") { String.prototype.isValidDate = function() { var data = this.split(/[ -./]/); var day = parseInt(data[1]); var month = parseInt(data[0]) - 1; var year = parseInt(data[2]); var date = new Date(year, month, day); return date.getDate() === day && date.getMonth() === month && date.getFullYear() === year; } } document.write("11 02 2011".isValidDate());​ document.write("<br />"); document.write("11 32 2011".isValidDate()); Prints: true false A demo is available here.
doc_23537563
The problem that I run into, is that when one kind of header works for a certain browser, another one may break completely. For example: Cache-Control: private Works fine on Webkit browsers, and they refresh and load updated files and replace them in the cache. However Firefox and IE10 both refuse to load the new files and instead get them from the cache (not appcache!), even though they recognize the updated manifest file. Cache-Control: no-cache works fine on webkit browsers also, and also makes Firefox AND IE10 load the new files, instead of loading them from their cache, but breaks offline functionality, since they essentially don't cache (as the header would tell) the files, even though they are explicitly mentioned in the appcache manifest. Lastly, I tried Cache-Control: must-revalidate Which works similarly to no-cache but instead of Firefox and IE10 not retaining the files for offline use it's Webkit that doesn't retain them. Sending no Cache-Control header yields the same results as private or public, since I assume the browser simply assumes that as the standard way. So what am I missing? public has the same results as private and setting a max-age is not an option since updates (including Hotfixes) are not delivered on a regular basis, but instead whenever they are available or needed. Can someone shed a light on which Cache-Control header is the correct one to use, which will work on all browsers?
doc_23537564
A: Angular provides 3 different ways of parent-child interaction. The suggested way for those interactions is via bindings (Input/Output). However, if the data does not belong to the parent component, a service is probably the better way. It is more clear and keeps the data hierarchy concise. For components that are not close in the hierarchy, a service is probably the only way.
doc_23537565
Is there a way to do this with PHP? Was thinking along the lines of calling the URL with php and then create a new link for them to click on that uses the printer css. Declared the print CSS file on the webpage when user using a browser chooses to print it uses it. But I want the user to be able to view the page in print view themselves. A: Page with printer unfriendly CSS file: <a href="friendlycss.php?clicked=yes">Click me</a> Page with printer friendly CSS file: if(isset($_GET['clicked']){ echo '<link rel="stylesheet" href="link_to_sheet"></link>'; } Or, the two pages can be identical and you can set the link to call the current page: <?php if(isset($_GET['clicked']){ echo '<link rel="stylesheet" href="link_to_sheet"></link>'; } ?> <a href="<?php echo $_SERVER['PHP_SELF']; ?>?clicked=yes" /> That's all there is to it
doc_23537566
PartialView. <div class="input width110"> @Html.EditorFor(x => x.Price, @Html.Attributes(@class: "right_text_align", @disabled: "true", @id: "Price")) </div> Model. public class ServiceModel { [DisplayFormat(DataFormatString = "{0:0.00}", ApplyFormatInEditMode = true)] public decimal Price { get; set; } } Controller public ActionResult SetService(ServiceModel model, string action) { if (ModelState.IsValid) { /*Does smthg.*/ ModelState.Clear(); } return View("Index", rcpModel); //Index is main view, which holds partialView //rcpModel holds, model } When view loads Decimal is displayed in format "0.00". But after post when modelState is invalid number in displayed in format "0.0000". If model state isvalid, everything goes well. Has anyone encountered anything similar? A: If you have javascript modifying the values on textboxes (currency formatting or commas) then you might be getting binding errors because it will behave as a string. Try this: Create a BindingProperty for decimal values public class DecimalModelBinder : IModelBinder { public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) { var valueResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); var modelState = new ModelState { Value = valueResult }; object actualValue = null; try { actualValue = Convert.ToDecimal(valueResult.AttemptedValue, CultureInfo.CurrentCulture); } catch (FormatException e) { modelState.Errors.Add(e); } bindingContext.ModelState.Add(bindingContext.ModelName, modelState); return actualValue; } } On your global.asax app_start or WebActivator.PostApplicationStartMethod add an entry to register the custom binder: ModelBinders.Binders.Add(typeof(decimal), new DecimalModelBinder()); A: To display dot instead of comma is enough to change the culture to english in every point of the code which is used before the view is called. Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("En");
doc_23537567
API_KEY = "abcdefg" Then, I set the key in info.plist like this The problem is when I get the value from info.plist, the value is returned with double quotations. Bundle.main.object(forInfoDictionaryKey: "API_KEY") as! String => "abcdefg" I'd like to get the value abcdefg, which not with double quotations. I workaround by removing " by if let str = self.object(forInfoDictionaryKey: key) as? String { return str.replacingOccurrences(of: "\"", with: "") } which I don't want to do. A: Just remove the quotation marks in your config file API_KEY = abcdefg
doc_23537568
File "c:\users\agniva roy\lib\runpy.py", line 194, in _run_module_as_main return _run_code(code, main_globals, None, File "c:\users\agniva roy\lib\runpy.py", line 87, in _run_code exec(code, run_globals) File "C:\Users\Agniva Roy\Scripts\pip.exe\__main__.py", line 4, in <module> File "c:\users\agniva roy\lib\site-packages\pip\_internal\cli\main.py", line 10, in <module> from pip._internal.cli.autocompletion import autocomplete File "c:\users\agniva roy\lib\site-packages\pip\_internal\cli\autocompletion.py", line 9, in <module> from pip._internal.cli.main_parser import create_main_parser File "c:\users\agniva roy\lib\site-packages\pip\_internal\cli\main_parser.py", line 7, in <module> from pip._internal.cli import cmdoptions File "c:\users\agniva roy\lib\site-packages\pip\_internal\cli\cmdoptions.py", line 25, in <module> from pip._internal.cli.progress_bars import BAR_TYPES File "c:\users\agniva roy\lib\site-packages\pip\_internal\cli\progress_bars.py", line 12, in <module> from pip._internal.utils.logging import get_indentation File "c:\users\agniva roy\lib\site-packages\pip\_internal\utils\logging.py", line 9, in <module> import logging.handlers File "c:\users\agniva roy\lib\logging\handlers.py", line 26, in <module> import logging, socket, os, pickle, struct, time, re File "c:\users\agniva roy\lib\socket.py", line 49, in <module> import _socket ImportError: DLL load failed while importing _socket: The specified module could not be found. Please do help me out
doc_23537569
I am calculating test results for n participants and each participant has m results. This will be done in nested for loops: n x m. So first For-Loop goes into 1st Proband. Second for loop calculates the test values. The test-result for 1 test for 1 proband is returned from a function. In the end I would like to have a table like this: I struggle setting this up with data frames and vectors as I am completely new to R. Pseudo Code: final_results[][] for (each folder in path) { proband_results[] for (each file in folder) { test_result <- someFunction(file) proband_results.append(test_result) } final_results.append(proband_results) } A: As advised in Circle 2 of the R Inferno: Growing Objects, do not expand especially larger objects like matrices/arrays and data frames in a loop using cbind, rbind, append, and c operators which leads to excessive copying in memory. Instead, build lists of objects and then bind in one call outside of iterations. Alternatively, initialize a large empty container and iteratively assign values by indexes of container without appending. For the former, the approach can be facilitated with R's apply family loops known to output objects of equal length to input. Below runs sapply for files nested in a larger lapply for subfolders. Somefunction is assumed to receive one argument being file name and to return a vector. # GET TOP LEVEL SUBFOLDERS subfolders <- list.dirs(path="/my/root/path", recursive=FALSE) # ITERATE THROUGH ALL FILES OF EACH FOLDER master_list <- lapply(subfolders, function(f) { tmp_files <- list.files(path=f, pattern=".ext", full.names=TRUE) sapply(tmp_files, someFunction) # RETURNS MATRIX }) final_obj <- do.call(rbind, master_list) # MASTER MATRIX A: There is the R version based on your code. Initializing with NULL and using cbind and rbind. I am assuming the test_result is already a data.frame type. final_results= NULL for (each folder in path) { proband_results = NULL for (each file in folder) { test_result <- someFunction(file) proband_results = cbind(proband_results,test_result) # column bind } final_results = rbind(final_results,proband_results) # row bind } However, this is not an efficient way in R to combine result. Because, for example, here you are calling rbind n times, where everytime the growing final_results are called (growing memory) and using rbind. A vectorized way is (small improvement) to use list structure (linked list): final_results= NULL i = 1 for (each folder in path) { proband_results = NULL for (each file in folder) { test_result <- someFunction(file) proband_results = cbind(proband_results,test_result) # column bind } final_results[[i]] = proband_results # A list that link all proband results i = i + 1 } res = do.call("rbind",final_results) # rbind for all the element in the list This version does rbind once for all.
doc_23537570
from what i know if on the first load, the setup of player api will be run great which is the player will create when triggered on load by youtube this is my first load code (partly) window.onYouTubePlayerAPIReady = function(){ vidModal = new YT.Player('vid-modal',{events: {'onReady': onPlayerReadyModal, 'onStateChange': onPlayerStateChangeModal}, playerVars: playerDefaults}); vidbgSlider = new YT.Player('tv',{events: {'onReady': onPlayerReady, 'onStateChange': onPlayerStateChange}, playerVars: playerDefaults}); for (var i = 0; i < blockPlayerID.length; i++) { blockPlayer[i] = new YT.Player(blockPlayerID[i],{events: {'onReady': onPlayerReadyBlock, 'onStateChange': onPlayerStateChangeBlock}, playerVars: playerDefaults}); } } That all run well when web on first load...all player will create on that event "onYouTubePlayerAPIReady" but the problem is when i try to create another object player when triggered by button click...it can not : newPlayer = new YT.Player('newplayerID',{events: {'onReady': onPlayerReadyModal, 'onStateChange': onPlayerStateChangeModal}, playerVars: playerDefaults}); after create that and call "loadVideoById" it's error said that loadVideoById is not a function, anyone have solution about this? seems that function just can be loaded one time...on web first load...thank you so much before! A: After couple days..i found my own solution, so when it click i just call again the "onYouTubePlayerAPIReady" function and make validation if the player is already create or not..if not then created it..and seems that not make any error on js..thank you!
doc_23537571
One constraint is to use the least amount of "whitespace" meaning empty pixels. And the other is to specify a maximum amount of images to split it into. For example lets look at the below image. There is a lot of "whitespace" in it. I would like to divide this images into a few other images so i can reduce the amount of memory this image occupies, and also to reduce the amount of "drawing" this image will take. .=transparent pixel x=colored pixel .................... .xxxxxxxxxxx........ ...xxxx...xxxxxx.... .............xxxxx.. ...............xxx.. ...............xxx.. .................... ..xxxxxx............ .....xxxxxxxxxxx.... .........xxxxxxxxxx. .................... Let's assume i want the image to be split into a maximum of 4 images, a possible sollution would be as drawn below. .................... .111111111111111.... .111111111111111.... .............22222.. .............22222. .............22222.. .................... ..3333333........... ..33333334444444444. .........4444444444. .................... Does anyone have an algorithm for this, or knows the name of an algorithm which does this? I have been looking for a while and found some related algorithms, but the algorithms i found don't account for the whitespace e.g. they split the image into rectangles covering only the non transparent pixels, resulting in a huge amount of rectangles. The real life data i am working with are images of 1024*1024 pixels and i would prefer to reduce them into a maximum of 16 parts. the trick is to extract the 16 images using the least amount of whitespace. A: I'd go with the same algorithm as ravloony, but with a slight and important modification, using a "crop" operation that looks for the minimal/maximal columns and rows that aren't completely empty and discarding the rest. In practice, the crop operation would get a X*Y region as input and would output 4 integers - the coordinates of the smallest rectangle that contains all the used pixels of the region. This can also be used to detect and discard empty regions. Example .................... .xxxxxxxxxxx........ xxxxxxxxxxx....... ...xxxx...xxxxxx.... ..xxxx...xxxxxx... .............xxxxx.. ............xxxxx. ...............xxx.. => ..............xxx. (first crop) ...............xxx.. ..............xxx. .................... .................. ..xxxxxx............ .xxxxxx........... .....xxxxxxxxxxx.... ....xxxxxxxxxxx... .........xxxxxxxxxx. ........xxxxxxxxxx .................... Now divide the image into NxN parts (using N=4 here) and use the crop operation on each of the parts: xxxxx|xxxxx|x....| ..xxx|x...x|xxxxx| --------------------- | | xxx|xx | | ..x|xx --------------------- | | x|xx | | | --------------------- xxxx|xx...| | ...x|xxxxx|xxxxx| |...xx|xxxxx|xxx For this example, we get 10+10+10+6+4+1+2+8+15+10+3=79 pixels instead of 21*11=231 which is only 34,2%. Note that this happens to be the same amount as with your handcrafted 4-part segmentation (30+15+14+20=79)! Conclusions Of course there will be some additional data to keep track of the position and size of the 16 parts for each and it won't always give best results, but I think it's a nice compromise between speed and savings and the algorithm is easy to write and maintain. About the additional data: Images of size 1024x1024 and splitting into 4x4 parts would give you the possibility to use 4 byte values to store each rectangle, so additional data size would be only 16*4 = 64 bytes - regarding this, you should perhaps consider to increase your 16 part maximum unless it will slow down some other part like the drawing heavily. Worst cases Worst cases for this algorithm would be parts with some pixels at or near the edges set, like these: x......x xxxxxxxx xx...... ........ ........ x....... ........ ........ ........ x......x ...x.... .......x Several solutions for these come to my mind: * *Splitting the region again (ending up with a quadtree implementation) *Using some additional step to detect completely empty rectangles in the inside. *Translating the grid that defines the parts a bit A: You want to write a run-lenght or a delta compression algorithm. Or you want to use a space-filing-curve or a spatial-index. A sfc recursively subdivide the surface into smaller 4 tiles and reduce the complexity of 2 dimension to 1 dimension thus it makes it easier to identify white-space. You want to look for Nick's hilbert-curve quadtree spatial index blog. You want to download my php class hilbert curve at phpclasses.org. A: I would look at doing it recursively, each time splitting in half or into four, until you get to the level you want (for you 2 -> 4^2 = 16). At the bottom level check for empty squares and discard them. Of course this gives you a grid of rectangles proportional to the shape of the original image, rather than optimally placed rectangles, but it might start you off on the right track. A: My gut says that an ideal solution is akin to the knapsack problem and is thus computationally impractical. You may be able to use some sort of heuristic to generate a "good-enough" solution. You could use a flood-fill algorithm to select connected regions of non-transparent pixels. As a first cut, that would give you a rectangle for each disjoint area of color. If you have more rectangles available in your budget, you could try cutting them in different ways to see which gives you the highest "density" of colored pixels. A: Sorry for the late comment but it took me some time to find a "good" algorithm. After some research i am going for the following solution. First i use a Quadtree and do a SplitAndMerge. i Split on "Whitespace" first. Then i am merging all the rectangles together into the largest area rectangles. After that i sort the quadtree on area size, only keeping the largest x area's. (So essentialy keeping the largest whitespace areas). But i don't want the whitespace, i want everything except the whitespace so i invert the Quadtree, and do a SplitAndMerge Again. Then extracting the remaining rectangles out of the image, and binpacking them in the final image. This has given me some excellent results, reducing the image size drastically (because my images had a lot of whitespace in it), and keeping the time to draw them to a minimum.
doc_23537572
Join tables any-to-any row Table1 Table2 +-----+ +-----+ | A | | 1 | | B | | 2 | +-----+ +-----+ Merge Table1 and Table2 to Table3 Table3 +-----+-----+ | A | 1 | | A | 2 | | B | 1 | | B | 2 | +-----+-----+ A: The link Hakan provided is great, so I'll just summarize it here. Starting with your Table1, go to Add Column > Custom Colum and simply input Table2 as the formula. Once that column is created, click the expand button and choose which columns from Table2 to expand. This should result in the desired table.
doc_23537573
After installing, as suggested in this blog(http://blogs.msdn.com/b/tfssetup/archive/2014/01/23/connecting-to-team-foundation-server-2013-using-visual-studio-2005-thru-msscci-provider.aspx) I don't see a plugin in the source control dropdown in VS 2008(Tools -> Options->Source Control). Neither I have an option under File-> Source Control to Launch Team Foundation Server MSSCCI Provider. Please help. A: Firstly, be sure that Team Explorer 2008 is installed, then install MSSCCI 2013 provider. Secondly, once the MSSCCI 2013 provider is installed, please restart Visual Studio 2008. Then you should get these options.
doc_23537574
I've a working application (legacy) and I'm trying to add a new page in dev machine to make run some scripts so the designers don't have to do a ssh login. I want it to run the script and return it's outputs to the html page, so I've done this: url.py: url(r'^DEVUpdate', 'myviewa.views.devUpdate'), In the view: def devUpdate(request): response = os.popen('./update.sh').read() print response return render_to_response('aux/update.html', locals(), context_instance=RequestContext(request)); And in the html: Response: {{ response }} The output when I go to DEVUpdate page is, in my machine: sh: 1: ./update.sh: not found but in the html: Response: How do I get the value of response in html? PD: I want to see the message ' sh: 1: ./update.sh: not found' in the html page A: os.popen returns the output of the command on stdout. An error message like that goes to stderr, so you won't get it. Besides, os.popen is deprecated, as the docs say. Instead, use subprocess.check_output: import subprocess try: # stderr=subprocess.STDOUT combines stdout and stderr # shell=True is needed to let the shell search for the file # and give an error message, otherwise Python does it and # raises OSError if it doesn't exist. response = subprocess.check_output( "./update.sh", stderr=subprocess.STDOUT, shell=True) except subprocess.CalledProcessError as e: # It returned an error status response = e.output Lastly, if update.sh takes more than a couple of seconds or so, it should probably be a background task called by Celery. Now the whole command has to finish before Django gives a response. But that's not related to the question. A: You need to pass response in context: return render_to_response('aux/update.html', locals(), context_instance=RequestContext(request, {'response': response}); Right now you try to access response from template but you don't pass it in context
doc_23537575
However, I can't find a good entrance to start study Silverlight. Is there an article that lists the good articles that has some kind of order so I can read them to launch my study process? p.s. I have some C# basics so I do not need to learn from zero. p.s.s "The WPF / Silverlight Zone" does not help much. It has no reasonable order to show articles. A: If you are just starting out, don't start there. Instead use the tutorials posted on the silverlight.net site in the learning area - it has literally everything you need to get started, starting with stuff for new people like yourself and going all the way to advanced topics like Out Of Browser and Windows Phone development, as well as illustrating all the latest features of the platform.
doc_23537576
I implemented that scroll by CSS. Can I implement the same thing with MVC kendo? Here is my code: @(Html.Kendo().Chart() .Name("chart") .Title("Sales vs. Quotes") .Legend(legend => legend .Position(ChartLegendPosition.Bottom) ) .ChartArea(chartArea => chartArea .Background("transparent") ) .SeriesDefaults(seriesDefaults => seriesDefaults.Line().Style(ChartLineStyle.Smooth) ) .Series(series => { series.Line(ViewBag.lineGraphSales).Name("Sales"); // series.Line(new double[] { 3.907, 7.943, 7.848, 9.284, 9.263, 9.801, 3.890, 8.238, 9.552, 6.855 }).Name("Sales"); // series.Line(new double[] { 1.988, 2.733, 3.994, 3.464, 4.001, 3.939, 1.333, -2.245, 4.339, 2.727 }).Name("Quotes"); }) .CategoryAxis(axis => axis // .Categories("Jan-18", "Feb-18", "Mar-18", "APR-18", "MAY-18", "JUN-18", "JUL-18", "AUG-18", "SEP-18", "OCT-18", "NOV-18", "DEC-18") .Categories((string[]) ViewBag.lineGraphMonths) .MajorGridLines(lines => lines.Visible(false)) ) .ValueAxis(axis => axis .Numeric() .Labels(labels => labels.Format("#,##0,,")) .Line(line => line.Visible(false)) // .AxisCrossingValue(10000) ) .Tooltip(tooltip => tooltip .Visible(true) .Format("${0}") ) )
doc_23537577
#gallery_prettyphoto.portfolio a span { z-index: 2000; position: absolute; top: 0; left: 0; width: 100%; height: 98%; display: none; cursor: pointer; } .portfolio .gallery_2columns a span.image_hover {background: black url("images/gallery_hover/hover_image_big.png") no-repeat center center; } Everything was fine till i updated my theme to newer version. I checked if the hover_image_big.png was missing, no, the file is there. A: This happened to me recently and it took me a long time to find the solution, but it turns out that you have to use the write the css like this: .portfolio .gallery_2columns a span.image_hover { background: black; background: url("..images/gallery_hover/hover_image_big.png") no-repeat center center; } I hope this helps!
doc_23537578
When the user taps the UILabel I want it to trigger an IBAction method: -(IBAction)next; which updates the text on the label to say something new. It would be really convenient if this allowed me to simply drag a connection from my method to my label and then select touch up inside, as with a button. but alas, no cigar. so anyways, I guess my question is, am I going to have to subclass UILabel to get this to work? Or is there some way I can drag a button over the label, but make it 0% opaque. Or is there a simpler solution I'm missing? A: UILabel inherits from UIView which inherits from UIResponder. All UIresponder objects can handle touch events. So in your class file which knows about your view (which contains the UIlabel) implement: -(void)touchesBegan:(NSSet*)touches withEvent:(UIEvent*)event; In interface builder set the UILabel's tag value. when touches occur in your touchesBegan method, check the tag value of the view to which the tag belongs: UITouch *touch = [touches anyObject]; if(touch.view.tag == MY_TAG_VAL) label.text = @"new text"; You connect your code in your class file with the UILabel object in interface builder by declaring your UILabel instance variable with the IBOutlet prefix: IBOutlet UILabel *label; Then in interface builder you can connect them up. A: You can use a UIButton, make it transparent, i.e. custom type without an image, and add a UILabel on it (centered). Then wire up the normal button events. A: Check it out: UILabel *label = ... label.userInteractionEnabled = YES; UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(labelTap)]; [label addGestureRecognizer:tapGesture]; The trick is to enable user interaction. A: Swift 3 You have an IBOutlet @IBOutlet var label: UILabel! In which you enable user interaction and add a gesture recognizer label.isUserInteractionEnabled = true let tapGesture = UITapGestureRecognizer(target: self, action: #selector(userDidTapLabel(tapGestureRecognizer:))) label.addGestureRecognizer(tapGesture) And finally, handle the tap func userDidTapLabel(tapGestureRecognizer: UITapGestureRecognizer) { // Your code goes here }
doc_23537579
I would like to avoid repeating this con function in every reactive function and just run it once and use it. Therefore, I have put it on the server function like : server <- function(input, output, session){ con <- dbConnect(odbc(), Driver = "MSODBC", Server = "myserver", Database = "mydatabase", UID = "User", PWD = "Pass", encoding = "windows-1252", Port = 1433) on.exit(odbc::dbDisconnect(con)) main <- reactive({ squery = dbSendQuery(con,"myQuery",stringsAsFactors = FALSE) parameterNmaes = dbFetch(squery ) result= list(parameterNmaes = parameterNmaes) return(result) }) } But this does not work and I'm getting the following error : Warning: Error in new_result: external pointer is not valid 82: <Anonymous> By Putting the con function inside the reactive function main, everything is fine : server <- function(input, output, session){ main <- reactive({ con <- dbConnect(odbc(), Driver = "MSODBC", Server = "myserver", Database = "mydatabase", UID = "User", PWD = "Pass", encoding = "windows-1252", Port = 1433) on.exit(odbc::dbDisconnect(con)) squery = dbSendQuery(con,"myQuery",stringsAsFactors = FALSE) parameterNmaes = dbFetch(squery ) result= list(parameterNmaes = parameterNmaes) return(result) }) } Even I tried to export the con function as result to use it in another reactive function like : result= list(parameterNmaes = parameterNmaes, con = con) sub1 <- reactive({ con <- main()$con }) but I am getting the same error ! So far the only solution was repeating the con function over and over again in all reactive functions ! Any smart idea to prevent this pointless repeating database connection will be much appreciated. A: If you run this small app: library(shiny) ui <- fluidPage() server <- function(input, output, session){ on.exit(cat("hello")) } shinyApp(ui, server) then you will see "hello" printed in the R console whenever the app starts. That's because Shiny has finished to execute the server function. So dbDisconnect is executed in your app whenever the app starts. I would try server <- function(input, output, session){ con <- dbConnect(odbc(), Driver = "MSODBC", Server = "myserver", Database = "mydatabase", UID = "User", PWD = "Pass", encoding = "windows-1252", Port = 1433) onStop(function() odbc::dbDisconnect(con)) main <- reactive({ squery = dbSendQuery(con,"myQuery",stringsAsFactors = FALSE) parameterNmaes = dbFetch(squery ) result= list(parameterNmaes = parameterNmaes) return(result) }) }
doc_23537580
class AClass { companion object { const val CONST_VAL = "THIS IS A CONST VAL STRING" val JUST_VAL = "THIS IS A NON-CONST VAL STRING" fun aFunction() {} } } and a Main class in Java which is accessing companion members: public class Main { public static void main(String[] args) { // aFunction can only be accessed by using Companion AClass.Companion.aFunction(); // CONST_VAL can only be accessed from the parent class String constValString = AClass.CONST_VAL; // JUST_VAL can only be accessed with Companion String valString = AClass.Companion.getJUST_VAL(); } } How come, in Java, both #aFunction() and JUST_VAL can only be accessed via the Companion while CONST_VAL can only be accessed via the parent class directly? Shouldn't CONST_VAL be accessed only via the Companion as well?
doc_23537581
<header id="header"> <div id="header-inner"> <div id="top-left"> <a href="#" title="something" rel="home">Site Title</a> </div> <nav id="top-right"> <div class="menu"> <ul> <li class="current_page_item"><a href="#">Home</a></li> <li class="page_item page-item-2"><a href="#">Home2</a></li> </ul> </div> </nav> </div> </header> #header {width:100%; float:left;} #header-inner {width:600px; margin:0 auto;} #top-left {float:left;} #top-right {float:right;} I also made a jsfiddle: http://jsfiddle.net/hqpb3cyc/ The only solution I know is to give the #header and / or #header-inner float:left; or display:inline-block; But I think thats not the right way to do this!? Hope someone can help me best regards A: You have to clear floats. For example: <br style="clear: both" /> #header { width: 100%; float: left; background: #D3D3D3; } #header-inner { width: 600px; margin: 0 auto; } #top-left { float: left; } #top-right { float: right; } <header id="header" role="banner"> <div id="header-inner"> <div id="top-left"> <a href="#" title="something" rel="home">Site Title</a> </div> <nav id="top-right"> <div class="menu"> <ul> <li class="current_page_item"><a href="#">Home</a> </li> <li class="page_item page-item-2"><a href="#">Home2</a> </li> </ul> </div> </nav> </div> <!-- clear both floats --> <br style="clear: both" /> </header> Addinional you can use pseudo-element :after to clear floats: #header { width: 100%; float: left; background: #D3D3D3; } #header-inner { width: 600px; margin: 0 auto; } #top-left { float: left; } #top-right { float: right; } #header-inner:after { content: ""; clear: both; } <header id="header" role="banner"> <div id="header-inner"> <div id="top-left"> <a href="#" title="something" rel="home">Site Title</a> </div> <nav id="top-right"> <div class="menu"> <ul> <li class="current_page_item"><a href="#">Home</a> </li> <li class="page_item page-item-2"><a href="#">Home2</a> </li> </ul> </div> </nav> </div> </header> A: You should clear the floated inner element. You don't even have to change your HTML. You can do that in CSS as well by using the after pseudo element: #header {width:100%; float:left;} #header-inner {width:600px; margin:0 auto; border: 1px solid red;} #top-left {float:left;} #top-right {float:right;} #header-inner::after{ display: block; content: ""; clear: both; } <header id="header" role="banner"> <div id="header-inner"> <div id="top-left"> <a href="#" title="something" rel="home">Site Title</a> </div> <nav id="top-right"> <div class="menu"> <ul> <li class="current_page_item"><a href="#">Home</a></li> <li class="page_item page-item-2"><a href="#">Home2</a></li> </ul> </div> </nav> </div> </header> Updated fiddle
doc_23537582
I mean I can set password to make document read-only but user still can copy information and change it. I need a tool which will allow to change protection properties of worksheet programmatically. Is there anything like this in such libraries as apache poi or jxl? if not is there any library which can do it (much better if it will be free-to-use)? Thanks for your replies and sorry for my english :) A: to make your excel-sheet protected do this: sheet.getSettings().setProtected(true); and to password-protect your sheets-individually do this: sheet.getSettings().setPassword("password"); but...i've seen that password doesnt work..
doc_23537583
params = 'DRIVER={ODBC Driver 13 for SQL Server};' \ 'SERVER=localhost;' \ 'PORT=XXX;' \ 'DATABASE=database_name;' \ 'UID=XXX;' \ 'PWD=XXX;' params = urllib.parse.quote_plus(params) db = create_engine('mssql+pyodbc:///?odbc_connect=%s' % params) sql = ''' select * from table_name where column_name= variable_in_python ''' dataframe = pd.read_sql_query(sql, db) Now, after the 'where' statement, I want to have a variable that I declare in Python, for example an id-number (let's say 1123581321). This variable needs to come in that 'variable_python'-place. I tried: import pyodbc as py import urllib from sqlalchemy import create_engine import pandas as pd x = 1123581321 params = 'DRIVER={ODBC Driver 13 for SQL Server};' \ 'SERVER=localhost;' \ 'PORT=XXX;' \ 'DATABASE=database_name;' \ 'UID=XXX;' \ 'PWD=XXX;' params = urllib.parse.quote_plus(params) db = create_engine('mssql+pyodbc:///?odbc_connect=%s' % params) sql = ''' select * from table_name where column_name= 'x' ''' dataframe = pd.read_sql_query(sql, db) This obviously doesn't work. But I have not a single idea how I can do this (if it can be done). Any suggestions are more than welcome! A: You can use ? as a placeholder in the query and pass the value as a parameter to the read_sql_query function: sql = ''' select * from table_name where column_name= ? ''' dataframe = pd.read_sql_query(sql, db, params=(variable_in_python,)) A: I like the answer by @blhsing. Another way is f-strings. I particularly like them because they make things very readable. For example: # Query Parameters column_name = 'x' and then: sql = f''' select * from table_name where column_name= {column_name} ''' You could go further with this and use a dictionary of parameters and call each one by key within the f-string itself. The advantage of this method is that if you have a lot of parameters for longer and more complex queries, you always have a dictionary to refer to. Another is that when you do a print(sql) in this case, you can see exactly what parameters you are passing (this helps in the case of longer queries with more parameters). A: You can do something like: sql = ''' select * from table_name where column_name= {} '''.format(variable_in_python) For more information, have a look at https://docs.python.org/3/tutorial/inputoutput.html
doc_23537584
I need to edit this following code and insert extra echo statements. The echo statements are needed in order to markup with RDFa Lite. echo '<td><a href="sportsteam.php?id='.$row['SportsTeam_id'].'">'.$row['name'].'?></a></td> <td>'.$row['startDate'].'</td> <td>'.$row['endDate'].'</td> </tr>'; I need to insert the echo statements before and after $row['name'], $row['startDate'] and $row['endDate']. A: Better add it to a variable and concatenate with '.' $value = '<td><a href="sportsteam.php?id='.$row['SportsTeam_id'].'">'.$row['name'].'?></a></td>' ; $value .= '<td>'.$row['startDate'].'</td>'; $value .= '<td>'.$row['endDate'].'</td></tr>'; echo $value; A: If short_open_tag is activated, always on since PHP 5.4. <?='<tr>'?> <?='<td><a href="sportsteam.php?id=' . $row['SportsTeam_id'] . '">' . $row['name'] . '?></a></td>'?> <?='<td>' . $row['startDate'] . '</td>'?> <?='<td>' . $row['endDate'] . '</td>'?> <?='</tr>'?> Or... <?php echo '<tr>'; echo '<td><a href="sportsteam.php?id=' . $row['SportsTeam_id'] . '">' . $row['name'] . '?></a></td>'; echo '<td>' . $row['startDate'] . '</td>'; echo '<td>' . $row['endDate'] . '</td>'; echo '</tr>'; ?>
doc_23537585
option and start the application everything works fine: The panel is displayed in front of everything else and when the mouse cursor hovers over the panel's edges it changes from a normal arrow-cursor to the appropriate resize-cursor, so the user knows that he can resize the panel. This works fine as longs as I don't click on any other application as for example Safari or Finder. From the moment I once give focus to another application, I can click on and hover over my panel as much as I want, the cursor style will not change anymore - it always stays an arrow and it's not possible to return to the normal behavior. The panel stays selectable and in the front, you still can move and resize it, but the mouse cursor stays an arrow all the time. You then cannot even change it manually using something like: [[NSCursor crosshairCursor] set]. So I need to find a way to create a NSPanel that keeps the normal automatic-change-cursorstyle-when-hovering-over-panel-edges-behaviour even when you give focus to another application. I have already tried to use an customized NSPanel-class, where I have overwritten the canBecomeKeyWindow and canBecomeMainWindow methods, so that they return YES but even when I make my Panel KeyWindow and MainWindow... [myPanel makeKeyAndOrderFront:self]; [myPanel makeMainWindow]; ...it doesn't solve the cursor issue. Would be great if someone could help me here :) PS.: the Base SDK and the Deployment Target are set to 10.8 in my project So I found out that the described issue has nothing to to with the panel's window-state. It really doesn't matter if it is set to key or to main, instead the cursor-problem (stays arrow all the time)is related to the application's activation state. Everything works fine as long as the application that owns the panel is active but if you click on another application my application is deactivated and does not get activated again - even if you click on the panel - because the "non-activating"-option is enabled. The problem is that i need the "non activating"-option because I am creating a status-bar-screen-capturing app that should be displayed and operate in front of everything else but without deactivating any running application. I could solve the cursor problem by [NSApp activateIgnoringOtherApps]; but then taking a screenshot of a fullscreen video running in Safari would deactivate Safari and minimize the video, which I don't want. A: I don’t think it’s possible through normal APIs to change the cursor when your app isn’t active. I’m pretty sure the window system doesn’t allow it: it’d be a violation of the boundaries between apps—if you try to set a cursor from the background, and the foreground app also tries to set a cursor, who would win? Of course the system can do it (like when you take a screenshot with ⌘⇧4), because that’s in the window system itself.
doc_23537586
package main import ( "net/http" "github.com/gorilla/mux" ) func main() { mux := mux.NewRouter() mux.Handle("/", myHandler()).Methods("GET") http.ListenAndServe(":9000", mux) } type myObject interface { Start() } type Object struct { } func (o *Object) Start() { // Something wild here, for example sending out an email, // query an external DB or something similar.. } func myHandler() http.Handler { // Inject myObject-like struct somewhere here? o := Object{} return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { o.Start() w.Write([]byte("Started Object")) }) } I have a problem with testing the Object struct. What I usually do is create an interface which can be used in testing by setting up a test struct. For instance, if I had a DB connection handler, in testing I can create a mock which satisfies the handler interface and pass this to the "myHandler" call as a parmeter. Unfortunately this only works if the struct is already instantiated when the "mux.Handle" call is made. I simply don't see any simple way to test the myHandler function with an Object struct which can be injected in tests, since it will be created after the handler gets called. Any hints or ideas on how to get this done? Maybe I have to rethink my testing approach, but I would really like to unit-test the Object struct, but also test the http handler separately (as this handler may perform more tasks than just creating the Object).
doc_23537587
The problem is if you change pages it all works fine most of the time. There are 2 search features built into the page. That is where the error occurs. If you use either of them without changing pages it works great. If you use one of them and then change pages and try to use either one of them the page crashes with an error that says something like Control Parameter 'X' is not found in 'Y'. The problem is that it is not a true error because there is a button that displays the bootstrap model which displays its gridview with no issues and the ODS is based on exactly the same control so it is obviously there. I imagine that it is related to the events, but they step through just fine. I am not sure what could be causing it. Here is a little test project that is basically the same setup only paging is setup in the formview and the ODS1 in the real project and it works perfectly. <asp:FormView ID="FormView1" runat="server" DataSourceID="ObjectDataSource1"> <ItemTemplate> ImportantID: <asp:Label Text='<%# Bind("ImportantID") %>' runat="server" ID="ImportantIDLabel" Visible="false" /><br /> Name: <asp:Label Text='<%# Bind("Name") %>' runat="server" ID="NameLabel" /><br /> <div id="nestedContent"> <asp:ObjectDataSource ID="ObjectDataSource2" runat="server" SelectMethod="listNested" TypeName="TestProject.DataSourceClass"> <SelectParameters> <asp:ControlParameter ControlID="ImportantIDLabel" PropertyName="Text" DefaultValue="-1" Name="ImportantIDFromOnject1ForNestedObject" Type="Int32"></asp:ControlParameter> </SelectParameters> </asp:ObjectDataSource> <asp:GridView ID="GridView1" runat="server" DataSourceID="ObjectDataSource2" AutoGenerateColumns="False"> <Columns> <asp:BoundField DataField="YetAnotherProperty" HeaderText="YetAnotherProperty" SortExpression="YetAnotherProperty"></asp:BoundField> <asp:BoundField DataField="OtherPropertiesGoInThisClass" HeaderText="OtherPropertiesGoInThisClass" SortExpression="OtherPropertiesGoInThisClass"></asp:BoundField> </Columns> </asp:GridView> </div> SomeProperty: <asp:Label Text='<%# Bind("SomeProperty") %>' runat="server" ID="SomePropertyLabel" /><br /> SomeOtherProperty: <asp:Label Text='<%# Bind("SomeOtherProperty") %>' runat="server" ID="SomeOtherPropertyLabel" /><br /> <asp:ObjectDataSource ID="ObjectDataSource3" runat="server" SelectMethod="GetDataObject2" TypeName="TestProject.DataSourceClass"> <SelectParameters> <asp:ControlParameter ControlID="ImportantIDLabel" PropertyName="Text" DefaultValue="-1" Name="ImportantID" Type="Int32"></asp:ControlParameter> </SelectParameters> </asp:ObjectDataSource> <div id="BootStrapModalPopup"> This displays the data with no problems </div> </ItemTemplate> </asp:FormView> <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" SelectMethod="GetDataObject1" TypeName="TestProject.DataSourceClass"> <SelectParameters> <asp:Parameter DefaultValue="-1" Name="ImportantID" Type="Int32"></asp:Parameter> <asp:Parameter DefaultValue="" Name="Name" Type="String"></asp:Parameter> <asp:Parameter Name="SomeProperty" Type="String"></asp:Parameter> </SelectParameters> </asp:ObjectDataSource> I would appreciate any ideas of where to look next. By the way I have used a textbox, hiddencontrol and Session variable for the ID field and nothing makes a difference for it. If I disable the ODS2 it goes back to working perfectly also but I need that data. Thanks Jimmy A: I actually lucked into the answer for this. It was not my nesting it was my paging. I will leave the question for anyone that has a similar problem since I don't see any successful errors to this. The issue I faced was I needed to reset my pageindex on search. It worked great searching from page one, but searching from any other page is an empty return due to the indexing so the controls did not exist. Hopefully it will help someone to search that if you run into this issue. Just set pageindex on the formview back to 0.
doc_23537588
tab2 <- tableGrob(df2) tab3 <- tableGrob(df3) pdf("file.pdf", height = 20, width = 15, pagecentre = FALSE) grid.arrange(tab2, tab3, ncol = 2, nrow = 1)) dev.off() How do I fix this using layout()? I looked at the function but can't understand how the to set the matrix. I'd also like to add table titles. Do I do this with using a data frame function or while writing to df to pdf?
doc_23537589
I have a trigger where the executed function must run as SECURITY DEFINER, but must receive the CURRENT_USER who raised the trigger. If I pass CURRENT_USER (unquoted) as a parameter, then, in the function, TG_ARGV[0] is the text string: "CURRENT_USER"... but I need "jq_public" or whatever the user's id was when the trigger fired. If it's running as SECURITY DEFINER, then, in the function body, CURRENT_USER is always the function's owner. Executing a wrapper routine and passing CURRENT_USER down to another routine (foo) works, but then I must GRANT EXECUTE ON foo TO PUBLIC. If I could do that, I wouldn't be writing this question. I need to grab the value of CURRENT_USER as a text string within the actual trigger and pass that down to the function. I don't need TG_ARGV explained and I don't want to go into why I'm doing that... although, I'd like to hear alternative methods of getting the CURRENT_USER into a SECURITY DEFINER trigger routine. I considered nesting subroutine definitions like we used to do in Ada and Pascal, but that has become extinct. I think that, if I could have two trigger routines where one acted as a wrapper calling the other, it might work, but I don't want to do any additional GRANTs. I tried writing a function that returned CURRENT_USER as a text string, the function worked but gave me a syntax error when I tried to pass the function call as a parameter within the trigger.
doc_23537590
[2013-06-04 02:02:10 - Dex Loader] Unable to execute dex: Target out of range: +0000fffa [2013-06-04 02:02:10 - MyApp] Conversion to Dalvik format failed: Unable to execute dex: Target out of range: +0000fffa
doc_23537591
example A1 =26 A2 =14 A3 =14 A4 =14 A5 =26 A6 =3 A7 =16 A8 =16 A9 =26 Result would be:26 and not 14 A: Array formulas to the rescue: =MODE(IF(A1:A6 <> 14,A1:A6)) Enter it via Ctrl + Shft + Enter A: Not very elegant, but it works: =(SUM(C3:C11)-COUNTIF(C3:C11,14)*14)/(COUNT(C3:C11)-COUNTIF(C3:C11,14)) c3:c11 is the range I am looking at on my test sheet. I am basically looking for the sum of all values in the considered range, subtract 14 times the occurence of the number 14 from this sum and then divide the result by the total number of cells minus the occurences of 14 again. The whole thing will look much nicer, if you have the luxury of another cell that could serve as the "14-counter". Edit: I overlooked the word "mode" in the question. This answer will only compute the average ...
doc_23537592
I have a VS2017 C# Windows Forms solution, .NET 4.5.2, with WCF Service Application using Entity Framework 6.2, that includes a logic layer, BDO layer and data layer. My entity context was created database-first. My service is self-hosted in my UI client project's Program.cs file. The transport is net.pipe since both the client and services are on the same computer. My database is remote, version SQL Server 2016 (130), requiring user id and password, and its connection string works great when defined in the App.config for my UI client project. But, I am currently trying to remove the connection string from App.config and to code it in the Program.cs Main() method for security purposes. I am using SqlConnectionStringBuilder and EntityConnectionStringBuilder to build the entity connection string "provider" and "metadata" pieces, and I can build the same connection string in my Program.cs code as I'm using in App.config. But, when my code opens the entity connection, I get an error: System.Data.MetadataException: Unable to load the specified metadata resource. Here is my App.config connectionString section which works fine: <connectionStrings> <add name="MyDBEntities" connectionString="metadata=res://*/MyDB.csdl|res://*/MyDB.ssdl|res://*/MyDB.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=myremotewebsite.com;initial catalog=MyDB;persist security info=True;user id=theUserID;password=thePassword;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" /> </connectionStrings> And here is my C# code from Program.cs in UI client project: using System.ServiceModel; using System.Windows.Forms; using System.Data.SqlClient; using System.Data.EntityClient; namespace myUICLient { static class Program { public static ServiceHost hostMyService; // Specify the provider name, server and database. public static string sqlProvider = "System.Data.SqlClient"; public static string serverName = "myremotewebsite.com"; public static string databaseName = "MyDB"; public static string userID = "theUserID"; public static string passWord = "thePassword"; public static string App = "EntityFramework"; public static string providerString; public static SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder(); public static EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder(); public static EntityConnection MyDBEntities; [STAThread] static void Main() { hostMyService = new ServiceHost(typeof(prjMyServiceApplication.MyService), new Uri("net.pipe://localhost/prjUICLient/MyService.svc")); hostMyService.Open(); // Set the properties for the data source. sqlBuilder.DataSource = serverName; sqlBuilder.InitialCatalog = databaseName; sqlBuilder.UserID = userID; sqlBuilder.Password = passWord; sqlBuilder.IntegratedSecurity = false; sqlBuilder.PersistSecurityInfo = true; sqlBuilder.MultipleActiveResultSets = true; sqlBuilder.ApplicationName = App; // Build the SqlConnection connection string. providerString = sqlBuilder.ToString(); // Set the provider name. entityBuilder.Provider = sqlProvider; // Set the Metadata location. entityBuilder.Metadata = @"res://*/MyDB.csdl|res://*/MyDB.ssdl|res://*/MyDB.msl"; // Set the provider-specific connection string. entityBuilder.ProviderConnectionString = providerString; using (MyDBEntities = new EntityConnection(entityBuilder.ToString())) { MyDBEntities.Open(); // gets the error here! Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new myWinForm()); hostMyService.Close(); MyDBEntities.Close(); } } } } When the code errors out, I can view the metadata portion of connection string in the error data, and also see a "Server Version" error: "metadata=res://*/MyDB.csdl| res://*/MyDB.ssdl| res://*/MyDB.msl; provider=System.Data.SqlClient;provider connection string=\"Data Source=myremotewebsite.com; Initial Catalog=MyDB;Integrated Security=False;Persist Security Info=True; User ID=MyUserID;Password=MyPassword; MultipleActiveResultSets=True;Application Name=EntityFramework\"" MyDBEntities.ServerVersion = 'MyDBEntities.ServerVersion' threw an exception of type 'System.InvalidOperationException' When I comment out the Open() statement in Main() and run again, I get the following error from the DAL layer when the Service call is made: The underlying provider failed on Open Thanks for any help or advice you have to offer. Update 2021.03.04 after finding the folder location of the model files in my data layer project under this path: prjDAL . obj . Release . edmxResourcesToEmbed . MyDB.csdl, MyDB.msl, MyDB.ssdl I changed my metadata string to the following: entityBuilder.Metadata = @"res://prjDAL.dll/MyDB.csdl| res://prjDAL.dll/MyDB.ssdl| res://prjDAL.dll/MyDB.msl"; And reran, got this new error: System.IO.FileNotFoundException: 'Unable to resolve assembly prjDAL.dll. I have read the article in the recommended link and what I have learned so far is that the "Resource" and the "Model" are two different things. The examples in the linked article look like MVC examples where the connection string is in the App.config file. I'm not using MVC, but .NET 4.5.2 n-Tier winforms design, and I don't have a problem when I use the connection string in the App.config file. My problem comes when trying to create the connection string in code, and trying to open the EntityConnection object. Here are more options I have tried: This metadata: entityBuilder.Metadata = @"res://prjDAL.dll/resources.MyDB.csdl| res://prjDAL.dll/resources.MyDB.ssdl| res://prjDAL.dll/resources.MyDB.msl"; Gets this error: System.IO.FileNotFoundException: Unable to resolve assembly 'prjDAL.dll'. And this metadata: entityBuilder.Metadata= @"res://prjUICLient/bin/prjDAL.dll/ prjUICLient.Resources.MyDB.csdl| res://prjUICLient/bin/prjDAL.dll/ prjUICLient.Resources.MyDB.ssdl| res://prjUICLient/bin/prjDAL.dll/ prjUICLient.Resources.MyDB.msl"; Gets this error: System.Data.MetadataException: The specified metadata path is not valid. A valid path must be either an existing directory, an existing file with extension '.csdl', '.ssdl', or '.msl', or a URI that identifies an embedded resource. Tried again pointing metadata to assembly in DAL layer: entityBuilder.Metadata = @"res://prjDAL/obj/Release/prjDAL.dll/ prjDAL.obj.release.edmxResourcesToEmbed.MyDB.csdl| res://prjDAL/obj/Release/prjDAL.dll/ prjDAL.obj.release.edmxResourcesToEmbed.MyDB.ssdl| res://prjDAL/obj/Release/prjDAL.dll/ prjDAL.obj.release.edmxResourcesToEmbed.MyDB.msl"; System.Data.MetadataException: The specified metadata path is not valid. A valid path must be either an existing directory, an existing file with extension '.csdl', '.ssdl', or '.msl', or a URI that identifies an embedded resource. Has anyone made this Entity connection string conversion from App.config to code in a .NET 4.5.2 WinForms multi-tiered application? Do I need to upgrade my application to .NET Standard or .NET CORE?
doc_23537593
But file upload not working because below error. Unable to move '/tmp/phpxQHW5q' to '/var/www/html/mri_image/test.jpg' in /var/www/html/server_form.php on line 49, referer: http://192.168.1.12/client_form.php I have searched this problem at stackoverflow. Most solution is permision problem. So, tmp and mri_image folder own by apache and changed mod 755. Then, not working i want to your help For reference, my os is CentOS 7, php version is 7.3 A: I had an issue recently with Apache and PHP trying to write to /tmp, but stating that the script failed with an error "No such file or directory" Centos 7 uses systemd, which has an awesome feature (PrivateTmp) that breaks Apache/PHP access to /tmp folders (particularly in cases where the files need to be shared to other processes/seen by others. This feature works by creating a sort of "virtual" /tmp directory for each process, so a file seen by Apache wouldn't be seen by PHP, etc. First, copy the httpd.service and php-fpm.service files from /usr/lib/systemd/system/ to /etc/systemd/system using the commands below. cp /usr/lib/systemd/system/httpd.service /etc/systemd/system/. && cp /usr/lib/systemd/system/php-fpm.service /etc/systemd/system/. After copying those into place, edit each copy of the files in the new location and change the line with PrivateTmp=true to PrivateTmp=false using vi, or your preferred text editor. vi /etc/systemd/system/httpd.service vi /etc/systemd/system/php-fpm.service After those changes, you need to restart systemd, as well as php-fpm and apache. Restart systemd: sudo systemctl daemon-reload Restart apache: sudo systemctl restart httpd Restart php-fpm: sudo systemctl restart php-fpm
doc_23537594
public void ExecuteList<T, T1>(out List<T> obj, out List<T1> obj1, string sql, params object[] parameters) where T : class { using (var db = _context) { var cmd = db.Database.Connection.CreateCommand(); cmd.CommandText = sql; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddRange(parameters); try { db.Database.Connection.Open(); using (var reder = cmd.ExecuteReader()) { obj = ((IObjectContextAdapter)db).ObjectContext.Translate<T>(reder).ToList(); reder.NextResult(); obj1 = ((IObjectContextAdapter)db).ObjectContext.Translate<T1>(reder).ToList(); } } finally { db.Database.Connection.Close(); cmd.Dispose(); } } } Call this method List<SqlParameter> parameterList = new List<SqlParameter>(); parameterList.Add(new SqlParameter("@pageNo", 1)); parameterList.Add(new SqlParameter("@pageSize", 5)); SqlParameter[] parameters = parameterList.ToArray(); List<PostModel> PostList = new List<PostModel>(); List<Tag> TagList = new List<Tag>(); Uow.ExecuteList<PostModel,Tag>(out PostList, out TagList, "[dbo].[sp_getdata]", parameters); Here I pass postmodel and tag class for casting and also pass two out parameter PostList and TagList for result. It will return perfect result. But my requirement is these casting classes and out parameters should be optional. Like this: When I want one Result then pass one casting class and one Out parameter. List<SqlParameter> parameterList = new List<SqlParameter>(); parameterList.Add(new SqlParameter("@pageNo", 1)); parameterList.Add(new SqlParameter("@pageSize", 5)); SqlParameter[] parameters = parameterList.ToArray(); List<PostModel> PostList = new List<PostModel>(); Uow.ExecuteList<PostModel>(out PostList, "[dbo].[sp_getdata]", parameters); And when I want two Result then pass two casting class and two out parameter. List<SqlParameter> parameterList = new List<SqlParameter>(); parameterList.Add(new SqlParameter("@pageNo", 1)); parameterList.Add(new SqlParameter("@pageSize", 5)); SqlParameter[] parameters = parameterList.ToArray(); List<PostModel> PostList = new List<PostModel>(); List<Tag> TagList = new List<Tag>(); Uow.ExecuteList<PostModel,Tag>(out PostList, out TagList, "[dbo].[sp_getdata]", parameters); Please help me to solve my issue A: You can create several overloads which will call the same private method: private void Execute<T, T1>(ref List<T> obj, ref List<T1> obj1, string sql, params object[] parameters) where T : class { using (var db = _context) { var cmd = db.Database.Connection.CreateCommand(); cmd.CommandText = sql; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddRange(parameters); try { db.Database.Connection.Open(); using (var reader = cmd.ExecuteReader()) { obj = ((IObjectContextAdapter)db).ObjectContext.Translate<T>(reader).ToList(); if(obj1 != null) { reader.NextResult(); obj1 = ((IObjectContextAdapter)db).ObjectContext.Translate<T1>(reader).ToList(); } } } finally { db.Database.Connection.Close(); cmd.Dispose(); } } } public void ExecuteList<T, T1>(out List<T> obj, out List<T1> obj1, string sql, params object[] parameters) where T : class { obj = new List<T>(); obj1 = new List<T1>(); Execute(ref obj, ref obj1, sql, parameters); } public void ExecuteList<T>(out List<T> obj, string sql, params object[] parameters) where T : class { obj = new List<T>(); List<object> stub = null;//generic argument doesn't matter because it will not be used Execute<T, object>(ref obj, ref stub, sql, parameters); } Note that my first method is private and should be called only from public overloads(it's possible to add as many output parameters/overloads as you wish). Also probably it makes sense to restrict T1 to class as well and use List<SqlParameter> instead of params object[] parameters as a last parameter.
doc_23537595
This is the table I would like to partition: CREATE TABLE `market` ( `leagueID` int(10) unsigned NOT NULL, `playerID` smallint(5) unsigned NOT NULL, `userID` int(10) unsigned DEFAULT, `price` int(10) unsigned NOT NULL , `date` int(10) unsigned NOT NULL, UNIQUE KEY `league_player` (`leagueID`,`playerID`), KEY `user_date` (`userID`,`date`) ); Which approach (column, ranges, number of partitions, etc.) do you recommend? This is my initial approach: ALTER TABLE market PARTITION BY HASH(leagueID) PARTITIONS 10; A: Why do you want to partition? I ask because most attempts at partitioning gain nothing. No performance boost; sometimes performance degradation. In particular BY HASH rarely helps. Are you using MyISAM? If so switch to InnoDB. Since you mentioned 'deadlocks', maybe you are already using InnoDB? Partitioning won't help in transaction deadlocks; we need to look at the queries in the two transactions. The solution may be as simple as sorting an IN list. But... Regardless of whether we 'solve' the deadlock you are having today, you need to check for errors and replay the entire transaction that was aborted. That's the only sure way to 'solve' deadlocks. Datacharmer's slides give you the gory details; my blog lists the very few cases where PARTITIONing is useful, thereby making most of his slides useless. Other issues... * *I don't see a PRIMARY KEY. Recommend you change your UNIQUE key to PRIMARY KEY. InnoDB really needs a PK. *There is a DATE datatype; it might be less clumsy to use than some INT. A: I've seen something similar a couple times now, and I'm not convinced that partitioning will solve your problem. The deadlock you're seeing on the unique index might be due to two non-conflict-violating inserts using the same database page which the lock is on. Due to the B-tree structure of the index, if a single league is write heavy in a particular window in time (seems plausible), there is a higher probability that there will be a race condition for the mutex on that page being hit. I'd consider distributing the index "hot spot" physically by changing the order of the two fields in the unique constraint, and adding the existing index as a regular index (for lookup reasons). ALTER TABLE `market` ADD UNIQUE KEY player_league (`playerID`,`leagueID`), DROP UNIQUE KEY `league_player`, ADD KEY league_player (`leagueID`,`playerID`); On that note, as you don't have a primary key yet (but InnoDB is gonna create one behind the scenes anyway), it logically makes sense for the new key to take on that role. ALTER TABLE `market` ADD PRIMARY KEY (`playerID`,`leagueID`), DROP UNIQUE KEY `league_player`, ADD KEY league_player (`leagueID`,`playerID`);
doc_23537596
I can mock the server with Pretender, but I need to know how to fill the input type="file" field with a file from my filesystem. So the questions are basically: * *How to fill the input file field with ember test helpers, do I use fillIn helper? *How to add sample files to a folder and get them from my acceptance test. Is it possible to get the current path of my Ember project from the acceptance test to select a file from the filesystem to be uploaded? In Rails we use to use Rails.root for this purpose. A: I solved it differently: I don't upload a file from the file system, but create a Blob manually and use triggerHandler on the input element: let inputElement = $('input[type=file]'); let blob = new Blob(['foo', 'bar'], {type: 'text/plain'}); blob.name = 'foobar.txt'; inputElement.triggerHandler({ type: 'change', target: { files: { 0: blob, length: 1, item() { return blob; } } } }); This triggers the upload. A: You can't use anything like fillIn to set up the file field with a file value ready to upload because the browser won't let you: How to set a value to a file input in HTML? I think the only possible way to pull this off would be to use xhr to download a file that exists on a server and then use xhr to upload it. I can't think of any way you could programmatically set the value of the file input field without introducing the security concern explained in that SO question I linked to. Here's somewhere to start when working with the demo file you want to test upload after you've downloaded it form a http url: https://developer.mozilla.org/en-US/docs/Web/API/FileReader
doc_23537597
Error in UseMethod("predict") : no applicable method for 'predict' applied to an object of class "list" > Is there any way to cast the list element back to the correct type? edit: thanks to @李哲源, the code immediately below does work: models <- list(m, logit, loglog) plot(x,y) abline(models[[1]],col="black",lty=2) lines(x,predict(models[[2]], df),col="red",lty=3) original code: if(!require(betareg)){install.packages("betareg")} set.seed(123) x=seq(1,9,1) print(x) y=x/10+0+rnorm(length(x),0,.1) print(y) m=lm(y~x) logit<-betareg(y~x,na.action=na.omit) plot(x,y) abline(m,col="red",lty=2) #lines(x,predict(logit, y),col="green",lty=3) models=c(m,logit) abline(models[1],col="blue",lty=4) lines(x,predict(models[2], y),col="blue",lty=5) A: A regression model is stored as a "list" with special "class". Direct concatenation using c drops such "class". Check length(models): you have 41 not 2. Use either of the following models <- c(list(m), list(logit)) models <- list(m, logit) to preserve "class" of regression models, and use models[[1]] and models[[2]] to access those models (for example, abline(models[[1]]) and predict(models[[2]], y)). Alternatively, set up a proper list beforehand and fill in (this is useful if you store models in a loop) models <- vector("list", 2) models[[1]] <- m models[[2]] <- logit
doc_23537598
A>E>D>S>H...... I tried more to find an example also I searched more but I couldn't find particular example searched I need any one help me! A: Are you refering to a page navigation breadcrumb that lists the heirarchy of parent pages based on the current child page? If so you can use the ASP:Sitemappath control which reads from a Web.sitemap file within your ASP .Net solution. This is appropriate for most static ASP .Net websites where you are manually keeping the sitemap up to date. If you are using a content management system there is usually a mechanism to generate the sitemap content dynamically. A: You want to this. http://en.wikipedia.org/wiki/Breadcrumb_%28navigation%29 You google breadcrumb keyword with which programming language you want to use.
doc_23537599
my current problem now is actually if the algorithm in the google maps implementation in finding the path from an origin to a destination point can be overriden. thank you for your understanding and any help will be appreciated. :)