text
stringlengths
14
21.4M
Q: What is the par baseName in ZIP a Folder in Android? The following code is from the article at What is a good Java library to zip/unzip files? The code compresses a folder and all included files and sub folders to a zip file. I can't understand what the par BaseName means, and how to pass a value to the par baseName ? private void addFolderToZip(File folder, ZipOutputStream zip, String baseName) throws IOException { File[] files = folder.listFiles(); for (File file : files) { if (file.isDirectory()) { addFolderToZip(file, zip, baseName); } else { String name = file.getAbsolutePath().substring(baseName.length()); ZipEntry zipEntry = new ZipEntry(name); zip.putNextEntry(zipEntry); IOUtils.copy(new FileInputStream(file), zip); zip.closeEntry(); } } } A: I think folderAbsolutePath would have probably be a better name than baseName. Basically, as can seen in the line String name = file.getAbsolutePath().substring(baseName.length());, takes only the name relative to folder path. The reason it is needed is because this method in recursive, so there's a need to pass the original folder path, in order to figure out relative file names. You probably don't want to use this method directly, but wrap it with another method like: private void addFolderToZip(File folder, ZipOutputStream zip){ addFolderToZip(folder, zip, folder.getAbsolutePath()); } or more useful: public void zip(String sourceFileName, String zipName){ File file = new File(source); FileOutputStream fileStream = new FileOutputStream(zipName); BufferedOutputStream bufferdStream = new BufferedOutputStream(fileStream); ZipOutputStream zip = new ZipOutputStream(bufferdStream); if (sourceFile.isFolder){ addFolderToZip(file, ZipOutputStream zip, sourceFile.getAbsolutePath()); } else { // some other handling for a single file int filePathLength = file.getAbsolutePath().length(); int fileNameLength = file.getName().length(); String basePath = file.getAbsolutePath().substring(0, filePathLength - fileNameLength); addFolderToZip(file, ZipOutputStream zip, basePath); } zip.close(); } A: Suppose this is the directory structure: mnt/sdcard/Android/data/testzip/ is the directory where all your files to be archived are presenet as follows under tobezipped directory: mnt/sdcard/Android/data/testzip/tobezipped/1.txt mnt/sdcard/Android/data/testzip/tobezipped/directory/2.txt If we want to create archive all of the above files and directory, we need to provide a name for the archive, and let it be zipcreated.zip which is created under the directory mnt/sdcard/Android/data/testzip/ as mnt/sdcard/Android/data/testzip/zipcreated.zip Below is the code for the directory to be archived: new Thread(new Runnable() { @Override public void run() { // Moves the current Thread into the background android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND); //tobezipped holds the content of the directory or folder to be zipped //zipcreated.zip zips or archive holds the contents of the tobezipped after archived ZipUtils.createZipFileOfDirectory("mnt/sdcard/Android/data/testzip/tobezipped/", "mnt/sdcard/Android/data/testzip/zipcreated.zip"); } }).start(); ========================================================================== import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; import org.apache.commons.io.IOUtils; /** * Created by Android Studio * User: Anurag Singh * Date: 28/2/17 * Time: 2:14 PM */ public class ZipUtils { private static final String TAG = ZipUtils.class.getSimpleName(); public static void createZipFileOfDirectory(String srcDir, String zipOutput) { try{ File srcDirFile = new File(srcDir); File zipOutputFile = new File(zipOutput); if ( !srcDirFile.exists() || !srcDirFile.isDirectory() ) { throw new IllegalArgumentException( srcDirFile.getAbsolutePath() + " is not a directory!"); } if ( zipOutputFile.exists() && !zipOutputFile.isFile() ) { throw new IllegalArgumentException( zipOutputFile.getAbsolutePath() + " exists but is not a file!"); } ZipOutputStream zipOutputStream = null; String baseName = srcDirFile.getAbsolutePath() + File.pathSeparator; try { zipOutputStream = new ZipOutputStream(new FileOutputStream(zipOutput)); addDirToZip(srcDirFile, zipOutputStream, baseName); } finally { IOUtils.close(zipOutputStream); } }catch(Exception e){ e.printStackTrace(); } } private static void addDirToZip(File dir, ZipOutputStream zip, String baseName) throws IOException { File[] files = dir.listFiles(); for (File file : files) { if (file.isDirectory()) { addDirToZip(file, zip, baseName); } else { String entryName = file.getAbsolutePath().substring( baseName.length()); ZipEntry zipEntry = new ZipEntry(entryName); zip.putNextEntry(zipEntry); FileInputStream fileInput = new FileInputStream(file); try { IOUtils.copy(fileInput, zip); zip.closeEntry(); } finally { IOUtils.close(fileInput); } } } } } What is baseName? baseName is used as a support for entryName in ZipUtils.addDirToZip() to get the file or directory name to be archived from in this case. baseName=/mnt/sdcard/Android/data/testzip/tobezipped: entryName=1.txt entryName=directory2/2.txt Basically, base name is nothing but the file names under directory mnt/sdcard/Android/data/testzip/tobezipped/. entryName cannot be directory2 becasue it's a directory.
Q: GetSerializableExtra returning null I need a little help to solve the following question. I have two activities, A and B. The activity A start B for result, and B sends back to A a serializable object. Activity a starting activity B: ... Intent intent = new Intent(MainActivity.this, ExpenseActivity.class); startActivityForResult(intent, EXPENSE_RESULT); ... Activity B sending data to A: ... ExpensePacket packet = new ExpensePacket(); ... Intent returnIntent = new Intent(); returnIntent.putExtra(MainActivity.PACKET_INTENT,packet); setResult(RESULT_OK,returnIntent); finish(); Point where the activity A gets the data sent from B: protected void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == EXPENSE_RESULT) { if(resultCode == RESULT_OK){ ExpensePacket result = (ExpensePacket)getIntent().getSerializableExtra(PACKET_INTENT); wallet.Add(result); PopulateList(); } else{ //Write your code otherwise } } } My Serializable object, the one who is sent from B to A: class ExpensePacket implements Serializable { private static final long serialVersionUID = 1L; private Calendar calendar; public void SetCalendar(Calendar aCalendar){ calendar = aCalendar; } public Calendar GetCalendar(){ return calendar; } public String GetMonthYear() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy"); sdf.format(calendar.getTime()); String returnString = ""; returnString += sdf.toString(); returnString += "/"; returnString += Functions.GetMonthName(calendar); return sdf.toString(); } } Somebody can help me to figure out why the data sent from B to A is a null pointer. A: I think I found your error: In your onActivityResult() method, you should use the Intent "data" parameter, instead of the getIntent() method. getIntent() returns the Intent used to invoke the Activity, not the Intent returned by the Activity invoked by startActivityForResult(). The result Intent is the "data" parameter passed in onActivityResult(). You should recover your Serializable object from there. I made a small project with your code and can reproduce your problem. Changing getIntent() with data parameter solved the issue. Just one more thing: I think you have another error in ExpensePacket.getMonthYear(), because you construct the String returnString, but return something else. Just check that part too to be sure you're doing what you want.
Q: redeclaration of C++ built-in type 'wchar_t' windows 10 glut cpp I'm trying to run some Glut app in c++, but my codeblocks gives me an error redeclaration of C++ built-in type 'wchar_t' and it points into glut.h file line 50 : typedef unsigned short wchar_t; I've downloaded this program and moved all src files in new codeblocks project http://www.mindcontrol.org/~hplus/graphics/fire-particles.html how to fix it? A: I have faced the sane problem. And that is how I have solved the problem. #include<windows.h> #include<bits/stdc++.h> #include <GL/glut.h> <windows.h> should be added at first or it will show a error. I hope it will solve the problem Thanks
Q: How can i get a live view of syslog-ng logs in a webfrontend? I currently have Syslog-ng set up to aggregate my logs. I want to show these logs in real time to my web frontend users. I however have no clue how to do this, is it possible to connect directly to Syslog-ng using WebSockets? Or do I need to first pass it on to something like elasticsearch, if so, how do I get my data live from elasticsearch? I found this table in the Syslog-ng documentation, but iIcould not find any output destination that would solve my problem. A: Unfortunately currently there's no mechanism to export real-time log traffic for a generic destination. You could however write your configuration in a way that places log information for a frontend to read. For instance, if you have a log statement delivering messages to elastic: log { source(s_network); destination(d_elastic); }; you could add an alternative destination to the same log statement, which would only serve as a buffer for exporting real-time log data. For instance: log { source(s_network); destination(d_elastic); destination { file("/var/log/buffers/elastic_snapshot.$SEC" overwrite-if-older(59)); }; }; Notice the 2nd destination in the log statement above, with curly braces you tell syslog-ng to use an in-line destination instead of a predefined one (or you could use a full-blown destination declaration, but I omitted that for brevity). This new file destination would write all messages that elastic receives to a file. The file contains the time based macro $SEC, meaning that you'd get a series of files: one for each second in a minute. Your frontend could just try to find the file with the latest timestamp and present that as the real-time traffic (from the last second). The overwrite-if-older() option tells syslog-ng that if the file is older than 59 seconds, then it should overwrite it instead of appending to it. This is a bit hacky, I even intend do implement something what you have asked for in a generic way, but it's doable even today, as long as the syslog-ng configuration is in your control.
Q: Is the solution set of Ax β‰₯ B convex set in different situation $\Omega_1:\{x\in R^n|Ax=b,x\ge0 \}$ $\Omega_2:\{x\in R^n|Ax\ge b\}$,$A$ is full row rank matrix. $\Omega_3:\{x\in R^n|Ax\ge b\}$,$A$ is full column rank matrix. Provided $\Omega_1,\Omega_2,\Omega_3 $ are not empty,then which set is to (must) have extreme point? I consider that I could prove it by proving the set to be convex set, but I have no idea how to do that.
Q: Ubuntu 20.04 newly installed; No ethernet connection I'm aware of the number of similar questions in this site, but most that I saw have solution's that require special permissions, which in my case are not available to me. I've just insalled Ubuntu 20.04 in a Dualboot. After plugging the Ethernet cable, I get a "Connected - 100 Mb/s" but a question mark appears on the network symbol. I cannot use Mozilla Firefox to open any site. It doesn't explicitly says "No connection", but it keeps loading forever. I tried desabling Ipv6 as some suggested in this site but it didn't work. A very similar problem to mine (I am unfortunately not able to link the question since I'm writing from my phone) suggested creating the file 10-globally-managed-devices.conf which should be located at /etc/NetworkManager/conf.d (the file doesn't exist for me). I however do not have the write/execute permissions on this folder nor I am able to put myself as owner. Any ideas would be gratly appreciated. I'm available to provide any information/command outputs that are necessary. A: Create the file with sudo in terminal. sudo touch /etc/NetworkManager/conf.d/10-globally-managed-devices.conf
Q: Create different margin setting for section 2 (dynamically) I have a Word template that has for starting only 1 page and that page has specific margins and header/footer pictures. The problem is that if the user fills the 1st page and jumps to the 2nd page or adds a page break/section break the same margins and header/footer are applied. Is there a solution where I can add a default margin and header/footer picture after 1st page? A: Respectfully, I disagree with the previous response, even though it answered the question as asked. That suggested a Section break, which is the only way to change margins. The problem is that in Word, the user does not really want to change the margin. There are standard, tried and true, methods for creating letterhead where the first page looks and acts as if there are different margins, without a section break. * *Setting Up Letter Templates by Word MVP Suzanne Barnhill *How Can I Have a Different Header/Footer on the Second Page? (my page) *Basic Letterhead Template (my page) The basic idea to simulate different margins within the same section is to insert a borderless TextBox or Frame with wrapping in either the first-page header or the first-page footer. This structure acts like a temporary margin, pushing text in the body out of the way. The actual page margin settings are the same throughout, but they appear to be different on the first page. That is, the margins are set for both pages at the settings for the second and following pages. Done this way, the user simply types on the first page as with any Word document. When text flows onto the second page it will act as if there are different margins even though there are not. This method works for all four sides of the paper, independently. If you have a section break, the user must be cognizant of that section break and type around it. You may also want to look at my writing on Margins and Indents. A: Add a new section and page to the template and apply the required setting to that section. Your template will now have two pages, the second page will be empty but with all the correct settings. Step by step instructions for Word 2010: * *Under the Page Layout menu click the Breaks drop-down menu and select Next Page (below the Section Breaks grey title). A new section and a new page are added. *Under the Page Layout menu click the Margins drop-down menu and apply your desired settings. *Initially the header and footer will be the same as the first section so click the Link to Previous button under the Design menu (this menu is displayed only when editing the header or footer). *Save the template.
Q: Connection refused - connect(2) for "localhost" port 25 rails During my training, I'm working on a website and we use Ruby on Rails. We need to send mails to users so I created a mailer. I have tried to put the smtp in both development.rb and environment.rb config.action_mailer.default_url_options = {host: '0.0.0.0:3000'} config.action_mailer.default charset: 'utf-8' config.action_mailer.delivery_method = 'smtp' config.action_mailer.perform_deliveries = true config.action_mailer.smtp_settings = { adress: $SMTP_SERVER, port: $PORT, from: $MAIL, enable_starttls_auto: true #authentication: 'login' } It tells me that the error comes from this method line 6 def create @user = User.new(user_params) respond_to do |format| if @user.save # Tell the UserMailer to send a welcome Email after save UserMailer.welcome_email(@user).deliver_now format.html { redirect_to(@user, :notice => 'User was successfully created.') } format.json { render :json => @user, :status => :created, :location => @user } else format.html { render :action => "new" } format.json { render :json => @user.errors, :status => :unprocessable_entity } end end end I have set the port to 587 but i keep getting the error: Errno::ECONNREFUSED: Connection refused - connect(2) for "localhost" port 25 It looks as if another file was overwriting my settings. I also saw that it might be related to my ssh key not being authorized by the server. Do know what is wrong? Thanks in advance A: replace config.action_mailer.delivery_method = 'smtp' with config.action_mailer.delivery_method = :smtp Ensure your Rails.configuration.action_mailer.smtp_settings is symbolized keys A: I ran into the same error message well developing my own application. What I discovered is that as I was not actually sending any emails in a development environment I needed to change one of the lines in the configuration file found at: /your_apps_name/config/environments/development.rb from config.action_mailer.raise_delivery_errors = true to config.action_mailer.raise_delivery_errors = false This was causing my application to raise errors when emails were not successfully delivered, and I wasn't actually sending emails so of course they were not being delivered successfully. A: First of all, when developing on localhost, it's common to not actually send out mail, rather to treat that as a deployment detail and stick with the Rails default behavior which is to spit out the mail headers and contents into the console STDOUT (where you can verify that the text looks right). Is there a specific reason why you need to test sending messages in the dev environment? Secondly, you mentioned that you set the SMTP settings in both development.rb and environment.rb. You shouldn't need to set these settings twice; in general I'd use development.rb for settings specific to the dev environment, and environment.rb only for settings that will always apply to all environments (dev, tests, and on the live deployed server). So if you're setting the same settings in both development.rb and environment.rb, I'd start by removing one or the other; redundancy will only make your job harder down the road. Finally, to troubleshoot this I'd start by asking Rails what its settings are rather than waiting for the mail delivery to fail. Try the following: * *Start up rails console *Enter Rails.configuration.action_mailer.smtp_settings and compare the resulting hash against your expectations. This hash should contain the port and domain settings that are used when sending out all mail (in the current environment), so if ActionMailer is trying the wrong port then I'd expect the port to be wrong here too. Where are you setting $SMTP_SERVER, $PORT and $MAIL? Is there any reason you aren't using Rails' convention for environment variables, ENV['SMTP_SERVER'] etc.? Hope some of that helps. Good luck! A: The app might be using mailcatcher gem for all outbound emails on development, which you haven't installed or don't have running. At least that was my issue. Check out https://mailcatcher.me and follow the instructions given. A: You need to remove config.action_mailer.perform_deliveries = true line. A: I was running into this issue when running Sidekiq::Worker.drain_all in my RSpec tests, and it was driving me crazy because I had config.action_mailer.delivery_method = :test in my config/environments/test.rb. The solution was to set config.action_mailer.delivery_method = :test in my config/environments/development.rb, which is confusing because the implication is that my config/environments/development.rb is overriding my config/environments/test.rb in my RSpec tests. Regardless, this might fix the problem for others. A: For anyone clumsy like me, I got this message when I had everything set up perfectly in my app, but I had simply forgotten to run the command that adds the mailing addon in my production environment. In my case, that line was heroku addons:create mailgun:starter.
Q: What are the best Architecture/design pattern/Best Practices for modular/component based development : part 2 It is second part of my Original Question:Original Question I have one Multi-Tenant Grails-based application(just migrated to Grails 2.1). Now I want to add many new features in my application, but my basic requirement is that all new modules should be configurable for each Tenant and the code base should be modular and loosely coupled with other features/components. In the short term, I want to convert my application into a module-based application which should be able to used as a plug-and-play base and also be able to configure it on a per-Tenant basis. In General, all new components/features are web-based. So My Question is : How to manage code base: I like to know the which approach I should follow for code base separation. a. Create a new plugin for each new module. b. Create a new module in Spring and use same in my application. c. Use OSGi framework for new module. d. Create a new web application for each new module and configure application with CAS. e. What are the best practices should be followed in this scenario. I like to know the ideal solution/suggestion in terms of design and architecture or Grails plugin . Also let me know If there is any issue with my requirement…… A: There are several design patterns you can use. For the base architecture the Composite Pattern might come in handy. For a good overview google "GOF design patterns". GOF stands for Gang of Four, the writers of the book. More info here. Design patterns offer you solutions for ever returning problems. Being familiar with them is good.
Q: Add number or character at the end of a string based on condition using R I have data that look like this: a <- c("t_1", "t_2", "100", "200") b <- c(100, 200, 300, 277) dat <- data.frame(a,b) I want to make column a into a numeric variable. What I want is to first add three 0's behind the first digit for the values starting with t_ and then remove the t_ and convert the column to a numerical data type. The result should be: a b <dbl> <dbl> 1 1000 100 2 2000 200 3 100 300 4 200 277 It's important to add the 0's before removing the t_s since the real data set looks somewhat different. A dplyr solution would be nice! A: We could do this without a condition statement. Here, we use str_replace to match the 't_', capture the digits (\\d+) as a group ((...)), replace it with the backreference (\\1) of the captured group followed by three zeros and convert to numeric class with as.numeric library(dplyr) library(stringr) dat %>% mutate(a = as.numeric(str_replace(a, 't_(\\d+)', '\\1000'))) # a b #1 1000 100 #2 2000 200 #3 100 300 #4 200 277 A: Here's an approach with readr::parse_number: library(dplyr);library(readr);library(stringr) dat %>% mutate(a = case_when(str_detect(a,"t_") ~ parse_number(a) * 1000, TRUE ~ parse_number(a))) a b 1 1000 100 2 2000 200 3 100 300 4 200 277 The benefit of case_when is that it's easy to add the millions case, IE str_detect(a,"m_") ~ parse_number(a) * 1000000. A: This is just a slight modification from what dear Mr. @Ian Campbell suggested. I think str_pad function can also be come in handy for this purpose: library(dplyr) library(stringr) dat %>% mutate(a = ifelse(str_detect(a, "t_"), str_pad(str_remove(a, "t_"), 4, "right", "0"), a), a = as.numeric(a)) a b 1 1000 100 2 2000 200 3 100 300 4 200 277 A: The most frugal solution, it seems, is this: library(dplyr) dat %>% mutate(a = sub('t_(\\d+)', '\\1000', a), a = as.numeric(a)) Here, \\1000 is in fact not the number 1000 preceded by \\ but a special regular expression syntax called backreference \\1, which 'remembers' the part in parentheses in the pattern argument, namely (\\d+), which matches one or more consecutive digits. The backreference repeats these digits and the three 000 following it are indeed the literal three 0you want to append.
Q: Windows Phone Privacy policy default message when you install a location app? I am building an app that uses the location service api. However I am not sure if I have to implement the default Windows Phone Privacy policy message when you install an app? I have already done the permission functionality when a user starts using my app but I am not sure what to do with the installation message? Is it set by default when you set the category of your app via the submission wizard or not? A: Microsoft will detect what services your app uses and prompt the user that your app includes these and ask them to confirm that they want to allow the installation to continue. So there's nothing you need to do in that respect. A: I'm not sure in what extent you implemented your permission functionality within your app, but just to be sure: you need a Privacy Statement prompt on first launch, an option to turn off location services and a link to access the statement again. I didn't read the guidelines properly, thus dooming the certification of my app.
Q: Show and hide a div when element isin-viewport I want <div class="sticky-info"> to hide when a <span class="waar"> is in the viewport. When <span class="waar"> leaves the viewport I want <div class="sticky-info"> to hide. The first part hide <div class="sticky-info"> works fine but second part show <div class="sticky-info"> doesn't. Probably it's something really stupid but I'm not that JS wizard. Here's the JS. <!--sticky info--> <script type="text/javascript"> $(window).scroll(function() { if ($('.waar:in-viewport')) { $('.sticky-info').hide(); } else { $('.sticky-info').show(); } }); </script> The page you can visit here http://www.joets.be/test/joetz/page_vakanties.html Thx A: Your if statement will always be true. $('.waar:in-viewport') will return a jQuery object, empty or not, it doesn't matter, it is a truthy value. I believe what you are looking for is .is(): $(window).scroll(function() { if ($('.waar').is(':in-viewport')) { $('.sticky-info').hide(); } else { $('.sticky-info').show(); } }); Note: This assumes that your plugin supports the same functionality as native jQuery pseudo selectors..
Q: Spring Rest docs custom snippets are ignored Setup: Intellij IDE community Spring Boot 2.4.0 Spring rest docs Hi, I use spring rest docs in all my services. The problem is that in one of them, the custom snippets are ignored and I just don't know why. Although if i'm sure that it's a mistake of mine I just can't find it. Example snippet One of the snippets I want to customize is the http request. So I placed a file http-request.snippet under src/test/resources/org/springframework/restdocs/templates/asciidoctor Content: [source,http,options="nowrap"] ---- {{method}} {{path}} HTTP/1.1 ---- So I would expect that the requestbody is not documented in this snippet but instead it is still included. Like I said all my snippets are ignored. UPDATE: I've debugged StandardTemplateResourceResolver class. In fact, my templates are ignored. I looked at the path and as you can see the method getFormatSpecificCustomTemplate should resolve my snippets but it doesn't. Is there something else I have to configure when I add a new resource folder and I add it to the classpath? SOLVED I found the problem by looking at the asciidoc path in my explorer. The problem was that the creation of the direktories went wrong. Instead of creatin nested subdirectories for org/springframework/.. there was one folder with the whole directory structure as one name. Sorry for the confusion but in intellij the structure looked right.
Q: gorm: json of json not work Sample: { "id": 1 "data": {"1": 2} } Struct definition: type Item struct { id int `json:"id"` data interface{} `json:"data"` } I need to parse the payload from a http post, so I used interface{} for data, json.Unmarshal() is successful, but gorm produces error while calling db.Create(item): (sql: converting Exec argument #5's type: unsupported type map[string]interface {}, a map) Instead, I change from interface{} to string, calling json.Unmarshal() to parse json POST payload produces error. unmarshal type error: expected=string, got=object Basically, one requires interface{}, one requires string. Anyone encountered this? A: The solution is defining a custom type that implements sql.Valuer, sql.Scanner, json.Marshaler and json.Unmarshaler interfaces. Sample of my implementation: type Data string func (t *Data) MarshalJSON() ([]byte, error) { return []byte(*t), nil } func (t *Data) UnmarshalJSON(data []byte) error { *t = Data(data) return nil } func (t Data) Value() (driver.Value, error) { return string(t), nil } func (t *Data) Scan(src interface{}) error { s, ok := src.([]byte) if !ok { return nil } *t = Data(s) return nil } // Data implements the below interfaces to satisfy both // json parser and sql parser var _ json.Marshaler = (*Data)(nil) var _ json.Unmarshaler = (*Data)(nil) var _ sql.Scanner = (*Data)(nil) var _ driver.Valuer = (*Data)(nil)
Q: Is it possible to write express app and native firebase functions together? I have this structure for my file and folders. . └── src/ β”œβ”€β”€ index.ts β”œβ”€β”€ auth/ β”‚ └── auth.ts β”œβ”€β”€ controllers/ β”‚ β”œβ”€β”€ user.ts β”‚ └── event.ts β”œβ”€β”€ functions/ β”‚ └── email.ts └── models/ β”œβ”€β”€ user-model.ts β”œβ”€β”€ event-model.ts └── email-model.ts index.ts contains this. import * as admin from "firebase-admin"; admin.initializeApp(); admin.firestore().settings({ ignoreUndefinedProperties: true }); module.exports = { ...require("./controllers/user"), ...require("./controllers/event"), ...require("./functions/email"), }; event.ts and user.ts follow this structure const eventApp: express.Application = express(); eventApp.use(bodyParser.json()); eventApp.use(cors({ origin: true })); eventApp.get("/", isAuthenticated, isAuthorized({ hasRole: ["admin"] }), async (req: express.Request, res: express.Response) => { ... }); module.exports.events = functions.https.onRequest(eventApp); email.ts follows this structure module.exports.sendInitialInvitation = functions.firestore .document('{collection}/{docId}') .onCreate((snap: QueryDocumentSnapshot, context: any) => { ... }); One thing to note here is that I'm trying to mix firebase functions with express app. When I try to deploy this I keep getting an error which I keep trying to figure out what it is and why this is happening. Error: Failed to load function definition from source: Failed to generate manifest from function source: TypeError: Cannot read properties of undefined (reading 'document') Does anyone know why this is happening and what I can do to fix it from their experience dealing with this? Let me know if you have any questions. Would appreciate the help. p.s. It deploys fine when I delete functions folder and content as well as remove the reference from index.ts file.
Q: Get id of field input in sonata using Javascript I use symfony and sonataAdminBundle, in my ProductAdmin Class I have a form with many input type : And i like to get the Id of one of this input called 'prixAchat' : with inspect element I see that sonata generate an auto prefix value before the id like this : s5988300197635_prixAchat so So I tried to use this code : prixAchat = document.getElementById('form [id$="_prixAchat"]').value But always the result is null Someone can help me please ? A: You only want to get input? I think the code should be prixAchat = $('input [id$="_prixAchat"]').val() A: prixAchat = document.getElementById('_prixAchat').id use id instead of value at the end A: I'm not sure, but document.getElementById looks like not suitable in your case. Try this: prixAchat = $('form [id$="_prixAchat"]').val() A: This worked for me: prixAchat = $("#{{ form.vars.id }}_prixAchat").val() A: You can get the id with {{ admin.uniqid }} Here is an example: var prixAchatId= $("#{{ admin.uniqid }}_prixAchat") so the {{ admin.uniqid }} gives you that s5988300197635
Q: Changing CSS styles when an event fires I'm trying to integrate THEOPlayer in my project and I want to customize styles depending on certain events. For instance, I would love to hide the toolbar and show an overlay image when the video is paused. They do expose some CSS classes that I can change manually but my question is, how do I change the values in CSS on a specific event. Since the player is imported as a single JSX element I don't know how to add custom classes to its specific parts. So I would like to know if there is another way. Here is a component where an instance of Player is created: class Player extends React.Component { _player = null; _el = React.createRef(); componentDidMount() { const { source, onPlay, onPause } = this.props; if (this._el.current) { this._player = new window.THEOplayer.Player(this._el.current, { libraryLocation: "https://cdn.myth.theoplayer.com/7aff3fa6-f92e-45f9-a40e-1bce9911b073/", }); this._player.source = source; this._player.addEventListener("play", onPlay); this._player.addEventListener("pause", onPause); } } componentWillUnmount() { if (this._player) { this._player.destroy(); } } render() { return ( <div className={ "theoplayer-container video-js theoplayer-skin vjs-16-9 THEOplayer" } ref={this._el} > </div> ); } } export default Player; And that's a part of code where I want to change styles onPlay and onPause <div className={"player-container"}> <Player source={source} onPlay={() => { console.log("playing"); }} onPause={() => { console.log("paused"); }} /> </div> A: Use like this state = { play: false, pause: true, } const playFn = () => { this.setState = ({ play: true, pause: false, }) } const pauseFn = () => { this.setState = ({ play: false, pause: true, }) } <div className={"player-container"}> <Player source={source} onPlay={playFn} onPause={pauseFn} activatePlayClasses={play} activatePauseClasses={pause} bg={'https://example/example.jpg'} /> </div> // on Player component const { source, onPlay, onPause, activatePauseClasses, activatePlayClasses , bg} = this.props; render() { return ( <div className={ `theoplayer-container video-js theoplayer-skin vjs-16-9 THEOplayer ${activatePauseClasses ? 'your pause class' : ''} ${activatePlayClasses ? 'your play class' : ''}` } style={{backgroundImage: `url(${bg})`}} ref={this._el} > </div> ); } I have updated code
Q: Wordpress How to change plugin settings in Theme function.php I'm new to Wordpress and working on my first theme. The theme will be heavily combined with one plugin. I'm wondering how I could change some of the plugin settings in the theme function.php without touching the plugin itself. I have tried looking it up on the internet but haven't found any concrete answers for my issue. What I'm using: Wordpress 4.2, Justimmo api plugin The Problem: I'm trying to figure out how I could in my theme function.php redirect/replace the plugin template files with the ones that are in my theme. Currently in the plugin folder are template files and how they will render on the website. I would write my own template file, making sure it looks like my theme and replace it with the plugin template file. If I were to edit the template files directly in the plugin folder, whenever there might be a update, they would be overwritten. I don't feel that is right. After looking around the internet, I feel I could achieve it with add_filter, but not fully sure how to. The Plugin On Github: https://github.com/justimmo/wordpress-plugin/blob/master/justimmo.php In the original plugin has a lines (row 240 for indexPage() and row 328 for getIndexUrl() ): class JiApiWpPlugin { function indexPage() { include(JI_API_WP_PLUGIN_DIR . '/templates/index.php'); } function getIndexUrl() { return $this->getUrlPrefix().'ji_plugin=search'; } } It dictates where one of the template files can be found, and also gives a permalink to the plugin. What I want I would like to add a filter to take the template file from my theme instead, and to rewrite the path to the template file. If there is an easy way for adding a hook, that overwrites it, great. Also I have found that I could do some template replacements with add_filter. Have tried: add_filter( 'template_include', 'gulz_justimmo_page_template' ); function gulz_justimmo_page_template( $page_template ) { if ( is_page( 'ji_plugin' ) ) { $page_template = dirname( __FILE__ ) . '/justimmotemp/justimmo-index.php'; } return $page_template; } But I'm not fully sure how to check if the plugin permalinks page is activated. I feel it should be a simple thing for users overwrite or redirect plugin template files with the ones that are in their theme, but I can't figure it out. I would be grateful for all help and advice. A: Unfortunately the function indexPage() is called by another function which is then hooked by reference..... add_action('template_redirect', array(&$this, 'templateRedirect')); What you need to do is remove this function and replace with your own custom function (copy the code from the plugin and modify to call a custom function for that page). The problem is you can't use remove_action because no name was passed with add_action so wp creates one that changes with every load. So we need a function to find the function added: function remove_anonymous_action( $name, $class, $method ){ $actions = $GLOBALS['wp_filter'][ $name]; if ( empty ( $actions ) ){ return; } foreach ( $actions as $prity => $action ){ foreach ( $action as $identifier => $function ){ if ( is_array( $function) && is_a( $function['function'][0], $class ) && $method === $function['function'][1]){ remove_action($tag, array ( $function['function'][0], $method ), $prity); } } } } What you can do then do is call this after the action has been added above using the priority argument (this removes the function for all pages inside the function btw) // the action adding the action is added in parse_query filter...use this as the point to remove the added action add_action('parse_query', 'remove_plug_action', 50); function remove_plug_action(){ // call our function with the name of the hook, classname and function name remove_anonymous_action('template_redirect','JiApiWpPlugin','templateRedirect'); //add a custom function to replace the one we removed. add_action('template_redirect', 'customtemplateRedirect'); } Modify the function below to call your theme based file. function customtemplateRedirect(){ global $wp; global $wp_query; if (get_query_var('ji_plugin') !== '') { switch (get_query_var('ji_plugin')) { case 'property': $this->propertyPage(); exit; break; case 'expose': $this->exposeDownload(); exit; break; default: $this->indexPage(); exit; break; } } } also you can check if the hook has been removed using $hook_name = 'template_redirect'; global $wp_filter; var_dump( $wp_filter[$hook_name] ); Anon filters will have a long key e.g. 12i90rkl2rkljeri (its random every time). Break down the process by just removing the add action in remove_plug_action() and see what you get. The action should be removed if not var dump $_GLOBALS['wp_filter']['template_redirect'] to see what it looks like. It might take a fit of fiddling around. You also need to check your if statements (var_dump values being fed to it to check if they will pass or fail etc)
Q: How do I enter fractions in Delphi? I have an application which will use measurements, specifically down to 1/16 of an inch. I would really like a convenient way for an end user to enter a value INCLUDING a fractional part, for example, 3 7/16. I realize that I can require the user to just enter decimal values (i.e. 3.1875), but I would really like a better way. Does anyone know of a drop down or spin control that makes this easy to enter? (ideally a DB version of the control.) A: You can do simply function FractionToFloat(const S: string): real; var BarPos: integer; numStr, denomStr: string; num, denom: real; begin BarPos := Pos('/', S); if BarPos = 0 then Exit(StrToFloat(S)); numStr := Trim(Copy(S, 1, BarPos - 1)); denomStr := Trim(Copy(S, BarPos + 1, Length(S))); num := StrToFloat(numStr); denom := StrToFloat(denomStr); result := num/denom; end; This will accept input of the form examplified by 3/7 and -4 / 91.5. To allow an integer part, add function FullFractionToFloat(S: string): real; var SpPos: integer; intStr: string; frStr: string; int: real; fr: real; begin S := Trim(S); SpPos := Pos(' ', S); if SpPos = 0 then Exit(FractionToFloat(S)); intStr := Trim(Copy(S, 1, SpPos - 1)); frStr := Trim(Copy(S, SpPos + 1, Length(S))); int := StrToFloat(intStr); fr := FractionToFloat(frStr); result := int + fr; end; This will in addition accept input of the form examplified by 1 1/2. A: I happen to have written a control many years ago and am currently finishing up an update to it that includes metric conversion as well. It allows the user and developer to toggle between ft in, dec in, dec ft, mm, cm, m just with a right click or setting the mode in design time. It also handles rounding to the nearest 16th, 32nd or what ever you need for metric. Check it out on most of the delphi component sites like torry.net or my old site at http://www.enhancedtechsolutions.com/delphi/ I hope to have the new version done in a day or 2 and published. Forgot to mention the most important part: It is call TMaskFtInch
Q: EF Code First Many to Many relationship creates a duplicate joining table? I'm trying to create a many to many relationship between Product and Category with a joining table using EF 6.4.4 and MySQL 8, but unfortunately without success? public class AppDbContext : DbContext { //Schema Tables public DbSet<Product> Products { get; set; } public DbSet<Category> Categories { get; set; } public DbSet<ProductCategory> ProductCategories { get; set; } } public abstract class BaseEntity { [Key] public int ID { get; set; } public string Name { get; set; } } public class Product : BaseEntity { public virtual IList<Category> Categories { get; set; } } public class Category : BaseEntity { public virtual IList<Product> Products { get; set; } } now for the joining table I tried this: public class ProductCategory { [Key, Column(Order = 1)] public int ProductID { get; set; } [Key, Column(Order = 2)] public int CategoryID { get; set; } public Product Product { get; set; } public Category Category { get; set; } } and this: public class ProductCategory : BaseEntity { public int ID { get; set; } [ForeignKey(nameof(Product)), Column(Order = 1)] public int ProductID { get; set; } [ForeignKey(nameof(Category)), Column(Order = 2)] public int CategoryID { get; set; } public Product Product { get; set; } public Category Category { get; set; } } and also this: protected override void OnModelCreating(DbModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.Entity<ProductCategory>().HasKey(x => new { x.ProductID, x.CategoryID }); } the real problem is no matter what I do EF creates a duplicate joining table? products categories productcategories productcategory1 (duplicate) Edit: apparently you can't do this according to this post and this one two, but there is a workaround. // a workaround for the problem public abstract class BaseEntity { [Key] public int ID { get; set; } public string Name { get; set; } } public class Product : BaseEntity { public virtual IList<ProductCategory> ProductCategories { get; set; } } public class Category : BaseEntity { public virtual IList<ProductCategory> ProductCategories { get; set; } } public class ProductCategory { [Key, Column(Order = 1)] public int ProductID { get; set; } [Key, Column(Order = 2)] public int CategoryID { get; set; } public virtual Product Product { get; set; } public virtual Category Category { get; set; } } A: I think you have created productcategory class twice. You can remove second one and add fk relationship s in first class definition A: You likely need to be explicit with the relationship mapping. I would get rid of the ProductCategories DbSet in the DbContext. If this is EF6 or EF Core 5 then I'd get rid of the ProductCategory entity definition all-together, especially if the table just consists of the two FKs/composite key: EF 6 modelBuilder.Entity<Product>() .HasMany(x => x.Categories) .WithMany(x => x.Products) .Map(x => { x.ToTable("ProductCategories"); x.MapLeftKey("ProductId"); x.MapRightKey("CategoryId"); }); EF Core < 5 For EF Core 2/3 the many-to-many needs to be mapped more as a many-to-one-to-many where the collections on each side need to be declared as ProductCategory entities. public class Product { // ... public virtual ICollection<ProductCategory> ProductCategories { get; set; } = new List<ProductCategory>(); } public class Category { // ... public virtual ICollection<ProductCategory> ProductCategories { get; set; } = new List<ProductCategory>(); } EF Core 5 EF Core 5 adds UsingEntity to help define the joining table for many-to-many relationships leaving Product to have Categories (instead of ProductCategories) and Category to have Products (likewise). modelBuilder.Entity<Product>() .HasMany(x => x.Categories) .WithMany(x => x.Products) .UsingEntity<ProductCategory>( x => x.HasOne(pc => pc.Product).WithMany().HasForeignKey(pc => pc.ProductId), x => x.HasOne(pc => pc.Category).WithMany().HasForeignKey(pc => pc.CategoryId));
Q: "New Line" connected to value when reading in a CSV? I am currently trying to read in a CSV file to place it into an array, but when I execute the code, the program seems to read over the endline to the next comma which messes up my output. Here is the code: while (!inFile.eof()) { string line = ""; while (count_1 <= numValuesPerLine) { getline(inFile, readFromFile, ','); line.append(readFromFile); count_1++; } cout << line << endl; count_1 = 0; } 'line' ends up having the value: 12345678910111213141516171819202122232425\n1 which when I print it, places that newline next to '25' and messes up the output. (numValuesPerLine = 25 and count_1 is initialized outside of the loop) I looked around for a similar answer but I could not find anything exactly like what I am trying to do, any help would be greatly appreciated, thank you. A: you changed the delimiter from \n to , so of course the newline is kept as part of the input
Q: Unix time formatting always returns "50 years ago" I am using Hacker news API. I want to format Unix time to be like "35 minutes ago, 1 hour ago" etc. I am using javascript-time-ago library. The value is always 50 years ago this is one API response: { "by" : "dhouston", "descendants" : 71, "id" : 8863, "kids" : [ 8952, 9224, 8917, 8884, 8887, 8943, 8869, 8958, 9005, 9671, 8940, 9067, 8908, 9055, 8865, 8881, 8872, 8873, 8955, 10403, 8903, 8928, 9125, 8998, 8901, 8902, 8907, 8894, 8878, 8870, 8980, 8934, 8876 ], "score" : 111, "time" : 1175714200, "title" : "My YC app: Dropbox - Throw away your USB drive", "type" : "story", "url" : "http://www.getdropbox.com/u/2/screencast.html" } This is my component: // @Flow import React from 'react'; import TimeAgo from 'javascript-time-ago' import en from 'javascript-time-ago/locale/en' ....other imports .... type PropsT = { id: number, by: string, kids: Array<number>, score: number, url: string, title: string, time: number | Date } const ListItem = (props: PropsT) => { const {by, kids = [], score, url, title, id, time} = props; const site = getSiteHostname(url) || 'news.ycombinator.com'; const link = getArticleLink({url, id}); const commentUrl = `${ITEM}${id}`; const userUrl = `${USER}${by}`; TimeAgo.addLocale(en) const timeAgo = new TimeAgo('en-US'); const formatedDate = timeAgo.format(time) return ( <Item> <TitleLink href={link} target="_blank"> {title}<Host>({site})</Host> </TitleLink> <Description> {score} points by <Link href={userUrl} target="_blank"> {by} </Link> {formatedDate} ago { ' | '} <Link href={commentUrl} target="_blank"> {kids.length} comments </Link> </Description> </Item> ); } export default ListItem; The result is always 50 years ago How to do a proper formating? A: I actually needed to multiply time with 1000. This fixed the issue: const formatedDate = timeAgo.format(time * 1000)
Q: ASP.NET Core DB First scaffolding Join doesn't work I've created a test ASP.NET Core project. I've generated the models from an existing DB using the Scaffold-DbContext command. Everything went fine. I've added an ApiController to return the data, and if I query, using LINQ, simple flat table data or I make joins on tables where the foreign keys have been explicitly defined in the DB it works. But if I make a query joining two tables where the foreign keys have not been set it doesn't return anything. Please note that the two tables are related to each other by an integer ID (MktId). Entity models generated by the scaffold: public partial class MonthlyPrice { public int MpId { get; set; } public int MktId { get; set; } public int CmId { get; set; } public decimal MpPrice { get; set; } public Commodities Cm { get; set; } public Currencies Cur { get; set; } public PriceTypes Pt { get; set; } public UnitOfMeasure Um { get; set; } } public partial class Commodities { public Commodities() { MonthlyPriceItem = new HashSet<MonthlyPriceItem>(); } public int CmId { get; set; } public string CmName { get; set; } public int CmCatId { get; set; } public ICollection<MonthlyPrice> MonthlyPriceItem { get; set; } } public partial class Markets { public int MktId { get; set; } public string MktName { get; set; } } the following query return results: var price= (from m in db.MonthlyPrice join c in db.Commodities on m.CmId equals c.CmId select new { c.CmName, m.MpPrice }); but this one doesn't return anything: var price= (from m in db.MonthlyPrice join mk in db.Markets on m.MktId equals mk.MktId select new { m.MpPrice, mk.MktName }); Please note that both queries on Entity Framework 6.x on ASP.NET 4.7 works perfectly. Should I have to specify all the foreign key in the DB to make EFCore works correctly? (Db is not always designed by me!!) UPDATE The model builder for the Markets has been generated by scaffold-dbcontext command like the following: modelBuilder.Entity<Markets1>(entity => { entity.HasKey(e => e.MktId); entity.ToTable("__Markets"); entity.Property(e => e.MktId).HasColumnName("mkt_id"); entity.Property(e => e.MktName) .IsRequired() .HasColumnName("mkt_name") .HasMaxLength(250); }); Respect to the one generated for Commodities table I've noticed that there is the line entity.ToTable("__Markets"); that looks very strange to me. A: * *If you want to fight with it a bit: Update to at least .NET Core 2.1 Preserve the original database names to remove the funk in the migration. Use the -UseDatabaseNames option. scaffold-dbcontext -UseDatabaseNames *Else, continue: Annotations might be valuable either way if your ids or table names on the current database are funky (spaces, prefixes, etc...) Add Markets to MonthlyPrice Class as a foreign key. Make the ids obvious to the migration using data annotations. [Table("MonthlyPrice")] public partial class MonthlyPrice { [Key] public int MpId { get; set; } [ForeignKey("Markets")] public int MktId { get; set; } public Markets Mkt { get; set; } [ForeignKey("Commodities")] public int CmId { get; set; } public Commodities Cm { get; set; } public decimal MpPrice { get; set; } public Currencies Cur { get; set; } public PriceTypes Pt { get; set; } public UnitOfMeasure Um { get; set; } } [Table("Commodities")] public partial class Commodities { public Commodities() { MonthlyPriceItem = new HashSet<MonthlyPriceItem>(); } [Key] public int CmId { get; set; } public string CmName { get; set; } public int CmCatId { get; set; } public ICollection<MonthlyPrice> MonthlyPriceItem { get; set; } } [Table("Markets")] public partial class Markets { [Key] public int MktId { get; set; } public string MktName { get; set; } } If recreating database: Add-Migration awesome Update-Database awesome Else, if just adding a migration: Add-Migration awesome –IgnoreChanges I guess the great thing is, you have a golden opportunity to make it better than the last guy. Starting out with Same-Same on everything (table names, column names, keys, would be nice). Clean up all the differences. There are clearly differences in both your table name and primary key names currently.
Q: restar entre diferentes tablas necesito de su ayuda. Resulta que estoy realizando un sistema de stock, sin embargo logre hacer que aumentara cada vez que ingresara un producto a mi bodega pero no logro hacer que reste cada vez que salga. Las tablas que trabajo son "producto" y "detalle_documento". en la tabla detalle_documento" tengo un atributo llamado "cantidad_haber" el cual tiene como funciΓ³n agregar la cantidad de producto que saldrΓ‘ del inventario para posterior ser descontado y tambiΓ©n el "cantidad_debe", el cual tiene como funciΓ³n poner la cantidad de producto que ingresan al inventario. El stock final lo tengo en la tabla "producto". mi cΓ³digo: class Producto(models.Model): cantidad_disponible=fields.Float(string="Cantidad disponible", compute="_stock") detalle_documento_ids=fields.One2many(...) @api.one @api.depends("detalle_documento_ids") def _stock(self): suma = 0 for detalle_documento in self.detalle_documento_ids: suma+= detalle_documento.cantidad_debe self.cantidad_disponible = suma @api.multi @api.depends("detalle_documento_ids", "producto_ids") def _stock(self): for detalle_documento in self.detalle_documento_ids: self.cantidad_disponible= self.cantidad_disponible - self.cantidad_haber este ultimo mΓ©todo trate que restarΓ‘ lo que ya habia pero me sale error. A: FΓ­jate en la lΓ­nea self.cantidad_disponible= self.cantidad_disponible - self.cantidad_haber pienso que debiera ser sustituida por self.cantidad_disponible= self.cantidad_disponible - **detalle_documento**.cantidad_haber que es donde tienes el atributo cantidad_haber
Q: Check if user has push notification turned on I need some help. We have an app build with React Native that communicates with API that is build on Laravel. For push notifications we used One Signal. It works great, no problems there. The only issue we have is how can we know if user has push notifications enabled for our app? Is there any way that through One Signal we can check this one out? Any help will be highly appreciated. A: found this post similar to: How can i check push notification permission for both ios and android in react native? get the permission status then update to server using api from laravel.
Q: Calling Google Cloud KMS from AWS Lambda I'm new to Google's Cloud services and to Java, but I'm trying to set up a Java function on AWS Lambda that makes a call to Google Cloud KMS. I have working Java code locally, but from what I can tell the only way to authenticate the Google client is to set an environment variable with the path to a JSON file containing your credentials. I can do that easily locally when triggering my Java function - I just set the environment variable pointing to a file on my computer when running the code. Can anyone give me any pointers for how to do that in Lambda where all I seem to be able to do is upload a single .jar file? A: You will probably want to store the JSON file in AWS Secret Manager and then retrieve the JSON file at function boot by authenticating to the AWS Secret Manager. Then you should configure the Google client library to use that credential contents. Alternatively (more complex but also more secure) would be to configure GCP as an OIDC provider for AWS and then create an AWS role with permission to call GCP KMS directly - no credential file required.
Q: НС рисуСтся Π³Ρ€Π°Ρ„ΠΈΠΊ ΠΏΡ€ΠΎΠ±Π»Π΅ΠΌΠ° Π² Ρ‚ΠΎΠΌ, Ρ‡Ρ‚ΠΎ Π½Π΅ отобраТаСтся Π³Ρ€Π°Ρ„ΠΈΠΊ, запросы написаны Π²Π΅Ρ€Π½ΠΎ ΠΈ ΠΎΡ‚Π»ΠΈΡ‡Π½ΠΎ Ρ€Π°Π±ΠΎΡ‚Π°ΡŽΡ‚, Π² консоли Ρ‚Π°ΠΊ ΠΆΠ΅ всС чисто. HTML <button class="val" name='param' value="day" >Π”Π΅Π½ΡŒ</button> <button class="val" name='param' value="month" >ΠœΠ΅ΡΡΡ†</button> <button class="val" name='param' value="minute" >10 ΠœΠΈΠ½ΡƒΡ‚</button> <div class="nav"> </div> <div class="chart-container pie-chart"> <canvas id="pie_chart"></canvas> </div> ΠšΠΎΠ½Ρ‚Ρ€ΠΎΠ»Π»Π΅Ρ€: if($_POST['status']=='month'){ $data = array(); foreach($selectHashMonth as $row) { $data[] = array( 'hash' => $row["suminday"], 'time' => date('m', strtotime($row["time"])).'-'.date('d', strtotime($row["time"])), ); } echo json_encode($data); } if($_POST['status']=='day'){ $data = array(); foreach($selectHashDay as $row) { $data[] = array( 'hash' => $row["suminhour"], 'time' => date('H', strtotime($row["time"])).":"."00", ); } echo json_encode($data); } МодСль public function selectHashMonth() { $params = [ 'month' => date("m"), ]; return $this->db->row('SELECT time,sum(summary_mhs_5s) AS suminday FROM miners_data WHERE MONTH(time) = :month GROUP BY DAY(time)', $params); } public function selectHashDay() { $params = [ 'month' => date("m"), 'day' => date("d"), ]; return $this->db->row('SELECT time, sum(summary_mhs_5s) AS suminhour FROM miners_data WHERE MONTH(time) = :month AND DAY(time) = :day GROUP BY HOUR(time)', $params); } JS $(document).ready(function() { var hash = []; var time = []; var status = ''; makechart(); $(".val").on('click',function() { switch($(this).val()){ case 'day': status = 'day'; break; case 'month': status = 'month'; break; case 'minute': status = 'minute'; break; } $.ajax({ url: "/miners/index", method:'POST', data:{ action:'insert', }, success:function(data){ hash =[]; time =[]; makechart(); } }) }); function makechart() { $.ajax({ url: "/miners/index", method: "POST", data: { action: 'fetch', status: status }, dataType: "JSON", cache: true, async: true, success: function(data) { $('#pie_chart').html(data); for (var count = 0; count < data.length; count++) { hash.push(data[count].hash); time.push(data[count].time); } console.log(hash); console.log(time); console.log(status1); function graphic(){ var chart_data = { labels: time, datasets: [{ label:'HASH', data: hash, borderColor:'#876ED7', backgroundColor:'#dae5f7', pointRadius:5, // pointHitRadius:5, pointBackgroundColor:'rgb(0,0,0)' }], options:{ legend:{display:true} } } var group_chart1 = $('#pie_chart'); var graph1 = new Chart(group_chart1, { type: "line", data: chart_data, options: { plugins: { legend: { labels: { usePointStyle: true, font: { size: 24 } }, } } } }); } setTimeout(graphic, 300); } }) } });
Q: but some kind of damage nevertheless These thoughts have to do with effects on othersβ€” not necessarily effects on their feelings, since they may never find out about it, but some kind of damage nevertheless [What does it all mean, Thomas Nagel] I don't understand the bold sentence. Is it connected with "these thoughts"? Thank you! A: The damage is referring to the effects on others. The thoughts have to do with an effect, which is some kind of damage to others. The word 'nevertheless' in this case means that it's not damage to their feelings, but some other kind of damage.
Q: Π Π°Π·Π±ΠΈΡ‚ΡŒ строку с html Ρ‚Π΅Π³Π°ΠΌΠΈ Π² массив php ЗдравствуйтС. Π£ мСня Π΅ΡΡ‚ΡŒ строка с html Ρ‚Π΅Π³Π°ΠΌΠΈ Ρ‚Π°Π±Π»ΠΈΡ†Ρ‹. Π—Π°Π΄Π°Ρ‡Π° Ρ€Π°Π·Π±ΠΈΡ‚ΡŒ строчку Π½Π° массив ΠΏΠΎ Ρ‚Π΅Π³Π°ΠΌ с ΠΈΡ… содСрТимым. ΠŸΡ€ΠΈΠΌΠ΅Ρ€: <table> <tr> <td> <table> <tr> <td>ВСкст ячСйки β„–1</td> <td>ВСкст ячСйки β„–2</td> </tr> </table> </td> <td> <table> <tr> <td></td> </tr> </table> </td> </tr> </table> ΠΠ°ΡˆΡ‘Π» Ρ€Π΅ΡˆΠ΅Π½ΠΈΠ΅ ΠΏΠΎ ссылкС a link: function walk($output, \DOMNode $node, $depth = 0) { if ($node->hasChildNodes()) { $children = $node->childNodes; foreach ($children as $child) { if ($child->nodeType === XML_TEXT_NODE) { continue; } $output[] = $child->nodeName; $item = walk(array(), $child, $depth + 1); if (!empty($item)) { $output[] = $item; } } } return $output; } $dom = new DOMDocument; $dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); $root = $dom->getElementsByTagName('body')->item(0); $output = walk(array(), $root, 0); Всё Ρ€Π°Π±ΠΎΡ‚Π°Π΅Ρ‚, ΠΊΠ°ΠΊ Π½ΡƒΠΆΠ½ΠΎ ΠΈ Π²Ρ‹Π²ΠΎΠ΄ΠΈΡ‚ Ρ‚ΠΎΠ»ΡŒΠΊΠΎ Ρ‚Π΅Π³ΠΈ Π² ΡΠ»Π΅Π΄ΡƒΡŽΡ‰Π΅ΠΌ Ρ„ΠΎΡ€ΠΌΠ°Ρ‚Π΅: ["table",["tr",["td",["table",["tr",["td","td"] ... Вопрос Π·Π°ΠΊΠ»ΡŽΡ‡Π°Π΅Ρ‚ΡΡ Π² Π²Ρ‹Π²ΠΎΠ΄Π΅ содСрТимого(Π½Π΅ Π°Ρ‚Ρ€ΠΈΠ±ΡƒΡ‚ΠΎΠ²) этих Ρ‚Π΅Π³ΠΎΠ². Π’ΠΈΠΏΠ°: ["table":"",["tr":"",["td":"",["table":"",["tr":"",["td":"ВСкст ячСйки β„–1","td":"ВСкст ячСйки β„–2"] ... ΠŸΡ€ΠΎΠ±ΠΎΠ²Π°Π»: array_push($output, array( $child->nodeName => $child->textContent)); Π½Π° Π²Ρ‹Ρ…ΠΎΠ΄Π΅: ["table":"ВСкст ячСйки β„–1ВСкст ячСйки β„–2 ... A: Ρ€Π΅ΡˆΠΈΠ» Ρ‚Π°ΠΊ: function walk($output, \DOMNode $node, $depth = 0) { if ($node->hasChildNodes()) { $children = $node->childNodes; foreach ($children as $child) { if ($child->nodeType === XML_TEXT_NODE) { $output[] = $child->textContent; // Π·Π°ΠΌΠ΅Π½ΠΈΠ» Ρ‚Π΅Π»ΠΎ Π² условии } $output[] = $child->nodeName; $item = walk(array(), $child, $depth + 1); if (!empty($item)) { $output[] = $item; } } } return $output; } $dom = new DOMDocument; $dom->loadHTML(mb_convert_encoding($html, 'HTML-ENTITIES', 'UTF-8')); $root = $dom->getElementsByTagName('body')->item(0); $output = walk(array(), $root, 0); $name = html_entity_decode(str_replace('\u','&#x',$output[1][1][1][1][1][1][0]), ENT_NOQUOTES,'UTF-8'); // для дСкодирования json Ρ„ΠΎΡ€ΠΌΠ°Ρ‚Π° ΠΊΠΈΡ€ΠΈΠ»Π»ΠΈΡ†Ρ‹ Ρ‚ΠΈΠΏΠ° - \u041d\u043e\u043c\u0435\u0440
Q: Modifying an element with javascript after jquery has loaded this element I am having an annoying problem. I am trying to modify the header of my web page, which is loaded with the jquery load function. The problem is that header is loaded after I want to modify an element in it. I can not get the sequence right of: * *load header *modify header Example: Main script <head> <script> $(function () {$('#includeHeader').load('path to Header.html');}); </script> </head> <body> <script> window.onload = function () { document.getElementById('aktdatum').innerHTML = 'some text'; }; </script> <header id="includeHeader"> </header> ... </body> Header: <div> <ul> ... <li class="nav_info"> <div id="aktdatum"> </div> </li> </ul> </div> Error: (index):34 Uncaught TypeError: Cannot set property 'innerHTML' of null Comment: So, the problem is that when I want to execute this piece of code document.getElementById('aktdatum').innerHTML = 'some text' the header is not in the body yet. Apparently the header is inserted after the call. So my question is how to execute the script: document.getElementById('aktdatum').innerHTML = 'some text' after the header has been loaded. Obviously window.onload doesn't do the job. Do you have any recommendation? Thanks, Rok
Q: GCP Dataflow, Dataproc, Bigtable I am selecting services to write and transform JSON messages from Cloud Pub/Sub to BigQuery for a data pipeline on Google Cloud. I want to minimize service costs. I also want to monitor and accommodate input data volume that will vary in size with minimal manual intervention. What should I do? A. Use Cloud Dataproc to run your transformations. Monitor CPU utilization for the cluster. Resize the number of worker nodes in your cluster via the command line. B. Use Cloud Dataproc to run your transformations. Use the diagnose command to generate an operational output archive. Locate the bottleneck and adjust cluster resources. C. Use Cloud Dataflow to run your transformations. Monitor the job system lag with Stackdriver. Use the default autoscaling setting for worker instances. D. Use Cloud Dataflow to run your transformations. Monitor the total execution time for a sampling of jobs. Configure the job to use non-default Compute Engine machine types when needed. A: C! Use Dataflow on pubsub to transform your data and let it write rows into BQ. You can monitor the ETL pipeline straight from data flow and use stackdriver on top. Stackdriver can also be used to start events etc. Use autoscaling to minimize the number of manual actions. Basically when this solution is setup correctly, it doesn't need work at all.
Q: Error Code: 1064 | Delimiter DELIMITER $$ ALTER ALGORITHM=UNDEFINED DEFINER=`root`@`localhost` SQL SECURITY DEFINER VIEW `v_t_buku_bank` AS SELECT `b`.`id` AS `id`, `b`.`no_bku` AS `no_bku`, `b`.`tanggal` AS `tanggal`, `b`.`tanggal_bayar` AS `tanggal_bayar`, `b`.`id_transaksi_bank` AS `id_transaksi_bank`, `b`.`no_bukti` AS `no_bukti`, `b`.`jumlah` AS `jumlah`, `b`.`id_akun_pendapatan` AS `id_akun_pendapatan`, `ap`.`kode` AS `pendapatan_kode`, `m`.`jenis` AS `jenis`, `m`.`nama` AS `transaksi`, `ap`.`nama` AS `pendapatan`, IF((`m`.`jenis` = 'm'),`b`.`jumlah`,0) AS `masuk`, IF((`m`.`jenis` = 'k'),`b`.`jumlah`,0) AS `keluar` FROM ((`t_buku_bank` `b` JOIN `t_master_transaksi_bank` `m` ON ((`m`.`id` = `b`.`id_transaksi_bank`))) LEFT JOIN `akun_pendapatan` `ap` ON ((`ap`.`id` = `b`.`id_akun_pendapatan`)))$$ IF((`b`.`id_transaksi_bank` = '11'),`b`.`jumlah`,0) AS `m11`, IF((`b`.`id_transaksi_bank` = '12'),`b`.`jumlah`,0) AS `m12`, IF((`b`.`id_transaksi_bank` = '21'),`b`.`jumlah`,0) AS `k21`, IF((`b`.`id_transaksi_bank` = '22'),`b`.`jumlah`,0) AS `k22`, IF((`b`.`id_transaksi_bank` = '23'),`b`.`jumlah`,0) AS `k23` FROM (`t_buku_bank` `b` JOIN `t_master_transaksi_bank` `tb` ON ((`tb`.`id` = `b`.`id_transaksi_bank`)))$$ DELIMITER ; i got Error Code: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'IF((b.id_transaksi_bank = '11'),b.jumlah,0) AS m11, IF((b.`id_tran' at line 1 please help me, iam new in mysql A: You have two $$ that break your query: ON ((`ap`.`id` = `b`.`id_akun_pendapatan`)))$$ and ON ((`tb`.`id` = `b`.`id_transaksi_bank`)))$$ Remove them and try again
Q: Mann-whitney tesy error: group factor 2 levels? I keep getting the below error: y <- as.factor(data$Pos.44) x <- as.factor(data$Neg.44) wilcox.test( x ~ y, alternative='two.sided', paired=FALSE, var.equal = TRUE, conf.level = 0.95) Error in wilcox.test.formula(x ~ y, alternative = "two.sided", paired = FALSE, : grouping factor must have exactly 2 levels I have tried turning the data into factors, as numbers and have told r that the header is TRUE. Any ideas?? Here are some of the data. Neg 44 Pos 44 13.8228455 7.126694925 13.8228455 8.402648457 13.8228455 8.402648457 6.85288518 12.27621627 9.232427575 11.31157309 195.5120218 82.61317544 9.751455813 4.490663867 7.732335943 3.72520288 17.51041865 8.56912795 17.59120857 12.3571618 A: Your format is wrong. The inputs to the Mann-Whitney test requires one column with values, and another column with a two level factor. You've tried to feed it two numeric vectors converted to factors. See the example below: x=c(rnorm(50,0,1),rnorm(50,1,1)) y=rep(c('A','B'),c(50,50)) wilcox.test(x~y, alternative='two.sided', paired=FALSE, var.equal = TRUE, conf.level = 0.95) A: You can try library(tidyverse) d %>% gather(k,v) %>% with(.,wilcox.test(v ~ k, data=., exact =F)) Wilcoxon rank sum test with continuity correction data: v by k W = 45, p-value = 0.2367 alternative hypothesis: true location shift is not equal to 0 Or visualize your data using a boxplot library(ggbeeswarm) library(ggsignif) d %>% gather(k,v) %>% ggplot(aes(k,v)) + geom_boxplot() + geom_beeswarm() + ggsignif::geom_signif(comparisons = list(c("Neg44", "Pos44"))) Your data d <- read.table(text="Neg44 Pos44 13.8228455 7.126694925 13.8228455 8.402648457 13.8228455 8.402648457 6.85288518 12.27621627 9.232427575 11.31157309 195.5120218 82.61317544 9.751455813 4.490663867 7.732335943 3.72520288 17.51041865 8.56912795 17.59120857 12.3571618",header=T, fill=T)
Q: Which versions of CustomContent are compatible with cmsms 1.5.3? I have cmsms 1.5.3 and I need to know which releases of the module CustomContent are compatible with the version I am using. Any thoughts? A: If you look at the xml files associated with each version of CustomContent you will see that version 1.5.3 of CustomContent requires cmsms 1.4.0. version 1.7.2 of CustomContent requires version 1.7.1 of cmsms. So you will only be able to use CustomContent version 1.5.3 with cmsms 1.5.3.
Q: Redirect user to HomePage after buying I am working with Reactjs in the UI and Java with Spring Boot in the Back End, My question is, How can I redirect the user after buying a chocolate just for given an example to the HomePage if the user clicks on back button in the browser? IΒ΄ve seen web pages like amazon and walmart doing this. Thank you very much for the help. A: Cient side you can do this using javascript: window.location.replace("https://www.yourDomain.com"); Server side you can do the redirect by using the response object. See this article for more information on server redirecting in spring boot: A Guide To Spring Redirects
Q: how to make mini_magick ruby gem put russian characters on image? ВмСсто русских Π±ΡƒΠΊΠ² Π²Ρ‹Π²ΠΎΠ΄ΠΈΡ‚ \u1234\u5678 Π° Ρ…ΠΎΡ‚Π΅Π»ΠΎΡΡŒ Π±Ρ‹ русскиС подписи Π½Π° ΠΊΠ°Ρ€Ρ‚ΠΈΠ½ΠΊΠΈ ΡΡ‚Π°Π²ΠΈΡ‚ΡŒ require 'mini_magick' text = "Hel1o! ΠŸΡ€ΠΈΠ²Π΅Ρ‚" img = MiniMagick::Image.open("jpeg.jpg") sign = MiniMagick::Image.open("im999.png") puts text img.combine_options do |c| c.draw "text 0,75 '#{text}'" c.encoding "UTF-8" c.gravity 'North' c.pointsize '22' c.font 'Tahoma' c.fill("#000000") end #img.write "new.jpg" res =img.composite sign do |c| c.gravity "South" end res.write("new.jpg")
Q: Can't build and run an android test project created using "ant create test-project" when tested project has jars in libs directory I have a module that builds an app called MyApp. I have another that builds some testcases for that app, called MyAppTests. They both build their own APKs, and they both work fine from within my IDE. I'd like to build them using ant so that I can take advantage of continuous integration. Building the app module works fine. I'm having difficulty getting the Test module to compile and run. Using Christopher's tip from a previous question, I used android create test-project -p MyAppTests -m ../MyApp -n MyAppTests to create the necessary build files to build and run my test project. This seems to work great (once I remove an unnecessary test case that it constructed for me and revert my AndroidManifest.xml to the one I was using before it got replaced by android create), but I have two problems. The first problem: The project doesn't compile because it's missing libraries. $ ant run-tests Buildfile: build.xml [setup] Project Target: Google APIs [setup] Vendor: Google Inc. [setup] Platform Version: 1.6 [setup] API level: 4 [setup] WARNING: No minSdkVersion value set. Application will install on all Android versions. -install-tested-project: [setup] Project Target: Google APIs [setup] Vendor: Google Inc. [setup] Platform Version: 1.6 [setup] API level: 4 [setup] WARNING: No minSdkVersion value set. Application will install on all Android versions. -compile-tested-if-test: -dirs: [echo] Creating output directories if needed... -resource-src: [echo] Generating R.java / Manifest.java from the resources... -aidl: [echo] Compiling aidl files into Java classes... compile: [javac] Compiling 1 source file to /Users/mike/Projects/myapp/android/MyApp/bin/classes -dex: [echo] Converting compiled files and external libraries into /Users/mike/Projects/myapp/android/MyApp/bin/classes.dex... [echo] -package-resources: [echo] Packaging resources [aaptexec] Creating full resource package... -package-debug-sign: [apkbuilder] Creating MyApp-debug-unaligned.apk and signing it with a debug key... [apkbuilder] Using keystore: /Users/mike/.android/debug.keystore debug: [echo] Running zip align on final apk... [echo] Debug Package: /Users/mike/Projects/myapp/android/MyApp/bin/MyApp-debug.apk install: [echo] Installing /Users/mike/Projects/myapp/android/MyApp/bin/MyApp-debug.apk onto default emulator or device... [exec] 1567 KB/s (288354 bytes in 0.179s) [exec] pkg: /data/local/tmp/MyApp-debug.apk [exec] Success -compile-tested-if-test: -dirs: [echo] Creating output directories if needed... [mkdir] Created dir: /Users/mike/Projects/myapp/android/MyAppTests/gen [mkdir] Created dir: /Users/mike/Projects/myapp/android/MyAppTests/bin [mkdir] Created dir: /Users/mike/Projects/myapp/android/MyAppTests/bin/classes -resource-src: [echo] Generating R.java / Manifest.java from the resources... -aidl: [echo] Compiling aidl files into Java classes... compile: [javac] Compiling 5 source files to /Users/mike/Projects/myapp/android/MyAppTests/bin/classes [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/GsonTest.java:4: package roboguice.test does not exist [javac] import roboguice.test.RoboUnitTestCase; [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/GsonTest.java:8: package com.google.gson does not exist [javac] import com.google.gson.JsonElement; [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/GsonTest.java:9: package com.google.gson does not exist [javac] import com.google.gson.JsonParser; [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/GsonTest.java:11: cannot find symbol [javac] symbol: class RoboUnitTestCase [javac] public class GsonTest extends RoboUnitTestCase<MyApplication> { [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/HttpTest.java:6: package roboguice.test does not exist [javac] import roboguice.test.RoboUnitTestCase; [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/HttpTest.java:7: package roboguice.util does not exist [javac] import roboguice.util.RoboLooperThread; [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/HttpTest.java:11: package com.google.gson does not exist [javac] import com.google.gson.JsonObject; [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/HttpTest.java:15: cannot find symbol [javac] symbol: class RoboUnitTestCase [javac] public class HttpTest extends RoboUnitTestCase<MyApplication> { [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/LinksTest.java:4: package roboguice.test does not exist [javac] import roboguice.test.RoboUnitTestCase; [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/LinksTest.java:12: cannot find symbol [javac] symbol: class RoboUnitTestCase [javac] public class LinksTest extends RoboUnitTestCase<MyApplication> { [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:4: package roboguice.test does not exist [javac] import roboguice.test.RoboUnitTestCase; [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:5: package roboguice.util does not exist [javac] import roboguice.util.RoboAsyncTask; [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:6: package roboguice.util does not exist [javac] import roboguice.util.RoboLooperThread; [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:12: cannot find symbol [javac] symbol: class RoboUnitTestCase [javac] public class SafeAsyncTest extends RoboUnitTestCase<MyApplication> { [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyApp/bin/classes/com/myapp/activity/Stories.class: warning: Cannot find annotation method 'value()' in type 'roboguice.inject.InjectResource': class file for roboguice.inject.InjectResource not found [javac] /Users/mike/Projects/myapp/android/MyApp/bin/classes/com/myapp/activity/Stories.class: warning: Cannot find annotation method 'value()' in type 'roboguice.inject.InjectResource' [javac] /Users/mike/Projects/myapp/android/MyApp/bin/classes/com/myapp/activity/Stories.class: warning: Cannot find annotation method 'value()' in type 'roboguice.inject.InjectView': class file for roboguice.inject.InjectView not found [javac] /Users/mike/Projects/myapp/android/MyApp/bin/classes/com/myapp/activity/Stories.class: warning: Cannot find annotation method 'value()' in type 'roboguice.inject.InjectView' [javac] /Users/mike/Projects/myapp/android/MyApp/bin/classes/com/myapp/activity/Stories.class: warning: Cannot find annotation method 'value()' in type 'roboguice.inject.InjectView' [javac] /Users/mike/Projects/myapp/android/MyApp/bin/classes/com/myapp/activity/Stories.class: warning: Cannot find annotation method 'value()' in type 'roboguice.inject.InjectView' [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/GsonTest.java:15: cannot find symbol [javac] symbol : class JsonParser [javac] location: class com.myapp.test.GsonTest [javac] final JsonParser parser = new JsonParser(); [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/GsonTest.java:15: cannot find symbol [javac] symbol : class JsonParser [javac] location: class com.myapp.test.GsonTest [javac] final JsonParser parser = new JsonParser(); [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/GsonTest.java:18: cannot find symbol [javac] symbol : class JsonElement [javac] location: class com.myapp.test.GsonTest [javac] final JsonElement e = parser.parse(s); [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/GsonTest.java:20: cannot find symbol [javac] symbol : class JsonElement [javac] location: class com.myapp.test.GsonTest [javac] final JsonElement e2 = parser.parse(s2); [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/HttpTest.java:19: cannot find symbol [javac] symbol : method getInstrumentation() [javac] location: class com.myapp.test.HttpTest [javac] assertEquals("MyApp", getInstrumentation().getTargetContext().getResources().getString(com.myapp.R.string.app_name)); [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/HttpTest.java:62: cannot find symbol [javac] symbol : class RoboLooperThread [javac] location: class com.myapp.test.HttpTest [javac] new RoboLooperThread() { [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/HttpTest.java:82: cannot find symbol [javac] symbol : method assertTrue(java.lang.String,boolean) [javac] location: class com.myapp.test.HttpTest [javac] assertTrue(result[0], result[0].contains("Search")); [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/HttpTest.java:87: cannot find symbol [javac] symbol : class JsonObject [javac] location: class com.myapp.test.HttpTest [javac] final JsonObject[] result = {null}; [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/HttpTest.java:90: cannot find symbol [javac] symbol : class RoboLooperThread [javac] location: class com.myapp.test.HttpTest [javac] new RoboLooperThread() { [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/HttpTest.java:117: cannot find symbol [javac] symbol : class JsonObject [javac] location: class com.myapp.test.HttpTest [javac] final JsonObject[] result = {null}; [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/HttpTest.java:120: cannot find symbol [javac] symbol : class RoboLooperThread [javac] location: class com.myapp.test.HttpTest [javac] new RoboLooperThread() { [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/LinksTest.java:27: cannot find symbol [javac] symbol : method assertTrue(boolean) [javac] location: class com.myapp.test.LinksTest [javac] assertTrue(m.matches()); [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/LinksTest.java:28: cannot find symbol [javac] symbol : method assertEquals(java.lang.String,java.lang.String) [javac] location: class com.myapp.test.LinksTest [javac] assertEquals( map.get(url), m.group(1) ); [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:19: cannot find symbol [javac] symbol : method getInstrumentation() [javac] location: class com.myapp.test.SafeAsyncTest [javac] assertEquals("MyApp", getInstrumentation().getTargetContext().getString(com.myapp.R.string.app_name)); [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:27: cannot find symbol [javac] symbol : class RoboLooperThread [javac] location: class com.myapp.test.SafeAsyncTest [javac] new RoboLooperThread() { [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:65: cannot find symbol [javac] symbol : method assertEquals(com.myapp.test.SafeAsyncTest.State,com.myapp.test.SafeAsyncTest.State) [javac] location: class com.myapp.test.SafeAsyncTest [javac] assertEquals(State.TEST_SUCCESS,state[0]); [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:74: cannot find symbol [javac] symbol : class RoboLooperThread [javac] location: class com.myapp.test.SafeAsyncTest [javac] new RoboLooperThread() { [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:105: cannot find symbol [javac] symbol : method assertEquals(com.myapp.test.SafeAsyncTest.State,com.myapp.test.SafeAsyncTest.State) [javac] location: class com.myapp.test.SafeAsyncTest [javac] assertEquals(State.TEST_SUCCESS,state[0]); [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:113: cannot find symbol [javac] symbol : class RoboLooperThread [javac] location: class com.myapp.test.SafeAsyncTest [javac] new RoboLooperThread() { [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:144: cannot find symbol [javac] symbol : method assertEquals(com.myapp.test.SafeAsyncTest.State,com.myapp.test.SafeAsyncTest.State) [javac] location: class com.myapp.test.SafeAsyncTest [javac] assertEquals(State.TEST_SUCCESS,state[0]); [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:154: cannot find symbol [javac] symbol : class RoboLooperThread [javac] location: class com.myapp.test.SafeAsyncTest [javac] new RoboLooperThread() { [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java:187: cannot find symbol [javac] symbol : method assertEquals(com.myapp.test.SafeAsyncTest.State,com.myapp.test.SafeAsyncTest.State) [javac] location: class com.myapp.test.SafeAsyncTest [javac] assertEquals(State.TEST_SUCCESS,state[0]); [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/StoriesTest.java:11: cannot access roboguice.activity.GuiceListActivity [javac] class file for roboguice.activity.GuiceListActivity not found [javac] public class StoriesTest extends ActivityUnitTestCase<Stories> { [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/StoriesTest.java:21: cannot access roboguice.application.GuiceApplication [javac] class file for roboguice.application.GuiceApplication not found [javac] setApplication( new MyApplication( getInstrumentation().getTargetContext() ) ); [javac] ^ [javac] /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/StoriesTest.java:22: incompatible types [javac] found : com.myapp.activity.Stories [javac] required: android.app.Activity [javac] final Activity activity = startActivity(intent, null, null); [javac] ^ [javac] 39 errors [javac] 6 warnings BUILD FAILED /opt/local/android-sdk-mac/platforms/android-1.6/templates/android_rules.xml:248: Compile failed; see the compiler error output for details. Total time: 24 seconds That's not a hard problem to solve. I'm not sure it's the right thing to do, but I copied the missing libraries (roboguice and gson) from the MyApp/libs directory to the MyAppTests/libs directory and everything seems to compile fine. But that leads to the second problem, which I'm currently stuck on. The tests compile fine but they won't run: $ cp ../MyApp/libs/gson-r538.jar libs/ $ cp ../MyApp/libs/roboguice-1.1-SNAPSHOT.jar libs/ 0 10:23 /Users/mike/Projects/myapp/android/MyAppTests $ ant run-testsBuildfile: build.xml [setup] Project Target: Google APIs [setup] Vendor: Google Inc. [setup] Platform Version: 1.6 [setup] API level: 4 [setup] WARNING: No minSdkVersion value set. Application will install on all Android versions. -install-tested-project: [setup] Project Target: Google APIs [setup] Vendor: Google Inc. [setup] Platform Version: 1.6 [setup] API level: 4 [setup] WARNING: No minSdkVersion value set. Application will install on all Android versions. -compile-tested-if-test: -dirs: [echo] Creating output directories if needed... -resource-src: [echo] Generating R.java / Manifest.java from the resources... -aidl: [echo] Compiling aidl files into Java classes... compile: [javac] Compiling 1 source file to /Users/mike/Projects/myapp/android/MyApp/bin/classes -dex: [echo] Converting compiled files and external libraries into /Users/mike/Projects/myapp/android/MyApp/bin/classes.dex... [echo] -package-resources: [echo] Packaging resources [aaptexec] Creating full resource package... -package-debug-sign: [apkbuilder] Creating MyApp-debug-unaligned.apk and signing it with a debug key... [apkbuilder] Using keystore: /Users/mike/.android/debug.keystore debug: [echo] Running zip align on final apk... [echo] Debug Package: /Users/mike/Projects/myapp/android/MyApp/bin/MyApp-debug.apk install: [echo] Installing /Users/mike/Projects/myapp/android/MyApp/bin/MyApp-debug.apk onto default emulator or device... [exec] 1396 KB/s (288354 bytes in 0.201s) [exec] pkg: /data/local/tmp/MyApp-debug.apk [exec] Success -compile-tested-if-test: -dirs: [echo] Creating output directories if needed... -resource-src: [echo] Generating R.java / Manifest.java from the resources... -aidl: [echo] Compiling aidl files into Java classes... compile: [javac] Compiling 5 source files to /Users/mike/Projects/myapp/android/MyAppTests/bin/classes [javac] Note: /Users/mike/Projects/myapp/android/MyAppTests/src/com/myapp/test/SafeAsyncTest.java uses unchecked or unsafe operations. [javac] Note: Recompile with -Xlint:unchecked for details. -dex: [echo] Converting compiled files and external libraries into /Users/mike/Projects/myapp/android/MyAppTests/bin/classes.dex... [echo] -package-resources: [echo] Packaging resources [aaptexec] Creating full resource package... -package-debug-sign: [apkbuilder] Creating MyAppTests-debug-unaligned.apk and signing it with a debug key... [apkbuilder] Using keystore: /Users/mike/.android/debug.keystore debug: [echo] Running zip align on final apk... [echo] Debug Package: /Users/mike/Projects/myapp/android/MyAppTests/bin/MyAppTests-debug.apk install: [echo] Installing /Users/mike/Projects/myapp/android/MyAppTests/bin/MyAppTests-debug.apk onto default emulator or device... [exec] 1227 KB/s (94595 bytes in 0.075s) [exec] pkg: /data/local/tmp/MyAppTests-debug.apk [exec] Success run-tests: [echo] Running tests ... [exec] [exec] android.test.suitebuilder.TestSuiteBuilder$FailedToCreateTests:INSTRUMENTATION_RESULT: shortMsg=Class ref in pre-verified class resolved to unexpected implementation [exec] INSTRUMENTATION_RESULT: longMsg=java.lang.IllegalAccessError: Class ref in pre-verified class resolved to unexpected implementation [exec] INSTRUMENTATION_CODE: 0 BUILD SUCCESSFUL Total time: 38 seconds Any idea what's causing the "Class ref in pre-verified class resolved to unexpected implementation" error? A: I had a similar problem, using Intellij IDEA (11.1.1). Whily my app would build and deploy to the device just fine, my test-app would spew tons of dex errors when I tried to run it: "Class ref in pre-verified class resolved to unexpected implementation"... app test-app common-libs app depends on common-libs (and exports common-libs) test-app depends on app This post helped me figure out that the problem was duplicate class files in the app and test app .dex files, which I then manually verified. It turns out that to exclude the app classes from the test-app, in the module settings for test-app, I needed to change the scope of it's dependency, app, from 'compile', to 'provided'. A: I don't see the actual error message in the text above, but I think I can answer. Generally, the warning happens because the same code appears in two different APKs. The implementation in one APK was used for pre-verification and optimization, but the other implementation is being used during execution. The VM detects the situation and rejects the class, because the verification and optimization were performed with a set of assumptions that are no longer true. The way to fix this is to ensure that there is only one implementation of a class available to the VM. This may require fighting with the build scripts a bit more. You can view the contents of an APK with "dexdump". (There's also "dexlist", which is a bit more concise, but I don't remember if that's part of the SDK.) A: Like @fadden said, the same code is in two different APKs. This can e.g. happen when your test and tested project both depend on the same android library project. That does not have to be direct as library projects can depend on other library projects. The problem in the ant rules file seems to be fixed. At least in SDK tools r11. The compile target can be found in mail_rules.xml and not in test_rules.xml, just for those who got confused. A: If you use Eclipse, a simpler approach is to not include your external library in the test project, but rather export it in the Eclipse Project settings. This will solve the issue Time ago, I wrote a blog post explaining this: http://juristr.com/blog/2010/06/android-instrumentation-test/ A: The problem is that there's a bug in the android ant build scripts that don't include the tested project's libs directory when compiling the tester project. If you try to get around this by copying the libs to the tester project's libs dir, you'll run into class verification problems at run time like I did, as pointed out by fadden. The solution is to tweak the compile target originally in android's android_test_rules.xml to add <fileset dir="${tested.project.absolute.dir}/libs" includes="*.jar" /> to the <classpath> directive. Here's the revised compile target. By adding it to the build.xml in your TESTER project, it will take precedence over the one in android_test_rules.xml: <!-- override "compile" target in platform android_rules.xml to include tested app's external libraries --> <target name="compile" depends="-resource-src, -aidl" description="Compiles project's .java files into .class files"> <!-- If android rules are used for a test project, its classpath should include tested project's location --> <condition property="extensible.classpath" value="${tested.project.absolute.dir}/bin/classes" else="."> <isset property="tested.project.absolute.dir" /> </condition> <javac encoding="ascii" target="1.5" debug="true" extdirs="" destdir="${out.classes.absolute.dir}" bootclasspathref="android.target.classpath" verbose="${verbose}" classpath="${extensible.classpath}"> <src path="${source.absolute.dir}" /> <src path="${gen.absolute.dir}" /> <classpath> <fileset dir="${tested.project.absolute.dir}/libs" includes="*.jar" /> <fileset dir="${external.libs.absolute.dir}" includes="*.jar" /> </classpath> </javac> </target> A: Have you tried to include the .class files on the test apk, instead of generating new .class files from your original project? This solved the problem in my case. A: I faced the same problem with unit tests being run by maven. By removing the link to the android libraries already imported by the main project the problem was fixed. A: The scope of the project to be tested should be compile and that of the libraries should be provided. For more, read here A: android update test-project -m <project path> -p <test project path> ant clean ant debug After running these commands, you can run ant tests. Note: If it gives JUnit related errors, please add Junit jar file in the test project libs folder.
Q: Cannot Create a frame for UITableView I have made a tableView which obviously starts from the top of the screen but I want to add a label at the top other than the table header. Could anyone provide help? thanks in advance .... I tried to do this by using cgrect and provide a frame for the table but when I execute the code, nothing happens and table is still only thing present on the view and label is nowhere to be found. I also made sure to add label after the table so that it dont get overlapped but didnt work. class TableViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.barTintColor = UIColor(red: 139/255, green: 26/255, blue: 137/255, alpha: 1.0) self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.white] self.navigationController?.navigationBar.tintColor = .white self.navigationItem.backBarButtonItem?.title = "Back" checkForVolume() self.coachMarksController.dataSource = self var tableFrame = self.tableView.frame; tableFrame.size.height = 200; self.tableView.frame = tableFrame; fileprivate var moduleTable: UITableView! moduleTable.frame = CGRect(x: 0, y: 100, width: 375 , height: 650) moduleTable = UITableView() moduleTable.delegate = self moduleTable.dataSource = self moduleTable.separatorStyle = .none moduleTable.allowsSelection = true moduleTable.rowHeight = view.frame.size.height * 0.11 moduleTable.allowsMultipleSelection = false moduleTable.register(SettingCell.self, forCellReuseIdentifier: identifier) moduleTable.frame = CGRect(x: 0, y: 1500, width: 375 , height: 650) view.addSubview(moduleTable) moduleTable.frame = CGRect(x: 0, y: 1500, width: 375 , height: 650) let moduleLabel = UILabel() moduleLabel.text = "MODULES" moduleLabel.textAlignment = .center moduleLabel.textColor = .purple moduleLabel.frame = CGRect(x: 0, y: 60, width: 375, height:40) self.view.addSubview(moduleLabel) A: import UIKit import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var myTableView: UITableView = UITableView() var itemsToLoad: [String] = ["One", "Two", "Three"] override func viewDidLoad() { super.viewDidLoad() // Get main screen bounds let screenSize: CGRect = UIScreen.main.bounds let screenWidth = screenSize.width let screenHeight = screenSize.height myTableView.frame = CGRect(x: 50, y: 50, width: 132, height: 555) myTableView.dataSource = self myTableView.delegate = self myTableView.register(UITableViewCell.self, forCellReuseIdentifier: "myCell") self.view.addSubview(myTableView) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return itemsToLoad.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell:UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath as IndexPath) cell.textLabel?.text = self.itemsToLoad[indexPath.row] return cell } func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) { print("User selected table row \(indexPath.row) and item \(itemsToLoad[indexPath.row])") } }
Q: storing e-signature from PDF in SQL database is there a way to store e-signatures in SQL Databases? I have designed a form in adobe LiveCycle designer and I store all the information in my SQL database. I use a signature field to add the signature to the pdf. The e-signature is from a USB token and certificate installed on my computer. My question is how to add a signature to this database? I hope you will understand my problem. Thanks for your answers! V. A: Many databases offer a BLOB (Binary Large OBject) or similar type that can be used to store arbitrary binary data alongside relational data. That said, what format is the signature? Is it a file of a certain type, or is it merely contained in a larger document? What database are you using? Without this additional information, the above is about as specific an answer as I can give.
Q: parallax scrolling image out of view I'm working on a little extracurricular side project to bolster my html5/css3/jquery knowledge and I'm working with Parallax Scrolling but I can't seem to get the bottom image to scroll into view. It seems stuck behind the above it and no matter what I do I can't seem to pull it down into view. There should be a giant dollar bill in the bottom black section where it says 'Abe is the money' my url is : http://www.petegetscreative.com/abe/index.html inspiration came from this tutorial: http://net.tutsplus.com/tutorials/html-css-techniques/simple-parallax-scrolling-technique/ cheers A: I think the dollar bill image is too small. Looking at this Fiddle, when I increase the size of the dollar bill image to 200%, it becomes visible in the preview. #known { background: url(http://www.petegetscreative.com/abe/images/US-$5-SC-1953-Fr.1655.2.jpg) 50% 0 no-repeat fixed; background-color: #000; background-size: 200%; height: 600px; margin: 0 auto; width: 100%; max-width: 1920px; position: relative; padding-top: 50px; } So what's probably happening is the height of the image is less than the difference in scroll positions. Try a larger (taller) image. A: I believe that the problem could be the dollar image is less than section tag and the script you're running put the bg image with negative Y position. You can make a test making the image bigger than the 650px ( the section's height ).
Q: How to change the "User License" type for customer portal users using a script? We want to move a large number of customer portal users (users who self-register via a pre-existing Contact record) from one "User License" type to another. But I note that in the User edit page the "User License" field is not editable (whereas it is for other license types) and in any case as thousands of users are involved we would like to automate the process. Can this be done via an Apex script? Or can this be done via a Salesforce support request? A: This Knowledge Article User license conversion when migrating from portal to communities covers the transitions that are simple: An administrator can change the license type and profile on the user record. and the transitions that when attempted result in the error message: cannot upgrade from or downgrade to LPU and so require this disruptive process to accomplish: An administrator must disable the contact as a Customer User and then re-enable as a Customer User to create a new user record and associate it with the new license. This Migrating from Portals to Communities cheatsheet includes a table that can be used to predict what is an upgrade/downgrade.
Q: How do I move the last item in a list to the front in O(1) time? My code looks like this, where heap is a list: heap[0] = heap.pop() The problem is it does not work when popping the only item. According to python wiki, popping last element is O(1). (I also want to remove the last element) So far what I've come up with: last_element = heap.pop() # I don't want to catch potential IndexError here try: heap[0] = last_element except IndexError: heap.append(last_element) which is a lot longer or this if len(heap) != 1: heap[0] = heap.pop() which should be slower. Is there a more pythonic way to do this? Internally python maybe does not even resize the array. UPDATE: I need O(1) access to elements at given indeces (so it cannot be a linked list). A: It sounds like you're implementing a heap, and this line is part of the implementation of the heap-pop operation. In context, it would look something like def heappop_wrong(heap): popped_value = heap[0] heap[0] = heap.pop() # <-- here sift_down(heap, 0) return popped_value In that case, if the list has only one element, you shouldn't be moving the last element to the front at all. You should just remove and return the only element: def heappop(heap): if len(heap) == 1: return heap.pop() popped_value = heap[0] heap[0] = heap.pop() sift_down(heap, 0) return popped_value As for the cost of the if, this cost is trivial and not at all something you should be worrying about. For moving the last element of a list to the front without replacing the old front element, this is not possible in O(1) time. You'd have to use a different data structure, like a collections.deque, or implement your own resizeable ring buffer. That's not relevant for a heap use case, though. For moving the last element of a list to the front, stomping over the old first element if there were multiple elements and leaving the list unchanged if there was only one, an if check would probably be clearest, but again, the "leave the list unchanged if there was only one element" behavior isn't actually useful for implementing a heap-pop. A: An approach that works (without exceptions, so long as the list is non-empty) is to assign to a slice of the list: heap[:1] = (heap.pop(),) That pops the final element and creates a length 1 tuple, which is then assigned to the heap such that it replaces the first element if it exists, or becomes the contents of the list if it's empty (as a result of the pop). It should remain O(n) because it's always replacing a single element with a single element; the higher indices are untouched. A: collections.deque supports removing from and appending to both the front and the back in O(1). See https://wiki.python.org/moin/TimeComplexity. A: You can check if the list is empty before attempting pop. if len(a) > 0: a.insert(0,a.pop()) By default, pop returns the last element from the list so you do not have to explicitly pass -1. And since it raises an error if the list is empty, we can check its length before attempting to pop. But insert operation on list is O(n). For O(1) you will need to use dequeue. from collections import deque a = deque() a.append(10) a.append(12) if len(a) > 0: a.appendleft(a.pop()) print a
Q: Parse complex json to DataTable I've a json string and a method to transform this into a DataTable, but nested objects isnt in DataTable. MyJSON [ { "id": 645162, "customerId": 9950, "created": "2021-07-19T23:06:39.462913Z", "updated": "2021-07-19T23:06:39.462913Z", "createdBy": "System", "updatedBy": "System", "createdById": 0, "updatedById": 0, "checkId": 289960, "cvssV2Score": 5, "cvssV2BaseScore": 5, "cvssV2Vector": "(AV:N/AC:L/Au:N/C:P/I:N/A:N)", "cvssV2Severity": "MEDIUM", "isAccepted": false, "commentsCount": 0, "source": [ "SCALE" ], "name": "X-Frame-Options Header Missing or Malformed", "description": "The clickjacking attack vector consists of an attacker creating a malicious web page that includes a section of the application within an <iframe>-element. The attacker cannot directly interact with the application, but they can control the main page and are able to overlay elements on top of the <iframe>. This can be leveraged in order to fool the end user that they are interacting with one page, when they are in reality interacting with another page.\n\nThe frameableness of a resource is determined by either the Content-Security-Policy header when used with the frame-ancestors directive, or using the X-Frame-Options header. \nBoth of these were missing or malformed on the found resource.", "cwe": "CWE-1021", "solution": "The Content-Security-Policy header with the frame-ancestors directive will resolve clickjacking in modern browsers that support it. Setting the frame-ancestors to 'self' (SAMEORIGIN) or 'none' (DENY) will limit which origins may frame this resource. Whitelisting external resources is possible using this method as well.\n\nTo ensure legacy client compatibility, set the X-Frame-Options header to either DENY (which means the resource can not be framed) or SAMEORIGIN (which means that only the same origin may frame this resource). Note that the 'allow-from' value is not implemented correctly in all browsers. If frameability in an external resource has to be permitted, use CSP.\n\nThese headers must be set on all server responses.", "exploitAvailable": false, "matchIds": [ 707510 ], "firstSeen": "2021-07-19T23:06:39.462913Z", "lastSeen": "2021-08-02T01:02:39.999Z", "firstScanId": 585696, "lastScanId": 602872, "owasp2013": [ 5 ], "owasp2017": [ 6 ], "capec": [ 103, 181, 222, 504, 506 ], "assetIdentifierId": 34431, "assetIdentifierType": "IP", "assetIdentifierName": "NOT TODAY", "potential": false, "softwareComponent": "Web Application Scanning", "secureCodeWarrior": { "name": "Improper Restriction of Rendered UI Layers or Frames", "description": "The web application does not restrict or incorrectly restricts frame objects or UI layers that belong to another application or domain, which can lead to user confusion about which interface the user is interacting with.", "url": "https://portal.securecodewarrior.com/?utm_source=partner-integration:scw#/website-trial/web/misconfig/securityfeatures/java/vanilla" }, "tags": [ { "id": 939, "key": "UNKNOWN", "value": "", "inherited": true } ] } ] MyMethod public static DataTable ToDataTable<T>( this IList<T> list ) { PropertyDescriptorCollection props = TypeDescriptor.GetProperties(typeof(T)); DataTable table = new DataTable(); //table.TableName = list.GetType().ReflectedType.Name; for(int i = 0; i < props.Count; i++) { PropertyDescriptor prop = props[i]; table.Columns.Add(prop.Name, Nullable.GetUnderlyingType(prop.PropertyType) ?? prop.PropertyType); } object[] values = new object[props.Count]; foreach(T item in list) { for(int i = 0; i < values.Length; i++) values[i] = props[i].GetValue(item) ?? DBNull.Value; table.Rows.Add(values); } return table; } My Object Class public class RestFinding { [JsonProperty("id")] public int Id { get; set; } [JsonProperty("customerId")] public int CustomerId { get; set; } [JsonProperty("created")] public DateTime Created { get; set; } [JsonProperty("updated")] public DateTime Updated { get; set; } [JsonProperty("createdBy")] public string CreatedBy { get; set; } [JsonProperty("updatedBy")] public string UpdatedBy { get; set; } [JsonProperty("createdById")] public int CreatedById { get; set; } [JsonProperty("updatedById")] public int UpdatedById { get; set; } [JsonProperty("checkId")] public int CheckId { get; set; } [JsonProperty("cvssV2Score")] public double CvssV2Score { get; set; } [JsonProperty("cvssV2BaseScore")] public double CvssV2BaseScore { get; set; } [JsonProperty("cvssV2Vector")] public string CvssV2Vector { get; set; } [JsonProperty("cvssV2Severity")] public string CvssV2Severity { get; set; } [JsonProperty("isAccepted")] public bool IsAccepted { get; set; } [JsonProperty("commentsCount")] public int CommentsCount { get; set; } [JsonProperty("source")] public List<string> Source { get; set; } [JsonProperty("name")] public string Name { get; set; } [JsonProperty("description")] public string Description { get; set; } [JsonProperty("cwe")] public string Cwe { get; set; } [JsonProperty("solution")] public string Solution { get; set; } [JsonProperty("exploitAvailable")] public bool ExploitAvailable { get; set; } [JsonProperty("matchIds")] public List<int> MatchIds { get; set; } [JsonProperty("firstSeen")] public DateTime FirstSeen { get; set; } [JsonProperty("lastSeen")] public DateTime LastSeen { get; set; } [JsonProperty("firstScanId")] public int FirstScanId { get; set; } [JsonProperty("lastScanId")] public int LastScanId { get; set; } [JsonProperty("owasp2013")] public List<int> Owasp2013 { get; set; } [JsonProperty("owasp2017")] public List<int> Owasp2017 { get; set; } [JsonProperty("capec")] public List<int> Capec { get; set; } [JsonProperty("assetIdentifierId")] public int AssetIdentifierId { get; set; } [JsonProperty("assetIdentifierType")] public string AssetIdentifierType { get; set; } [JsonProperty("assetIdentifierName")] public string AssetIdentifierName { get; set; } [JsonProperty("potential")] public bool Potential { get; set; } [JsonProperty("softwareComponent")] public string SoftwareComponent { get; set; } [JsonProperty("secureCodeWarrior")] public SecureCodeWarrior SecureCodeWarrior { get; set; } [JsonProperty("tags")] public List<Tag> Tags { get; set; } [JsonProperty("cvssV3Score")] public double? CvssV3Score { get; set; } [JsonProperty("cvssV3BaseScore")] public double? CvssV3BaseScore { get; set; } [JsonProperty("cvssV3Vector")] public string CvssV3Vector { get; set; } [JsonProperty("cvssV3Severity")] public string CvssV3Severity { get; set; } [JsonProperty("wasc")] public List<int> Wasc { get; set; } [JsonProperty("owasp2010")] public List<int> Owasp2010 { get; set; } [JsonProperty("cve")] public string Cve { get; set; } [JsonProperty("sans25")] public int? Sans25 { get; set; } [JsonProperty("owasp2004")] public List<int> Owasp2004 { get; set; } [JsonProperty("owasp2007")] public List<int> Owasp2007 { get; set; } [JsonProperty("bugTraq")] public List<int> BugTraq { get; set; } } public class Tag { [JsonProperty("id")] public int Id { get; set; } [JsonProperty("key")] public string Key { get; set; } [JsonProperty("value")] public string Value { get; set; } [JsonProperty("inherited")] public bool Inherited { get; set; } } Expected output of the nested object Tag is: Tag_id | Tag_key | Tag_value <int> | <string>| <string> But my output is SecureCodeWarrior | Tags | cvssV3Score <string> | NULL | <string> Is there a way to flatten json nested object as itemName_subitemName as mentioned? I've tried inumerous posts but dont return as mentioned...
Q: Downgrade ASP.NET Core Hosting Bundle 5 to 3.1 or install them side by side? Windows 2019 Server with IIS and ASP.NET Core Hosting Bundle 5.0.1 installed. I need to run Asp.Net Core 3.1 site on the machine. Should I just install ASP.NET Core Hosting Bundle 3.1 side by side with the existing one or downgrade the installation in a way? A: Just installing ASP.NET Core Hosting Bundle 3.1 alongside with 5.0.1 worked for me. A: ASP.NET Core Hosting Bundle make IIS to know how to run core sites. To run site with specific core version you need appropriate core runtime version to be installed or choose "self contained" build so runtime will be a pert of a build
Q: problem with changing colour of a textbox *I want the background colour of a text box to change to lightgreen when the textbox gets focus and its background colour to revert to white when it loses focus. My code works perfectly on localhost and when the browser is Safari. However, with all the other browsers (Chrome, Edge, Firefox, Opera ) nothing happens. I'm doing something stupid, but what?! <script> function test(id) { var ctrl_name = id; document.getElementById('Name').value = ctrl_name; } </script> <body> <script src="http://ajax.googleapis.com/ajax/libs/jquery /1/jquery.min.js"></script> <script type='text/javascript'> $(document).ready(function(){ $('.clickOnMe').blur(function(){ $(this).css('background', 'white' ); }); $('.clickOnMe').mousedown(function(){ $(this).css( 'background', 'lightgreen'); }); }); </script> and in the textboxes - onclick="test(this.id)" class="clickOnMe" No error messages/ Simply won't work except on localhost and Safari.* A: CSS only This can be done with css without javascript. Example: .custom-textarea:focus { background-color: lightgreen; } <textarea class="custom-textarea">Click on me</textarea> JS with jQuery If you would like to use js and jQuery anyway: You can use .focus() event instead of .mousedown(). * *This method is a shortcut for .on( "focus", handler ) in the first and second variations, and .trigger( "focus" ) in the third. *The focus event is sent to an element when it gains focus. *Source: api.jquery.com Example: $('textarea').focus(function() { $(this).css("background-color","lightgreen"); }); $('textarea').blur(function() { $(this).css("background-color","white"); }); <script src="https://code.jquery.com/jquery-3.4.1.js"></script> <textarea class="custom-textarea">Click on me</textarea> Or in ES6 $('textarea').focus((e) => $(e.currentTarget).css("background-color","lightgreen")); $('textarea').blur((e) => $(e.currentTarget).css("background-color","white")); <script src="https://code.jquery.com/jquery-3.4.1.js"></script> <textarea class="custom-textarea">Click on me</textarea>
Q: Bash FTP login into Microsoft FTP Service, Invalid command This is my script. As you can see it executes only 1 command (cd /) after connecting to a remote FTP server. It's very simple... but it doesn't work and give me "Invalid command". I don't understand why. #!/bin/bash HOST=xxx #This is the FTP servers host or IP address. USER=xxx #This is the FTP user that has access to the server. PASS=xxx #This is the password for the FTP user. # Call 1. Uses the ftp command with the -inv switches. #-i turns off interactive prompting. #-n Restrains FTP from attempting the auto-login feature. #-v enables verbose and progress. ftp -inv $HOST << EOF # Call 2. Here the login credentials are supplied by calling the variables. user $USER $PASS pass # Call 3. I change to the directory where I want to put or get cd / # Call4. Here I will tell FTP to put or get the file. #put... # End FTP Connection bye EOF This is the output: Connected to [IP] 220 Microsoft FTP Service ?Invalid command 331 Password required for logweb. 230 User logged in. Remote system type is Windows_NT. Passive mode on. ?Invalid command 250 CWD command successful. ?Invalid command ?Invalid command ?Invalid command 221 Goodbye. A: The "Invalid command" error is due to those # lines. The ftp does not recognize the # as a comment prefix. If you need the comments in the script, you can abuse an escape to shell command ! and follow that by a shell comment: !# This is comment Other than that, I believe all commands in your script are executed, despite your claim that only one is: > user $USER $PASS < 331 Password required for logweb. < 230 User logged in. > cd / < 250 CWD command successful. > bye < 221 Goodbye.
Q: C# Script in SSIS Script Task to convert Excel Column in "Text" Format to "General" I am exporting Data from SQL Server to Excel, utilizing SSIS Data Flow Task. Here all columns appear as Text despite export formatting. Hence I need to develop a SSIS Script task to do the necessary conversion. I am facing trouble in developing the script. Excel Workbook before Formatting See, the Excel Cell has no Apostrophe and the Number type is also "General" but the message says The number in this cell is formatted as text or preceded by an apostrophe I have Tried different options available in the internet, but unsuccessfully. #region Namespaces using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Text.RegularExpressions; using System.Data; using Microsoft.SqlServer.Dts.Runtime; using System.Windows.Forms; using System.Runtime.InteropServices; using Excel = Microsoft.Office.Interop.Excel; #endregion namespace ST_de899f405b7b4083b0ad8cba6b3df2e3 { [Microsoft.SqlServer.Dts.Tasks.ScriptTask.SSISScriptTaskEntryPointAttribute] public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase { public void Main() { string inputFile = (string)Dts.Variables["Target_FullFilePath"].Value; Excel.Application ExcelApp = new Excel.Application(); Excel.Workbook ExcelWorkbook = ExcelApp.Workbooks.Open(inputFile); Excel.Range formatRange; ExcelApp.Visible = true; foreach (Excel.Worksheet ExcelWorksheet in ExcelWorkbook.Sheets) { ExcelWorksheet.Select(Type.Missing); ExcelWorksheet.Columns[2].NumberFormat = ""; ExcelWorksheet.Columns[3].NumberFormat = ""; ExcelWorksheet.Columns[4].NumberFormat = "0.00000"; ExcelWorksheet.Columns[5].NumberFormat = "yyyy-MM-dd"; } ExcelWorkbook.Save(); GC.Collect(); GC.WaitForPendingFinalizers(); ExcelWorkbook.Close(Type.Missing, Type.Missing, Type.Missing); Marshal.FinalReleaseComObject(ExcelWorkbook); ExcelApp.Quit(); Marshal.FinalReleaseComObject(ExcelApp); } enum ScriptResults { Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success, Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure }; #endregion } } Expected Result: Columns numbered B, C, D to look like decimal/integer numbers and also similarly filtered. Column E to look like Date and also similarly filtered. This is how I want Excel file to look like, after formatting through SSIS I confirm the corresponding columns have relevant values only except column header. A: Before providing the solution, i have to explain some points about Excel Number Format What is Number Format property? Referring to Number format codes documentation: You can use number formats to change the appearance of numbers, including dates and times, without changing the actual number. The number format does not affect the cell value that Excel uses to perform calculations. The actual value is displayed in the formula bar. What is General Number format? Referring to Reset a number to the General format documentation: The General format is the default number format that Excel applies when you type a number. For the most part, numbers that are formatted with the General format are displayed just the way that you type them. How Date are stored in Excel? Referring to How Dates Work in Excel: The dates in Excel are actually stored as numbers, and then formatted to display the date. Your excepted result You mentioned that: Expected Result: Columns numbered 16, 17, 22 to be converted to "General" and look like decimal numbers. Column 31 to be converted to "General" and look like Date. Based on what we mentioned you cannot convert column 31 to "General" and make it look like Date. Solution You just need to set NumberFormat property to an empty string to set it as "General" ExcelWorksheet.Columns[16].NumberFormat = ""; Experiments I Created an Excel file with 4 columns: NumberColumn, DateColumn, DecimalColumn and StringColumn as shown in the image above: I created a console application with the following code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Text.RegularExpressions; using Excel = Microsoft.Office.Interop.Excel; using System.Runtime.InteropServices; namespace ConsoleApp1 { class Program { static void Main(string[] args) { string inputFile = @"D:\Test.xlsx"; Excel.Application ExcelApp = new Excel.Application(); Excel.Workbook ExcelWorkbook = ExcelApp.Workbooks.Open(inputFile); ExcelApp.Visible = true; foreach (Excel.Worksheet ExcelWorksheet in ExcelWorkbook.Sheets) { ExcelWorksheet.Select(Type.Missing); ExcelWorksheet.Columns[1].NumberFormat = ""; ExcelWorksheet.Columns[2].NumberFormat = "yyyy-MM-dd"; // convert format to date ExcelWorksheet.Columns[2].NumberFormat = ""; ExcelWorksheet.Columns[3].NumberFormat = "0.00000"; // convert format to decimal with 5 decimal digits ExcelWorksheet.Columns[3].NumberFormat = ""; ExcelWorksheet.Columns[4].NumberFormat = ""; } ExcelWorkbook.Save(); GC.Collect(); GC.WaitForPendingFinalizers(); ExcelWorkbook.Close(Type.Missing, Type.Missing, Type.Missing); Marshal.FinalReleaseComObject(ExcelWorkbook); ExcelApp.Quit(); Marshal.FinalReleaseComObject(ExcelApp); } } } After executing the application, the Excel looked like the following: Discussion and Conclusion From the image above, we can see that all columns are changed to General Number format, but if values are stored as numbers they will be shown as they are stored: Date values are shown as Excel serials (numbers), decimal values are shown with only one decimal digit, even if we changed the format to five digits before resetting the format to General. In Brief, you cannot handle how the values are shown when the Number Format is "General", if you need to show values as dates you have to set the number format to yyyy-MM-dd or any other date format. Reference * *C# Accessing EXCEL, formatting cell as General Update 1 Instead of using ExcelWorksheet.Columns[1].NumberFormat, try using the following code: ExcelWorksheet.Cells[1,1].EntireColumn.NumberFormat = ""; ExcelWorksheet.Cells[1,2].EntireColumn.NumberFormat = "";
Q: Unity Game Assets with OpenGL for a course at my university I am building a small engine with C++, using the OpenGL API. Since I need some 3D models for my characters I'd like to know if it is possible to make use of the sets without having unity installed. I would like to import the FBX files into Maya or another 3D modeling package and then export it as obj sequence which I read into OpenGL as individual VBOs for the animation. I know this technique is outdated but that is not the point here. Since this ( https://www.assetstore.unity3d.com/en/#!/content/68910 ) is a whole kit which is highly customizable I highly doubt that it is convenient to use with any other software than unity. A: Use an asset importing library like ASSIMP so your OpenGL application can directly load the FBX files. Converting poses into static meshes is just impractical and would just be harder to manage than writing a skeletal animation module for your application.
Q: Is it necessary to restart node.js's http-server when updating html files I can't find anywhere an answer for this: do I need to restart the simple http-server if I edit client files like .html, .css or .js (e.g.: index.html) from the directory the server is based on? I want to use http-server for development phase, when I edit various files multiple times. Note: this question is not related to How can I edit on my server files without restarting nodejs when i want to see the changes? A: No. The simple http-server should recognize any changes you make to static files like html, css, and js. The simplest thing to do is give it a try. A: The http-server uses ecstatic to serve static content. This library returns a Cache-Control header where default timeout is 3600 seconds (1 hour). You can change the timeout by specifying cache (in seconds) in the options you pass to http-server - which in turn will be passed on to ecstatic
Q: I'm creating a news app with NEWSAPI's API. whenever i'm clicking the news it crashes Whenever I click to the news it crashes, below is LOGCAT java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.Date.getTime()' on a null object reference at com.jimdo.saifstudios.lynknews.Adapter.ListNewsAdapter.onBindViewHolder(ListNewsAdapter.java:105) at com.jimdo.saifstudios.lynknews.Adapter.ListNewsAdapter.onBindViewHolder(ListNewsAdapter.java:70) ListNewsAdapter class ListNewsViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener { ItemClickListener itemClickListener; TextView article_title; RelativeTimeTextView article_time; CircleImageView article_image; public ListNewsViewHolder(View itemView) { super(itemView); article_image = (CircleImageView)itemView.findViewById(R.id.article_image); article_title = (TextView) itemView.findViewById(R.id.article_title); article_time = (RelativeTimeTextView) itemView.findViewById(R.id.article_time); itemView.setOnClickListener(this); } public void setItemClickListener(ItemClickListener itemClickListener) { this.itemClickListener = itemClickListener; } public void setArticle_title(TextView article_title) { this.article_title = article_title; } public void setArticle_time(RelativeTimeTextView article_time) { this.article_time = article_time; } public void setArticle_image(CircleImageView article_image) { this.article_image = article_image; } @Override public void onClick(View view) { itemClickListener.onClick(view,getAdapterPosition(),false); } } public class ListNewsAdapter extends RecyclerView.Adapter<ListNewsViewHolder> { private List<Article> articleList; private Context context; public ListNewsAdapter(List<Article> articleList, Context context) { this.articleList = articleList; this.context = context; } @Override public ListNewsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { LayoutInflater inflater = LayoutInflater.from(parent.getContext()); View itemView = inflater.inflate(R.layout.news_layout,parent,false); return new ListNewsViewHolder(itemView); } @Override public void onBindViewHolder(ListNewsViewHolder holder, int position) { Picasso.with(context) .load(articleList.get(position).getUrlToImage()) .into(holder.article_image); if (articleList.get(position).getTitle().length() > 65) holder.article_title.setText(articleList.get(position).getTitle().substring(0,65)+"..."); else holder.article_title.setText(articleList.get(position).getTitle()); Date date=null; try { date = ISO8601Parse.parse(articleList.get(position).getPublishedAt()); }catch (ParseException ex) { ex.printStackTrace(); } holder.article_time.setReferenceTime(date.getTime()); // Set event click holder.setItemClickListener(new ItemClickListener() { @Override public void onClick(View view, int position, boolean isLongClick) { Intent detail = new Intent(context,DetailArticle.class); detail.putExtra("webURL",articleList.get(position).getUrl()); detail.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startActivity(detail); } }); } @Override public int getItemCount() { return articleList.size(); } } A: Your date object is null. You are doing date.getTime() without checking if it is null. Move your holder.article_time.setReferenceTime(date.getTime) into the try block below the date and you should no longer crash. Then you need to figure out what is wrong with how you are parsing the date to begin with. A: you have a problem at holder.article_time.setReferenceTime(date.getTime()); the date variable still null it is not initialized so you have problem at ISO8601Parse.parse(articleList.get(position).getPublishedAt()); it throws ParseException check it.
Q: Protractor: Syntax to select elements based on html attributes I want to select this element: <span class="required" ng-class="{'disabled': saveInProgress}" input-control="{okCallback:setFieldValue, params:['firstName'], title:'First Name', value: person.firstName, validate:{length:100},empty:false}"> <span hs-placeholder="Type First Name" class="ng-binding"></span> </span> And this one too: <span class="required" ng-class="{'disabled': saveInProgress}" input-control="{okCallback:setFieldValue, params:['lastName'], title:'Last Name', value: person.lastName, validate:{length:100}}"> <span hs-placeholder="Type Last Name" class="ng-binding"> </span> </span> I tried to do so using var input = element(by.css('span.required span.ng-binding')); browser.actions().mouseMove(input).click().perform(); But it kept on calling the first name element only. Any ideas? please :) A: You need to use element.all(by.css('span.required span.ng-binding')).get(0) //to access 1st element element.all(by.css('span.required span.ng-binding')).get(1) //to access 2nd element because in dom there are two elements available for the selector by.css('span.required span.ng-binding') if you use element(by.css('span.required span.ng-binding')) then protractor by default will take the first displayed element. Hope it will solve your problem!
Q: Prove that the language $\{ww \mid w \in \{a,b\}^*\}$ is not FA (Finite Automata) recognisable. Hint: Assume that $|xy| \le k$ in the pumping lemma. I have no idea where to begin for this. Any help would be much appreciated. A: Suppose that $L$ is regular. The pumping lemma for regular languages then says that there is a positive integer $p$ such that whenever $w\in L$ and $|w|\ge p$, $w$ can be written as a concatenation $xyz$ such that $|y|\ge 1$, $|xy|\le p$, and $xy^kz\in L$ for all integers $k\ge 0$. To show that $L$ is not regular, you need only find a word $w\in L$ that cannot be written as such a concatenation. Let $w=ab^pab^p$; clearly $w\in L$ and $|w|=2p+2\ge p$. Suppose that $w=xyz$, where $|y|\ge 1$, $|xy|\le p$, and $xy^kz\in L$ for all integers $k\ge 0$. Then $xy=ab^n$ for some $n\le p-1$ (why?), so either $x$ is empty and $y=ab^n$, or $y=b^m$ for some $m\ge 1$. In either case, explain why $xz=xy^0z\notin L$, contradicting the hypothesis that $xy^kz\in L$ for all integers $k\ge 0$. Conclude that this word $w$ cannot be decomposed as in the pumping lemma and hence that $L$ cannot be regular. A: It's also possible β€” and perhaps simpler β€” to prove this directly using the pigeonhole principle without invoking the pumping lemma. Namely, assume that the language $L = \{ww \,|\, w \in \{a,b\}^*\}$ is recognized by a finite state automaton with $n$ states, and consider the set $W = \{a,b\}^k \subset \{a,b\}^*$ of words of length $k$, where $2^k > n$. By the pigeonhole principle, since $|W| = 2^k > n$, there must be two distinct words $w,w' \in W$ such that, after reading the word $w$, the automaton is in the same state as after reading $w'$. But this means that, since the automaton accepts $ww \in L$, it must also accept $w'w \notin L$, which leads to a contradiction.
Q: Event handler cause problem when i force application quit I have a macro that captures word events. In this macro in the Document_Open event, I'm going to show the dialog box and force word to quit. With the latest update, the exit instruction causes me a serious error that is shown to me when I go to recall the same document. If I delete the Word close statement and do it manually everything works fine. I tried different solutions but could not solve the problem. I use Word 365 . This is the event class where i call the routine and then close the document and quit from Word. Public WithEvents App As Application Private Sub App_DocumentOpen(ByVal Doc As Document) StampaModulo Doc.Close False App.Quit End Sub This is the module where in AutoExec I associate the application with the class. Dim x As New EventClassHandler Public Sub AutoExec() Set x.App = Application End Sub When I open the same word document, the document is in the disativated element and I receive this message. I tried also to force the quit in the routine of the print of the word document but I have the same problem.
Q: Swift Storyboard app launches to a black screen Hi everyone, I'm building a Swift app using Storyboards. I've been working fine for a few months now, but all of a sudden my app won't load properly. Whenever I open it on a Simulator or my physical iPhone, the launch screen is displayed before a black screen appears. My Mac is on macOS Big Sur Developer Beta 5 with Xcode 12 Beta 6, and my iPhone is on iOS 14 Developer Beta 5. This happened all of a sudden and I don't recall doing anything to cause it. Here's what I've tried so far... * *Renaming the storyboard and updating the target's General tab to the new name, as well as doing the same but manually editing Info.plist *Moving the storyboard in and out of "Copy Bundle Resources" *Updating to the latest Xcode 12 beta (I'm on macOS Big Sur) *Clearing Derived Data with DevCleaner *Starting a whole new project and moving all of my code and resources over via drag-and-drop (Interesting observation: when I started a new project, I added a simple label to the default Main.storyboard and ran it on my iPhone. The label wasn't displayed.) *Adding a function to my AppDelegate to load the storyboard manually on launch *Adding various print statements in AppDelegate and my Home View Controller AppDelegate I've added let storyboard = UIStoryboard(name: "Main", bundle: nil) let initialViewController = storyboard.instantiateViewController(withIdentifier: "Home") self.window.rootViewController = initialViewController self.window.makeKeyAndVisible() print("App launched") to my AppDelegate. Now, when I run my app, I get printed. I also added override func viewDidLoad() { super.viewDidLoad() print("Home view loaded") to my Home View Controller. Now, when I run my app, I get this printed in Xcode: 2020-08-28 13:11:20.140963+0100 MY-APP[11077:1951343] libMobileGestalt MobileGestaltCache.c:166: Cache loaded with 4536 pre-cached in CacheData and 53 items in CacheExtra. 2020-08-28 13:11:20.759943+0100 MY-APP[11077:1951162] Metal API Validation Enabled Home view loaded App launched Still, nothing on my iPhone. The launch screen appears, fades to black, and that's it. I'm so confused. If anyone knows how to fix this, or something I can try, please let me know. Thank you in advance! A: Make sure there a window like this present in your sceneDelegate and AppDelegate both. class AppDelegate: UIResponder, UIApplicationDelegate { // check for this var window: UIWindow? // check for this func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { } } A: If you don't want to switch to the Scene API just yet, you can also just set UIApplicationSupportsMultipleScenes to NO in the UIApplicationSceneManifest section which probably recently appeared in your Info.plist. That's what I just did, and it fixed the issue for me. A: In latest version, window property is no more available in AppDelegate. Now, it is moved to SceneDelegate.swift . You can try doing as below in func scene willConnectTo: func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) { guard let _ = (scene as? UIWindowScene) else { return } if let windowScene = scene as? UIWindowScene { self.window = UIWindow(windowScene: windowScene) let storyBoard = UIStoryboard(name: "Main", bundle: nil) let initialViewController = storyBoard.instantiateViewController(withIdentifier: "Home") self.window?.rootViewController = initialViewController self.window!.makeKeyAndVisible() } } Update: Also make your Main Interface under General menu is empty Also you have to remove the <key>UIMainStoryboardFile</key><string>Main</string> and <key>UISceneStoryboardFile</key> <string>Main</string> from your Info.plist of your project. A: I also faced the same issue. The original question says, "This happened all of a sudden and I don't recall doing anything to cause it." This is exactly what happened to me and following is how I solved the issue. In Main.storyboard, there is an entry point to the app which is visually depicted as an arrow pointing to the Navigation Controller. Once the issue showed up, I noticed that this arrow is now somehow missing and Is Initial View Controller checkbox in the View Controller section of the Attribute Inspector tab in the Inspectors pane is now unchecked. The issue was resolved when I checked the Is Initial View Controller checkbox mentioned above(The arrow in the storyboard navigation controller also reappeared upon checking this). Below is an image of xcode after solving the issue to help get a better understanding. This is an image showing the Navigation Controller and Inspectors pane after the issue was fixed. Hope someone finds this useful.
Q: explorer don't get cookie, but chrome do i am korean. so i don't speak english well. first, i have a four page, named A.php, B.php, cookie.php, view.php i want get a cookie in page, chrome is done, but explorer is do not..^^:; plz give me a hint, you see my code. A.php - this page set a cookie, exclude call. <script type='text/javascript'> var m3_u = "http://[myip]/cookie.php?"; document.write ("<scr"+"ipt type='text/javascript' src='"+m3_u); document.write ("'></scr"+"ipt>"); B.php - this page get a cookie, exclude call. <script type='text/javascript'> var m3_u = "http://[myip]/view.php?"; document.write ("<scr"+"ipt type='text/javascript' src='"+m3_u); document.write ("'></scr"+"ipt>"); </script> cookie.php - this page set a cookie <? setcookie('sheep','mehehe~',time()+100,"/"); ?> view.php - this page set a cookie <? if(isset($_COOKIE['sheep']) echo $_COOKIE['sheep']; ?> * *A,B is same server, cookie.php,view.php is same server i want get a cookie in B.php and use $_COOKIE['sheep'] value. chrome is done, explore do not..; why? give me a hint plz..
Q: How to colour groups in a PCA plot when the group information is in another data frame I'm brand new to R and any type of coding. I have an gene expression matrix that has columns as the sample and rows as probe name and then the value for that probe I have made a PCA plot using: pc<- prcomp(t(matrix), scale=TRUE) pca <- data.frame(Sample=rownames(pc$x), X=pc$x[,1], Y=pc$x[,2]) ggplot(data=pca, aes(x=X, y=Y, label=Sample)) + geom_text() + xlab(paste("PC1 - ", pca.var.per[1], "%", sep="")) + ylab(paste("PC2 - ", pca.var.per[2], "%", sep="")) + theme_bw() + ggtitle("PCA Graph") I would like to colour the points on my PCA graph according to the patient type but obviously this information isn't within the data frame. What is the easiest way of doing it?
Q: Issue in alternate Row color using each() method of JQuery I have a table as under <table > <tr> <th scope="col">EmpId</th><th scope="col">EmpName</th> </tr> <tr> <td>1</td><td>ABC</td> </tr> <tr> <td>2</td><td>DEF</td> </tr> </table> I want to set the alternate row color of only the "td" elements of the table and not "th" by using only each() function. I have tried with <style type="text/css"> tr.even { background-color: green; } tr.odd { background-color: yellow; } </style> $(document).ready(function () { $('table > tbody').each(function () { $('tr:odd', this).addClass('odd').removeClass('even'); $('tr:even', this).addClass('even').removeClass('odd'); }); }); Though this works but it accepts also "th" element. How to avoid that? Please help Thanks A: An easy solution would be to put your <th> row inside a <thead> and add an explicit <tbody>: <table> <thead> <tr> <th scope="col">EmpId</th><th scope="col">EmpName</th> </tr> </thead> <tbody> <tr> <td>1</td><td>ABC</td> </tr> <tr> <td>2</td><td>DEF</td> </tr> </tbody> </table>​ Demo: http://jsfiddle.net/ambiguous/bGvA2/ If you can't change the HTML to make it sensible, then you could do something like this: $('table tr').not(':first').each(function(i) { $(this).addClass(i % 2 ? 'odd' : 'even'); });​ Demo: http://jsfiddle.net/ambiguous/TGfrF/ Or perhaps: $('table tr').not(':first') .filter(':even').addClass('even').end() .filter(':odd' ).addClass('odd'); Demo: http://jsfiddle.net/ambiguous/GNFaC/ These two do assume that you only have one row of <th>s. ​ A: Demo: on Jsfiddle $('table tr').not(':first') .filter(':even').addClass('even').end() .filter(':odd' ).addClass('odd');​ $('table tr:first-child').addClass('head').removeClass('odd');// will style the heading OR $(document).ready(function () { $('table > tbody').each(function () { $('tr:odd', this).addClass('odd').removeClass('even'); $('tr:even', this).addClass('even').removeClass('odd'); }); $('table tr:first-child').addClass('head').removeClass('odd'); // will style the heading }); Style: tr.even { background-color: green; } tr.odd { background-color: yellow; } tr.head { background-color: red; } A: Simple fix with css only: <style type="text/css"> tr.even td{ background-color: green; } tr.odd td{ background-color: yellow; } </style>
Q: How to pass 2D char array to another function by reference I want to pass my 2D char array to another function by reference. I did same thing with my int ** it works perfectly. But when it come to char ** same method is broken. I try too many things. I read almost every question but I couldn't see my case. First of all I have a one char ** which is set to NULL and I pass it to another function by reference. This my main function int main(){ int **recommendU2 = NULL; char **bookNames = NULL; readFromCsv(&recommendU2,&bookNames,&bookCount,&userCount); printf("\n user[2][3] = %d \n",recommendU2[2][3]); //this works printf("\n bookNames[1] = %s \n,bookNames[1]); //this doesn't works return 0; } Here is my another function which reads from csv and process this data. It is do it purpose without and issue. It reads from csv and read data line by line and process it without a problem. But I can't access my char ** data. But I can reach my int ** data. I didn't notice any difference between too. void readFromCsv(int ***user,char ***bookNames,int *bookCount,int *userCount){ FILE * fpointer; int lineCount = 0; int count; int sizes[3]; fpointer = fopen("recdataset.csv","r"); char recommendationSheet[RECOMMENDATIONSIZE]; while(fgets(recommendationSheet,RECOMMENDATIONSIZE,fpointer)){ if(lineCount>1){ //this part is not important for this question } else if(lineCount == 0){ userArraysMemoryAllocate(recommendationSheet,user,nuser,bookNames,&sizes[0]); (*user)[2][3] = 4; //I can access this user data both within this function and main function } else if(lineCount == 1){ //actually I send variables to another function which named getBookNames() but when I can't reach data I suspect it and move it's code to here. But this doesn't make any different too. char *p = recommendationSheet; int j = 0; int i = 0; while(1) { char *p2 = strchr(p, ';'); if(p2 != NULL) *p2 = '\0'; if(i>0) strcpy((*bookNames)[i],p); printf("\n Book Name is = %s \n",(*bookNames)[i]); //This line works read bookNames correctly i++; if(p2 == NULL) break; p = p2 + 1; } printf("\nbookName = %s \n",(*bookNames)[2]); //this line doesn't work } lineCount++; } fclose(fpointer); } I couldn't make it work. I tried so many variations but none of them works. If you have any solution or any other idea to make this work I will appreciate it. Thanks in advance. Note : This program is too long to put here. So I only copied problematic part here. This includes so many functions calls. So If you don't understand anywhere please say it and I could add this part of code too. Update I add memory allocate function to readfromCsv function too. Here is the code. My problem still occurs. I thought I fixed it but it cause unnormal behaviour. void readFromCsv(int ***user,char ***bookNames,int *bookCount,int *userCount,){ FILE * fpointer; int lineCount = 0; int i = 0; int j = 0; int len; int count; int sizes[3]; fpointer = fopen("recdataset.csv","r"); char recommendationSheet[RECOMMENDATIONSIZE]; while(fgets(recommendationSheet,RECOMMENDATIONSIZE,fpointer)){ len = strlen(recommendationSheet); if( recommendationSheet[len-1] == '\n' ) recommendationSheet[len-1] = 0; if(lineCount>1){ //not important } else if(lineCount == 0){ char *p = recommendationSheet; i = 0; j = 0; int row = 0; int col = 0; while(i<3) { char *p2 = strchr(p, ';'); if(p2 != NULL) *p2 = '\0'; if(i==0){ row = atoi(p); col = row; if((*bookNames = (char**)malloc(row * sizeof(char*))) == NULL){ printf("\nMemory allocation problem \n"); exit(0); } for(j = 0; j < row; ++j){ if(((*bookNames)[j] = (char*)malloc(50 * sizeof(char))) == NULL){ printf("\nMemory allocation problem \n"); exit(0); } } } else if(i==1){ row = atoi(p); if((*user = (int**)malloc(row * sizeof(int*))) == NULL){ printf("\nMemory allocation problem \n"); exit(0); } for(j = 0; j < row; ++j){ if(((*user)[j] = (int*)malloc(col * sizeof(int))) == NULL){ printf("\nMemory allocation problem \n"); exit(0); } } } else if(i==2){ row = atoi(p); if((*nuser = (int**)malloc(row * sizeof(int*))) == NULL){ printf("\nMemory allocation problem \n"); exit(0); } for(j = 0; j < row; ++j){ if(((*nuser)[j] = (int*)malloc(col * sizeof(int))) == NULL){ printf("\nMemory allocation problem \n"); exit(0); } } } sizes[i] = row; i++; if(p2 == NULL) break; p = p2 + 1; } (*user)[2][3] = 4; // this works still here and main function } else if(lineCount == 1){ char *pMemory = recommendationSheet; j = 0; i = 0; while(1) { char *p2 = strchr(pMemory, ';'); if(p2 != NULL) *p2 = '\0'; if(i>0) (*bookNames)[i] = pMemory; printf("\n %d. Book name is = %s \n",i,(*bookNames)[i]); // works perfectly i++; if(p2 == NULL) break; pMemory = p2 + 1; } } lineCount++; } fclose(fpointer); } Still I couldn't access my char ** from my main function. I add memory allocation process. I though I fixed it but problem occurs again without any change. I didn't understand the problem at all.
Q: WCF channelfactory exception I try to set up an connection to another pc, but then i try to create a channel i get an exception, i have no idea what is cousing this problem, becouse to some pc's it works this is the code: var ep = "net.tcp://" + targetIpAddress + ":9985/IBC"; NetTcpBinding binding = new NetTcpBinding(SecurityMode.None); binding.ListenBacklog = 2000; binding.MaxConnections = 2000; binding.TransferMode = TransferMode.Buffered; binding.MaxReceivedMessageSize = 1048576; binding.SendTimeout = new TimeSpan(0, 1, 0); ChannelFactory<IBlissRequest> pipeFactory = new ChannelFactory<IBlissRequest>(binding, new EndpointAddress(ep)); //here i get the exception client.ChannelFactory = pipeFactory; Exception: Source array was not long enough. Check srcIndex and length, and the array's lower bounds. Full stack trace: bij System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) bij System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) bij System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) bij System.ServiceModel.Description.TypeLoader.GetKnownTypes(Object[] knownTypeAttributes, ICustomAttributeProvider provider) bij System.ServiceModel.Description.TypeLoader.UpdateOperationsWithInterfaceAttributes(ContractDescription contractDesc, ContractReflectionInfo reflectionInfo) bij System.ServiceModel.Description.TypeLoader.LoadContractDescriptionHelper(Type contractType, Type serviceType, Object serviceImplementation) bij System.ServiceModel.ChannelFactory`1.CreateDescription() bij System.ServiceModel.ChannelFactory.InitializeEndpoint(Binding binding, EndpointAddress address) bij System.ServiceModel.ChannelFactory`1..ctor(Binding binding, EndpointAddress remoteAddress) bij System21.Network.InterBlissCommunication.InternalMethodInvoke(String targetIpAddress, Boolean Async, Object state, CallbackMethod callbackMethod, BpuMethod MethodName, Object[] Parameters) This code is accesed by multiple threads, when i put a lock around it the problem seems to be solved (the problem might be that it trys to make a duplicate connection with the same ipAddress)
Q: Return all elements of an ArrayList, not print them public double getAllElementsInCollection(ArrayList<Double> nameofCollection){ double result = 0.0; for(Double nameofDouble : nameofCollection){ result = nameofDouble; } return result; } I'm trying to write a method that returns all elements of the ArrayList passed it but i'm just getting that last was that was insert in the array. how can I accomplish this task? I have been trying to do this since yesterday. i have noticed that if i do a System.out.println(nameofDouble); that would actually print all elements.. but i don't want to print them. I want to returns all the content inside of passed ArrayList. A: This question doesn't make sense... do you want to turn ArrayList into double[]? Simply call: public Double[] getAllElementsInCollection(ArrayList<Double> nameofCollection){ return nameofCollection.toArray(new Double[nameofCollection.size()]); } A: You could do one of two things: Firstly: ArrayList<Double> list = new ArrayList<Double>(); ... Double[] elements = list.toArray(new Double[list.size()]); Or, if you want to use the method: public double[] getAllElementsInCollection(ArrayList<Double> list){ double[] elements = new double[list.size()]; for(int i = 0; i < elements.length; i++){ elements[i] = list.get(i); } return elements; } A: You have got it all wrong. First of all the return type of your method is double, which indicates you can just return a single double value and not the entire array. Also the variable 'result' will hold only one value within it. So here is the modified version of your code : public List<Double> getAllElementsInCollection(List<Double> nameofCollection){ List<Double> resultList = new ArrayList<Double>(); for(Double nameofDouble : nameofCollection){ // some processing on the elements (if required) resultList.add(nameofDouble); } return resultList; } Also, I suggest you to use super classes/interfaces(like List instead of ArrayList) as parameters or return types, because you may not know the actual argument passed to the method(like LinkedList or ArrayList). Read OOP concepts throughly for this. Polymorphism samples : sample1 and sample2 A: You can change your method in following way to return all elements of ArrayList in String which can be printed further. public String getAllElementsInCollection(ArrayList<Double> nameofCollection){ return java.util.Arrays.toString(nameofCollection); } A: Your question is not clear, what do you mean with "returns all elements"? The ArrayList has all elements, in which form do you ant to return them? Looking on your code, do you mean the sum of all elements? Then you have just a little mistake. Your code result = nameofDouble just replaces the result, so the last is returned. result = result + nameofDouble or result += nameofDouble would sum all the elements.
Q: Π’ ΠΊΠ°ΠΊΠΎΠΌ python web framework ΠΈΡΠΏΠΎΠ»ΡŒΠ·ΡƒΡŽΡ‚ΡΡ ΠΏΠΎΠ»Π½ΠΎΡ†Π΅Π½Π½Ρ‹Π΅ ΠΊΠΎΠ½Ρ‚Ρ€ΠΎΠ»Π»Π΅Ρ€Ρ‹? ΠŸΡ€ΠΈΠ²Π΅Ρ‚ всСм! Π‘ΠΎΡ€Ρ€ΠΈ Π·Π° сумбур. МСня интСрСсуСт организация ΠΊΠΎΠ½Ρ‚Ρ€ΠΎΠ»Π»Π΅Ρ€ΠΎΠ² Π² стилС Yii, Π² ΠΊΠΎΡ‚ΠΎΡ€Ρ‹Ρ… Π΅ΡΡ‚ΡŒ before/after action, Ρ„ΠΈΠ»ΡŒΡ‚Ρ€Ρ‹, ΠΈ Π½Π΅ Π½ΡƒΠΆΠ½ΠΎ ΠΊΠ°ΠΆΠ΄Ρ‹ΠΉ экшн ΠΏΡ€ΠΎΠΏΠΈΡΡ‹Π²Π°Ρ‚ΡŒ Π²Ρ€ΡƒΡ‡Π½ΡƒΡŽ Π² ΠΊΠΎΠ½Ρ„ΠΈΠ³Π°Ρ…) Π’ ΠΈΠ΄Π΅Π»Π°Π΅ Π½ΡƒΠΆΠ½ΠΎ Ρ‡Ρ‚ΠΎ-Ρ‚ΠΎ ΠΏΠΎΡ…ΠΎΠΆΠ΅Π΅ Π½Π° CherryPy, Π½ΠΎ Ρ‚Π°ΠΌ ΠΊΠ°ΠΆΠ΄Ρ‹ΠΉ доступный ΠΌΠ΅Ρ‚ΠΎΠ΄ Π½ΡƒΠΆΠ½ΠΎ ΠΎΠ±ΠΎΡ€Π°Ρ‡ΠΈΠ²Π°Ρ‚ΡŒ Π² Π΄Π΅ΠΊΠΎΡ€Π°Ρ‚ΠΎΡ€, Π° Π½Π΅ Ρ…ΠΎΡ‚Π΅Π»ΠΎΡΡŒ Π±Ρ‹ лишнСго ΠΏΠΈΡΠ°Ρ‚ΡŒ Ρ€ΡƒΠΊΠ°ΠΌΠΈ. ΠœΠΎΠ³Ρƒ Π½Π° основС Ρ‡Π΅Ρ€Ρ€ΠΈ Π² ΠΏΡ€ΠΈΠ½Ρ†ΠΈΠΏΠ΅, сам Π·Π°ΠΏΠΈΠ»ΠΈΡ‚ΡŒ вСлосипСд с Π½ΡƒΠΆΠ½Ρ‹ΠΌΠΈ ΠΌΠ½Π΅ Π½ΠΈΡˆΡ‚ΡΠΊΠ°ΠΌΠΈ, Π½ΠΎ думаСтся ΠΌΠ½Π΅, Ρ‡Ρ‚ΠΎ Ρ‚ΠΎ-Ρ‚ΠΎ ΠΏΠΎΠ΄ΠΎΠ±Π½ΠΎΠ΅ ΡƒΠΆΠ΅ сущСствуСт. Π”ΠΎ этого сталкивался Ρ‚ΠΎΠ»ΡŒΠΊΠΎ с Π΄ΠΆΠ°Π½Π³ΠΎΠΉ. A: посмотритС Π½Π° Flask-Classy. ΠŸΠΎΡ…ΠΎΠΆΠ΅ Π½Π° Ρ‚ΠΎ Ρ‡Ρ‚ΠΎ Π²Π°ΠΌ Π½Π°Π΄ΠΎ.
Q: How to use Hystrix with Spring WebFlux WebClients? I'm using Spring WebFlux with functional endpoints to create an API. To provide the results I want, I need to consume an external RESTful API, and to do that in a async way I'm using a WebClient implementation. It works well and goes like this: public WeatherWebClient() { this.weatherWebClient = WebClient.create("http://api.openweathermap.org/data/2.5/weather"); } public Mono<WeatherApiResponse> getWeatherByCityName(String cityName) { return weatherWebClient .get() .uri(uriBuilder -> uriBuilder .queryParam("q", cityName) .queryParam("units", "metric") .queryParam("appid", API_KEY) .build()) .accept(APPLICATION_JSON) .retrieve() .bodyToMono(WeatherApiResponse.class); } As this performs network access, it's a good use case for NetFlix OSS Hystrix. I've tried using spring-cloud-starter-netflix-hystrix, adding @HystrixCommand to the method above, but there's no way to make it trip the circuit, even if I set a bad URL (404) or wrong API_KEY (401). I thought this could be a problem of compatibility with the WebFlux itself, but setting property @HystrixProperty(name="circuitBreaker.forceOpen", value="true") indeed forces the fallback method to run. Am I missing something? Is this approach incompatible with Spring WebClients? Thanks! A: @HystrixCommand won't really work, because Hystrix doesn't threat Mono/Flux any different from Java primitives. Hystrix doesn't monitor content of Mono, but only the result of call public Mono<WeatherApiResponse> getWeatherByCityName(String cityName). This result is always OK, because reactive-call-chain creation will always succeed. What you need, is to make Hystrix threat Mono/Flux differently. In Spring Cloud, there is a builder, to wrap Mono/Flux with HystrixCommand. Mono<WeatherApiResponse> call = this.getWeatherByCityName(String cityName); Mono<WeatherApiResponse> callWrappedWithHystrix = HystrixCommands .from(call) .fallback(Mono.just(WeatherApiResponse.EMPTY)) .commandName("getWeatherByCityName") .toMono();
Q: Setting cookie by PHP and reading using JavaScript I use the Laravel PHP framework and set a cookie using Cookie::put(..), Code to set cookie using Laravel PHP, Cookie::put('id', $id , 0, '/'); when I looked into it I found cookie is being set to a root path that's good for me. Now in JS I use a jQuery plugin to read the cookie but it returns null while reading cookie setted by PHP. JS code to access cookie, function getCookie(c_name) { var i,x,y,ARRcookies=document.cookie.split(";"); for (i=0;i<ARRcookies.length;i++) { x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("=")); y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1); x=x.replace(/^\s+|\s+$/g,""); if (x==c_name){ return unescape(y); } } } print_r($_COOKIE) Array ( [id] => 653a8dbd0903d2eacfdfe87bce29640d136a4380+1 [session_payload] => 2c3e260bb766ea1519dcbc3d13025d3ede6e2e63+mSfAHUAPvmFefQbIArozzbQfY0IzZpAeTarpQsHHOseN+SD3xmmUWfUduVYWf7qVu1Rwo2XYIBSBTUt+J1DhbE9sN2yEelpjsHzU0CVw3F1aPpcPh6oSTzIfskr2hHuWIGi5sf1lvD7qRHtcjPOBD700vnQSy2+DIMTNT4eMS7pz85zi9TMpgLQfWbtUUtNQk1SRHwncwgQyp1xhgPqp4d6eLjaZQ2hXBtOgYbC2Ty5xS4e76WCW+dumNMj3hkSfMoDssKnmRTzV7jYUT6a+oH26tZkKOR8EMMh04xHMWlt73aFsL9EZrIXZFKHkOXqU883qThWot//emOpakBKWyA== [laravel_session] => 2729bdfca6fe6e6f3c98d03c11a65915649af09b+ML1G6xZ5YkImViUxm9gOaTo5AT8jyBfqagdoeyAs ) 1 Update: I really don't know why this was voted down but here, I want to access the cookie using JS previously added using PHP. A: If COOKIE expiry set to 0, the cookie will expire at the end of the session (when the browser closes). So, JS will not read expired COOKIEs Try setting the COOKIE expiration for longer, Cookie::put('id', $id , time()+3600, '/'); //set the cookie alive for 1 hour
Q: Where is YouTube Channel ID input in BigQuery Data Transfer Service? I'm working on GCP BigQuery. And I use BigQuery Data Transfer Service to get market data from YouTube, Goolge Ads, so on. Yesterday, I found out that there is no input box of YouTube Channel Page Id in BigQuery Data Transfer Service. The YouTube channel page ID is needed to connect YouTube Channel. Why does the channel page Id input box disappear? I guess that Transfer Service account always should be equal to YouTube Channel account, So It doens't needed. Anyway, I want to know why the input box disappear A: The Channel Page Id has recently been removed as this input is not necessary for anything related to loading reports/data. It is only used within YouTube data source for logging purpose.
Q: Javascript canvas is not filling in with the correct color? I must be doing something very dumb, because I am very confused over what's going on. I am simply filling in a rectangle with a specified color, like this: const c = document.querySelector("canvas"); const ctx = c.getContext("2d"); ctx.fillStyle = "#D53F2E"; ctx.fillRect(0, 0, 150, 150); .example { height: 4em; background-color: #D53F2E; } <div>The canvas:</div> <canvas></canvas> <div>A div using the same color:</div> <div class="example"></div> As you can see, I am specifying the fill color to be #D53F2E. However, the rectangle (on my screen at least), appears to be filled with #C04F34. The colors don't match! However, I just thought to check Firefox, and they do match there. Was there a regression in the latest Chrome or something? I'm just using the latest Chrome and Windows 10, with uBlock Origin. Is there a flag I should be setting somewhere to ensure the colors match exactly? A: While typing this question, I thought to check Firefox vs Chrome, and noticed the colors matched in Firefox. This lead me to google "inaccurate colors Chrome" and found a comment online with this solution: * *Navigate to chrome://flags *Search for color profile *Find the option Force color profile *Change it from Default to sRGB This fixed the issue for me. Chrome now renders the specified color. I think the issue occurred because my monitor uses the "Cool" color setting, and Chrome adopted this from my monitor settings. This overrides that and renders the actual color, instead of using the color profiled one.
Q: Share data between users on multi-user Android (4.2 or later) Android introduced the Multiple Users feature in 4.2 (Jelly Bean MR1) and its documentation states: From your app's point of view, each user is running on a completely separate device. And here is a quote from the Environment.getExternalsStorageDirectory() and getExternalStoragePublicDirectory() methods doc: On devices with multiple users (as described by UserManager), each user has their own isolated external storage. Applications only have access to the external storage for the user they're running as. Could it be true that there really is no reliable way to communicate data between users on a single device without using the network as mediator? I'm looking for solutions that don't rely on quirks of how the device's file system is laid out by a manufacturer. Also, for security, the sharing should be internal to my app. Even if file sharing is indeed impossible, is communication via intents somehow possible? There are use cases for this. Use Case 1: let's say I'm writing an input method app that requires a 100MB dictionary file. I'd like to code things so that if User A downloads this file, then User B can access it also without needing to re-download. Use Case 2: let's say I'm writing a fun Leave My Wife a Note app that allows User A to type messages that will appear next time User B logs in (without using the network). This thread on a separate site proposes a solution, but their method seems undocumented and possibly unreliable. And there are a few other SO questions that have a title similar to this one but are actually discussing different topics. A: OBB Folder (/sdcard/Android/obb) is used to share files and folder between the multi users. But OBB folder not shown in my second user (One plus 5 mobile). So I have tried to create an OBB folder in Android folder (/sdcard/Android/) in second user and "BOOM" it worked. Now i am able to access the shared files in second user. Try this trick if OBB folder not shown in your second user. A: OBB files (stored in /sdcard/Android/obb) and used as expansion files in Google Play are shared between all users by design, as they are fairly large. If you Input method uses expansion files, the downloaded data will be shared automatically. You can send broadcasts to other users but that requires the INTERACT_ACROSS_USERS permission, which is reserved for system applications. A: I also had the same question, and have tried various approaches such as using /sdcard/Android/obb but it does not work in Android 10. So I followed below approach, and I am able to copy files seamlessly between users. * *Login to the User from where you would like to copy files from (lets call U1) *Run FTP Server using any application of choice like MiXplorer / ES Explorer etc... Note down the details of the port#, username, password etc... and point it to /sdcard *Switch user, to where you want to copy files to (lets call U2) *Install the FTP browser. If you use MiXplorer / ES Explorer, they will allow you to add a FTP share *Use ftp://localhost:2121 assuming the port is 2121, if not change it accordingly and add the FTP share *Open the FTP share and you can see all the files & folders of U1 here *Copy across to your heart's content !
Q: can't replace file in amazon s3 bucket can't replace file in amazon s3 bucket when i am going to upload an image to amazon s3 bucket it shows error like below An item with the same key has already been added. i have uploaded an image file and i wanted replace that image when i need it. but it does not allow. how can I fix it? i am using C# using (s3Client = Amazon.AWSClientFactory.CreateAmazonS3Client("key", "secret key", Amazon.RegionEndpoint.USWest2)) { var stream2 = new System.IO.MemoryStream(); bitmap.Save(stream2, ImageFormat.Jpeg); stream2.Position = 0; PutObjectRequest request2 = new PutObjectRequest(); request2.InputStream = stream2; request2.BucketName = "ezcimassets"; request2.CannedACL = S3CannedACL.PublicRead; fileName = webpage + ".jpeg"; //fileName = Guid.NewGuid() + webpage + ".jpeg";) request2.Key = "WebThumbnails/" + fileName; Amazon.S3.Model.PutObjectResponse response = s3Client.PutObject(request2); } Thanks in advance A: this line must be changed as request2.CannedACL = S3CannedACL.PublicReadWrite A: You can check if an object with that key already exists, and if so delete it: public bool Exists(string fileKey, string bucketName) { try { response = _s3Client.GetObjectMetadata(new GetObjectMetadataRequest() .WithBucketName(bucketName) .WithKey(key)); return true; } catch (Amazon.S3.AmazonS3Exception ex) { if (ex.StatusCode == System.Net.HttpStatusCode.NotFound) return false; //status wasn't not found, so throw the exception throw; } } public void Delete(string fileKey, string bucketName) { DeleteObjectRequest request = new DeleteObjectRequest(); request.BucketName = bucketName; request.Key = fileKey; client.DeleteObject(request); }
Q: Failed to patch object for unit testing I have a class used to authenticate with google sheet API and retrieve data from some spreadsheets. Here a part of it: spreadsheet.py from typing import Optional from google.oauth2.credentials import Credentials from google.auth.transport.requests import Request import gspread class GoogleSheet: def __init__(self, token_file: str): self.token_file: str = token_file self.google_client: Optional[gspread.Client] = None self.gsheet: Optional[gspread.Spreadsheet] = None def setup_connection(self) -> None: credentials: Credentials = Credentials.from_authorized_user_file(self.token_file) if credentials.expired: credentials.refresh(Request()) self.google_client = gspread.authorize(credentials) def open_gsheet_by_url(self, gsheet_url: str) -> None: self.gsheet = self.google_client.open_by_url(gsheet_url) I wanted to create some tests for the previous code. Here is what I ended to: test_spreadsheet.py import pytest from spreadsheet import GoogleSheet from unittest.mock import patch class TestSpreadSheetData: @patch('spreadsheet.Credentials') @patch('spreadsheet.gspread') def test_setup_connection(self, mocked_creds, mocked_auth): google_sheet = GoogleSheet('api_token.json') google_sheet.setup_connection() assert mocked_creds.from_authorized_user_file.call_count == 1 assert mocked_auth.authorize.call_count == 1 I tried the code above but it didn't work although I had similar approach with different project and packages. So whenever I run the test, I get the following error: AssertionError Assert 0 == 1 Can anyone helps me fix this?
Q: What made aerogel so insulating? In many science videos, it is shown that aerogel can insulate an extremely high temperature even though it is very fragile, what properties of aerogel made it so capable of insulating heat? A: Basically, nearly all of the volume of aerogels, that is, $99.8\%$, is actually air which is contained in tiny air pockets which are called nanopores. Since the motion of the air molecules in these nanopores is very restricted (the air has very little room to move), and the fact that the microstructure of these aerogels prevents net gas motion, this will severely inhibit both conduction and convection, therefore making aerogels highly effective thermal insulators. The concept behind such a substance is similar to how an igloo maintains a relatively warm interior, although counterintuitively, an igloo is made of snow. This is similar to how aerogels work, insomuch as snow is composed of air pockets, as per aerogels. In both cases, these air pockets behave as fairly effective insulators.
Q: How to overwrite anchor element's href target and remove other bugs in my click-to-go-to-target javascript? I've made a webpage. I want to implimenet the feature which scrolls the webpage to the location of href target of menu anchors. My code is as following var myscroll = {}; myscroll.list = document.getElementsByClassName("navbar-right")[0].getElementsByTagName("li"); myscroll.bodypos = function getScrollY() { scrOfY = 0; if (typeof(window.pageYOffset) == 'number') { //Netscape compliant scrOfY = window.pageYOffset; } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) { //DOM compliant scrOfY = document.body.scrollTop; } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) { //IE6 standards compliant mode scrOfY = document.documentElement.scrollTop; } return scrOfY; } function getScrollpos(idname) { return document.getElementById(idname).offsetTop; } myscroll.point = []; myscroll.point[0] = getScrollpos("home"); myscroll.point[1] = getScrollpos("artists"); myscroll.point[2] = getScrollpos("songs"); myscroll.point[3] = getScrollpos("beats"); myscroll.point[4] = getScrollpos("contact"); function removeclass() { for (var i = 0; i < 5; i++) { myscroll.list[i].className = ""; } } window.addEventListener('scroll', function(e) { if (myscroll.bodypos() >= myscroll.point[0]) { removeclass(); myscroll.list[0].className = "active"; } if (myscroll.bodypos() >= myscroll.point[1]) { removeclass(); myscroll.list[1].className = "active"; } if (myscroll.bodypos() >= myscroll.point[2]) { removeclass(); myscroll.list[2].className = "active"; } if (myscroll.bodypos() >= myscroll.point[3]) { removeclass(); myscroll.list[3].className = "active"; } if (myscroll.bodypos() >= myscroll.point[4]) { removeclass(); myscroll.list[4].className = "active"; } }); for (var j = 0; j < 5; j++) { (function(j) { myscroll.list[j].anchor = document.getElementsByClassName("navbar-right")[0].getElementsByTagName("li")[j].getElementsByTagName("a")[0]; myscroll.list[j].anchor.addEventListener("click", function() { if ((document.body.scrollTop != undefined) && (document.body.scrollTop < myscroll.point[j])) { var clr1 = setInterval(function() { if (document.body.scrollTop < myscroll.point[j] - 10) { document.body.scrollTop += 3; } else { document.body.scrollTop = myscroll.point[j]; clearInterval(clr1); } }, 1); } if ((document.documentElement.scrollTop != undefined) && (document.documentElement.scrollTop < myscroll.point[j])) { var clr2 = setInterval(function() { if (document.documentElement.scrollTop < myscroll.point[j] - 10) { document.documentElement.scrollTop += 3; } else { document.documentElement.scrollTop = myscroll.point[j]; clearInterval(clr2); } }, 1); } if ((document.body.scrollTop != undefined) && (document.body.scrollTop > myscroll.point[j])) { var clr3 = setInterval(function() { if (document.body.scrollTop >= myscroll.point[j] + 4) { document.body.scrollTop -= 3; } else { document.body.scrollTop = myscroll.point[j]; clearInterval(clr3); } }, 1); } if ((document.documentElement.scrollTop != undefined) && (document.documentElement.scrollTop > myscroll.point[j])) { var clr4 = setInterval(function() { if (document.documentElement.scrollTop >= myscroll.point[j] + 4) { document.documentElement.scrollTop -= 3; } else { document.documentElement.scrollTop = myscroll.point[j]; clearInterval(clr4); } }, 1); } alert(j); }, true); }(j)); } #navbar, #navbar a:link, #navbar a:visited, #navbar a:hover { position: fixed; color: red !important; } #home { width: 500px; height: 500px; background-color: black; display: block; } #artists { width: 500px; height: 500px; background-color: gray; display: block; } #songs { width: 500px; height: 500px; background-color: yellow; display: block; } #beats { width: 500px; height: 500px; background-color: blue; display: block; } #contact { width: 500px; height: 500px; background-color: green; display: block; } <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li class="active"><a href="#">Home</a> </li> <li><a href="#artists">Artists</a> </li> <li><a href="#songs">Songs</a> </li> <li><a href="#beats">Beats</a> </li> <li><a href="#contact">Contact</a> </li> </ul> </div> <div id="home"></div> <div id="artists"></div> <div id="songs"></div> <div id="beats"></div> <div id="contact"></div> As such the code doesn't do what it is supposed to. If we remove href attributes of menu's anchor tags then the code works as expected but with one bug. The problem with the href tags is that before the onclick function could do anything the webpages scrolls quickly to the href target. Other posts say returntning false with onclick would disable the href target. The problem is that I am not using onclick; I am using addEventListener("click"). I tried returning both false and true but nothing worked. So, * *Why is it said returning false stops href function of anchor elements? Now I know that preventDefault will do what I want. But I want to know how to acheive the same by returning false. Now comes the bug. When I click on contact link it scrolls down to the bottom of page and remains fixed there. If I scroll upwards then the page is automatically scrolled to bottom. var myscroll = {}; myscroll.list = document.getElementsByClassName("navbar-right")[0].getElementsByTagName("li"); myscroll.bodypos = function getScrollY() { scrOfY = 0; if (typeof(window.pageYOffset) == 'number') { //Netscape compliant scrOfY = window.pageYOffset; } else if (document.body && (document.body.scrollLeft || document.body.scrollTop)) { //DOM compliant scrOfY = document.body.scrollTop; } else if (document.documentElement && (document.documentElement.scrollLeft || document.documentElement.scrollTop)) { //IE6 standards compliant mode scrOfY = document.documentElement.scrollTop; } return scrOfY; } function getScrollpos(idname) { return document.getElementById(idname).offsetTop; } myscroll.point = []; myscroll.point[0] = getScrollpos("home"); myscroll.point[1] = getScrollpos("artists"); myscroll.point[2] = getScrollpos("songs"); myscroll.point[3] = getScrollpos("beats"); myscroll.point[4] = getScrollpos("contact"); function removeclass() { for (var i = 0; i < 5; i++) { myscroll.list[i].className = ""; } } window.addEventListener('scroll', function(e) { if (myscroll.bodypos() >= myscroll.point[0]) { removeclass(); myscroll.list[0].className = "active"; } if (myscroll.bodypos() >= myscroll.point[1]) { removeclass(); myscroll.list[1].className = "active"; } if (myscroll.bodypos() >= myscroll.point[2]) { removeclass(); myscroll.list[2].className = "active"; } if (myscroll.bodypos() >= myscroll.point[3]) { removeclass(); myscroll.list[3].className = "active"; } if (myscroll.bodypos() >= myscroll.point[4]) { removeclass(); myscroll.list[4].className = "active"; } }); for (var j = 0; j < 5; j++) { (function(j) { myscroll.list[j].anchor = document.getElementsByClassName("navbar-right")[0].getElementsByTagName("li")[j].getElementsByTagName("a")[0]; myscroll.list[j].anchor.addEventListener("click", function(event) { event.preventDefault(); if ((document.body.scrollTop != undefined) && (document.body.scrollTop < myscroll.point[j])) { var clr1 = setInterval(function() { if (document.body.scrollTop < myscroll.point[j] - 10) { document.body.scrollTop += 3; } else { document.body.scrollTop = myscroll.point[j]; clearInterval(clr1); } }, 1); } if ((document.documentElement.scrollTop != undefined) && (document.documentElement.scrollTop < myscroll.point[j])) { var clr2 = setInterval(function() { if (document.documentElement.scrollTop < myscroll.point[j] - 10) { document.documentElement.scrollTop += 3; } else { document.documentElement.scrollTop = myscroll.point[j]; clearInterval(clr2); } }, 1); } if ((document.body.scrollTop != undefined) && (document.body.scrollTop > myscroll.point[j])) { var clr3 = setInterval(function() { if (document.body.scrollTop >= myscroll.point[j] + 4) { document.body.scrollTop -= 3; } else { document.body.scrollTop = myscroll.point[j]; clearInterval(clr3); } }, 1); } if ((document.documentElement.scrollTop != undefined) && (document.documentElement.scrollTop > myscroll.point[j])) { var clr4 = setInterval(function() { if (document.documentElement.scrollTop >= myscroll.point[j] + 4) { document.documentElement.scrollTop -= 3; } else { document.documentElement.scrollTop = myscroll.point[j]; clearInterval(clr4); } }, 1); } alert(j); }, true); }(j)); } #navbar, #navbar a:link, #navbar a:visited, #navbar a:hover { position: fixed; color: red !important; } #home { width: 500px; height: 500px; background-color: black; display: block; } #artists { width: 500px; height: 500px; background-color: gray; display: block; } #songs { width: 500px; height: 500px; background-color: yellow; display: block; } #beats { width: 500px; height: 500px; background-color: blue; display: block; } #contact { width: 500px; height: 500px; background-color: green; display: block; } <div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li class="active"><a href="#">Home</a> </li> <li><a href="#artists">Artists</a> </li> <li><a href="#songs">Songs</a> </li> <li><a href="#beats">Beats</a> </li> <li><a href="#contact">Contact</a> </li> </ul> </div> <div id="home"></div> <div id="artists"></div> <div id="songs"></div> <div id="beats"></div> <div id="contact"></div> * *How do I remove this bug? A: Use preventDefault() on the event, to stop the default for the click event to be executed. window.addEventListener('scroll', function(e) { e.preventDefault(); ... Then do your thing in your handler, and at the end, manually update the window.location with the value of the event target's href attribute. EDIT RE the comment: your event still bubbles, only the default action is prevented. To stop it from bubbling up, there is event.stopPropagation(). The default action for you event is simply to set the window.location to the value of your event target's href attribute window.location = e.target.getAttribute('href');
Q: Unable to print out the desired output So I am creating a program that reads customer details and order details from two different files. I created methods to read the file, store the data in the object of customers and then add the object of customers into linkedlist.. Now when I try doing the same for order file, I am getting the wrong output. so in the code shown below, I am trying to check if the customer name entered in order file matches the name stored in customer linkedlist.. So say I have two rows in the order.txt file: Ord101 true James Ord102 false Jim with what I have done, I get the following output: Ord102 false Jim Ord102 false Jim instead of getting the correct output which would be: Ord101 true James Ord102 false Jim because both, James and Jim are names present in Customer file and linkedlist. So here is my code for reading order file: public void readFileOrder() { Scanner y; String b,c,d; LinkedList<Customers> list=new LinkedList<Customers>(); //another method was already created to add data inside list and its working so list contains data LinkedList<order> list1=new LinkedList<order>(); Boolean isOpen; order Order1=new order(); while(y.hasNext()) { b=y.next(); isOpen=y.nextBoolean(); d=y.next(); System.out.println(list); Customers customers1=new Customers(); for(int i=0;i<list.size();i++) //this is where i'm checking if the customer name in the order file matches the value in list { if(list.get(i).getName().equals(d)) { customers1=list.get(i); Order1.setCustomer(customers1); Order1.setName(b); Order1.setIsOpen(isOpen); list1.add(Order1); } } } for(int j=0;j<list1.size();j++) { System.out.println(list1.get(j).getCustomer()+" and "+list1.get(j).getName()+" and "+list1.get(j).getIsOpen()); } } just in case, provided below are Customer and order class: import java.util.LinkedList; public class Customers { @Override public String toString() { return "Customers [Name=" + Name + ", age=" + age + ", email=" + email + ", Address=" + Address + "]"; } String Name; int age; String email; String Address; public String getName() { return Name; } public void setName(String name) { Name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getAddress() { return Address; } public void setAddress(String address) { Address = address; } public void removeCustomer(String name2, LinkedList<Customers> list) { for(int k=0;k<list.size();k++) { if(list.get(k).getName().equals(name2)) { list.remove(list.get(k)); } } } } order class: import java.util.LinkedList; public class order{ String name; Boolean isOpen; Customers customer; String cusName; public order() { super(); } public String getName() { return name; } public order(Customers customer) { super(); this.customer = customer; } public void setName(String name) { this.name = name; } public Boolean getIsOpen() { return isOpen; } public void setIsOpen(Boolean isOpen) { this.isOpen = isOpen; } public String getCustomer() { return customer.getName(); } public void setCustomer(Customers customer) { this.customer=customer; this.cusName=customer.getName(); } } A: You are adding references to the same order to the list over and over again, each time overwriting the attributes set in the previous iteration of the loop. Instead, create a new order inside the loop. In other words, change this: order Order1=new order(); while(y.hasNext()) { to this: while(y.hasNext()) { order Order1=new order();
Q: convexity of the range I'm currently trying to prove this one statement (IDK if it's true yet): Let $f:\mathbb R^m \to \mathbb R^m$ be a $C^1$ function such that, for all $x,v\in \mathbb R^m$, we have $\langle f'(x)\cdot v,f'(x)\cdot v\rangle = \langle v, v\rangle$ $\big($ i.e. $|f'(x)\cdot v|=|v|\big)$. Show that the line segment $[f(x);f(y)]\subset f(\mathbb R^m)$ for all $x,v\in \mathbb R^m$ (in others words, $f(\mathbb R^m)$ is a convex subset of $\mathbb R^m$). [My results] $\bullet$ $f$ is a local diffeomorphism (i.e. for all $a\in\mathbb R^m$, there is opens sets $a\in V_a$ and $f(a)\in V_{f(a)}$ such that $f|_{V_a}:V_a\to V_{f(a)}$ is a diffeomorphism) $\bullet$ $f|_{V_a}:V_a\to V_{f(a)}$ also preserve the distance (i.e. $|f(x)-f(y)|=|x-y|$ for all $x,y\in V_a$) Any help would be really appreciated! A: First, note that if $f'(x)$ is an isometry, by the polarization identity, it has to belong to $O(m)$, the orthogonal group. Let $x, x_0 \in \mathbb{R}^m$, and define the path joining $x_0$ with $x$: $$p(s) = s x + (1 - s) x_0,$$ with $0 \leq s \leq 1$. Define $\int_0^1 (f\circ p)'(s)\, ds$ integrating element-wise, then the fundamental theorem of calculus implies $$\int_0^1 (f\circ p)'(s)\, ds = f(x) - f(x_0).$$ Applying the chain rule to the left hand side of the previous equation, it turns out that $$\int_0^1 f'\circ p (s)\, (x - x_0) \, ds = f(x) - f(x_0).$$ Since we are integrating element-wise, the constant vector $x - x_0$ can be factored out of the previous equation, so that $$\left(\int_0^1 f'\circ p (s) \, ds\right)\, (x - x_0) = f(x) - f(x_0).$$ Let $A = \int_0^1 f'\circ p (s) \, ds$, again, element-wise integration implies that $A \in O(m)$, and therefore $$f(x) = A(x - x_0) + f(x_0).$$ i.e. $f(x)$ is an affine transformation. In particular, $f(\mathbb{R}^m) = \mathbb{R}^m$.
Q: JSON response and converting it to a JSON object I have a piece of sample code to request for data from a website and the response I get turns out to be gibberish. import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class NetClientGet { public static void main(String[] args) { try { URL url = new URL("http://fids.changiairport.com/webfids/fidsp/get_flightinfo_cache.php?d=0&type=pa&lang=en"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); if (conn.getResponseCode() != 200) { throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); } System.out.println("the connection content type : " + conn.getContentType()); // convert the input stream to JSON BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream()))); String output; System.out.println("Output from Server .... \n"); while ((output = br.readLine()) != null) { System.out.println(output); } conn.disconnect(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } How do I convert the InputStream to a readable JSON Object. Found a few questions but they already have the response and trying to parse. A: The first problem with your code is that the server is g'zipping the response data, which you aren't handling. You can easily verify this by retrieving the data via a browser and looking at the response headers: HTTP/1.1 200 OK Date: Fri, 10 May 2013 16:03:45 GMT Server: Apache/2.2.17 (Unix) PHP/5.3.6 X-Powered-By: PHP/5.3.6 Vary: Accept-Encoding Content-Encoding: gzip Keep-Alive: timeout=5, max=100 Connection: Keep-Alive Transfer-Encoding: chunked Content-Type: application/json Thats why your output looks like 'gibberish'. To fix this, simply chain a GZIPInputStream on top of the URL connections output stream. // convert the input stream to JSON BufferedReader br; if ("gzip".equalsIgnoreCase(conn.getContentEncoding())) { br = new BufferedReader(new InputStreamReader( (new GZIPInputStream(conn.getInputStream())))); } else { br = new BufferedReader(new InputStreamReader( (conn.getInputStream()))); } The second issue is that the data returned is actually in JSONP format (JSON wrapped in a callback function, something like callback_function_name(JSON);). You need to extract it before parsing: // Retrieve data from server String output = null; final StringBuffer buffer = new StringBuffer(16384); while ((output = br.readLine()) != null) { buffer.append(output); } conn.disconnect(); // Extract JSON from the JSONP envelope String jsonp = buffer.toString(); String json = jsonp.substring(jsonp.indexOf("(") + 1, jsonp.lastIndexOf(")")); System.out.println("Output from server"); System.out.println(json); So thats it, now you have the desired data from the server. At this point you can use any standard JSON library to parse it. For example, using GSON: final JSONElement element = new JSONParser().parse(json);
Q: ListView Adapter's getView() not working properly Using ViewHolder pattern in adapter, I'm listing some categories in ListView. The code is working fine untill I'm not scrolling the ListView. To quickly observe the problem, have a look on the screen shot... ListActivity.class public class ListActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_list); Map<String, String> vehicleDetails = new LinkedHashMap<>(); vehicleDetails.put("Chassis Number", "UVXZ123TR3546"); vehicleDetails.put("Engine Number", "12332-WF1231"); vehicleDetails.put("Model Number", "MODEL ONE OF TRUCK"); vehicleDetails.put("Vehicle Type", "FARM TRUCK"); Map<String, String> dealerDetails = new LinkedHashMap<>(); dealerDetails.put("Dealer Name", "Mr. Abcd Pqrstuv"); dealerDetails.put("Dealer Contact Number", "1234567890"); dealerDetails.put("Dealer Contact Number 2", "0987654321"); Map<String, String> driverDetails = new LinkedHashMap<>(); driverDetails.put("Driver Name", "Mr. Xyz Abcdefg"); driverDetails.put("Driver Contact Number 1", "1234567890"); driverDetails.put("Driver Contact Number 2", "0987654321"); Map<String, String> yardDetails = new LinkedHashMap<>(); yardDetails.put("Yard Code", "YARD - 6"); yardDetails.put("Plant", "P-2134"); yardDetails.put("Storage Location", "1000"); yardDetails.put("Zone Code", "1"); yardDetails.put("Bay Number", "2"); Map<String, String> vehicleStatus = new LinkedHashMap<>(); vehicleStatus.put("Dispatch Date", "12 Jan 2016 00:00:00"); vehicleStatus.put("Estimated Delivery Date", "12 Feb 2016 00:00:00"); vehicleStatus.put("Delivery Date", "13 Feb 2016 00:00:00"); vehicleStatus.put("Status", "Delivered"); Map<String, Map<String, String>> data = new LinkedHashMap<>(); data.put("Vehicle Details", vehicleDetails); data.put("Dealer's Details", dealerDetails); data.put("Yard Details", yardDetails); data.put("Driver's Details", driverDetails); data.put("Vehicle Status", vehicleStatus); ListView listView = (ListView) findViewById(R.id.list); listView.setAdapter(new CategoryAdapter(this, R.layout.layout_category_list, data)); } } CategoryAdapter.class public class CategoryAdapter extends ArrayAdapter<HashMap<String, HashMap<String, String>>> { private final Activity context; private final int layoutId; private Map<String, Map<String, String>> data; private Map<String, String> map; public CategoryAdapter(Activity context, int layoutId, Map<String, Map<String, String>> data) { super(context, layoutId); this.context = context; this.layoutId = layoutId; this.data = data; this.map = new LinkedHashMap<>(); } @Override public int getCount() { return data.size(); } @Override public long getItemId(int position) { return position; } @Override public View getView(final int position, View convertView, ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { LayoutInflater inflater = context.getLayoutInflater(); convertView = inflater.inflate(layoutId, parent, false); viewHolder = new ViewHolder(); viewHolder.table = (TableLayout) convertView.findViewById(R.id.table); viewHolder.txtTitle = (TextView) convertView.findViewById(R.id.txtTitle); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } String title = new ArrayList<>(data.keySet()).get(position); viewHolder.txtTitle.setText(title); map.clear(); map = data.get(title); ArrayList<String> keys = new ArrayList<>(map.keySet()); for (int i = 0; i < keys.size(); i++) { TableRow row = new TableRow(context); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.setPadding(4, 10, 4, 10); TextView txtKey = new TextView(context); txtKey.setTextSize(17); txtKey.setTextColor(Color.BLACK); txtKey.setText(keys.get(i)); TextView txtValue = new TextView(context); txtValue.setTextSize(15); txtValue.setText(map.get(keys.get(i))); linearLayout.addView(txtKey); linearLayout.addView(txtValue); row.addView(linearLayout); viewHolder.table.addView(row); } return convertView; } private static class ViewHolder { private TableLayout table; private TextView txtTitle; } } category_list_item.xml <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.v7.widget.CardView android:id="@+id/cardView" style="@style/DetailCardView" android:layout_margin="5dp" android:layout_height="wrap_content"> <TableLayout android:id="@+id/table" android:layout_width="match_parent" android:layout_height="wrap_content"> <TableRow> <TextView android:id="@+id/txtTitle" style="@style/DetailGroupTitleText" android:text="TITLE" /> </TableRow> </TableLayout> </android.support.v7.widget.CardView> </LinearLayout> Now the issue is in getView() method. It is giving unexpected results I mean Vehicle Details are coming with Yard Details Or Driver Details are listed in Vehicle status and something like this. This is happening only when I'm scrolling the ListView otherwise everything is fine. Please help me How can I fix this situation? Downvoters! Please keep calm yaar, I really want help... A: Try something like this, Copy and paste/replace your code. @Override public View getView(final int position, final View convertView, final ViewGroup parent) { ViewHolder viewHolder; if (convertView == null) { final LayoutInflater inflater = context.getLayoutInflater(); convertView = inflater.inflate(layoutId, parent, false); viewHolder = new ViewHolder(); viewHolder.table = (TableLayout) convertView.findViewById(R.id.table); viewHolder.txtTitle = (TextView) convertView.findViewById(R.id.txtTitle); convertView.setTag(viewHolder); } else { viewHolder = (ViewHolder) convertView.getTag(); } String title = new ArrayList<>(data.keySet()).get(position); viewHolder.txtTitle.setText(title); map.clear(); map = data.get(title); final ArrayList<String> keys = new ArrayList<>(map.keySet()); for (int i = 0; i < keys.size(); i++) { final TableRow row = new TableRow(context); final LinearLayout linearLayout = new LinearLayout(context); linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.setPadding(4, 10, 4, 10); final TextView txtKey = new TextView(context); txtKey.setTextSize(17); txtKey.setTextColor(Color.BLACK); txtKey.setText(keys.get(i)); final TextView txtValue = new TextView(context); txtValue.setTextSize(15); txtValue.setText(map.get(keys.get(i))); linearLayout.addView(txtKey); linearLayout.addView(txtValue); row.addView(linearLayout); viewHolder.table.addView(row); } return convertView; } Hope this helps. A: You need to know that getView calls every time ListView needs to get a new item after scroll. This means your loop with filling by new views repeated without cleaning older one. I guess it is reason of your problem, so you should clear your TableRow from result if it is contained there.
Q: What cannot have redundancy\high availability\failover in a server? I know some big companies such as IBM, Amazon, and governments require a high degree for availability and data retention with their servers. To achieve this they use redundancy. My question is, what components of a server (and cluster) are usually made redundant? I had briefly worked in such a server room and noticed redundancy in things such as * *power supplies *RAID was used with minimum ~10 disks and usually had hot spare *network cards *the networks cards themselves had multiple Ethernet ports *UPS backup *diesel generator What else is common to have in redundancy? I know an entire server could be mirrored. Can any computer component be made redundant, for example computers DO have multiple CPUs these days but I guess you wouldn't consider that redundant since they're all being used at once so the chance of failure is equivalent for all them, do I understand that correct? Can memory be made redundant? I'd be interested in seeing statistics for which part of a server fails most frequently. A: Any part of a server can be made redundant, but there can be significant tradeoffs which might be deal-breakers - depending on what you are doing - The biggest one in many cases is redundant sites - even if you have 2 PC's if they are situated far from each other, latency can play havock with your IO. Getting into the devices - You can't really make memory redundant, but you can use ECC memory for added integrity. You can't really have redundant motherboards - that really means 2 computers. You can't really have redundant CPU's, although you can have multiple CPU's and disable one which does not perform. The part of a computer to fail most often is the hard drive - by a long way. Memory failures are also fairly common.
Q: Add annotations at right margin of plot I'd like to add annotations outside the plotting area, at the right axis, and at positions that depend on the coordinates of the plot. I could do that with custom ticks, or adding nodes manually, but in the latter case I have to give the code in after end axis or disable clipping (which can have other undesirable effects, such as... not clipping). The best solution I've found so far is this: \documentclass{article} \usepackage{pgfplots} \begin{document} \begin{tikzpicture} \def\angs{0.529177208354} \def\ev{27.2113838656} \begin{axis}[ xmin = 2, xmax = 4, ymin = 0, ymax = 5, xlabel = {$r$}, ylabel = {$E$}, after end axis/.code = { \path (axis cs:4.0,1.6) node[right] {B3LYP}; } ] \def\ezero{-1.11} \addplot+ table[x expr={\thisrowno{0}*2*\angs}, y expr={(\thisrowno{2}-\ezero)*\ev}] {data.dat}; \end{axis} \end{tikzpicture} \end{document} It has to problems: * *I'd like to give the code next to \addplot, and not in the axis options. *I'd like the coordinates (in particular the ordinate) to be calculated automatically. This shows the result with the following data.dat file: 2.0 -13840.8142382 -0.8142382 2.1 -13840.9230067 -0.9230067 2.2 -13840.9967745 -0.9967745 2.3 -13841.0454158 -1.0454158 2.4 -13841.0762998 -1.0762998 2.5 -13841.0944654 -1.0944654 2.6 -13841.1038383 -1.1038383 2.7 -13841.1070221 -1.1070221 2.8 -13841.1059849 -1.1059849 2.9 -13841.1022183 -1.1022183 3.0 -13841.0966277 -1.0966277 3.1 -13841.0899909 -1.0899909 3.2 -13841.0828688 -1.0828688 3.3 -13841.0755779 -1.0755779 3.4 -13841.0687860 -1.0687860 3.5 -13841.0626993 -1.0626993 3.6 -13841.0572297 -1.0572297 3.7 -13841.0527363 -1.0527363 3.8 -13841.0493218 -1.0493218 3.9 -13841.0467450 -1.0467450 4.0 -13841.0447949 -1.0447949 4.1 -13841.0433105 -1.0433105 4.2 -13841.0421877 -1.0421877 4.3 -13841.0413471 -1.0413471 4.4 -13841.0407159 -1.0407159 4.5 -13841.0402353 -1.0402353 4.6 -13841.0398710 -1.0398710 4.7 -13841.0395993 -1.0395993 4.8 -13841.0393960 -1.0393960 4.9 -13841.0392397 -1.0392397 5.0 -13841.0391747 -1.0391747 PS. Another question as a bonus: is there a way to use the numbers in the 2nd column, rather than the 3rd (which is just the 2nd + 13840), without losing precision? A: You can use the code from pgfplots - Placing Nodes on x Coordinates of a Plot for this. It allows you to write \addplot+ [add node at x={4}{[anchor=west]B3LYP}] table ... (or `\addplot+ [add node at x={\pgfkeysvalueof{/pgfplots/xmax}}{[anchor=west]B3LYP}] table... if you don't want to specify the x value manually) to get Note that you have to set clip mode=individual if you're using plot styles without markers to prevent the node from being clipped away. \documentclass{article} \usepackage{pgfplots} \usetikzlibrary{intersections} \begin{document} \begin{tikzpicture} \makeatletter \def\parsenode[#1]#2\pgf@nil{% \tikzset{label node/.style={#1}} \def\nodetext{#2} } \tikzset{ add node at x/.style 2 args={ name path global=plot line, /pgfplots/execute at end plot visualization/.append={ \begingroup \@ifnextchar[{\parsenode}{\parsenode[]}#2\pgf@nil \path [name path global = position line #1-1] ({axis cs:#1,0}|-{rel axis cs:0,0}) -- ({axis cs:#1,0}|-{rel axis cs:0,1}); \path [xshift=1pt, name path global = position line #1-2] ({axis cs:#1,0}|-{rel axis cs:0,0}) -- ({axis cs:#1,0}|-{rel axis cs:0,1}); \path [ name intersections={ of={plot line and position line #1-1}, name=left intersection }, name intersections={ of={plot line and position line #1-2}, name=right intersection }, label node/.append style={pos=1} ] (left intersection-1) -- (right intersection-1) node [label node]{\nodetext}; \endgroup } } } \def\angs{0.529177208354} \def\ev{27.2113838656} \begin{axis}[ xmin = 2, xmax = 4, ymin = 0, ymax = 5, xlabel = {$r$}, ylabel = {$E$}, cycle list name = linestyles*, clip mode=individual ] \def\ezero{-1.11} \addplot+ [,add node at x={4}{[anchor=west,]B3LYP}] table[x expr={\thisrowno{0}*2*\angs}, y expr={(\thisrowno{2}-\ezero)*\ev}] { 2.0 -13840.8142382 -0.8142382 2.1 -13840.9230067 -0.9230067 2.2 -13840.9967745 -0.9967745 2.3 -13841.0454158 -1.0454158 2.4 -13841.0762998 -1.0762998 2.5 -13841.0944654 -1.0944654 2.6 -13841.1038383 -1.1038383 2.7 -13841.1070221 -1.1070221 2.8 -13841.1059849 -1.1059849 2.9 -13841.1022183 -1.1022183 3.0 -13841.0966277 -1.0966277 3.1 -13841.0899909 -1.0899909 3.2 -13841.0828688 -1.0828688 3.3 -13841.0755779 -1.0755779 3.4 -13841.0687860 -1.0687860 3.5 -13841.0626993 -1.0626993 3.6 -13841.0572297 -1.0572297 3.7 -13841.0527363 -1.0527363 3.8 -13841.0493218 -1.0493218 3.9 -13841.0467450 -1.0467450 4.0 -13841.0447949 -1.0447949 4.1 -13841.0433105 -1.0433105 4.2 -13841.0421877 -1.0421877 4.3 -13841.0413471 -1.0413471 4.4 -13841.0407159 -1.0407159 4.5 -13841.0402353 -1.0402353 4.6 -13841.0398710 -1.0398710 4.7 -13841.0395993 -1.0395993 4.8 -13841.0393960 -1.0393960 4.9 -13841.0392397 -1.0392397 5.0 -13841.0391747 -1.0391747 }; \end{axis} \end{tikzpicture} \end{document}
Q: .htaccess ModRewrite: Url was not found My goal is to redirect http://ipaddress/directory/file.php?id=47 to http://ipaddress/directory/47 with .htaccess. The id parameter will vary and can be any string of numbers like 1, 2, 3, 10, 20, 300, etc. My current .htaccess file is below: RewriteEngine on RewriteCond %{QUERY_STRING} id=([0-9]+) [NC] RewriteRule (.*) /directory/%1? [R=301,L] The rewrite does change the url to what I want! But I get an error after being redirected, which states, Not Found - The requested URL was not found on this server. I'm not sure why the redirect works but does not load the previous page which had the id parameter and actual PHP file. Thank you! A: With your shown samples please try following rules. Make sure your htaccess is present in root folder. Make sure to clear your browser cache before testing your URLs. ##Making RewriteEngine ON here. RewriteEngine on ##Checking condition if THE_REQUEST is in same format which OP has mentioned for URI and mentioning Rule then. RewriteCond %{THE_REQUEST} \s/file\.php\?id=(\d+)\s [NC] RewriteRule ^ /directory/%1? [R=301,L] RewriteRule ^directory/(\d+)/?$ /directory/file.php?id=$1 [NC,L,QSA] A: You will need an internal rewrite for RewriteEngine on RewriteCond %{ENV:REDIRECT_STATUS} ^$ RewriteCond %{QUERY_STRING} id=([0-9]+) [NC] RewriteRule ^file\.php$ /directory/%1? [R=301,L,NC] RewriteRule ^directory/(\d+)/?$ /directory/file.php?id=$1 [L,QSA,NC] RewriteCond %{ENV:REDIRECT_STATUS} ^$ condition is used to make sure that redirect rule is not executed in the next loop of mod_rewrite after rewriting is done from last rules.
Q: ListView - Item selection disappears with scrolling I'm newbie. For couple of days I'm trying to resolve this issue, but no luck. Any help ? Thanks in advance. Below is the images, I selected few items and then scrolled up Once scrolled down selection disappears Below the adapter class I implemented, /** * Created by abcd on 27/1/17. */ public class ListItemAdapterTaxCheckBox extends BaseAdapter { //flag = 1 name/id //flag =2 //ID/Name public class HolderCheck { TextView tv; CheckBox ck; } private static LayoutInflater inflater=null; Tax[] result; Context context; Tax[] selections = null; String [] IDs = null; boolean bAllSel = false; Resources res = null; public ListItemAdapterTaxCheckBox(Activity mainActivity, Tax[] prgmNameList, Tax[] sel, Resources rs, String [] ids) { result=prgmNameList; context=mainActivity; selections = sel; if(selections==null) { selections = new Tax[1]; selections[0] = new Tax(); } IDs = ids; res = rs; inflater = ( LayoutInflater )context. getSystemService(Context.LAYOUT_INFLATER_SERVICE); } @Override public int getCount() { return result.length + 1; } @Override public Object getItem(int position) { return position; } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { final HolderCheck holderCk = new HolderCheck();; View rowView = convertView; final int pos = position; rowView = inflater.inflate(R.layout.custom_list_check_box, null); holderCk.tv = (TextView) rowView.findViewById(R.id.code); holderCk.ck = (CheckBox) rowView.findViewById(R.id.checkBox1); if(position==0) { holderCk.tv.setText(context.getString(R.string.all_text)); } else { holderCk.tv.setText("" + result[position-1].m_TaxID + " - " + result[position-1].m_TaxName); } holderCk.tv.setTextSize(16); holderCk.tv.setTextColor(Color.BLACK); rowView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (holderCk.ck.isChecked()) { holderCk.tv.setBackgroundColor(Color.WHITE); holderCk.ck.setChecked(false); if(pos!=0) { if (IDs != null) IDs[pos -1] = "0"; } else { bAllSel = false; } } else { holderCk.tv.setBackgroundColor(GetResourceColor.getColorWrapper(context, R.color.selHintColor)); holderCk.ck.setChecked(true); if(pos!=0) { if (IDs != null) IDs[pos -1] = "" + result[pos-1].m_TaxID; } else { bAllSel = true; } } } }); return rowView; } public String [] getIDs() { if(bAllSel) return null; else { ArrayList<String> arrayList = new ArrayList<String>(); for (int i = 0, j = 0; i < IDs.length; i++) { if (IDs[i].trim() != "0") { arrayList.add(j, IDs[i].trim()); j = j + 1; if (arrayList.size() == MySQLHelper.MAXITEMSLISTDELETE) break; } } return arrayList.toArray(new String[arrayList.size()]); } } } Below the way I'm populating the ListView //class member Tax[] valuesTaxID = null; //inside a method //default Tax[] tx = new Tax[1]; tx[0] = new Tax(); if (valuesTaxID != null) { listV.setAdapter(null); listV.setAdapter(new ListItemAdapterTaxCheckBox(ctx, valuesTaxID, tx, rs, Ids)); listV.setVisibility(View.VISIBLE); A: ListView will create and destroy views when you scroll. Your code is changing a checkbox when a view is clicked, but you store that info nowhere else, you scroll, ListView destroys the view when you scroll, and there you lost the status of the view. You want to store the "checked" state of the view somewhere. Could be an ArrayList with states, could be a tag attached to the ViewHolders, ... just store it somewhere.
Q: Swiping horizontally on UIScrollView snaps back to original position I have a ScrollView which contains many TableViews aligned horizontally. I would like to be able to swap horizontally to go to the previous/next TableView, however the current TableView always snaps back into the original position. The next/previous TableView is visible mid-swipe. I've seen other SO questions which suggest checking the contentSize of the ScrollView but I have had no luck with this. Can anyone advise? Setting scrollView.pagingEnabled = YES or NO did not seem to make any difference either. - (void)viewDidLayoutSubviews { self.scrollView.contentSize = CGSizeMake(self.scrollView.bounds.size.width * self.numTableViews, self.scrollView.bounds.size.height); }
Q: Storing stylus in JSON / Document database I want to store Stylus in JSON, so it would look something like: { "file": "main", "content:" "body font: 12px Helvetica, Arial, sans-serif; a.button -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px;" } but I understand that its impossible to store with out using the /n is there any way I can format the tabbing / identation automatically so it can be stored and retrieved from a document database i.e. MongoDB or ArangoDB. A: Another example storing the content of a file as string attribute value, without RegExp or the like (no processing of input data, it is already a UTF-8 string): const fs = require('fs'); const arangojs = require('arangojs'); const aql = arangojs.aql; // Const variables for connecting to ArangoDB database const host = '127.0.0.1' const port = '8529' const username = 'root' // default user const password = '' // blank password by default const database = '_system' // default database // Connection to ArangoDB db = new arangojs.Database({ url: `http://${host}:${port}`, databaseName: database }); db.useBasicAuth(username, password); // authenticate fs.readFile('assets/total.styl', 'utf-8', (error, content) => { if (error) { throw error; } db.query(aql` INSERT { name: "Total", type: "stylus", content: ${content} } INTO stylesheets RETURN NEW `).then( cursor => cursor.all() ).then( docs => docs.forEach(doc => console.log(doc)), err => console.error('Query failed:\n', err.response.body) ); }); Resulting document (system attributes left out): { "name": "Total", "type": "stylus", "content": "{\r\n \"file\": \"main\",\r\n \"content:\" \"body\r\n font: 12px Helvetica, Arial, sans-serif;\r\n\r\n a.button\r\n -webkit-border-radius: 5px;\r\n -moz-border-radius: 5px;\r\n border-radius: 5px;\"\r\n}" } To quote the RFC: 2.5. Strings The representation of strings is similar to conventions used in the C family of programming languages. A string begins and ends with quotation marks. All Unicode characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F). Any character may be escaped. If your .styl file contained such characters... 00 01 02 03 04 05 06 07 08 09 10 5C 11 12 22 13 they would end up encoded properly in the document: { "name": "Total", "type": "stylus", "content": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\u0010\\\u0011\u0012\"\u0013" } A: Okay, so after some extensive research I found out for ArangoDB, you can do the following: var removeSpace = content.replace(new RegExp(/(?:\r\n|\r|\n)/g, 'g'), '\n') and remember no need to escape the \n, for other databases this isn't necessary as those databases automatically do the JSON.stringify the values passed. An example: (assuming the DB variable holds the Database connection) import IO from 'fs' IO.readFile('assets/total.styl', 'utf8', function(error, content) { if(error) { throw error } var contentUpdated = content.replace(new RegExp(/(?:\r\n|\r|\n)/g, 'g'), '\n') console.log(contentUpdated) cursor = DB.query('INSERT { name: "Total", type: "stylus", content: "' + contentUpdated + '"} INTO stylesheets RETURN NEW').then( console.log(cursor) ) }) In the end, as mentioned you don't need to replace anything, ArangoDB did it automatically for me.
Q: what is the difference between invalidateList and invalidateDisplayList? I have a DataGrid, populated with objects in an ArrayCollection. After updating one of the objects' fields, I want the screen to update. The data source is not bindable, because I'm constructing it at runtime (and I don't understand how to make it bindable on the fly yet -- that's another question). In this situation, if I call InvalidateDisplayList() on the grid nothing seems to happen. But if I call invalidateList(), the updates happen. (And it's very smooth too -- no flicker like I would expect from invalidating a window in WIN32.) So the question: what is the difference between InvalidateList and InvalidateDisplayList? From the documentation it seems like either one should work. A: invalidateList tells the component that the data has changed, and it needs to reload it and re-render it. invalidateDisplayList tells the component that it needs to redraw itself (but not necessarily reload its data). A: invalidateDisplayList() merely sets a flag so that updateDisplayList() can be called later during a screen update. invalidateList() is what you want. http://livedocs.adobe.com/flex/2/langref/mx/core/UIComponent.html#invalidateDisplayList()
Q: find word in a file and delete to the end of file i need to find a expression in a file and delete it and every thing after that to the end of file for example i have file like: <html> <body> <p>HELLO WORLD!</p> </body> </html><script> HELLO I AM VIRUS </script> and I want to change it to this: <html> <body> <p>HELLO WORLD!</p> </body> </html> it must solve with sed but I don't know how to match multiple line in sed. A: Use this: sed '/<script>/{s/<script>.*$//;q;}' infile > outfile You don't need to match multiple lines, just match the one line and exit with q to stop printing the remainder.
Q: Correct way to generate random numbers On page 3 of "Lecture 8, White Noise and Power Spectral Density" it is mentioned that rand and randn create Pseudo-random numbers. Please correct me if I am wrong: a sequence of random number is that which for the same seed, two sequences are never really exact. Whereas, Pseudo-random numbers are deterministic i.e., two sequences are same if generated from the same seed. How can I create random numbers and not pseudo-random numbers since I was under the impression that Matlab's rand and randn functions are used to generate identically independent random numbers? But, the slides mention that they create pseudo random numbers. Googling for creating of random numbers return rand and randn() functions. The reason for distinguishing random numbers from pseudo-random numbers is that I need to compare performance of cryptography (A) random with white noise characteristics and (B) pseudo-random signal with white noise characteristic. So, (A) must be different from (B). I shall be grateful for any code and the correct way to generate random numbers and pseudo-random numbers. A: Generation of "true" random numbers is a tricky exercise, you can check Wikipedia on RNG and the tests of randomness (http://en.wikipedia.org/wiki/Random_number_generation). This link offers RNG based on atmospheric noise (http://www.random.org/). A: As mentioned above, it is really difficult (probably impossible) to create real random numbers with computer software. There are numerous projects on the internet that provide real random numbers that are generated by physical processes (for example the one Kostya mentioned). A Particularly interesting one is this from HU Berlin. That being said, for experiments like the one you want to perform, Maltab's psedo RNGs are more than fine. Matlab's algorithms include Mersenne Twister which is one of the best known pseudo RNG (I would suggest you google the Mersenne Twister's properties). See Maltab rng documentation here. Since you did not mention which type of system you want to simulate, one simple approach to solve your issue would be to use a good RNG (Mersenne Twister) for process A and a not-so-good for process B.
Q: Critical exponents from Ising free energy at zero magnetic field? Consider the free energy of an Ising model $f(J,h,T)$, where $J$ is the coupling between neighboring sites, $h$ is the magnitude of a homogeneous external magnetic field and $T$ is the temperature. Assume that we know the quantity $f(J,0,T)$ exactly, where the external magnetic field is set to zero. From the above knowledge, we can easily calculate the specific heat $C=-T^2\frac{\partial^2f}{\partial T^2}$, and obtain the critical exponent $\alpha$ from its behavior around the critical temperature $T_c$. By the scaling relation $\nu d = 2-\alpha$, this would also provide us with the critical exponent $\nu$ within the correlation length $\xi$. My question is, knowing only $f(J,0,T)$, are there any further critical exponents we can obtain?
Q: CSS styling in MVC to display different @Html.ActionLink links In an MVC application, I need to display links rendered by @Html.ActionLink as buttons. I have the following code in site.css: .linkbutton { font-family: Constantia, Georgia, serif; text-align:justify; padding-left: 22px; background-color:#FF7F00; color:#fff; border: 1px solid #333; cursor: pointer; font-size:1.2em; width: auto; height:auto; } In the view I used a table layout for the links and referred the linkbutton class as: <td class="linkbutton"> @Html.ActionLink("Add Cab", "Create") </td> The link is using the styles from the .linkbutton class. However, the text color that needs to be in white (#fff) is not inherited, despite being defined as color:#fff; in the CSS. Instead the default blue link color with an underline is getting displayed. I need the link to appear with white font color and without the underline. In CSS I tried: a.linkbutton.link { /*Style code*/ } Then refer it from the view as: Html.ActionLink("Add Cab", "Create", new {@class = "linkbutton"}). But, it is not working. Please help. A: You can override the rules for links inside .linkbutton element, so instead of a.linkbutton.link { /*Style code*/ } write .linkbutton a { color: #fff; text-decoration: none; }
Q: Using nant to compile LESS via exec I have a continuous integration server running CruiseControl.NET on Windows Server 2012. The service runs as user ccnet. I have logged on to the server via RDP, opened a command window, and verified the PATH contains C:\Tools\NodeJS. I installed less globally, since I have a bunch of projects that I'm starting to use LESS in, and for the CI server, it makes sense to just have a single instance of it, rather than have to install it into every single project (the projects don't need it to run locally; we use LessJS in development with flags that remove it when not running in debug mode). C:\Tools\NodeJS>npm install less -g C:\Users\ccnet\AppData\Roaming\npm\lessc -> C:\Users\ccnet\AppData\Roaming\npm\node_modules\less\bin\lessc [email protected] C:\Users\ccnet\AppData\Roaming\npm\node_modules\less β”œβ”€β”€ [email protected] ... etc... I can invoke lessc manually: C:\CruiseControl\MyProject\private\working>lessc.cmd Website\Content\MyProject.less MyProject.css C:\CruiseControl\MyProject\private\working>dir MyProject.css ... 06/24/2014 11:52 AM 159,145 MyProject.css But when I try to run this via exec in nant, I get the infamous "module not found": module.js:340 throw err; ^ Error: Cannot find module 'c:\CruiseControl\MyProject\private\working\node_modules\less\bin\lessc' at Function.Module._resolveFilename (module.js:338:15) at Function.Module._load (module.js:280:25) at Module.runMain (module.js:492:10) at process.startup.processNextTick.process._tickCallback (node.js:244:9) Clearly it's looking in the wrong place for less. But why? My PATH is correct as noted. It works from command line. The workingdir attribute is set to the same folder as in the command-line example. Is there a better way to set this up for a CI scenario? A: I was able to fix the problem by tricking nant. Realizing that it ran fine from a command prompt, I simply told nant to invoke a command prompt, with the /c parameter, followed by lessc and all the parameters I wanted to pass to it: <exec program="cmd.exe" workingdir="${buildfolder}" failonerror="true"> <arg line="/c lessc.cmd --clean-css Website\Content\Site.less Website\Content\Site.min.css" /> </exec>
Q: Trying to save a model to a pb file and I don't have a .meta file I trained a custom object detector model through TensorFlow object detection module and I used mobilenetssd as my pretrained model. After training was done, I have three files: checkpoint ckpt-11.data-00000-of-00001 ckpt-11.index Additionally I have this file as well: pipeline.config I am trying to save this model as a pb file and I want to use the program provided in this tutorial. Can I run this program without the .meta file? How would I generate the .meta file? Additionally, where would I get the output_node_names as well? Edit: I did manage to inference on this model using the chpt-11.index as well. A: You can load the model with the above files only. The model will load weights based on the index file ckpt-11.index and shard file ckpt-11.data-00000-of-00001 Basically, shard file will contain the model weights and the index file indicates which weights are stored in which shard. Usually, there will be only single shard, if you are training on a single machine. For more details on save and load model using Tensorflow, you can refer this document.
Q: C++ Lambdas, Capturing, Smart Ptrs, and the Stack: Why Does this Work? I've been playing around with some of the new features in C++11, and I tried to write the following program, expecting it not to work. Much to my surprise, it does (on GCC 4.6.1 on Linux x86 with the 'std=c++0x' flag): #include <functional> #include <iostream> #include <memory> std::function<int()> count_up_in_2s(const int from) { std::shared_ptr<int> from_ref(new int(from)); return [from_ref]() { return *from_ref += 2; }; } int main() { auto iter_1 = count_up_in_2s(5); auto iter_2 = count_up_in_2s(10); for (size_t i = 1; i <= 10; i++) std::cout << iter_1() << '\t' << iter_2() << '\n' ; } I was expecting 'from_ref' to be deleted when each execution of the returned lambda runs. Here's my reasoning: once count_up_in_2s is run, from_ref is popped off the stack, yet because the returned lambda isn't neccessarily ran straight away, since it's returned, there isn't another reference in existence for a brief period until the same reference is pushed back on when the lambda is actually run, so shouldn't shared_ptr's reference count hit zero and then delete the data? Unless C++11's lambda capturing is a great deal more clever than I'm giving it credit for, which if it is, I'll be pleased. If this is the case, can I assume that C++11's variable capturing will allow all the lexical scoping/closure trickery a la Lisp as long as /something/ is taking care of dynamically allocated memory? Can I assume that all captured references will stay alive until the lambda itself is deleted, allowing me to use smart_ptrs in the above fashion? If this is as I think it is, doesn't this mean that C++11 allows expressive higher-order programming? If so, I think the C++11 committee did an excellent job =) A: The lambda captures from_ref by value, so it makes a copy. Because of this copy, the ref count is not 0 when from_ref gets destroyed, it is 1 because of the copy that still exists in the lambda. A: The following: std::shared_ptr<int> from_ref(new int(from)); return [from_ref]() { return *from_ref += 2; }; is mostly equivalent to this: std::shared_ptr<int> from_ref(new int(from)); class __uniqueLambdaType1432 { std::shared_ptr<int> capture1; public: __uniqueLambdaType1432(std::shared_ptr<int> capture1) : capture1(capture1) { } decltype(*capture1 += 2) operator ()() const { return *capture1 += 2; } }; return __uniqueLambdaType1432(from_ref); where __uniqueLambdaType1432 is a program-globally unique type distinct from any other, even other lambda types generated by a lexically identical lambda expression. Its actual name is not available to the programmer, and besides the object resulting from the original lambda expression, no other instances of it can be created because the constructor is actually hidden with compiler magic. A: from_ref is captured by value. Your reasoning works if you substitute return [from_ref]() { return *from_ref += 2; }; with return [&from_ref]() { return *from_ref += 2; };
Q: error: undefined symbol: gzclose opencv emscripten When I'm trying to compile OpenCV code with following the command, An error is coming. Command sudo /home/xyz/emsdk/upstream/emscripten/em++ ./test_wasm.cpp -s WASM=1 -I/usr/local/include/opencv4/ -L/home/xyz/opencv/build_wasm/lib -llibopencv_core -llibopencv_calib3d -llibopencv_imgproc -llibopencv_photo -llibopencv_flann -llibopencv_features2d -o test_wasm/test_wasm.html -s ALLOW_MEMORY_GROWTH=1 -s EXPORTED_FUNCTIONS='["_image_input"]' -s "EXTRA_EXPORTED_RUNTIME_METHODS=['ccall', 'cwrap']" -std=c++11 -s DISABLE_EXCEPTION_CATCHING=0 Error: error: undefined symbol: gzclose warning: To disable errors for undefined symbols use `-s ERROR_ON_UNDEFINED_SYMBOLS=0` error: undefined symbol: gzeof error: undefined symbol: gzgets error: undefined symbol: gzopen error: undefined symbol: gzputs error: undefined symbol: gzrewind Error: Aborting compilation due to previous errors shared:ERROR: '/home/xyz/emsdk/node/12.9.1_64bit/bin/node /home/xyz/emsdk/upstream/emscripten/src/compiler.js /tmp/tmptCnzix.txt' failed (1) Other info Ubuntu 18.4, Opencv 4.1 A: It's working after add zlib. -s USE_ZLIB=1
Q: OpenVPN FreeNAS BSD installation issues im following this guide to install OpenVPN on my FreeNAS system. http://joepaetzel.wordpress.com/2013/09/22/openvpn-on-freenas-9-1/ I have ran in to the issues detailed below when trying to create the CA.cert. [root@freenas] /mnt/NAS/openvpn# chmod -R 755 easy-rsa/2.0/* [root@freenas] /mnt/NAS/openvpn# cd easy-rsa/2.0 [root@freenas] /mnt/NAS/openvpn/easy-rsa/2.0# sh #./clean-all Please source the vars script first (i.e. "source ./vars") Make sure you have edited it to reflect your configuration. # . ./vars NOTE: If you run ./clean-all, I will be doing a rm -rf on /mnt/NAS/openvpn/easyrsa/2.0/keys # ./build-ca Please edit the vars script to reflect your configuration, then source it with "source ./vars". Next, to start with a fresh PKI configuration and to delete any previous certificates and keys, run "./clean-all". Finally, you can run this tool (pkitool) to build certificates/keys. I have tried creating the keys directory manually as i have read this has worked for others but still no luck. Being new to BSD I've hit a road block and looking for some advice. Any ideas? cheers guys UPDATE: When trying to source ./vars i get the following output [root@freenas] /mnt/NAS/openvpn/easy-rsa/2.0# source ./vars export: Command not found. export: Command not found. export: Command not found. export: Command not found. EASY_RSA: Undefined variable. export: Command not found. EASY_RSA: Undefined variable. A: FreeNAS's default shell is not sh, and therefore doesn't support the 'export' command. The ./vars script needs the export command to set environment variables it then needs. So before you call ./vars (don't call source) call: sh This is clearly stated in the site: http://joepaetzel.wordpress.com/2013/09/22/openvpn-on-freenas-9-1/ A: Not sure about the original issue, i think nrathaus has covered that well. demonLaMagra - If you want to check if openvpn in running use this command: service openvpn status Sorry I couldn't comment on the last answer because of being a new new user, otherwise I would have.
Q: Can't create database manager under Fragment Activity class I am now trying to create new database manager under Fragment class. But unfortunately, I just stuck in the middle of some strage error that i never face with it before. Please have a look at below codes. public class About extends Fragment { DBManager gDatabase = new DBManager(this); private AboutInfo ai; The error code is that The constructor DBManage(About) is undefined. Two quick fix available: Change constructor 'DBManager(Context) to 'DBManager(About)'' Create constructor 'DBManager(About)' And here is my database manager codes. public DBManager(Context context) { super(context, DB_NAME, null, 1); DBManager.myContext = context; } What is wrong with my codes? Any quick help would be appreciate. A: It needs an Activity context, not a Fragment context. Try: DBManager gDatabase = new DBManager(getActivity()); A: use new DBManager(this.getActivity()); but in OnCreateView or other function called after onAttach' as per Fragment lifecyle ......
Q: how to make multiple subset in enum I'm having troubles using enum as a flag. This is the description : This is my enum: [Flags] public enum AuthorityFlagsEnum : short { Output_1_enable = 1 << 0, Output_2_enable = 1 << 1, Output_3_enable = 1 << 2, Output_4_enable = 1 << 3, Arm_Disarm = 1 << 4, Bypass_enable = 1 << 5, Open_Close_report_enable = 1 << 6, Arm_only = Output_2_enable, Arm_only_during_close_window = Output_3_enable, Master_Program = Output_4_enable, } How can I know in my method if the flags set are from the first set (arm only, master/program) or from the second set (output 1 - 4)? A: You really can't. In the end, enum is just a pretty integer. The underlying value of the enum will just be the number you specified. The Enum class provides functionality to convert an integer to an object of your enum type, and back, but it will get confused when you have duplicate numbers. Really the only way to go is to have multiple enum's if you need to differentiate between the values. A: According to the documentation you provided, it looks like you need to look at bit 7. I'd recommend including that last bit in your enum as a flag (and also change the type of the enum to byte) like this: [Flags] public enum AuthorityFlagsEnum : byte { Output_1_enable = 1 << 0, Output_2_enable = 1 << 1, Output_3_enable = 1 << 2, Output_4_enable = 1 << 3, Arm_Disarm = 1 << 4, Bypass_enable = 1 << 5, Open_Close_report_enable = 1 << 6, SecondSet = 1 << 7, // <--- Include a flag that indicates First/Second set Arm_only = Output_2_enable, Arm_only_during_close_window = Output_3_enable, Master_Program = Output_4_enable, } This would enable you to convert a byte directly to the enum value, and also know whether it is first or second set: byte byte3 = 2; //00000010 --> SecondSet is False (FirstSet) var authFlags = (AuthorityFlagsEnum)byte3; if (authFlags.HasFlag(AuthorityFlagsEnum.SecondSet)) { //Second set: bit 2 is Output_2_enable if (authFlags.HasFlag(AuthorityFlagsEnum.Output_2_enable)) //... } else { //First set: bit 2 is Arm_only if (authFlags.HasFlag(AuthorityFlagsEnum.Arm_only)) //... }
Q: What will be the latex code for this Specifically I want the code for this diagram. I am very new to latex…Please help A: I suggest tikz-cd for this diagram. Use arrow type - for the lines, and <-> for the bijection. The package amsmath (probably already in your document) is needed for \DeclareMathOperator, to get proper spacing and shape of Gal. \documentclass{article} \usepackage{amsmath} \usepackage{tikz-cd} \DeclareMathOperator{\Gal}{Gal} \begin{document} Let $K/F$ be a Galois extension and set $G=\Gal(K/F)$. Denote by $E$ the subfields of $K$ containing $F$ and $H$ the subgroups of $G$. Then there is a bijection: \[ \begin{tikzcd} K\arrow[d, -] & 1\arrow[d, -]\\ E\arrow[d, -]\arrow[r, <->] & H\arrow[d, -]\\ F & G \end{tikzcd} \] given by the correspondence \end{document} A: One solution is given by tikz-cd package like this example. \documentclass[a4paper,12pt]{article} \usepackage{tikz-cd} \begin{document} \[\begin{tikzcd}[column sep =-1.2] K & & 1 \\ E \arrow[u, no head] & \leftrightarrow & H \arrow[u, no head] \\ F \arrow[u, no head] & & G \arrow[u, no head] \end{tikzcd}\] \end{document} A: Without "fancy" packages and avoiding the inconsistency appearing in the image, \documentclass{article} \usepackage{amsmath} \DeclareMathOperator{\Gal}{Gal} \begin{document} Let $K/F$ be a Galois extension and set $G=\Gal(K/F)$. Denote by $E$ the subfields of $K$ containing $F$ and $H$ the subgroups of $G$. Then there is a bijection \[ \begin{array}{ccc} K && 1 \\ \Bigl| && \Bigl| \\ \noalign{\vspace{2pt}} E & \leftrightarrow & H \\ \Bigl| && \Bigl| \\ \noalign{\vspace{2pt}} F && G \end{array} \] given by the correspondence \[ \begin{aligned} E &\rightarrow \{\text{elements of $G$ fixing $E$}\} \\ \{\text{the fixed field of $H$}\} &\mspace{-1mu}\leftarrow H \end{aligned} \] \end{document} Note the \mspace{-1mu} that's needed to avoid the impression that the arrows are not aligned. Note also the usage of math mode inside \text to have proper italic letters, not the wrong upright ones in the image. However, since you will be probably needing other diagrams, maybe more complex than the one above, learning the basics of tikz-cd is much better.
Q: How to Catch Invocation Target Exception? I have following piece of code: try { glogger.debug("Calling getReportData (BudgetInBriefDAO)"); lHashData = objBudgetInBriefDAO.getReportData(lStrFinYrId, lStrLangId, lStrContextPath, lStrFinYrDesc); glogger.debug("Returning from getReportData (BudgetInBriefDAO)"); } // catch( InvocationTargetException ie ) // { // glogger.error("InvocationTargetException !!!"); // glogger.error("InvocationTargetException in calling BudgetInBriefBean -> getReportData"); // glogger.error("Target Exception is : " + ie.getTargetException()); // glogger.error("Cause is : " + ie.getCause()); // ie.printStackTrace(); // } catch( Exception e ) { glogger.error("Exception !!!"); glogger.error( "Error in calling BudgetInBriefBean -> getReportData. Error is :- " + e ); e.printStackTrace(); } I am getting following Error: FATAL : AJPRequestHandler-ApplicationServerThread-25 com.tcs.sgv.common.util.GenericEJBObject - InvocationTargetException :java.lang.reflect.InvocationTargetException - 14 Feb 2012 12:36:00,155 - 5210474 milliseconds It is not printing Stack Trace. How would I know the Cause of the Exception ? I have uncommented code & still not getting the Stack Trace printed. Between, my BudgetInBriefDAO Implementation (BudgetInBriefDAOImpl) contains 4 classes. BudgetInBriefDAOImpl & 3 other Thread classes I have decompiled all the class file successfullly without corruption. Please help to find out Actual Cause of Exception. Thanks in advance. A: Try to decompile com.tcs.sgv.common.util.GenericEJBObject; maybe it swallows the exception. Alternatively, start the app in debug mode and set a break point in all the constructors of InvocationTargetException. Note: This might turn out to be impractical because other code causes a ton of these exceptions long before you get to the place you want to debug. If that happens, disable these breakpoints, add a new breakpoint at the first glogger.debug and enable the exception's breakpoints again when this one is hit. When you have stack trace in your debugger, set a breakpoint in the place where the exception is thrown before doing anything else. Last option: Set a breakpoint in glogger.fatal (or the place where the exception is logged).
Q: If you toss 10 fair coins in how many ways can you obtain at least two tails? $\binom{10}0 = 1 \rightarrow $ no tails $\binom{10}1 = 10 \rightarrow $ one tail only $2^{10} = 1024$ $1024-11 = 1013 $ is this correct? A: Correct. # of possibilities that at least two tails would occur: $2^{10}-11$
Q: Numpy does not create binary file When trying to write numpy matrix M to binary file as: from io import open X = [random.randint(0, 2 ** self.stages - 1)for _ in range(num)] Matrix = np.asarray([list(map(int, list(x))) for x in X]) file_output = open('result.bin', 'wb') M = np.ndarray(Matrix, dtype=np.float64) file_output.write(M) file_output.close() I get this error: Traceback (most recent call last): File "experiments.py", line 164, in <module> write_data(X, y) File "experiments.py", line 39, in write_data arr = np.ndarray(Matrix, dtype=np.float64) ValueError: sequence too large; cannot be greater than 32 Can I know how to fix this? Thank you A: You can do this in one of two equivalent ways: import numpy as np a = np.random.normal(size=(10,10)) a.tofile('test1.dat') with open('test2.dat', 'wb') as f: f.write(a.tobytes()) # diff test1.dat test2.dat See the docs for tofile. However from the original example, it looks like Matrix is failing to be convert into an ndarray. A: Replace: M = np.ndarray(Matrix, dtype=np.float64) with M = Matrix.astype(np.float64) np.array(Matrix, dtype=np.float64) would also work, but the astype is simpler. I'm having some problems recreating your Matrix variable. What's its shape? np.save is the best way of saving a multidimensional array to a file. There are other methods, but they don't save the shape and dtype information. ndarray is wrong because the first (positional) argument is supposed to be the shape, not another array. The data if any is provided in the buffer parameter. ndarray is not normally used by beginners or even advanced numpy users. What is Matrix supposed to be. When I try your code with a couple of parameters, I get an error in the map step: In [495]: X = [np.random.randint(0, 2 ** 2 - 1)for _ in range(4)] ...: Matrix = np.asarray([list(map(int, list(x))) for x in X]) ...: -----> 2 Matrix = np.asarray([list(map(int, list(x))) for x in X]) .... TypeError: 'int' object is not iterable In [496]: X Out[496]: [1, 2, 1, 0] Is X just a list of numbers? Not some sort of list of arrays? And why the Matrix step? Is it trying to convert a nested list of lists into integers? Even though randint already creates integers? Then you follow with a conversion to float?
Q: How to generate a table of contents when converting from LaTeX to EPUB using Pandoc? I'm converting a LaTeX document into an EPUB ebook: pandoc input.tex -o output.epub Everything works fine, however the ebook has a broken TOC: It contains only one item - the book's title. How can I make the TOC to contain all parts or all chapters of my book? A: It is difficult for Pandoc to process all types of LaTeX code as input. However, you should add --toc --toc-depth=N (where N is a digit indicating the depth of the ToC you want to generate. I've had good success converting some critical LaTeX source files to EPUB by... * *...first converting to Markdown, *...then hand-massaging the b0rken parts into proper Markdown, *...last converting from Markdown to EPUB.
Q: I want to draw on the TPanel in C++Builder I dynamically add several TImage controls to a TPanel, and want to draw lines between them, but TPanel does not have Canvas. You can draw on a TPaintBox, but I cannot use TImage smiles on it. Tell me how to get out of this simple situation. A: I have dealt with this issue // before describing the form class in the h-file: namespace CanvasPanel { class TPanel : public Extctrls::TPanel { public: __property Canvas; }; } #define TPanel CanvasPanel::TPanel // next - the form class, and everything is unchanged... class TForm1 : public TForm
Q: Missing DLL in Unity. System.Reflection.ReflectionTypeLoadException: The classes in the module cannot be loaded I have a Unity project that works great on my stationary PC, it can publish to my Android device with no problems. Since I will be travelling for a few weeks I thought I might try getting it over to my laptop as well. I have the project checked in to a TFS and did a GET in VS2015 on my laptop. Now when I load the project up on my laptop I get this (see quote below) in the Console in Unity. The interesting thing here is that these dll's are not missing. They are there, and I have given Unity Admin permissions so it should be able to read them no matter what. I've also gone through all settings in Unity and my stationary and laptop have (as far as I can tell) identical settings. They both also have the same .Net frameworks installed (everything from .Net 2 - 4.6.1). I have re installed Unity on the laptop with all checkboxes ticked, and both are running Unity 5.4.0f3. I have read on forums that this can be caused by having .Net 2.0 Subset in the Compatibility setting, but I have .Net 2 and Backend set to IL2CPP. Also note that I am using OneSignal for push notifications and this is working on my stationary, so I dont think the error is with their dll even though the stacktrace mentions them towards the end. Any advice would be highly appreciated. Unhandled Exception: System.Reflection.ReflectionTypeLoadException: The classes in the module cannot be loaded. at (wrapper managed-to-native) System.Reflection.Assembly:GetTypes (bool) at System.Reflection.Assembly.GetTypes () [0x00000] in :0 at Mono.CSharp.RootNamespace.ComputeNamespaces (System.Reflection.Assembly assembly, System.Type extensionType) [0x00000] in :0 at Mono.CSharp.RootNamespace.ComputeNamespace (Mono.CSharp.CompilerContext ctx, System.Type extensionType) [0x00000] in :0 at Mono.CSharp.GlobalRootNamespace.ComputeNamespaces (Mono.CSharp.CompilerContext ctx) [0x00000] in :0 at Mono.CSharp.Driver.LoadReferences () [0x00000] in :0 at Mono.CSharp.Driver.Compile () [0x00000] in :0 at Mono.CSharp.Driver.Main (System.String[] args) [0x00000] in :0 The following assembly referenced from ..\Assets\OneSignal\Platforms\Metro\Newtonsoft.Json.dll could not be loaded: Assembly: System.Runtime (assemblyref_index=0) Version: 4.0.0.0 Public Key: b03f5f7f11d50a3a The assembly was not found in the Global Assembly Cache, a path listed in the MONO_PATH environment variable, or in the location of the executing assembly (..\Assets\OneSignal\Platforms\Metro). Could not load file or assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. Missing method .ctor in assembly ..\Assets\OneSignal\Platforms\Metro\Newtonsoft.Json.dll, type System.Reflection.AssemblyCompanyAttribute Can't find custom attr constructor image: ..\Assets\OneSignal\Platforms\Metro\Newtonsoft.Json.dll mtoken: 0x0a00003b The following assembly referenced from ..\Assets\OneSignal\Platforms\Metro\OneSignalSDK_WP_WNS.dll could not be loaded: Assembly: System.Runtime (assemblyref_index=0) Version: 4.0.10.0 Public Key: b03f5f7f11d50a3a The assembly was not found in the Global Assembly Cache, a path listed in the MONO_PATH environment variable, or in the location of the executing assembly (..\Assets\OneSignal\Platforms\Metro). Missing method .ctor in assembly ..\Assets\OneSignal\Platforms\Metro\OneSignalSDK_WP_WNS.dll, type System.Reflection.AssemblyTrademarkAttribute Can't find custom attr constructor image: ..\Assets\OneSignal\Platforms\Metro\OneSignalSDK_WP_WNS.dll mtoken: 0x0a000008
Q: Packaging a C# application with a database I have packed a WPF C# application that is using a database. However, when I install the packaged application it is using the database I created at the start through visual studio (.mdf) rather than creating another one. The whole purpose of packaging the application was so that I could share it on other computers, so I was install it I need it to create a new database for that instance of the application. Is there a way to accomplish this? Is there a property I need to set to say that the database is a local instance? Or force the package to create a new one on installation? Any help would be much appreciated. Thanks. A: Just been in the middle of doing this myself, one thing I would suggest is using SQL Compact Edition makes the process a lot easier, but if it's too late in the process at the moment then stick with the current database, However I do not know if the below method works with an MDF file. How are you deploying the application on the client machine? does the users machine have sql installed? The first thing you need to do is go to the properties of your MDF and ensure copy to output directory is set to copy if newer and build action is set to content. If you're using a setup project to install the application then you need to make sure in project, application properties, publish, application files that you're mdf is in the list and is set to Data File auto, required and include. and right click on the "Application Folder" in the installers file system, then add, project output, file contents Finally change the connection string in your code so that it reads using ( SqlCeConnection sqlCon = new SqlCeConnection( @"Data Source=|DataDirectory|\App.sdf;Persist Security Info=False;" ) or if you're not using compact Edition using ( SqlConnection sqlCon = new SqlConnection( @"Data Source=|DataDirectory|\App.mdf;Persist Security Info=False;" ) ^using "DataDirectory" means that you don't care where the user puts the application, you will always get the right file before you run and change your database to compact, it doesnt support a lot of things a proper sql database will. After all this, you may still encounter errors with permissions and because its quite long winded I might have missed out a step so just comment if you need more? EDIT If the user does not have either sql server or sql Compact, your easiest solution would be to require them to install SQL CE or there is a way of using DLLs that do the same thing but I couldn't get that to work the link for that is here http://msdn.microsoft.com/en-us/library/aa983326.aspx A: Make sure your db is deployed client side and change the connection string in the application to point to it.