qid
int64
1
74.7M
question
stringlengths
0
70k
date
stringlengths
10
10
metadata
sequence
response
stringlengths
0
115k
13,831,447
The Ocaml manual contains an exercise ([here](http://caml.inria.fr/pub/docs/manual-ocaml-4.00/manual003.html#toc11)) in which library object files are loaded in the toplevel loop (the ocaml interactive interpreter) in the following way: ``` #load "dynlink.cma";; #load "camlp4o.cma";; ``` I'm trying to replicate the subsequent code in a compilable source file, and the code requires the above library object files. Can I load these files with a line of code within the source file and compile it with ocamlc? I've tried "#load", "load", "#use", "use", "#require", "require", and all these proceded by "#directory" and "directory". I know that you can include modules with "include ;;", but this shouldn't work either, because they're just library files, not modules. I've tried to find a way to do this in the manual, but to no avail. Do I need to reference the files in the compilation command? If so, how do I do this?
2012/12/12
[ "https://Stackoverflow.com/questions/13831447", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1896328/" ]
I'm assuming your source is written using extensions implemented by camlp4o. To compile your source, you can say: ``` ocamlc -pp camlp4o -o myfile myfile.ml ``` I believe the complexities of the #load command are required only when you want to use the extensions in the toplevel (the interpreter).
55,678,914
Let's say I have a number from user, for exemple: 456789. I know how to print in reverse the number, but I am not sure how I can stop the execution to print only 3 first reversed digits. What I mean is that I want to print only 987 from the given number I have to stop somehow with break; but I am not sure how. ``` public static void main(String[] args) { int number= 0; int numberInReverse = 0; System.out.println("Input a number"); Scanner sc=new Scanner(System.in); numar=sc.nextInt(); while (number !=0){ numberInReverse*=10; numberInReverse=numar%10; number/=10; System.out.print(numberInReverse); } } ```
2019/04/14
[ "https://Stackoverflow.com/questions/55678914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11301177/" ]
You could follow this algo: 1. modulo the number by 1000 2. reverse it 3. print
779,898
How can I pass a arbitrary number of arguments to the class constructor using the Object() function defined below? ``` <?php /* ./index.php */ function Object($object) { static $instance = array(); if (is_file('./' . $object . '.php') === true) { $class = basename($object); if (array_key_exists($class, $instance) === false) { if (class_exists($class, false) === false) { require('./' . $object . '.php'); } /* How can I pass custom arguments, using the func_get_args() function to the class constructor? $instance[$class] = new $class(func_get_arg(1), func_get_arg(2), ...); */ $instance[$class] = new $class(); } return $instance[$class]; } return false; } /* How do I make this work? */ Object('libraries/DB', 'DATABASE', 'USERNAME', 'PASSWORD')->Query(/* Some Query */); /* ./libraries/DB.php */ class DB { public function __construct($database, $username, $password, $host = 'localhost', $port = 3306) { // do stuff here } } ?> ```
2009/04/23
[ "https://Stackoverflow.com/questions/779898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/89771/" ]
``` $klass = new ReflectionClass($classname); $thing = $klass->newInstanceArgs($args); ``` Although the need to use reflection suggests that you are overcomplicating something in your design. Why do you want to write this function in the first place?
14,063,072
So I would like to do a select from an SQL database, using Java, subject to a conditional statement (less than or equal to something) subject to some loop in Java. In other words, something like the following: ``` for (int i=0; i< 195; i++) { // Get the results of the SQL query resultSet = statement.executeQuery( "SELECT max( millisFromMid ) FROM stockInfo1 WHERE ( millisFromMid <= 34200000 + (120000)*i ) GROUP BY stockID" ); ``` Now Java is returning an exception here, because it doesn't want me to use "i" in this condition; however, without being able to use it here, I'm not sure how I can change this condition. The problem is this: I'm looking to retrieve data from one database, with the intent of doing some manipulation and putting the results into a new database. These manipulations depend on taking the most recent data available, which is why I'm wanting to increase the number bounding millisFromMid. Does that make sense? Does anyone have a suggestion on how someone might do something like this? This seems like a fundamental skill to have when using Java and SQL together, so I'd very much like to know it.
2012/12/28
[ "https://Stackoverflow.com/questions/14063072", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1849003/" ]
The SQL statement is parsed and run in a different environment than your Java code - different language, different scope, and unless you use SQLite they run in different processes or even different machines. Because of that, you can't just refer to the Java variable `i` from your SQL code - you have to either inject it or use special API. The first option - injection - is to simply put the value of i inside the string: ``` "SELECT max( millisFromMid ) FROM stockInfo1 WHERE ( millisFromMid <= 34200000 + (120000)*"+i+" ) GROUP BY stockID" ``` Personally, I prefer to do it using `String.format` - but that's just me. ``` String.format("SELECT max( millisFromMid ) FROM stockInfo1 WHERE ( millisFromMid <= 34200000 + (120000)*%d ) GROUP BY stockID",i) ``` The second option - via API - is more complex but also faster(especially if you combine it with transactions) - using SQL parameters. You need to create a prepared statement: ``` PreparedStatement preparedStatement = connection.prepareStatement("SELECT max( millisFromMid ) FROM stockInfo1 WHERE ( millisFromMid <= 34200000 + (120000)*? ) GROUP BY stockID") ``` Notice the `?` that is replacing the `i` - this is your parameter. You create `prepareStatement` **once** - before the loop, and inside the loop you set the parameter every time and execute it: ``` for (int i=0; i< 195; i++) { preparedStatement.setInt(1,i); //Set the paramater to the current value of i. resultSet = preparedStatement.executeQuery(); //Execute the statement - each time with different value of the parameter. } ```
98,812
I seek a reference for the fact that "coefficients of the Hirzebruch $L$-polynomial have odd denominators". The coefficients are $$\frac{2^{2k}(2^{2k-1}-1)B\_k}{(2k)!}$$ where $B\_k$ is the Bernoulli number, but I cannot locate the appropriate divisibility property of $B\_k$. Of course, $2^{2k-1}-1$ is odd, so it can be ignored.
2012/06/04
[ "https://mathoverflow.net/questions/98812", "https://mathoverflow.net", "https://mathoverflow.net/users/1573/" ]
This follows from the Clausen - von Staudt theorem. See <http://www.bernoulli.org> (structure of the denominator)
9,287,960
I currently have this code that parses imdbAPI http returns: ``` text = 'unicode: {"Title":"The Fountain","Year":"2006","Rated":"R","Released":"22 Nov 2006","Genre":"Drama, Romance, Sci-Fi","Director":"Darren Aronofsky","Writer":"Darren Aronofsky, Darren Aronofsky","Actors":"Hugh Jackman, Rachel Weisz, Sean Patrick Thomas, Ellen Burstyn","Plot":"Spanning over one thousand years, and three parallel stories, The Fountain is a story of love, death, spirituality, and the fragility of our existence in this world.","Poster":"http://ia.media-imdb.com/images/M/MV5BMTU5OTczMTcxMV5BMl5BanBnXkFtZTcwNDg3MTEzMw@@._V1_SX320.jpg","Runtime":"1 hr 36 mins","Rating":"7.4","Votes":"100139","ID":"tt0414993","Response":"True"}' def stripData(tag="Title"): tag_start = text.find(tag) data_start = tag_start + len(tag)+3 data_end = text.find('"',data_start) data = text[data_start:data_end] return tag, data ``` I'm wondering: is there a better way to do this I am missing?
2012/02/15
[ "https://Stackoverflow.com/questions/9287960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1176502/" ]
``` >>> ast.literal_eval(text.split(' ', 1)[1]) {'Plot': 'Spanning over one thousand years, and three parallel stories, The Fountain is a story of love, death, spirituality, and the fragility of our existence in this world.', 'Votes': '100139', 'Rated': 'R', 'Response': 'True', 'Title': 'The Fountain', 'Poster': 'http://ia.media-imdb.com/images/M/MV5BMTU5OTczMTcxMV5BMl5BanBnXkFtZTcwNDg3MTEzMw@@._V1_SX320.jpg', 'Writer': 'Darren Aronofsky, Darren Aronofsky', 'ID': 'tt0414993', 'Director': 'Darren Aronofsky', 'Released': '22 Nov 2006', 'Actors': 'Hugh Jackman, Rachel Weisz, Sean Patrick Thomas, Ellen Burstyn', 'Year': '2006', 'Genre': 'Drama, Romance, Sci-Fi', 'Runtime': '1 hr 36 mins', 'Rating': '7.4'} >>> json.loads(text.split(' ', 1)[1]) {u'Plot': u'Spanning over one thousand years, and three parallel stories, The Fountain is a story of love, death, spirituality, and the fragility of our existence in this world.', u'Votes': u'100139', u'Rated': u'R', u'Response': u'True', u'Title': u'The Fountain', u'Poster': u'http://ia.media-imdb.com/images/M/MV5BMTU5OTczMTcxMV5BMl5BanBnXkFtZTcwNDg3MTEzMw@@._V1_SX320.jpg', u'Writer': u'Darren Aronofsky, Darren Aronofsky', u'ID': u'tt0414993', u'Director': u'Darren Aronofsky', u'Released': u'22 Nov 2006', u'Actors': u'Hugh Jackman, Rachel Weisz, Sean Patrick Thomas, Ellen Burstyn', u'Year': u'2006', u'Genre': u'Drama, Romance, Sci-Fi', u'Runtime': u'1 hr 36 mins', u'Rating': u'7.4'} ```
52,466,555
I want to find (or make) a python script that reads a different python script line by line and prints the commands executed and the output right there after. Suppose you have a python script, `testfile.py` as such: ``` print("Hello world") for i in range(3): print(f"i is: {i}") ``` Now, I want a different python script that parses the `testfile.py` and outputs the following: ``` print("Hello world") ## Hello world for i in range(3): print(f"i is: {i}") ## i is: 0 ## i is: 1 ## i is: 2 ``` Any suggestions on existing software or new code on how to achieve this is greatly appreciated! --- Attempts / concept code: ======================== ### Running `ipython` from python: One of the first thoughts were to run ipython from python using `subprocess`: ``` import subprocess import re try: proc = subprocess.Popen(args=["ipython", "-i"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, universal_newlines=True) # Delimiter to know when to stop reading OUTPUT_DELIMITER = ":::EOL:::" # Variable to contain the entire interaction: output_string = "" # Open testfile.py with open("testfile.py") as file_: for line in file_: # Read command cmd = line.rstrip() # Add the command to the output string output_string += cmd + "\n" proc.stdin.write(f"{cmd}\n") # Print the delimiter so we know when to end: proc.stdin.write('print("{}")\n'.format(OUTPUT_DELIMITER)) proc.stdin.flush() # Start reading output from ipython while True: thisoutput = proc.stdout.readline() thisoutput = thisoutput.rstrip() # Now check if it's the delimiter if thisoutput.find(OUTPUT_DELIMITER) >= 0: break output_string += thisoutput + "\n" except Exception as e: proc.stdout.close() proc.stdin.close() raise proc.stdout.close() proc.stdin.close() print("-" * 4 + "START OUTPUT" + "-" * 4) print(output_string) print("-" * 4 + "END OUTPUT" + "-" * 4) ``` In this approach, the problem becomes indented blocks, like the `for` loop. Ideally something like this would work using just plain `python` (and not `ipython`).
2018/09/23
[ "https://Stackoverflow.com/questions/52466555", "https://Stackoverflow.com", "https://Stackoverflow.com/users/997253/" ]
[`code.InteractiveConsole.interact`](https://docs.python.org/3/library/code.html#code.InteractiveConsole.interact) does exactly what is asked.
30,205,906
I have been using oauth 2.0 with Linkedin as the provider. Now as of today suddenly the authentication is no longer working. Looked on Linkedin its API profile page and figured that they have been updating their program. The error that I am getting is the following: > > No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '<http://localhost:3000>' is therefore not allowed access. > > > This is in JS in the Console. I am wondering if this is the actual error or if there is another error. I am using Rails on the back-end
2015/05/13
[ "https://Stackoverflow.com/questions/30205906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2164689/" ]
LinkedIn February 12th 2015 update effects LinkedIn applications between May 12th - May 19th, 2015. Maybe, your application affected today. I'm getting error after updating. Your application has not been authorized for the scope "r\_fullprofile". The update affected somethings. <https://developer.linkedin.com/support/developer-program-transition>
50,886,900
I'm trying to make a test for some of my students where they need to type in missing words from a paragraph (see picture). The key problem I'm hitting is trying to embed input boxes into a text paragraph, so that when there is a gap, tkinter can make an entry box for the student to type in. Sketch of desired Output: [Target](https://i.stack.imgur.com/wP42t.png) --------------------------------------------- Code attempt: ``` import tkinter as tk root = tk.Tk() tk.Label(root, font=("Comic Sans MS",24,"bold"),\ text="The largest bone in the human body is the").grid(row=0,column=0) ent1 = tk.Entry(root) ent1.grid(row=0,column=1) tk.Label(root, font=("Comic Sans MS",24,"bold"),\ text="which is found in the").grid(row=0,column=2) ent2 = tk.Entry(root) ent2.grid(row=0,column=3) tk.mainloop() ``` Thank you for reading, and any help is very much appreciated.
2018/06/16
[ "https://Stackoverflow.com/questions/50886900", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9181800/" ]
You can add widgets to a text widget with the `window_create` method. Here's a quick example to show how you can use it to embed widgets into a block of text. The code inserts a string that contains `{}` wherever you want an entry widget. The code then searches for that pattern in the widget, deletes it, and inserts an entry widget. ``` import Tkinter as tk quiz = ( "The largest bone in the human body is the {} " "which is found in the {}. It is mainly made " "of the element {}, and is just below the {}." ) root = tk.Tk() text = tk.Text(root, wrap="word") text.pack(fill="both", expand=True) text.insert("end", quiz) entries = [] while True: index = text.search('{}', "1.0") if not index: break text.delete(index, "%s+2c"%index) entry = tk.Entry(text, width=10) entries.append(entry) text.window_create(index, window=entry) root.mainloop() ```
14,527,237
We have a website running and my boss wanted to use a WordPress website as a cover. I am trying to create a log in in WordPress using our existing user database. So that when the user log in in WordPress, they will be redirect to our current website. Any suggestions on how should I approach this? I tried using jQuery `$.post` but it didn't work out well for external links.
2013/01/25
[ "https://Stackoverflow.com/questions/14527237", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2011844/" ]
Thanks, I've found the problem. My resource identifier `R.id.listItem_date` is declared as `@+id/listItem.date` in my resource xml file. Android seems to convert the "." in the name to an "\_" in the generated R file. This works fine when compiling and running the code but apparently robolectric has problems with this. When I change the dot in my resource name to an underscore, my robolectric code works fine. Now that I know what to look for, I've found that there is an open bug ticket for this: <https://github.com/pivotal/robolectric/issues/265>
29,252,113
I am using [PredicateBuilder](http://www.albahari.com/nutshell/predicatebuilder.aspx) to build reusable expressions as return values of objects. For example: ``` public interface ISurveyEligibilityCriteria { Expression<Func<Client, bool>> GetEligibilityExpression(); } ``` I want to have automated tests that determine whether a particular expression is translateable into T-SQL by Entity Framework (ie that it doesn't throw a `NotSupportedException` while "executing"). I can't find anything on the internet - is this possible (seems like it should be)?
2015/03/25
[ "https://Stackoverflow.com/questions/29252113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1860652/" ]
You can create a LINQ statement containing the expression and then check whether it can be translated without actually executing it: ``` var connString = @"server=x;database=x"; using(var db = new MyContext(connString)) { // ToString() shows the generated SQL string. var sql = db.Entities.Where(generatedExpression).ToString(); Assert.IsTrue(sql.StartsWith("SELECT"); } ``` In the `Assert` you can test anything you'd expect to be part of the generated SQL string, but of course if the expression can't be translated, the test will fail because e.g. a `NotSupportedException` is thrown. --- You can wrap this up into a handy extension method: ``` public static class EntityFrameworkExtensions { public static void CompilePredicate<T>(this DbContext context, Expression<Func<T, bool>> predicate) where T : class { context.Set<T>().Where(predicate).ToString(); } } ``` Then in your test: ``` // act Action act = () => context.CompilePredicate(predicate); // assert act.ShouldNotThrow(); ```
35,828,328
I am using Swashbuckle (swagger for C#) with my Web API. I have several GET End-Points that return lists and I allow the user to add a perpage and page params into the QueryString Example: <http://myapi.com/endpoint/?page=5&perpage=10> I see that swagger does support parameter in 'query' but how do I get Swashbuckle to do it? --- I mention in one of the comments that I solved my issue by creating a custom attribute to allow me to do what I needed. Below is the code for my solution: ``` [AttributeUsage(AttributeTargets.Method, Inherited = false, AllowMultiple = true)] public class SwaggerParameterAttribute : Attribute { public SwaggerParameterAttribute(string name, string description) { Name = name; Description = description; } public string Name { get; private set; } public Type DataType { get; set; } public string ParameterType { get; set; } public string Description { get; private set; } public bool Required { get; set; } = false; } ``` Register the Attribute with the Swagger Config: ``` GlobalConfiguration.Configuration .EnableSwagger(c => { c.OperationFilter<SwaggerParametersAttributeHandler>(); }); ``` Then add this attribute to your methods: ``` [SwaggerParameter("page", "Page number to display", DataType = typeof(Int32), ParameterType = ParameterType.inQuery)] [SwaggerParameter("perpage","Items to display per page", DataType = typeof(Int32), ParameterType = ParameterType.inQuery)] ```
2016/03/06
[ "https://Stackoverflow.com/questions/35828328", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4202984/" ]
You can achieve that quite easily. Suppose you have an `ItemsController` with an action like this: ``` [Route("/api/items/{id}")] public IHttpActionResult Get(int id, int? page = null, int? perpage = null) { // some relevant code return Ok(); } ``` Swashbuckle will generate this specification (only showing relevant part): ``` "paths":{ "/api/items/{id}":{ "get":{ "parameters":[ { "name":"id", "in":"path", "required":true, "type":"integer", "format":"int32" }, { "name":"page", "in":"query", "required":false, "type":"integer", "format":"int32" }, { "name":"limit", "in":"query", "required":false, "type":"integer", "format":"int32" } ] } } ``` When you want `page` and `perpage` to be required, just make the parameters not nullable.
34,870
My pro tools version is HD 10.3.7. When I arm and start recording, everything is working, the meters going up, wave form is bulit. And when I stop it, the wave form (aka. region) immediately disappears. This happens only to short recordings. (As far as my test goes, it happens to recordings under 4 seconds). However, the disappeared recording is saved in audio files. It's not just there anymore on pro tools edit view. ????
2015/04/05
[ "https://sound.stackexchange.com/questions/34870", "https://sound.stackexchange.com", "https://sound.stackexchange.com/users/11447/" ]
Try this: click off pre-roll on transport window (CMND + 1)
14,809,861
I'm having trouble with reverse navigation on one of my entities. I have the following two objects: ``` public class Candidate { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public long CandidateId { get; set; } .... // Reverse navigation public virtual CandidateData Data { get; set; } ... // Foreign keys .... } public class CandidateData { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] public long CandidateDataId { get; set; } [Required] public long CandidateId { get; set; } // Foreign keys [ForeignKey("CandidateId")] public virtual Candidate Candidate { get; set; } } ``` Now my foreign key navigation on the CandidateData object works fine. I am having trouble getting the reverse navigation for the candidate object to work (if that's even possible). This is my OnModelCreating function: ``` protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Conventions.Remove<PluralizingTableNameConvention>(); modelBuilder.Entity<Candidate>() .HasOptional(obj => obj.Data) .WithOptionalPrincipal(); base.OnModelCreating(modelBuilder); } ``` It's close to working except in the database I get two columns that link to the CandidateId. I get the one I from the POCO object the I get another column Candidate\_CandidateId I assume was created by the modelBuilder. I am quiet lost at the moment. Can someone please shed some light on what's going on?
2013/02/11
[ "https://Stackoverflow.com/questions/14809861", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2056149/" ]
The One to One problem.... The issue is EF and CODE First, when 1:1 , for the dependent to have a Primary key that refers to the principal. ALthough you can define a DB otherwise and indeed with a DB you can even have OPTIONAL FK on the Primary. EF makes this restriction in Code first. Fair Enough I think... TRy this instead: IS have added a few **opinions** on the way which you may **ignore** if you disagree:-) ``` using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Data.Entity; namespace EF_DEMO { class FK121 { public static void ENTRYfk121(string[] args) { var ctx = new Context121(); ctx.Database.Create(); System.Console.ReadKey(); } } public class Candidate { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]// best in Fluent API, In my opinion.. public long CandidateId { get; set; } // public long CandidateDataId { get; set; }// DONT TRY THIS... Although DB will support EF cant deal with 1:1 and both as FKs public virtual CandidateData Data { get; set; } // Reverse navigation } public class CandidateData { [Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)] // best in Fluent API as it is EF/DB related public long CandidateDataId { get; set; } // is also a Foreign with EF and 1:1 when this is dependent // [Required] // public long CandidateId { get; set; } // dont need this... PK is the FK to Principal in 1:1 public virtual Candidate Candidate { get; set; } // yes we need this } public class Context121 : DbContext { static Context121() { Database.SetInitializer(new DropCreateDatabaseIfModelChanges<Context121>()); } public Context121() : base("Name=Demo") { } public DbSet<Candidate> Candidates { get; set; } public DbSet<CandidateData> CandidateDatas { get; set; } protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity<Candidate>(); modelBuilder.Entity<CandidateData>() .HasRequired(q => q.Candidate) .WithOptional(p=>p.Data) // this would be blank if reverse validation wasnt used, but here it is used .Map(t => t.MapKey("CandidateId")); // Only use MAP when the Foreign Key Attributes NOT annotated as attributes } } ``` }
65,797,290
I need to ask the user for input on entering height and width to find perimeter and area while using the main function, I'm getting a simple error which is ( Area= (Width \* Height) NameError: name 'Width' is not defined) but I've tried everything I know to fix it ``` print("Find the Area and Perimeter of a retangle.") def main(): Width = input("Enter the Width:") Height = input("Enter the Height:") Area() Perimeter() def Area(): Area= (Width * Height) print("The area is", Area) def Perimeter(): Perimeter = (Width * 2 + Height * 2) main() ```
2021/01/19
[ "https://Stackoverflow.com/questions/65797290", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Cant you define an `AnswerManager`, if you want answers filtered by section? Maybe like this: ```py class AnswerManager(models.Manager): def answer_by_section(self, section): if section: return self.filter(questions__section__slug=section.slug) class Answer(models.Model): ... objects = AnswerManager() ```
19,615,784
I'm trying to run a simple batch file. ``` for /f %%a IN ('dir /b /s "%~dp0\EnsembleIndependant\*.mis"') DO (ECHO %%a >> ResultatVorace.txt & CALL vorace.exe -f %%a >> ResultatVorace.txt) ``` this only works if there is no space in the path of the batch file. the batch is in: C:\Users\Rafael\Documents\Visual Studio 2012\Projects\vorace\Release\vorace.exe the files I want to loop through are in: C:\Users\Rafael\Documents\Visual Studio 2012\Projects\vorace\Release\EnsembleIndependant can anyone help me. thanks. thank you guys for the suggestions. for /f "delims=" solved my problem.
2013/10/27
[ "https://Stackoverflow.com/questions/19615784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2453139/" ]
``` for /f "delims=" %%a IN ('dir /b /s "%~dp0EnsembleIndependant\*.mis"') DO (ECHO %%a >> ResultatVorace.txt & CALL vorace.exe -f %%a >> ResultatVorace.txt) ``` `%~dp0` has already a backspace at the end.
4,764,553
I want to create computer for the word-game [Ghost](http://en.wikipedia.org/wiki/Ghost_%28game%29). However, I'm having problems thinking of a good way to deal with accessing the huge word list. Here's my current implementation (which doesn't work): ``` import os, random, sys, math, string def main(): #Contains a huge wordlist-- opened up for reading dictionary = open("wordlist.txt", "r") wordlist = [] win= 0 turn= 0 firstrun = 0 word = "" #while nobody has won the game while win==0: if turn == 0: #get first letter from input foo = raw_input("Choose a letter: ")[0] word+=foo print "**Current word**: "+ word #Computer's turn turn = 1 if turn == 1: #During the first run the program gets all definitively #winning words (words that have odd-number lengths) #from the "dictionary" file and puts them in a list if firstrun== 0: for line in dictionary: #if the line in the dictionary starts with the current #word and has an odd-number of letters if str(line).startswith(word) and len(line)%2 == 0: wordlist.append(line[0: len(line)-1]) print "first run complete... size = "+str(len(wordlist)) firstrun = 1 else: #This is run after the second computer move for line in wordlist: #THIS DOES NOT WORK-- THIS IS THE PROBLEM. #I want it to remove from the list every single #word that does not conform to the current limitations #of the "word" variable. if not line.startswith(word): wordlist.remove(line) print "removal complete... size = "+str(len(wordlist)) turn = 0 if __name__ == "__main__": main() ``` I have demarcated the problem area in the code. I have no idea why it doesn't work. What should happen: Imagine the list is populated with all words that start with 'a.' The user then picks the letter 'b.' The target word then must have the starting letters 'ab.' What should happen is that all 'a' words that are in the list that are not directly followed with a 'b' should be removed. I also would appreciate it if somebody could let me know a more efficient way of doing this then making a huge initial list.
2011/01/21
[ "https://Stackoverflow.com/questions/4764553", "https://Stackoverflow.com", "https://Stackoverflow.com/users/372526/" ]
I would suggest not deleting words from your list. It will be extremely slow because deleting in the middle of a list is O(N). It is better to just make a new list. One possible way to do this is to replace the lines ``` for line in wordlist: if not line.startswith(word): wordlist.remove(line) ``` with ``` wordlist = [w for w in wordlist if w.startswith(word)] ```
62,465,566
I am trying to first upload images to firebase then retrieving in in an activity(gallery) but getting a code error. ``` @Override public void onBindViewHolder(ImageViewHolder holder, int position) { ImageUploaderAdapter uploadCurrent = mUploads.get(position); holder.textViewName.setText(uploadCurrent.getName()); Picasso.get().load(mContext).into(imageView) .load(uploadCurrent.getImageUrl()) .fit() .centerCrop() .into(holder.imageView); ``` Error in code `Picasso.get().load(mContext).into(imageView)` getting error ``` error: method get in class Picasso cannot be applied to given types; Picasso.get(mContext) ```
2020/06/19
[ "https://Stackoverflow.com/questions/62465566", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13607439/" ]
matchTemplate wont work well in this case, as they need exact size and viewpoint match. Opencv Feature based method might work. You can try SIFT based method first. But the general assumption is that the rotation, translation, perspective changes are bounded. It means that for adjacent iamge pair, it can not be 1 taken from 20m and other picture taken from 10km away. Assumptions are made so that the feature can be associated. [![enter image description here](https://i.stack.imgur.com/WgfIQ.png)](https://i.stack.imgur.com/WgfIQ.png) Deep learning-based method might work well given enough datasets. take POSEnet for reference. It can matches same building from different geometry view point and associate them correctly. [![enter image description here](https://i.stack.imgur.com/sr0c2.png)](https://i.stack.imgur.com/sr0c2.png) Each method has pros and cons. You have to decide which method you can afford to use Regards Dr. Yuan Shenghai
15,795,748
I am hosting an ASP.NET MVC 4 site on AppHarbor (which uses Amazon EC2), and I'm using CloudFlare for Flexible SSL. I'm having a problem with redirect loops (310) when trying to use RequireHttps. The problem is that, like EC2, CloudFlare terminates the SSL before forwarding the request onto the server. However, whereas Amazon sets the X-Forwarded-Proto header so that you can handle the request with a custom filter, CloudFlare does not appear to. Or if they do, I don't know how they are doing it, since I can't intercept traffic at that level. I've tried the solutions for Amazon EC2, but they don't seem to help with CloudFlare. Has anyone experienced this issue, or know enough about CloudFlare to help?
2013/04/03
[ "https://Stackoverflow.com/questions/15795748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1141679/" ]
The `X-Forwarded-Proto` header is intentionally overridden by AppHarbor's load balancers to the actual scheme of the request. Note that while CloudFlare's flexible SSL option may add slightly more security, there is still unencrypted traffic travelling over the public internet from CloudFlare to AppHarbor. This arguably defies the purpose of SSL for anything else than appearances and reducing the number of attack vectors (like packet sniffing on the user's local network) - i.e. it may look "professional" to your users, but it actually is still insecure. That's less than ideal particularly since AppHarbor supports both installing your own certificates and includes piggyback SSL out of the box. CloudFlare also recommends using "Full SSL" for scenarios where the origin servers/service support SSL. So you have a couple of options: * Continue to use the insecure "Flexible SSL" option, but instead of inspecting the `X-Forwarded-Proto` header in your custom `RequireHttps` filter, you should inspect the `scheme` attribute of the `CF-Visitor` header. There are more details in [this discussion](https://support.cloudflare.com/entries/22088068-How-do-I-redirect-HTTPS-traffic-with-Flexible-SSL-and-Apache-). * Use "Full SSL" and point CloudFlare to your `*.apphb.com` hostname. This way you can use the complimentary piggyback SSL that is enabled by default with your AppHarbor app. You'll have to override the `Host` header on CloudFlare to make this work and [here's a blog post on how to do that](http://blog.cloudflare.com/ssl-on-custom-domains-for-appengine-and-other). This will of course make requests to your app appear like they were made to your `*.apphb.com` domain - so if for instance you automatically redirect requests to a "canonical" URL or generate absolute URLs you'll likely have to take this into consideration. * Upload your certificate and add a custom hostname to AppHarbor. Then turn on "Full SSL" on CloudFlare. This way the host header will remain the same and your application will continue to work without any modifications. You can read more about the SSL options offered by AppHarbor in [this knowledge base article](http://support.appharbor.com/kb/tips-and-tricks/ssl-and-certificates).
27,343,087
I am developing an application which requires the youtube api. I am stuck at a point where i need the keywords of a youtube channel. I am getting all keywords in a string. ``` $string = 'php java "john smith" plugins'; ``` I am trying to get the above keywords in an array. I can use `explode(' ',$string)` but the problem is `john smith` itself is a keyword. I am expecting my array to be like this: ``` array( [0] => 'php', [1] => 'java', [2] => 'john smith', [3] => 'plugins' ) ``` Any quick/dirty solution to achieve this ?
2014/12/07
[ "https://Stackoverflow.com/questions/27343087", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1015448/" ]
``` char *get_set(int size, char *set){// size : size of set as buffer size char ch; int i; for(i = 0; i < size-1 && (ch=getchar()) != '\n'; ){ if(!isspace(ch)) set[i++] = ch; } set[i] = '\0'; return set; } ```
25,382,103
I have created a Login page using MVC Razor. The page contains a User name & Password to be entered and two button Login and SignUp button. I have applied required field validation for both textboxes. It works fine when i click Login button. For Signup button i want the page to be redirected to signup page. But when i click SignUp button, it throws error as UserName and Password are required. How to check for validation when only login button is clicked. View page: ``` <body> @using (Html.BeginForm("CheckLogin", "Login")) { <div> <div> <img src="@Url.Content("../../Content/Images/Logo.png")" alt="logo" style="margin-top:17px;" />@*width="184" height="171"*@ </div> <div class="LoginBg"> <h3 class="LoginHdng"> @Html.Label("lblLogin", "Login") </h3> <table style="width: 745px;"> <tr> <td> <br /> </td> </tr> <tr> <td style="font-size: 20px; text-align: right; width: 250px"> @Html.LabelFor(model => model.FirstName, "User Name: ") </td> <td> @Html.TextBoxFor(model => model.FirstName, new { @class = "txtBox" }) @Html.ValidationMessageFor(model => model.FirstName) </td> </tr> <tr> <td> <br /> </td> </tr> <tr> <td style="font-size: 20px; text-align: right;"> @Html.LabelFor(model => model.Password, "Password: ") </td> <td> @Html.PasswordFor(model => model.Password, new { @class = "txtBox" }) @Html.ValidationMessageFor(model => model.Password) </td> </tr> <tr> <td colspan="2" style="font-size: 16px; text-align: center; color: Red;"> <br /> @TempData["Error"] </td> </tr> <tr> <td> <br /> </td> </tr> <tr> <td colspan="2" style="text-align: center;"> <input type="submit" value="Login" name="Command" class="loginBtn" /> &nbsp;&nbsp;&nbsp;&nbsp; <input type="submit" value="SignUp" name="Command" class="loginBtn" /> </td> </tr> </table> </div> </div> } </body> ``` Controller: ``` [HttpPost] public ActionResult CheckLogin(FormCollection coll)//, string command { if (coll["Command"] == "Login") { using (var db = new MVC_DBEntities()) { if (db.tbl_UserDetails.ToList().Select(m => m.FirstName == coll["FirstName"] && m.Password == coll["Password"]).FirstOrDefault()) { TempData["Error"] = ""; return this.RedirectToAction("Index", "Home"); } else { TempData["Error"] = "Invalid UserName/Password"; return this.RedirectToAction("Login", "Login"); } } } else if (coll["Command"] == "SignUp") { return this.RedirectToAction("SignUp", "SignUp"); } else { return this.RedirectToAction("Login", "Login"); } } ``` Thanks in Advance...
2014/08/19
[ "https://Stackoverflow.com/questions/25382103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3211705/" ]
Take `Signup` button as **input type button** not **input type submit** as shown :- ``` <input type="button" value="SignUp" name="Command" class="loginBtn" id="SignUpBtn" /> ``` and use some **Jquery/Javascript** to go to `SignUp Page` as :- ``` $("#SignUpBtn").click(function(){ window.location.href="/SignUp/SignUp"; }); ```
11,838
My website can only be accessed by authenticated users. How can I automatically make the author's name the user's name without giving users the option to input anything else in the name field?
2011/09/22
[ "https://drupal.stackexchange.com/questions/11838", "https://drupal.stackexchange.com", "https://drupal.stackexchange.com/users/1273/" ]
Custom datepicker options are now supported (as of Date module version 7.x-2.6) by setting the necessary values with `#datepicker_options`. Alex's use case of a custom form element to display only future dates would look like this: ``` $form['date'] = array( '#prefix'=>t('When do you want to start the featured campaign?'), '#date_format' => 'Y-m-d', '#date_year_range' => '0:+1', '#type' => 'date_popup', '#weight'=>0, '#datepicker_options' => array('minDate' => 0), ); ```
2,646,463
I have a XMLDocument like: ``` <Folder name="test"> <Folder name="test2"> <File>TestFile</File> </Folder> </Folder> ``` I want only the folder´s, not the files. So, how to delete / manipulate the XML Document in c# to delete / remove ALL elements in the document? Thanks!
2010/04/15
[ "https://Stackoverflow.com/questions/2646463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/298926/" ]
If you can use `XDocument` and LINQ, you can do ``` XDocument doc = XDocument.Load(filename) // or XDocument.Parse(string) doc.Root.Descendants().Where(e => e.Name == "File").Remove(); ``` -- edited out an error
45,041,702
My Application wants to Request for Wifi Permission on the start.So far I have managed to give permission through **Setting**.But I don't want to Do that anymore.So far I have seen this previous [Question](https://stackoverflow.com/questions/40301628/how-to-request-permissions-during-run-time-when-using-gluon-mobile-environment/40370076?noredirect=1#comment77053866_40370076).I could understand a bit.but it's not Enough. I created a ***.class*** that that manages Wifi Activity like turning ON/OFF , checking wifi state.It works well if Wifi permission is *granted*.but if not it does'nt work. Here's the **WifiController.class** that I have created. ``` import android.content.Context; import android.net.wifi.WifiManager; import javafxports.android.FXActivity; public class WifiController implements WifiInterface { WifiManager wifiManager=null; WifiController() { wifiManager = (WifiManager)FXActivity.getInstance().getSystemService(Context.WIFI_SERVICE); } WifiManager getWifimanager() { return wifiManager; } public boolean isTurnedOn() { return wifiManager.isWifiEnabled(); } public boolean turnOn() { wifiManager.setWifiEnabled(true); return true; } public boolean turnOff() { wifiManager.setWifiEnabled(false); return true; } } ``` So, Please Enlighten Me. Thanks in Advance.
2017/07/11
[ "https://Stackoverflow.com/questions/45041702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7315145/" ]
The Android Developers Website has a great walkthrough example on how runtime permissions work here: <https://developer.android.com/training/permissions/requesting.html> Also don't forget to add the permissions into your manifest as well.
45,062,106
So i have two different queries as follows: ``` Query1 CPT Resource 1 2 3 4 5 2017-06-12 RM1 5.00 5.00 4.00 4.00 2.00 2017-06-12 RM2 3.00 6.00 4.00 7.00 4.00 2017-06-12 RM3 3.00 4.00 6.00 8.00 6.00 2017-06-13 RM1 3.00 7.00 5.00 3.00 5.00 2017-06-13 RM2 4.00 5.00 4.00 2.00 4.00 2017-06-13 RM3 2.00 4.00 5.00 2.00 7.00 2017-06-14 RM1 2.00 4.00 6.00 4.00 2.00 2017-06-14 RM2 6.00 5.00 4.00 5.00 2.00 2017-06-14 RM3 5.00 3.00 7.00 4.00 5.00 ``` and ``` Query2 CPT Resource 1 2 3 4 5 2017-06-12 RM1 0.00 -2.00 0.00 0.00 -2.00 2017-06-12 RM2 -3.00 -3.00 0.00 0.00 0.00 2017-06-12 RM3 -1.00 -3.00 0.00 0.00 0.00 2017-06-13 RM1 0.00 -1.00 0.00 0.00 0.00 2017-06-13 RM2 0.00 -1.00 -1.00 -2.00 -2.00 2017-06-13 RM3 -2.00 -3.00 -1.00 0.00 0.00 2017-06-14 RM1 0.00 0.00 0.00 0.00 0.00 2017-06-14 RM2 0.00 -4.00 -3.00 -2.00 0.00 2017-06-14 RM3 0.00 -3.00 -1.00 0.00 -2.00 ``` With these two queries how would I go about creating a new query that multiplies data from query1 with the corresponding number in query 2 that is in the same position based on that date, resource, and the hour (which are the headings 1, 2, 3, 4, and 5). I also want only positive numbers so the new data should be multiplied by -1. If I do this by hand the new table should look like this: ``` Query3 CPT Resource 1 2 3 4 5 2017-06-12 RM1 0.00 10.00 0.00 0.00 4.00 2017-06-12 RM2 9.00 18.00 0.00 0.00 0.00 2017-06-12 RM3 3.00 12.00 0.00 0.00 0.00 2017-06-13 RM1 0.00 7.00 0.00 0.00 0.00 2017-06-13 RM2 0.00 5.00 4.00 4.00 8.00 2017-06-13 RM3 4.00 12.00 5.00 0.00 0.00 2017-06-14 RM1 0.00 0.00 0.00 0.00 0.00 2017-06-14 RM2 0.00 20.00 12.00 10.00 0.00 2017-06-14 RM3 0.00 9.00 7.00 0.00 10.00 ```
2017/07/12
[ "https://Stackoverflow.com/questions/45062106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8249331/" ]
Just join for the key field and use `ABS()` to return a positive result. ``` SELECT Q1.CPT, Q1.Resource, ABS(Q1.[1] * Q2.[1]) as [1], ABS(Q1.[2] * Q2.[2]) as [2], ABS(Q1.[3] * Q2.[3]) as [3], ABS(Q1.[4] * Q2.[4]) as [4], ABS(Q1.[5] * Q2.[5]) as [5] FROM Query1 Q1 JOIN Query2 Q2 ON Q1.CPT = Q2.CPT AND Q1.Resourece = Q2.Resource ```
31,903,819
I am using in memory H2 database for my tests. My application is Spring Boot and I am having trouble when running a CTE (Recursive query) from the application. From the H2 console the query works like a charm but not when it's called from the application (it returns no records, although they are there, I can see from the H2 console using the very same query Hibernate prints in Java console). I tried to annotate the native query in the repository at first and now I am trying to run it from a Custom repository. None works. Here is my custom repository: ``` public class RouteRepositoryImpl implements CustomRouteRepository{ @PersistenceContext private EntityManager entityManager; @SuppressWarnings("unchecked") @Override public List<Route> findPossibleRoutesByRouteFrom(String name, String routeFrom) { StringBuffer sb = new StringBuffer(); sb.append("WITH LINK(ID ,ROUTE_FROM ,ROUTE_TO,DISTANCE, LOGISTICS_NETWORK_ID ) AS "); sb.append("(SELECT ID , ROUTE_FROM ,ROUTE_TO, DISTANCE, LOGISTICS_NETWORK_ID FROM ROUTE WHERE ROUTE_FROM=:routeFrom "); sb.append("UNION ALL "); sb.append("SELECT ROUTE.ID , ROUTE.ROUTE_FROM , ROUTE.ROUTE_TO, ROUTE.DISTANCE, ROUTE.LOGISTICS_NETWORK_ID "); sb.append("FROM LINK INNER JOIN ROUTE ON LINK.ROUTE_TO = ROUTE.ROUTE_FROM) "); sb.append("SELECT DISTINCT L.ID, L.ROUTE_FROM, L.ROUTE_TO, L.DISTANCE, L.LOGISTICS_NETWORK_ID "); sb.append("FROM LINK L WHERE LOGISTICS_NETWORK_ID = (SELECT L.ID FROM LOGISTICS_NETWORK L WHERE L.NAME=:name) "); sb.append("ORDER BY ROUTE_FROM, ROUTE_TO "); Query query= entityManager.createNativeQuery(sb.toString(), Route.class); query.setParameter("routeFrom", routeFrom); query.setParameter("name", name); List<Route> list = query.getResultList(); return list; } } ``` The parameters are not the problem as I tested with them hard coded into the query. Data is being loaded into the database before each test with RunScript.execute and being truncated right after the test finishes. I also tried to save data using regular repositor.save in the test (to make sure data is being saved in the same database instance) and the results are always the same, no matter what I do. This app is being built as a test before the interview for a job and I am already late because of this. Any help is much appreciated. Thanks, Paulo
2015/08/09
[ "https://Stackoverflow.com/questions/31903819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1474815/" ]
H2 only support recursive CTE without named parameter.
194,571
What is the meaning of ''one block into'' in the below sentences? Which grammar rule ? **You own a house one block into the ward.**
2019/01/29
[ "https://ell.stackexchange.com/questions/194571", "https://ell.stackexchange.com", "https://ell.stackexchange.com/users/88975/" ]
In the context of housing, a ***block*** is either a single (multi-storey) building containing multiple apartments / offices / etc., or a (usually rectangular) area between two pairs of intersecting roads, mostly or completely filled with buildings (houses / offices / shops / etc.). And a ***ward*** usually refers to a residential area that's significant in the context of elections (all the voters who live in one ward get to decide who they will elect as their local councilor, for example). I don't know the exact context of OP's example, but basically it means the addressee's house isn't on the very *edge* of a ward - there's one more block between his house and the one that's right on the electoral boundary (but considered to be *within* the ward). --- Syntactically, it's the same general construction as... > > *I'm three weeks into my new job* > > > ...meaning *I started my new job three weeks ago.*
11,558,710
Hi guys i have to pass the checked value from checkbox and selected value from DropDown, my view looks like this ``` Project:DropDown ----------------------------- EmployeeNames -------------------------- checkbox,AnilKumar checkBox,Ghouse this is my aspx page <body> <% using (Html.BeginForm()) { %> ``` <%:Html.ValidationSummary(true)%> ``` <div></div><div style="margin:62px 0 0 207px;"><a style="color:Orange;">Projects : </a><%:Html.DropDownList("Projects")%></div> <fieldset style="color:Orange;"> <legend>Employees</legend> <% foreach (var item in Model) { %> <div> <%:Html.CheckBox(item.EmployeeName)%> <%:Html.LabelForModel(item.EmployeeName)%> </div> <%} %> <%} %> </fieldset> <p> <input type="button" value="AssignWork" /></p> </div> </body> ``` i have to get the all the checked employyee names with selected project ID from dropdown into my post method..how can i do this can any one help me here please ``` this is my controller [AcceptVerbs(HttpVerbs.Get)] public ActionResult AssignWork() { ViewBag.Projects = new SelectList(GetProjects(), "ProjectId", "ProjectName"); var employee = GetEmployeeList(); return View(employee); } public List<ResourceModel> GetEmployeeList() { var EmployeeList = new List<ResourceModel>(); using (SqlConnection conn = new SqlConnection("Data Source=LMIT-0039;Initial Catalog=BugTracker;Integrated Security=True")) { conn.Open(); SqlCommand dCmd = new SqlCommand("select EmployeId,EmployeeName from EmployeeDetails", conn); SqlDataAdapter da = new SqlDataAdapter(dCmd); DataSet ds = new DataSet(); da.Fill(ds); conn.Close(); for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++) { var model = new ResourceModel(); model.EmployeeId = Convert.ToInt16(ds.Tables[0].Rows[i]["EmployeId"]); model.EmployeeName = ds.Tables[0].Rows[i]["EmployeeName"].ToString(); EmployeeList.Add(model); } return EmployeeList; } } public List<ResourceModel> GetProjects() { var roles = new List<ResourceModel>(); SqlConnection conn = new SqlConnection("Data Source=LMIT-0039;Initial Catalog=BugTracker;Integrated Security=True"); SqlCommand Cmd = new SqlCommand("Select ProjectId,projectName from Projects", conn); conn.Open(); SqlDataAdapter da = new SqlDataAdapter(Cmd); DataSet ds = new DataSet(); da.Fill(ds); for (int i = 0; i <= ds.Tables[0].Rows.Count - 1; i++) { var model = new ResourceModel(); model.ProjectId= Convert.ToInt16(ds.Tables[0].Rows[i]["ProjectId"]); model.ProjectName = ds.Tables[0].Rows[i]["projectName"].ToString(); roles.Add(model); } conn.Close(); return roles ; } [AcceptVerbs(HttpVerbs.Post)] public ActionResult AssignWork(int projectid,string EmployeeName,FormCollection form,ResourceModel model) { using (SqlConnection conn = new SqlConnection("Data Source=LMIT-0039;Initial Catalog=BugTracker;Integrated Security=True")) { conn.Open(); SqlCommand insertcommande = new SqlCommand("AssignWork", conn); insertcommande.CommandType = CommandType.StoredProcedure; insertcommande.Parameters.Add("@EmployeeName", SqlDbType.VarChar).Value = EmployeeName; insertcommande.Parameters.Add("@projectId", SqlDbType.VarChar).Value = projectid; //insertcommande.Parameters.Add("@Status", SqlDbType.VarChar).Value = model.status; insertcommande.ExecuteNonQuery(); } return View(); } ```
2012/07/19
[ "https://Stackoverflow.com/questions/11558710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1206468/" ]
use `android:gravity` like this: ``` TextView android:id="@+id/gateNameText" android:layout_width="0dip" android:layout_height="match_parent" android:gravity="center_vertical|center" android:layout_weight=".7" android:textSize="15dp" /> ```
19,306,342
My PHP code is this: ``` $userdetails = mysqli_query($con, "SELECT *FROM aircraft_status"); #$row = mysql_fetch_row($userdetails) ; while($rows=mysqli_fetch_array($userdetails)){ $status[]= array($rows['Aircraft']=>$rows['Status']); } #Output the JSON data echo json_encode($status); ``` and gives this: ``` [{"A70_870":"1"},{"A70_871":"1"},{"A70_872":"1"},{"A70_873":"1"},{"A70_874":"1"},{"A70_875":"1"},{"A70_876":"2"},{"A70_877":"1"},{"A70_878":"2"},{"A70_879":"2"},{"A70_880":"2"},{"A70_881":"0"},{"A70_882":"0"},{"A70_883":"0"},{"A70_884":"0"},{"A70_885":"0"}] ``` The java code that reads it is this: ``` // Create a JSON object from the request response JSONObject jsonObject = new JSONObject(result); //Retrieve the data from the JSON object n870 = jsonObject.getInt("A70_870"); n871 = jsonObject.getInt("A70_871"); n872 = jsonObject.getInt("A70_872"); n873 = jsonObject.getInt("A70_873"); n874 = jsonObject.getInt("A70_874"); n875 = jsonObject.getInt("A70_875"); n876 = jsonObject.getInt("A70_876"); n877 = jsonObject.getInt("A70_877"); n878 = jsonObject.getInt("A70_878"); n879 = jsonObject.getInt("A70_879"); n880 = jsonObject.getInt("A70_880"); n881 = jsonObject.getInt("A70_881"); n882 = jsonObject.getInt("A70_882"); n883 = jsonObject.getInt("A70_883"); n884 = jsonObject.getInt("A70_884"); n885 = jsonObject.getInt("A70_885"); ``` When i run my android app I seem to keep getting the error: ``` "of type org.json.JSONArray cannot be converted into Json object" ``` However when I send the app dummy code without the square brackets, it seems to work fine! How do I get rid of those [ and ] brackets on the ends??? Alternatively is there a way to accept the json as it is and adapt the java to read it?
2013/10/10
[ "https://Stackoverflow.com/questions/19306342", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2840648/" ]
``` echo json_encode($status, JSON_FORCE_OBJECT); ``` Demo: <http://codepad.viper-7.com/lrYKv6> or ``` echo json_encode((Object) $status); ``` Demo; <http://codepad.viper-7.com/RPtchU>
27,005,824
I would like to construct a match spec to select the first element from a tuple when a match is found on the second element, or the second element when the first element matches. Rather than calling ets:match twice, can this be done in one match specification?
2014/11/18
[ "https://Stackoverflow.com/questions/27005824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/450706/" ]
Yes. In [documentation](http://www.erlang.org/doc/man/ets.html#select-2) there is example of `is_integer(X), is_integer(Y), X + Y < 4711`, or `[{is_integer, '$1'}, {is_integer, '$2'}, {'<', {'+', '$1', '$2'}, 4711}]`. If you are using `fun2ms` just write funciton with two clauses. ``` fun({X, Y}) when in_integer(X) andalso X > 5 -> Y; ({X, Y}) when is_integer(Y) andalso Y > 5 -> X. ``` But you could also create two `MatchFunctions`. Each consist `{MatchHead, [Guard], Return}`. Match head basically tells you how your data looks (is it a tuple, how many elements ...) and assigns to each element match variable `$N` where `N` will be some number. Lets say are using two-element tuples, so your match head would be `{'$1', '$2'}`. Now lets create guards: For first function we will assume something simple, like first argument is integer greater than 10. So first guard will be `{is_integer, '$2'}`, and second `{'>', '$2', 5}`. In both we use firs element of our match head `'$2'`. Second match function would have same guards, but with use of `'$1'`. And at last the return. Since we would like to just return one element, for first function it will be `'$1'`, and for second `'$2'` (returning tuple is little more complicated, since you would have to wrap it in additional on-element tuple). So finally, when put together it gives us ``` [ _FirstMatchFunction = {_Head1 = {'$1', '$2'}, _Guard1 = [{is_integer, '$2}, {'>', '$2', 5}], % second element matches _Return1 = [ '$1']}, % return first element _SecondMatchFunction = {_Head2 = {'$1', '$2'}, _Guard2 = [{is_integer, '$1}, {'>', '$1', 5}], % second element matches _Return2 = [ '$2']} ] % return first element ``` Havent had too much time to test it all, but it should work (maybe with minor tweaks).
328,965
I understand that Hamiltonian has to be hermitian. For a two level system, why does the general form of an Hamiltonian of a qubit have all real entries : $$ \hat{H} = \frac{1}{2}\left( \begin{array}{cc} \epsilon & \delta \\ \delta & -\epsilon \end{array} \right) $$ where $\epsilon$ as the offset between the potential energy and $\delta$ as the matrix element for tunneling between them. Or equivalently in the following form why is there an absence of $\sigma\_y$ term: $$H=\frac{1}{2} \delta\sigma\_x + \frac{1}{2}\epsilon\sigma\_z \,.$$
2017/04/25
[ "https://physics.stackexchange.com/questions/328965", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/75725/" ]
Perfectly incompressible bodies are actually prohibited by stability of thermodynamic equilibrium (entropy maximization). Section 21 of Landau & Lifshitz Vol 5: *Statistical Physics* has a nice discussion and derivation of the general thermodynamic inequality $C\_V > 0$. So the equation of state $T = T(V)$ is pathological, and lets you derive all sorts of silly results: Assume that $T = T(V)$, and imagine going from $(P\_1,V\_1) \to (P\_1,V\_2)$ in two different ways. On one hand, you can just go from $V\_1 \to V\_2$ at fixed $P = P\_1$. The change in internal energy is $\Delta U = Q\_1 + P\_1 (V\_1 - V\_2)$ by the first law. On the other hand, you can also go along the path $(P\_1, V\_1) \to (0,V\_1) \to (0,V\_2) \to (P\_1,V\_2)$. The first and third legs must have $\Delta U = 0$ because nothing depends on $P$. The second leg will have $\Delta U = Q\_0$. If internal energy is a state variable, then these should be equal: $$ Q\_1 + P\_1(V\_1 - V\_2) = Q\_0 $$ Here $Q\_1$ is the amount of heat needed to change the temperature of the body from $T(V\_1)$ to $T(V\_2)$ at $P = P\_1$, and $Q\_0$ is the amount of heat needed to change the temperature of the body from $T(V\_1)$ to $T(V\_2)$ at $P = 0$. The equation above says that these must differ. But this contradicts the original assumption that the equation of state $T = T(V)$ is independent of $P$!
18,545,018
I have two Textviews in a RelativeLayout like this: ``` <RelativeLayout> <TextView android:id="@+id/title" android:layout_width="wrap_content" android:layout_height="wrap_content" (*) android:layout_above="@+id/message" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" /> <ScrollView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1"> <TextView android:id="@+id/message" android:layout_width="302dp" android:layout_height="wrap_content" android:layout_above="@+id/editText1"/> </ScrollView> ``` I want the Textview id'd "message" to be scrollable. So I added it within a ScrollView but where I have put a star (android:layout\_above) I am getting the error: @+id/message is not a sibling in the same RelativeLayout How do I fix this? Any help is appreciated
2013/08/31
[ "https://Stackoverflow.com/questions/18545018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2693419/" ]
First of all you have to remove **"+"** from This `android:layout_above="@+id/message"` To ``` android:layout_above="@id/message" ``` And use TextView's scrolling method rather than scrollview ``` <TextView android:scrollbars="vertical" // Add this to your TextView in .xml file android:maxLines="ANY_INTEGER" // also add the maximum line android:id="@+id/message" android:layout_width="302dp" android:layout_height="wrap_content" android:layout_above="@id/editText1"/> ``` Then after in your .java file add following methods for your textview above. ``` TextView message = (TextView) findViewById(R.id.message); message.setMovementMethod(new ScrollingMovementMethod()); ```
63,515,655
I was solving the basic problem of finding the number of distinct integers in a given array. My idea was to declare an `std::unordered_set`, insert all given integers into the set, then output the size of the set. Here's my code implementing this strategy: ``` #include <iostream> #include <fstream> #include <cmath> #include <algorithm> #include <vector> #include <unordered_set> using namespace std; int main() { int N; cin >> N; int input; unordered_set <int> S; for(int i = 0; i < N; ++i){ cin >> input; S.insert(input); } cout << S.size() << endl; return 0; } ``` This strategy worked for almost every input. On other input cases, it timed out. I was curious to see *why* my program was timing out, so I added an `cout << i << endl;` line inside the for-loop. What I found was that when I entered the input case, the first `53000` or so iterations of the loop would pass nearly instantly, but afterwards only a few `100` iterations would occur each second. I've read up on how a hash set can end up with `O(N)` insertion if a lot of collisions occur, so I thought the input was causing a lot of collisions within the `std::unordered_set`. However, this is not possible. The hash function that the `std::unordered_set` uses for integers maps them to themselves (at least on my computer), so no collisions would ever happen between different integers. I accessed the hash function using the code written on [this link](https://www.geeksforgeeks.org/unordered_set-hash_function-in-c-stl/#:%7E:text=The%20unordered_set%3A%3Ahash_function(),type%20size_t%20based%20on%20it.). My question is, is it possible that the input itself is causing the `std::unordered_set` to slow down after it hits around `53000` elements inserted? If so, why? **[Here](https://www.writeurl.com/text/3l8roj635wdkiws2vb2d/rnpxybe1s664o8p03pwt) is the input case that I tested my program on. It's pretty large, so it might lag a bit.**
2020/08/21
[ "https://Stackoverflow.com/questions/63515655", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14023031/" ]
The input file you've provided consists of successive integers congruent to `1` modulo `107897`. So what is most likely happening is that, at some point when the load factor crosses a threshold, the particular library implementation you're using resizes the table, using a table with `107897` entries, so that a key with hash value `h` would be mapped to the bucket `h % 107897`. Since each integer's hash is itself, this means all the integers that are in the table so far are suddenly mapped to the same bucket. This resizing itself should only take linear time. However, each subsequent insertion after that point will traverse a linked list that contains all the existing values, in order to make sure it's not equal to any of the existing values. So each insertion will take linear time until the next time the table is resized. In principle the `unordered_set` implementation could avoid this issue by also resizing the table when any one bucket becomes too long. However, this raises the question of whether this is a hash collision with a reasonable hash function (thus requiring a resize), or the user was just misguided and hashed every key to the same value (in which case the issue will persist regardless of the table size). So maybe that's why it wasn't done in this particular library implementation. See also <https://codeforces.com/blog/entry/62393> (an application of this phenomenon to get points on Codeforces contests).
57,380,963
I am using Spring Webflux, and I need to return the ID of user upon successful save. Repository is returning the Mono ``` Mono<User> savedUserMono = repository.save(user); ``` But from controller, I need to return the user ID which is in object returned from save() call. I have tried using doOn\*, and subscribe(), but when I use return from subscribe, there is an error 'Unexpected return value'
2019/08/06
[ "https://Stackoverflow.com/questions/57380963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1037492/" ]
Any time you feel the need to *transform* or *map* what's in your `Mono` to something else, then you use the `map()` method, passing a lambda that will do the transformation like so: ``` Mono<Integer> userId = savedUserMono.map(user -> user.getId()); ``` (assuming, of course, that your user has a `getId()` method, and the `id` is an integer.) In this simple case, you could also use optionally use the double colon syntax for a more concise syntax: ``` Mono<Integer> userId = savedUserMono.map(User::getId); ``` The resulting `Mono`, when subscribed, will then emit the user's ID.
18,454,052
I'm wondering if I will miss any data if I replace a trigger while my oracle database is in use. I created a toy example and it seems like I won't, but one of my coworkers claims otherwise. ``` create table test_trigger (id number); create table test_trigger_h (id number); create sequence test_trigger_seq; --/ create or replace trigger test_trigger_t after insert on test_trigger for each row begin insert into test_trigger_h (id) values (:new.id); end; / --/ begin for i in 1..100000 loop insert into test_trigger (id) values (test_trigger_seq.nextval); end loop; end; / --/ begin for i in 1..10000 loop execute immediate 'create or replace trigger test_trigger_t after insert on test_trigger for each row begin insert into test_trigger_h (id) values (:new.id); end;'; end loop; end; / ran the two loops at the same time select count(1) from test_trigger; COUNT(1) 100000 select count(1) from test_trigger_h; COUNT(1) 100000 ```
2013/08/26
[ "https://Stackoverflow.com/questions/18454052", "https://Stackoverflow.com", "https://Stackoverflow.com/users/558585/" ]
`create or replace` is locking the table. So all the inserts will wait until it completes. Don't worry about missed inserts.
48,735,869
I opened up localhost:9870 and try to upload a txt file to the hdfs. I see the error message below ``` Failed to retrieve data from /webhdfs/v1/?op=LISTSTATUS: Server Error ```
2018/02/11
[ "https://Stackoverflow.com/questions/48735869", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8824687/" ]
I had the same issue with JDK 9. The fix for me was to add this line in hadoop-env.sh > > export HADOOP\_OPTS="--add-modules java.activation" > > > Thats because java.activation package is deprecated in Java 9.
33,625,063
I haven't long time in touch with C language. I have some questions related to chinese words and strncpy. ``` char* testString = "你好嗎?" sizeof(testString) => it prints out 4. strlen(testString) => it prints out 10. ``` When i want to copy to another char array, i have some issue. char msgArray[7]; /\* This is just an example. Due to some limitation, we have limited the buffer size. \*/ If i want to copy the data, i need to check ``` if (sizeof(testString) < sizeof(msgArray)) { strncopy(msgArray, testString, sizeof(msgArray)); } ``` It will have problem. The result is it will only copy a partial data. Actually it should have compared with ``` if (strlen(testString) < sizeof(msgArray)) { } else { printf("too long"); } ``` But i don't understand why it happened. If i want to define to limit the characters count (including unicode (eg. chinese characters), how can i achieve to define the array? I think i can't use the char[] array. Thanks a lot for all the responses. My workaround solution: I finally decide to cut the strings to meet the limited bytes.
2015/11/10
[ "https://Stackoverflow.com/questions/33625063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3733534/" ]
Pointers are not arrays. `testString` is a pointer and therefore, `sizeof(testString)` will give the size of pointer instead of the string it points to. `strlen` works differently and only for null terminated `char` arrays and string literals. It gives the length of the string preceding the null character.
45,007,249
In my code:(works well on tf1.0) ``` from tensorflow.contrib.rnn.python.ops import core_rnn from tensorflow.contrib.rnn.python.ops import core_rnn_cell from tensorflow.contrib.rnn.python.ops import core_rnn_cell_impl ``` report error with tf1.2: from tensorflow.contrib.rnn.python.ops import core\_rnn ImportError: cannot import name 'core\_rnn'
2017/07/10
[ "https://Stackoverflow.com/questions/45007249", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4344990/" ]
Here you go with the solution <https://jsfiddle.net/w0nefkfo/> ```js $('button').prop('disabled', true); setTimeout(function(){ $('button').prop('disabled', false); }, 2000); ``` ```html <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button type="submit" value="submit">Submit</button> ```
31,355,287
I'm a learner of C++ and I'm currently making my assignment and I can't seem to update my value. It's a must to use define for the balance: ``` #define balance 5000.00 ``` In the end of the statement I can't seem to able to update my balance: ``` printf("Deposit Successful!\nYou have deposited the following notes : \n"); printf("RM100 x %d = RM %.2f\n",nd100,td100); printf("RM 50 x %d = RM %.2f\n",nd50,td50); printf("RM 20 x %d = RM %.2f\n",nd20,td20); printf("RM 10 x %d = RM %.2f\n\n",nd10,td10); dtotal=td100+td50+td20+td10; printf(" TOTAL = RM %.2f\n\n",dtotal); newbalance=5000+dtotal; printf("Your current balance is RM %.2f\n\n",newbalance); ``` I want to update my `newbalance` to become my balance so that I can continue with my Withdrawal. I can show a bit of my Withdrawal ``` printf("\nWithdrawal Successful!\n"); printf("%d notes x RM 50 = RM%d.00\n",wnotes,wamount); printf("Your current balance is RM %.2f\n\n",newbalance); ``` Please do give me some suggestions.
2015/07/11
[ "https://Stackoverflow.com/questions/31355287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5105438/" ]
`#define`s are directives to the so called preprocessor. This is transforming the source code of your programm by textual substitution before it is actually compiled. When you write something like: ``` #define value 42; printf("%d", value); ``` then the compiler effectively sees ``` printf("%d", 42); ``` This happens completely at (or better before) compile time and is in no way related to the runtime of the programm, i.e. when it gets executed. What your looking for are variables, though I'd advise looking for a tutorial or book, since that is a very basic aspect of the language, and explaining everything here is out of the scope of this answer. They allow mutating values during the execution of the programm: ``` int main(int argc, char ** argc) { int counter = 0; for (; counter < 10; ++counter ) { printf("counter is %d\n", counter); } return 0; } ``` For the sake of completeness, you actually can change the meaning of a define somewhere in the source code: ``` #undef SOMETHING #define SOMETHING 21 // for the rest of this TEXT (!) every occurrence // of SOMETHING will be replaced with 21 ``` [Source](https://gcc.gnu.org/onlinedocs/cpp/Undefining-and-Redefining-Macros.html) Effectively you should see defines as separate language, and not touch them unless you're really knowing what you're doing. --- **Note:** I used code in this answer that would be fine both for a C and C++ compiler. You state that you're learning C++, but then you shouldn't be using `printf` but rather the facilities of `iostream`, e.g. ``` std::cout << "Hello World" << std::endl; ```
832,362
In my calculus III textbook, the following sentence is causing trouble for me and preventing me from understanding the theory behind Lagrange multipliers. > > "Since the gradient vector for a given function is orthogonal to its level curves at any given point, for a level curve of $f$ to be tangent to the constraint curve $g(x,y) = 0$, the gradients of $f$ and $g$ must be parallel" > > > There are bits and pieces I understand, but I'm missing the holistic picture that will put my mind at ease. I'm quite certain that I understand that for a given curve $f(x,y)$, its gradient will be tangent to the level surface $f(x,y,z) = k$ because its directional derivative will be $0$. Specifically, I'm hung up on the idea that they **must be parallel** I cannot directly see how the case where they are anti-parallel isn't possible. Furthermore, I'm not sure why the constraint curve $g(x,y)$ is set to $0$ in this explanation. If someone could explain in detail the ideas behind this sentence, I would appreciate it.
2014/06/12
[ "https://math.stackexchange.com/questions/832362", "https://math.stackexchange.com", "https://math.stackexchange.com/users/156816/" ]
Let $\displaystyle a = \prod\_{p\text{ is prime}}p^{i\_p}$, $\displaystyle b = \prod\_{p\text{ is prime}}p^{j\_p}$, and $\displaystyle c = \prod\_{p\text{ is prime}}p^{k\_p}$. Then $\displaystyle (a,b,c) = \prod\_{p\text{ is prime}}p^{\min\{i\_p,j\_p,k\_p\}}$ and $\displaystyle [a,b,c] = \prod\_{p\text{ is prime}}p^{\max\{i\_p,j\_p,k\_p\}}$. Hence $\displaystyle (a,b,c)[a,b,c] = \prod\_{p\text{ is prime}}p^{\min\{i\_p,j\_p,k\_p\}+\max\{i\_p,j\_p,k\_p\}}$ and $\displaystyle abc = \prod\_{p\text{ is prime}}p^{i\_p+j\_p+k\_p}$. This means $\min\{i\_p,j\_p,k\_p\}+\max\{i\_p,j\_p,k\_p\} = i\_p+j\_p+k\_p$. Suppose for some prime $p$, we have $0<i\_p$. What are the possibilities for $j\_p,k\_p$? If either $j\_p=0$ or $k\_p=0$, then $\min\{i\_p,j\_p,k\_p\}=0$. That implies $\max\{i\_p,j\_p,k\_p\} = i\_p+j\_p+k\_p$. Can you show that equality holds if and only if $j\_p=k\_p=0$? Next, if both $j\_p>0$ and $k\_p>0$, then without loss of generality, we have $0<i\_p\le j\_p\le k\_p$, so $\min\{i\_p,j\_p,k\_p\}+\max\{i\_p,j\_p,k\_p\} = i\_p+k\_p \neq i\_p+j\_p+k\_p$, so it cannot be that both $j\_p>0$ and $k\_p>0$. That leaves only the possibility that both are zero. That shows $(a,b)=(a,c)=1$, and a similar argument shows $(b,c)=1$.
57,377,905
I have a deep network using Keras and I need to apply cropping on the output of one layer and then send to the next layer. for this aim, I write the following code as a lambda layer: ``` def cropping_fillzero(img, rate=0.6): # Q = percentage residual_shape = img.get_shape().as_list() h, w = residual_shape[1:3] blacked_pixels = int((rate) * (h*w)) ratio = int(np.floor(np.sqrt(blacked_pixels))) # width = int(np.ceil(np.sqrt(blacked_pixels))) x = np.random.randint(0, w - ratio) y = np.random.randint(0, h - ratio) cropingImg = img[y:y+ratio, x:x+ratio].assign(tf.zeros([ratio, ratio])) return cropingImg decoded_noise = layers.Lambda(cropping_fillzero, arguments={'rate':residual_cropRate}, name='residual_cropout_attack')(bncv11) ``` but it produces the following error and I do not know why?! > > Traceback (most recent call last): > > > File "", line 1, in > runfile('E:/code\_v28-7-19/CIFAR\_los4x4convolvedw\_5\_cropAttack\_RandomSize\_Pad.py', > wdir='E:/code\_v28-7-19') > > > File > "D:\software\Anaconda3\envs\py36\lib\site-packages\spyder\_kernels\customize\spydercustomize.py", > line 704, in runfile > execfile(filename, namespace) > > > File > "D:\software\Anaconda3\envs\py36\lib\site-packages\spyder\_kernels\customize\spydercustomize.py", > line 108, in execfile > exec(compile(f.read(), filename, 'exec'), namespace) > > > File > "E:/code\_v28-7-19/CIFAR\_los4x4convolvedw\_5\_cropAttack\_RandomSize\_Pad.py", > line 143, in > decoded\_noise = layers.Lambda(cropping\_fillzero, arguments={'rate':residual\_cropRate}, > name='residual\_cropout\_attack')(bncv11) > > > File > "D:\software\Anaconda3\envs\py36\lib\site-packages\keras\engine\base\_layer.py", > line 457, in **call** > output = self.call(inputs, \*\*kwargs) > > > File > "D:\software\Anaconda3\envs\py36\lib\site-packages\keras\layers\core.py", > line 687, in call > return self.function(inputs, \*\*arguments) > > > File > "E:/code\_v28-7-19/CIFAR\_los4x4convolvedw\_5\_cropAttack\_RandomSize\_Pad.py", > line 48, in cropping\_fillzero > cropingImg = img[y:y+ratio, x:x+ratio].assign(tf.zeros([ratio, ratio])) > > > File > "D:\software\Anaconda3\envs\py36\lib\site-packages\tensorflow\python\ops\array\_ops.py", > line 700, in assign > raise ValueError("Sliced assignment is only supported for variables") > > > ValueError: Sliced assignment is only supported for variables > > > could you please tell me how can I solve this error? Thank you
2019/08/06
[ "https://Stackoverflow.com/questions/57377905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11013499/" ]
Use `pd.Grouper` along with `Country` and `City` as your `groupby` keys. I chose `60S` as the frequency, but change this as needed. --- ``` keys = ['Country', 'City', pd.Grouper(key='Datetime', freq='60S')] df.groupby(keys, sort=False).agg(Unit=('Unit', 'first'), count=('count', 'sum')) ``` ``` Unit count Country City Datetime USA NY 2019-08-03 13:32:00 00002 6 ITALY Roma 2019-08-03 07:47:00 00002 1 2019-08-03 07:26:00 00003 1 Spain Madrid 2019-08-03 07:47:00 00004 4 2019-08-03 07:58:00 00007 1 ```
51,917,574
I am new on using a Kinect sensor, I have Kinect XBOX 360 and I need to use it to get a real moving body 3D positions. I need to use it with c++ and openCV. I could not find anything helpful on the web. So, please if anyone can give me some advice or if there any code for opening Kinect XBOX 360 with c++ to start with I will appreciate that.
2018/08/19
[ "https://Stackoverflow.com/questions/51917574", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10245929/" ]
3 days ago, Our team had met this question. We spent a lot of time for that. Problem reason should be in AWS ecs-agent(we have 2 envrionment, one ecs-agent's version is 1.21 and another one is 1.24) Yesterday, We solved this problem: Using AWS console to update ecs-agent to the latest version: 1.34 and restart the ecs-agent(docker contianer) Then the problem was solved. Just paste this solution here. Hope it would be helpful to others!
18,820,233
I'm working on a CMS back-end with Codeigniter. Maybe it's not clear to state my question with word. So I use some simple html code to express my question: There is a html page called `A.html`. The code in `A.html` is following: ``` <html> <head> /*something*/ </head> <!-- menu area --> <div class="menu"> <ul class="nav"> <li class="nav-header">menu item1</li> <li class="nav-header">menu item2</li> <li class="nav-header">menu item3</li> </ul> </div> <!-- content area --> <div id="content"> </div> </html> ``` I know we can use jQuery's load to change the `#content`'s content when I click the `nav-header`.But my question is that how can I make content change just in the content area(`#content`) while the rest of page content stay same when I click the link in the content area(`#content`). I have tried the `iframe`,but it make the page more complex and I don't like it. Thanks. **UPDATE:** Another example:Such as, I click the "News List" menu item and then the `#content` change to show news list.Now I click the "Add news" link in the `#content`, How can I make the `#content` area show add news form while the rest of the page stay same.
2013/09/16
[ "https://Stackoverflow.com/questions/18820233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/669647/" ]
If you want all links to load content into `#content`, you can use this: ``` $(document).on('click', 'a', function(){ $('#content').load(this.href); }); ``` But this won't work for external links. If all your pages have the structure you described for A.html, you can add another div around `#content` (say, `#contentWrapper`), then use `.load` [like this](http://api.jquery.com/load/#loading-page-fragments): ``` $(document).on('click', 'a', function(){ $('#contentWrapper').load(this.href + ' #content'); }); ``` If you can't change the HTML, you can use `.get` instead, and replace the contents manually: ``` $(document).on('click', 'a', function(){ $('#content').get(this.href, function(data){ var content = $(data).find('#content').html(); $('#content').html(content); }); }); ```
131,444
We received a note from the security review team highlighting a CRUD/FLS vulnerability in our package and in the note it says there is a "Instances of SELECT vulnerability found across the application". An example provided is shown below in a "with sharing" class: > > myAttachments = [SELECT name, id, parentid, CreatedDate,CreatedById FROM Attachment WHERE parentid=:myAccount.id]; > > > If the user does not have access to the object or the field, the result will be null. So the FLS must be enforced. The documentation [here](https://developer.salesforce.com/page/Enforcing_CRUD_and_FLS) does not specify the issue. How can we resolve this issue?
2016/07/14
[ "https://salesforce.stackexchange.com/questions/131444", "https://salesforce.stackexchange.com", "https://salesforce.stackexchange.com/users/11790/" ]
I contacted Salesforce's Support team and they provided [this article](https://support.microsoft.com/en-us/kb/2994633) as a temporary fix. They also mentioned: > > "Our R&D team has investigated this matter and logged a New Issue for it to be repaired. Unfortunately, I cannot provide a timeline as to when this repair will be implemented due to Safe Harbor constraints." > > > [Salesforce Known Issue](https://success.salesforce.com/issues_view?id=a1p3A000000IZSEQA4)
6,877,117
I'm writing a small GUI program. Everything works except that I want to recognize mouse double-clicks. However, I can't recognize mouse clicks (as such) at all, though I can click buttons and select code from a list. The following code is adapted from Ingo Maier's "The scala.swing package": ``` import scala.swing._ import scala.swing.event._ object MouseTest extends SimpleGUIApplication { def top = new MainFrame { listenTo(this.mouse) // value mouse is not a member of scala.swing.MainFrame reactions += { case e: MouseClicked => println("Mouse clicked at " + e.point) } } } ``` I've tried multiple variations: mouse vs. Mouse, SimpleSwingApplication, importing MouseEvent from java.awt.event, etc. The error message is clear enough--no value mouse in MainFrame--so, where is it then? Help!
2011/07/29
[ "https://Stackoverflow.com/questions/6877117", "https://Stackoverflow.com", "https://Stackoverflow.com/users/303624/" ]
Maybe that way? ``` object App extends SimpleSwingApplication { lazy val ui = new Panel { listenTo(mouse.clicks) reactions += { case e: MouseClicked => println("Mouse clicked at " + e.point) } } def top = new MainFrame { contents = ui } } ``` BTW, `SimpleGUIApplication` is deprecated
29,044,357
I have a `main activity A` -> `call activity B` -> `call activity C` -> `call activity D`. Activity is called by `startActivity(intent).` `Activity D` have a "Close" button. How to I notify to `Activity A` when hit "close" button on `Activity D`? Any help is appreciated.
2015/03/14
[ "https://Stackoverflow.com/questions/29044357", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1773083/" ]
Try this: Use SharedPreference to store the status of button in Activity D. In activity A under onResume() get the status of button from the SharedPreference.
18,706,544
I'm currently using the latest release of bootstrap 3.0.0 The issue is simple. In the jumbotron container I use how do i center align the text with the logo I've been playing for hours, with col-md-\* and with little luck. In bootstrap 2.3.2 I achieved the effect of centering everything in hero by using `.text-center` and `.pagination center` (for the image?? - it worked) <http://jsfiddle.net/zMSua/> This fiddle shows the text and image im trying to center with bootstrap 3.0.0
2013/09/09
[ "https://Stackoverflow.com/questions/18706544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1408559/" ]
Here is another answer, that can center some content inside the actual div: ``` <head> <link href="http://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet"> <style> .centerfy img{ margin: 0 auto; } .centerfy{ text-align: center; } </style> </head> <body style=" padding: 10px;"> <div class="jumbotron"> <div class="container"> <div class="row well well-lg"> <div class="col-md-6 col-md-offset-3 centerfy"> <h1 class="">Home of the</h1> <div class=""> <img src="http://www.harrogatepoker.co.uk/profile/HPL%20V%20Logo%20%20Revised%20and%20Further%20reduced.jpg" class="img-responsive text-center" /> </div> <h2 class="">"All In", Fun!</h2> </div> </div> </div> </body> ``` Check the classes I added.
33,248,694
I am using pure javascript (no jquery or any other framework) for animations. Which one's more optimized? Creating classes for transition like: CSS class: ``` .all-div-has-this-class { transition: all 1s; } .class1 { left: 0; } .class2 { left: 30px; } ``` Javscript: ``` testdiv.className += " class1"; testdiv.className += " class2"; ``` or just this in javascript => Initialize the `testdiv` position in the css then just do`testdiv.style.left = "30px";` in the js code? By the way, these are all in setTimeout functions to set the properties according to timing. Also, it has to be only javascript without any jquery or any other framework specifically for animations.
2015/10/20
[ "https://Stackoverflow.com/questions/33248694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3141303/" ]
Hoisting moves function declarations and variable declarations to the top, but doesn't move assignments. Therefore, you first code becomes ``` var a; function f() { console.log(a.v); } f(); a = {v: 10}; ``` So when `f` is called, `a` is still `undefined`. However, the second code becomes ``` var a, f; a = {v: 10}; f = function() { console.log(a.v); }; f(); ``` So when `f` is called, `a` has been assigned.
3,638,312
When I use JTAG to load my C code to evaluation board, it loads successfully. However, when I executed my code from main(), I immediately got "CPU is not halted" error, followed by "No APB-AP found" error. I was able to load and executed the USB-related code before I got this error. I googled for it and use JTAG command "rx 0" to reset the target, but it does not make any change. I am using ARM Cortex-M3 Processor, J-Link ARM V4.14d, IAR Embedded workbench IDE. Thanks for ur help.
2010/09/03
[ "https://Stackoverflow.com/questions/3638312", "https://Stackoverflow.com", "https://Stackoverflow.com/users/310567/" ]
One possibility: **watchdog** If your hardware has a watchdog, then you must ensure that it does not reset the CPU when the JTAG wants to halt it. If the watchdog resets the CPU you would typically get a "CPU not halted" type of error you described. If the CPU has an internal watchdog circuit, on some CPUs it is automatically "paused" when the JTAG halts the CPU. But on others, that doesn't happen, and you need to ensure the watchdog is disabled while doing JTAG debugging. If your circuit has a watchdog circuit that is external to the CPU, then typically you need to be able to disable it in some way (typically the hardware designer provides some sort of switch/jumper on the board to do so).
69,263,443
I have extracted an email and save it to a text file that is not properly formatted. How to remove unwanted line spacing and paragraph spacing? The file looks like this: ``` Hi Kim, Hope you are fine. Your Code is: 42483423 Thanks and Regards, Bolt ``` I want to open and edit this file and arrange it in a proper format removing all the spaces before the text and below the text in the proper format like: ``` Hi Kim, Hope you are fine. Your Code is: 42483423 Thanks and Regards, Bolt ``` My start procedure, ``` file = open('email.txt','rw') ```
2021/09/21
[ "https://Stackoverflow.com/questions/69263443", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14364775/" ]
You can use `re.sub`: ``` import re re.sub('\s\s+', '\n', s) ```
514,828
So my understanding of one scenario that ZFS addresses is where a RAID5 drive fails, and then during a rebuild it encountered some corrupt blocks of data and thus cannot restore that data. From Googling around I don't see this failure scenario demonstrated; either articles on a disk failure, or articles on healing data corruption, but not both. 1) Is ZFS using 3 drive raidz1 susceptible to this problem? I.e. if one drive is lost, replaced, and data corruption is encountered when reading/rebuilding, then there is no redundancy to repair this data. My understanding is that the corrupted data will be lost, correct? (I do understand that periodic scrubbing will minimize the risk, but lets assume some tiny amount of corruption occurred on one disk since the last scrubbing, and a different disk also failed, and thus the corruption is detected during the rebuild) 2) Does raidz2 4 drive setup protect against this scenario? 3) Does a two drive mirrored setup with copies=2 would protect against this scenario? I.e. one drive fails, but the other drive contains 2 copies of all data, so if corruption is encountered during rebuild, there is a redundant copy on that disk to restore from? It's appealing to me because it uses half as many disks as the raidz2 setup, even though I'd need larger disks. I am not committed to ZFS, but it is what I've read the most about off and on for a couple years now. **It would be really nice if there were something similar to par archive/reed-solomon that generates some amount of parity that protects up to 10% data corruption and only uses an amount of space proportional to how much *x*% corruption protection you want.** Then I'd just use a mirror setup and each disk in the mirror would contain a copy of that parity, which would be relatively small when compared to option #3 above. Unfortunately I don't think reed-solomon fits this scenario very well. I've been reading an old NASA document on implementing reed-solomon(the only comprehensive explanation I could find that didn't require buying a journal articular) and as far as I my understanding goes, the set of parity data would need to be completely regenerated for each incremental change to the source data. I.e. there's not an easy way to do incremental changes to the reed-solomon parity data in response to small incremental changes to the source data. **I'm wondering though if there's something similar in concept(proportionally small amount of parity data protecting X% corruption ANYWHERE in the source data) out there that someone is aware of, but I think that's probably a pipe dream.**
2013/06/11
[ "https://serverfault.com/questions/514828", "https://serverfault.com", "https://serverfault.com/users/15810/" ]
Mostly you get things right. 1. You can feel safe if only one drive fails out of raidz1 pool. If there is some corruption on one more drive some data would be lost forever. 2. You can feel safe if two out of 4 drives fail in raidz2 pool. If there is... and so on. 3. You can be mostly sure about that but for no reason. With `copies` ZFS tries to place block copies at least 1/8 of disk size apart. However if you will encounter problems with controller it can saturate all your pool with junk quickly. What you think about parity is mostly said about raidz. In case of ZFS data can be evenly split before replicating yielding higher possible IO. Or do you want to have your data with parity on the same disk? If disk silently fails you will lose all your data and parity. The good catchphrase about data consistency is "Are you prepared for the fire?" When computer burns every single disk inside burns. There is a possibility of catching fire despite it's occurrence would be lower then of full disk fail. Full disk fail is almost common yet partial disk fail occurs more often. If I'd like to secure my data I'd first check in which category this falls. If I want to survive any known disaster I'd rather think of remote nodes and distant replication at first place. Next would be drive failure so I wouldn't bother with mirrors or copies, zraid2 or zraid3 is a nice thing to have, just build it from bigger set of different disks. You known, disks from the same distribution tends to fail in common circumstances... And ZFS mirror covers anything about partial disk failure. When some disk start showing any errors I'll throw in a third one, wait when the data be synced and only then I'll detach failed drive.
24,322,973
I want to test database performance and understand how database throughput (in terms of transactions per second) depends on disk properties like IO latency and variation, write queue length, etc. Ideally, I need a simulator that can be mounted as a disk volume and has a RAM disk inside wrapped into a controller that allows to set desired IO profile in terms of latency, throughput, stability etc. I wonder is there such a simulator for Linux or what is the best way to write it in C?
2014/06/20
[ "https://Stackoverflow.com/questions/24322973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1128016/" ]
You declare globals inside function scope. Try to declare them at class scope: ``` class Someclass{ function topFunction() { function makeMeGlobal($var) { global $a, $b; $this->a = "a".$var; $this->b = "b".$var; } makeMeGlobal(1); echo $this->a . "<br>"; echo $this->b . " <br>"; makeMeGlobal(2); echo $this->a . "<br>"; echo $this->b . "<br>"; } } ```
69,152,970
I am trying to generate CSV files from a set of records from Excel. Column A is the file name and the rest of the columns are the data to write to the the file. As of now, I am using `WriteLine`, but it doesn't work as expected: [![Example of input and output data](https://i.stack.imgur.com/l3IUo.png)](https://i.stack.imgur.com/l3IUo.png) As you can see, I don't get the expected output. How do I get the expected output? ```vb Private Sub ommandButton1_Click() Dim Path As String Dim Folder As String Dim Answer As VbMsgBoxResult Path = "C:\Access Permissions\Users" Folder = Dir(Path, vbDirectory) If Folder = vbNullString Then '-------------Create Folder ----------------------- MkDir ("C:\Access Permissions") MkDir ("C:\Access Permissions\Roles") MkDir ("C:\Access Permissions\Users") Else Set rngSource = Range("A4", Range("A" & Rows.Count).End(xlUp)) rngSource.Copy Range("AA1") Range("AA:AA").RemoveDuplicates Columns:=1, Header:=xlNo Set rngUnique = Range("AA1", Range("AA" & Rows.Count).End(xlUp)) Set lr = Cells(rngSource.Rows.Count, rngSource.Column) Set fso = CreateObject("Scripting.FileSystemObject") For Each cell In rngUnique n = Application.CountIf(rngSource, cell.Value) Set C = rngSource.Find(cell.Value, lookat:=xlWhole, after:=lr) Set oFile = fso.CreateTextFile("C:\Access Permissions\Users\" & cell.Value & "-Users.csv") For i = 1 To n oFile.WriteLine C.Offset(0, 1).Value oFile.WriteLine C.Offset(0, 2).Value oFile.WriteLine C.Offset(0, 3).Value oFile.WriteLine C.Offset(0, 4).Value oFile.WriteLine C.Offset(0, 6).Value oFile.WriteLine C.Offset(0, 7).Value Set C = rngSource.FindNext(C) Next i Next cell rngUnique.ClearContents MsgBox "Individual Users.csv files got generated" & vbCrLf & " " & vbCrLf & "Path - C:\Access Permissions\Groups " End If End Sub ``` **Updated Image**: ![Updated Image](https://i.stack.imgur.com/JhYv7.png) Let me re-phrase my questions. Updated Image Enclosed. 1. Using the Data Set [Updated Image point 1], It creates unique CSV files based on column A. 2. File got saved at the path given. 3. As of now the row data associated with each file name got written in the files but in a new line manner. 4. As expected, how the output can be written in Columns.[ Updated Image Point 4] 5. Given code is working without any error. 5.1. I just need to click twice if the Path folder does not exist. 5.2. at first click, it creates the Folder at the given path. 5.3. at Second click it generates the unique files, with its records. If you can please guide me on how the records can be written in columns [ Updated Image Point 4 ], expected output. [Download File](https://drive.google.com/file/d/15N0jWuUqrRhMtelk-2XTLB5RseduyUSI/view?usp=sharing)
2021/09/12
[ "https://Stackoverflow.com/questions/69152970", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13611682/" ]
``` @echo off for /F "skip=1" %%a in ('dir /B /S D:\TargetFolder\Settings.txt 2^>NUL') do ( del /Q /S D:\TargetFolder\Settings.txt >NUL goto break ) :break ``` The `for /F` loop process file names from `dir /S` command, but the first one is skipped (because `"skip=1"`switch), that is to say, if there are *more than one file*, the next commands are executed. The first command in the `for` deletes all files with "Settings.txt" name and the `for` is break because the `goto` command.
10,992,077
I have this fiddle and i would like to make it count the number of boxes that are selected. Now it shows the numbers of the boxes. Any idea how to do it?? ``` $(function() { $(".selectable").selectable({ filter: "td.cs", stop: function(){ var result = $("#select-result").empty(); var result2 = $("#result2"); $('.ui-selecting:gt(31)').removeClass("ui-selecting"); if($(".ui-selected").length>90) { $(".ui-selected", this).each(function(i,e){ if(i>3) { $(this).removeClass("ui-selected"); } }); return; } $(".ui-selected", this).each(function(){ var cabbage = this.id + ', '; result.append(cabbage); }); var newInputResult = $('#select-result').text(); newInputResult = newInputResult.substring(0, newInputResult.length - 1); result2.val(newInputResult); } }); }); ``` **jsfiddle:** <http://jsfiddle.net/dw6Hf/44/> Thanks
2012/06/12
[ "https://Stackoverflow.com/questions/10992077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1421432/" ]
Just try this withih `stop()`: ``` $(".ui-selected").length ``` **[DEMO](http://jsfiddle.net/dw6Hf/46/)** ### NOTE To get all selected div you need to place above code like following: ``` alert($(".ui-selected").length); // here to place if ($(".ui-selected").length > 4) { $(".ui-selected", this).each(function(i, e) { if (i > 3) { $(this).removeClass("ui-selected"); } }); return; // because you've used a return here } alert($(".ui-selected").length); // so not to place here ```
52,772,908
[![](https://i.stack.imgur.com/PfIiJ.gif)](https://i.stack.imgur.com/PfIiJ.gif) How do I develop the above gif image using Unity3D?
2018/10/12
[ "https://Stackoverflow.com/questions/52772908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6008065/" ]
why don't you just use CSS to do the job? ```css .uppercase{ text-transform: uppercase; } ``` ```html <input class="uppercase" type="text" placeholder="type here"> ```
32,216,118
I have a nested class structure where when I instantiate the top level class it instantiates a bunch of objects of other classes as attributes, and those instantiate a few other classes as their own attributes. As I develop my code I want to override a class definition in a new module (this would be a good way for me to avoid breaking existing functionality in other scripts while adding new functionality). As a toy example, there is a module where I define two classes where one has a list of the other, Deck and Card. When I instantiate a Deck object it instantiates a list of Card objects. **module\_1.py** ``` class Card(object): def __init__(self, suit, number): self.suit = suit self.number = number class Deck(object): def __init__(self): suit_list = ['heart', 'diamond', 'club', 'spade'] self.cards = [] for suit in suit_list: for number in range(14): self.cards.append(Card(suit, number)) ``` I have another type of Card and I want to make a Deck of those, so I import Deck into a new module and define a new Card class in the new module, but when I instantiate Deck, it has cards from module\_1.py **module\_2.py** ``` from module_1 import Deck class Card(object): def __init__(self, suit, number): self.suit = suit self.number = number self.index = [suit, number] if __name__ == '__main__': new_deck = Deck() print new_deck.cards[0] ``` Output: ``` >python module_2.py <module_1.Card object at 0x000001> ``` Is there some way that I can use my Deck class from module\_1.py but have it use my new Card class? Passing the class definition is cumbersome because the actual case is deeply nested and I may want to also develop other classes contained within the top level object. Also, I expected this to be consistent with object oriented paradigms. Is it?
2015/08/26
[ "https://Stackoverflow.com/questions/32216118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5266259/" ]
Make the Card class an optional parameter to the Deck instance initializer that defaults to your initial Card class, and override it by passing a second parameter of your second Card class when you initialize a deck of your new cards. **EDIT** Made names more Pythonic and made index a tuple as suggested by cyphase . ``` class Card(object): def __init__(self, suit, number): self.suit = suit self.number = number class Deck(object): def __init__(self, card_type=Card): suit_list = ['heart', 'diamond', 'club', 'spade'] self.cards = [] for suit in suit_list: for number in range(14): self.cards.append(card_type(suit, number)) ``` Your second module will pass its Card class into the Deck: ``` from module_1 import Deck class FancyCard(object): def __init__(self, suit, number): self.suit = suit self.number = number self.index = suit, number if __name__ == '__main__': new_deck = Deck(FancyCard) print new_deck.cards[0] ```
3,515,059
I have some objects on the screen and would like to rotate only one of them. I tried using the glRotatef(...) function but turns out glRotatef(...) rotates all my objects (rotates the camera, maybe?). How can I rotate only one? I use openGL ES 1.1
2010/08/18
[ "https://Stackoverflow.com/questions/3515059", "https://Stackoverflow.com", "https://Stackoverflow.com/users/110028/" ]
You need the rotation to be in effect only when the geometry you're interested in is being drawn. ``` ... draw stuff ... glPushMatrix(); glRotatef(angle, 0, 1, 0); ... draw rotated stuff ... glPopMatrix(); ... draw more stuff ... ```
2,957,996
Im stuck, Im setting a variable when someone clicks, then testing with if to see if the variable exists and doing something else. Its a simple script which Im probably overthinking, would love someone's thoughts. ``` $('.view-alternatives-btn').live('click', function() { //$("#nc-alternate-wines").scrollTo(); //$('.nc-remove').toggle(); var showBtn = null; if (showBtn == null) { $('.view-alternatives-btn img').attr("src","../images/wsj_hide_alternatives_btn.gif"); $('#nc-alternate-wines').show(); showBtn = 1; console.log(showBtn); } else if (showBtn == 1) { $('.view-alternatives-btn img').attr("src","../images/wsj_view_alternatives_btn.gif"); $('#nc-alternate-wines').hide(); console.log("this " + showBtn); } return false; }); ```
2010/06/02
[ "https://Stackoverflow.com/questions/2957996", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28454/" ]
You're *always* setting it to `null` when the button is clicked, so you'll never reach the `else if`... You might instead use a global variable, or [`$.data()`](http://api.jquery.com/jQuery.data/)
9,597,122
I have established a basic hadoop master slave cluster setup and able to run mapreduce programs (including python) on the cluster. Now I am trying to run a python code which accesses a C binary and so I am using the subprocess module. I am able to use the hadoop streaming for a normal python code but when I include the subprocess module to access a binary, the job is getting failed. As you can see in the below logs, the hello executable is recognised to be used for the packaging, but still not able to run the code. . . packageJobJar: [**/tmp/hello/hello**, /app/hadoop/tmp/hadoop-unjar5030080067721998885/] [] /tmp/streamjob7446402517274720868.jar tmpDir=null ``` JarBuilder.addNamedStream hello . . 12/03/07 22:31:32 INFO mapred.FileInputFormat: Total input paths to process : 1 12/03/07 22:31:32 INFO streaming.StreamJob: getLocalDirs(): [/app/hadoop/tmp/mapred/local] 12/03/07 22:31:32 INFO streaming.StreamJob: Running job: job_201203062329_0057 12/03/07 22:31:32 INFO streaming.StreamJob: To kill this job, run: 12/03/07 22:31:32 INFO streaming.StreamJob: /usr/local/hadoop/bin/../bin/hadoop job -Dmapred.job.tracker=master:54311 -kill job_201203062329_0057 12/03/07 22:31:32 INFO streaming.StreamJob: Tracking URL: http://master:50030/jobdetails.jsp?jobid=job_201203062329_0057 12/03/07 22:31:33 INFO streaming.StreamJob: map 0% reduce 0% 12/03/07 22:32:05 INFO streaming.StreamJob: map 100% reduce 100% 12/03/07 22:32:05 INFO streaming.StreamJob: To kill this job, run: 12/03/07 22:32:05 INFO streaming.StreamJob: /usr/local/hadoop/bin/../bin/hadoop job -Dmapred.job.tracker=master:54311 -kill job_201203062329_0057 12/03/07 22:32:05 INFO streaming.StreamJob: Tracking URL: http://master:50030/jobdetails.jsp?jobid=job_201203062329_0057 12/03/07 22:32:05 ERROR streaming.StreamJob: Job not Successful! 12/03/07 22:32:05 INFO streaming.StreamJob: killJob... Streaming Job Failed! ``` Command I am trying is : ``` hadoop jar contrib/streaming/hadoop-*streaming*.jar -mapper /home/hduser/MARS.py -reducer /home/hduser/MARS_red.py -input /user/hduser/mars_inputt -output /user/hduser/mars-output -file /tmp/hello/hello -verbose ``` where hello is the C executable. It is a simple helloworld program which I am using to check the basic functioning. My Python code is : ``` #!/usr/bin/env python import subprocess subprocess.call(["./hello"]) ``` Any help with how to get the executable run with Python in hadoop streaming or help with debugging this will get me forward in this. Thanks, Ganesh
2012/03/07
[ "https://Stackoverflow.com/questions/9597122", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1253987/" ]
Used simple id and hash token like Amazon for now...
10,945,303
I've started to learn PHP. `$_POST` variable is working in some of files, that I'm even able to post the data obtained through `$_POST` to database. Strangely, `$_POST` is not working in few files. I mean its inconsistent. Below is the html: ``` <html> <title></title> <head> </head> <body> <form method="POST" action="addemail.php"> <label for="firstname">First name:</label> <input type="text" id="firstname" name="firstname" /><br /> <label for="lastname">Last name:</label> <input type="text" id="lastname" name="lastname" /><br /> <label for="email">Email:</label> <input type="text" id="email" name="email" /><br /> <input type="submit" name="submit" value="Submit" /> </form> </body> </html> ``` And below is the PHP code: ``` <html> <body> <?php $first_name = $_POST['firstname']; $last_name = $_POST['lastname']; $email = $_POST['email']; print($first_name); $dcf = mysqli_connect('localhost','uname','XXX','elvis_store') or die('Error connecting to MYSQL Server.'); $query = "INSERT INTO email_list (first_name, last_name, email) " . "VALUES ('$first_name', '$last_name', '$email')"; $result = mysqli_query($dcf, $query); mysqli_close($dcf); ?> </body> </html> ``` Any pointers to overcome this issue will be of great help.
2012/06/08
[ "https://Stackoverflow.com/questions/10945303", "https://Stackoverflow.com", "https://Stackoverflow.com/users/840352/" ]
$\_POST should not have any consistency issues. It could be many things: **Possible Code Errors** 1. You misspelled a key name 2. Ensure that you actually set the values 3. Perhaps you are passing some variables via the URL www.example.com?var=x (GET) and then trying to reference `$_POST['var']` instead of `$_GET['var']` 4. Perhaps you did not actually POST to the page. If you are submitting from a form ensure the `method` attribute is set to `POST` (method="POST") I'm sure there are many other possibilities (like your dev environment), but it is unlikely that `$_POST` is inconsistent. I would need to see more code on your end. **Possible Environment/Usage Errors** 1. Ensure WAMP is started (It doesn't always auto start) 2. Ensure you are accessing your page via `http://localhost/path/file.php` and not trying to open it up straight from the folder it is in i.e. `C:\path\file.php`. It must run through Apache. i.e. Is it only `$_POST` that is not working? if you type `<?php echo "TEST"; ?>` in your script, doest it echo out `TEST`?
68,336,882
I have a Java servlet app running on Ubuntu 20.04.2 in Tomcat9 apache. The servlets are required to run using https transport. I am using a self signed certificate to enable https/TLS on Tomcat9. The servlet attempts to upload a file using a form that includes an html input tag with type file. On my local area network, tomcat is running on the machine with ip4 address 10.0.0.200. If I access the servlet from a browser on the same machine ( example ip4 address 10.0.0.200) as the tomcat server is running (example url <https://10.0.0.200:8443/MyServlet>), it works fine and the file is uploaded. If I access the servlet from a browser on a machine other than where the tomcat server is running (example from machine with ip4 address 10.0.0.30) the post request from form submit button **never reaches the servlet** (example url <https://10.0.0.200:8443/MyServlet> from machine 10.0.0.30). The browser (FireFox) reports: "An error occurred during a connection to 10.0.0.200:8443. PR\_CONNECT\_RESET\_ERROR The page you are trying to view cannot be shown because the authenticity of the received data could not be verified. Please contact the website owners to inform them of this problem." Why does this not work? This is recorded form post: ``` POST /TempClientServlet/TempResult undefined Host: 24.63.181.39:8443 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:89.0) Gecko/20100101 Firefox/89.0 Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate, br Content-Type: multipart/form-data; boundary=---------------------------3698066889622667783588722062 Content-Length: 970929 Origin: https://24.63.181.39:8443 Connection: keep-alive Referer: https://24.63.181.39:8443/TempClientServlet/TempResult Cookie: user_name=ccervo; textCookie=ccervo; JSESSIONID=401E418CE0A56EFB5A34784DE97DC996 Upgrade-Insecure-Requests: 1 ``` This is the web.xml file: ``` <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>TempClientServlet</display-name> <absolute-ordering /> <welcome-file-list> <welcome-file>TempClient</welcome-file> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <session-config> <cookie-config> <http-only>true</http-only> <secure>true</secure> </cookie-config> </session-config> <security-constraint> <web-resource-collection> <web-resource-name>secured page</web-resource-name> <url-pattern>/*</url-pattern> </web-resource-collection> <user-data-constraint> <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security-constraint> </web-app> ``` This is the server.xml file: ``` <?xml version="1.0" encoding="UTF-8"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --><!-- Note: A "Server" is not itself a "Container", so you may not define subcomponents such as "Valves" at this level. Documentation at /docs/config/server.html --> <Server port="8081" shutdown="SHUTDOWN"> <Listener className="org.apache.catalina.startup.VersionLoggerListener"/> <!--APR library loader. Documentation at /docs/apr.html --> <Listener SSLEngine="on" className="org.apache.catalina.core.AprLifecycleListener"/> <!-- Prevent memory leaks due to use of particular java/javax APIs--> <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener"/> <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"/> <Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"/> <!-- Global JNDI resources Documentation at /docs/jndi-resources-howto.html --> <GlobalNamingResources> <!-- Editable user database that can also be used by UserDatabaseRealm to authenticate users --> <Resource auth="Container" description="User database that can be updated and saved" factory="org.apache.catalina.users.MemoryUserDatabaseFactory" name="UserDatabase" pathname="conf/tomcat-users.xml" type="org.apache.catalina.UserDatabase"/> </GlobalNamingResources> <!-- A "Service" is a collection of one or more "Connectors" that share a single "Container" Note: A "Service" is not itself a "Container", so you may not define subcomponents such as "Valves" at this level. Documentation at /docs/config/service.html --> <Service name="Catalina"> <!--The connectors can use a shared executor, you can define one or more named thread pools--> <!-- <Executor name="tomcatThreadPool" namePrefix="catalina-exec-" maxThreads="150" minSpareThreads="4"/> --> <Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" /> <!-- uncomment this to run servlets secure ie. https --> <Connector SSLEnabled="true" clientAuth="false" keystoreFile="/home/foobar/.keystore" keystorePass="changeit" maxThreads="200" port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol" scheme="https" secure="true" sslProtocol="TLS" /> <!-- Define an AJP 1.3 Connector on port 8009 --> <!-- <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" /> --> <!-- An Engine represents the entry point (within Catalina) that processes every request. The Engine implementation for Tomcat stand alone analyzes the HTTP headers included with the request, and passes them on to the appropriate Host (virtual host). Documentation at /docs/config/engine.html --> <!-- You should set jvmRoute to support load-balancing via AJP ie : <Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1"> --> <Engine defaultHost="localhost" name="Catalina"> <!--For clustering, please take a look at documentation at: /docs/cluster-howto.html (simple how to) /docs/config/cluster.html (reference documentation) --> <!-- <Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/> --> <!-- Use the LockOutRealm to prevent attempts to guess user passwords via a brute-force attack --> <Realm className="org.apache.catalina.realm.LockOutRealm"> <!-- This Realm uses the UserDatabase configured in the global JNDI resources under the key "UserDatabase". Any edits that are performed against this UserDatabase are immediately available for use by the Realm. --> <Realm className="org.apache.catalina.realm.UserDatabaseRealm" resourceName="UserDatabase"/> </Realm> <Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true"> <!-- SingleSignOn valve, share authentication between web applications Documentation at: /docs/config/valve.html --> <!-- <Valve className="org.apache.catalina.authenticator.SingleSignOn" /> --> <!-- Access log processes all example. Documentation at: /docs/config/valve.html Note: The pattern used is equivalent to using pattern="common" --> <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" pattern="%h %l %u %t &quot;%r&quot; %s %b" prefix="localhost_access_log" suffix=".txt"/> <Context docBase="TempClientServlet" path="/TempClientServlet" reloadable="true" source="org.eclipse.jst.jee.server:TempClientServlet"/> <Context path="/TempClientServlet/images" docBase="/var/opt/TempClientServletimages" crossContext="true"/> <Context docBase="Temp_Service" path="/Temp_Service" reloadable="true" source="org.eclipse.jst.jee.server:Temp_Service"/> <Context docBase="Temp_ServiceClient" path="/Temp_ServiceClient" reloadable="true" source="org.eclipse.jst.jee.server:Temp_ServiceClient"/> </Host> </Engine> </Service> </Server> ```
2021/07/11
[ "https://Stackoverflow.com/questions/68336882", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10234883/" ]
This looks like a simple typo, you define ``` ... const productsDom = document.querySelector('.products-center') ... ``` but use ``` ... productsDOM.innerHTML = result; ... ``` in your function. Case sensitivity matters, so you get an error saying that `productsDOM` doesn't exist - it doesn't, `productsDom` exists instead.
7,042,626
I need to validate a number entered by a user in a textbox using JavaScript. The user should not be able to enter 0 as the first digit like 09, 08 etc, wherein he should be allowed to enter 90 , 9.07 etc.. Please help me.. I tried to use the below function but it disallows zero completely: ``` function AllowNonZeroIntegers(val) { if ((val > 48 && val < 58) || ((val > 96 && val < 106)) || val == 46 || val == 8 || val == 127 || val == 189 || val == 109 || val == 45 || val == 9) return true; return false; } ``` on ``` Texbox1.Attributes.Add("onkeypress", "return AllowNonZeroIntegers(event.keyCode)"); Texbox1.Attributes.Add("onkeydown", "return AllowNonZeroIntegers(event.keyCode)"); ```
2011/08/12
[ "https://Stackoverflow.com/questions/7042626", "https://Stackoverflow.com", "https://Stackoverflow.com/users/622096/" ]
Use `charAt()` to control the placement of X at Y: ``` function checkFirst(str){ if(str.charAt(0) == "0"){ alert("Please enter a valid number other than '0'"); } } ```
1,003,105
I'm trying to host a static website on Azure storage with a custom domain and HTTPS. I have created a storage account, uploaded my files, and enabled static site hosting. The site works nicely from the `<foo>.web.core.windows.net` domain provided by Azure. I have created a CDN endpoint for the site with the origin hostname set to the primary endpoint provided by Azure, added a custom domain for my `www` subdomain, provisioned a CDN-managed certificate for it, and added a rule to redirect non-HTTPS requests to `https://www.<my-domain>.com`. This also works well. Now I want my apex domain to redirect to my `www` subdomain. [CNAMEs aren't an option](https://serverfault.com/q/613829/374091), but I have added an alias `A` record for `@` pointing to my CDN endpoint and added the apex domain as a custom domain to the CDN. Requests to `http://<my-domain>.com` redirect nicely, but requests to `https://<my-domain>.com` understandably give a scary `SSL_ERROR_BAD_CERT_DOMAIN` error. [Azure does not support CDN-managed certificate for apex domains](https://docs.microsoft.com/en-us/azure/cdn/cdn-custom-ssl?tabs=option-1-default-enable-https-with-a-cdn-managed-certificate): > > CDN-managed certificates are not available for root or apex domains. If your Azure CDN custom domain is a root or apex domain, you must use the Bring your own certificate feature. > > > I don't want to actually host anything on my apex domain—I just want to redirect it to my `www` subdomain. Manually provisioning (and maintaining) a certificate seems like a lot of overhead. The domain registrar, GoDaddy, has a "forwarding" feature that did what I want, but I prefer to keep my DNS hosted with Azure. Is there a way to redirect apex domain HTTPS requests to my `www` subdomain without manually provisioning a certificate for my apex domain or moving my DNS out of Azure?
2020/02/14
[ "https://serverfault.com/questions/1003105", "https://serverfault.com", "https://serverfault.com/users/374091/" ]
You could automate certificates for the apex using Let's Encrypt, making the cert part a little more easy to handle. Other than that, you basically need to host a 301 redirect somewhere that talks both HTTP and HTTPS to get this to work, no shortcut I'm afraid, especially if you're going to be using HSTS. There are some DNS providers that actually support CNAMEs at the apex, but I'd be a bit hesitant trying those out.
59,956,586
We have just upgraded a .NET 4.6 project to .NET 4.8 and this function ``` Private Function MeasureTextSize(ByVal text As String, ByVal fontFamily As FontFamily, ByVal fontStyle As FontStyle, ByVal fontWeight As FontWeight, ByVal fontStretch As FontStretch, ByVal fontSize As Double) As Size Dim ft As New FormattedText(text, System.Globalization.CultureInfo.CurrentCulture, FlowDirection.LeftToRight, New Typeface(fontFamily, fontStyle, fontWeight, fontStretch), fontSize, Brushes.Black) Return New Size(ft.Width, ft.Height) End Function ``` Is showing the following warning ``` warning BC40000: 'Public Overloads Sub New(textToFormat As String, culture As CultureInfo, flowDirection As FlowDirection, typeface As Typeface, emSize As Double, foreground As Brush)' is obsolete: 'Use the PixelsPerDip override'. ``` Bearing in mind this is a module, how can this be corrected? Thank you
2020/01/28
[ "https://Stackoverflow.com/questions/59956586", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1956080/" ]
You have three options basically: * Create a visual and use the `GetDpi` method to get a value for the `pixelsPerDip` parameter: ``` VisualTreeHelper.GetDpi(new Button()).PixelsPerDip ``` * Define a static value yourself, e.g. `1.25`. * Ignore the warning and use the obsolete overload.
36,386,362
I'm about a couple weeks into learning Python. With the guidance of user:' Lost' here on Stackoverflow I was able to figure out how to build a simple decoder program. He suggested a code and I changed a few things but what was important for me was that I understood what was happening. I understand 97% of this code except for the `except: i += 1` line in the `decode()`. As of now the code works, but I want to understand that line. So basically this code unscrambles an encrypted word based on a specific criteria. You can enter this sample encrypted word to try it out. `"0C1gA2uiT3hj3S"` the answer should be `"CATS"` I tried replacing the except: `i += 1` with a Value Error because I have never seen a Try/Except conditional that just had an operational and no Error clause. But replacing it with Value Error created a never ending loop. My question is what is the purpose of writing the except: `i += 1` as it is. 'Lost' if you're there could you answer this question. Sorry, about the old thread ``` def unscramble(elist): answer = [] i = 0 while i <= len(elist): try: if int(elist[i]) > -1: i = i + int(elist[i]) + 1 answer.append(elist[i]) except: i += 1 return "".join(answer) def boom(): eword = input("paste in your encrypted message here >> ") elist = list(eword) answer = unscramble(elist) print (answer) clear() boom() ```
2016/04/03
[ "https://Stackoverflow.com/questions/36386362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3564925/" ]
You need to use a smaller fixed length buffer when reading from the socket, and then append the received data to a dynamically growing buffer (like a `std::string`, or a file) on each loop iteration. `recv()` tells you how many bytes were actually received, do not access more than that many bytes when accessing the buffer. ``` char buffer[1024]; std::string myString; int nDataLength; while ((nDataLength = recv(Socket, buffer, sizeof(buffer), 0)) > 0) { myString.append(buffer, nDataLength); } std::cout << myString << "\n"; ```
70,653,677
I would like to use nls to fit a global parameter and group-specific parameters. The closest I have found to a minimum reproducible example is below (found here: <https://stat.ethz.ch/pipermail/r-help/2015-September/432020.html>) ``` #Generate some data d <- transform(data.frame(x=seq(0,1,len=17), group=rep(c("A","B","B","C"),len=17)), y = round(1/(1.4+x^ifelse(group=="A", 2.3, ifelse(group=="B",3.1, 3.5))),2)) #Fit to model using nls nls(y~1/(b+x^p[group]), data=d, start=list(b=1, p=rep(3,length(levels(d$group))))) ``` This gives me an error: > > Error in numericDeriv(form[[3L]], names(ind), env, central = nDcentral) : > Missing value or an infinity produced when evaluating the model > > > I have not been able to figure out if the error is coming from bad guesses for the starting values, or the way this code is dealing with group-specific parameters. It seems the line with `p=rep(3,length(levels(d$group)))` is for generating `c(3,3,3)`, but switching this part of the code does not remove the problem (same error obtained as above): ``` #Fit to model using nls nls(y~1/(b+x^p[group]), data=d, start=list(b=1, p=c(3, 3, 3))) ``` Switching to nlsLM gives a different error which leads be to believe I am having an issue with the group-specific parameters: ``` #Generate some data library(minpack.lm) d <- transform(data.frame(x=seq(0,1,len=17), group=rep(c("A","B","B","C"),len=17)), y = round(1/(1.4+x^ifelse(group=="A", 2.3, ifelse(group=="B",3.1, 3.5))),2)) #Fit to model using nlsLM nlsLM(y~1/(b+x^p[group]), data=d, start=list(b=1, p=c(3,3,3))) ``` Error: > > Error in dimnames(x) <- dn : > length of 'dimnames' [2] not equal to array extent > > > Any ideas?
2022/01/10
[ "https://Stackoverflow.com/questions/70653677", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16491398/" ]
I think you can do this much more easily with `nlme::gnls`: ```r fit2 <- nlme::gnls(y~1/(b+x^p), params = list(p~group-1, b~1), data=d, start = list(b=1, p = rep(3,3))) ``` Results: ``` Generalized nonlinear least squares fit Model: y ~ 1/(b + x^p) Data: d Log-likelihood: 62.05887 Coefficients: p.groupA p.groupB p.groupC b 2.262383 2.895903 3.475324 1.407561 Degrees of freedom: 17 total; 13 residual Residual standard error: 0.007188101 ``` The `params` argument allows you to specify fixed-effect submodels for each nonlinear parameter. Using `p ~ b-1` parameterizes the model with a separate estimate for each group, rather than fitting a baseline (intercept) value for the first group and the differences between successive groups. (In R's formula language, `-1` or `+0` signify "fit a model without intercept/set the intercept to 0", which in this case corresponds to fitting all three groups separately.) I'm quite surprised that `gnls` and `nls` *don't* give identical results (although both give reasonable results); would like to dig in further ... [![points and fitted curves for nls and gnls](https://i.stack.imgur.com/AhUug.png)](https://i.stack.imgur.com/AhUug.png) Parameter estimates (code below): ``` term nls gnls 1 b 1.41 1.40 2 pA 2.28 2.28 3 pB 3.19 3.14 4 pC 3.60 3.51 ``` --- ```r par(las = 1, bty = "l") plot(y~x, data = d, col = d$group, pch = 16) xvec <- seq(0, 1, length = 21) f <- function(x) factor(x, levels = c("A","B","C")) ## fit1 is nls() fit ll <- function(g, c = 1) { lines(xvec, predict(fit1, newdata = data.frame(group=f(g), x = xvec)), col = c) } Map(ll, LETTERS[1:3], 1:3) d2 <- expand.grid(x = xvec, group = f(c("A","B","C"))) pp <- predict(fit2, newdata = d2) ll2 <- function(g, c = 1) { lines(xvec, pp[d2$group == g], lty = 2, col = c) } Map(ll2, LETTERS[1:3], 1:3) legend("bottomleft", lty = 1:2, col = 1, legend = c("nls", "gnls")) library(tidyverse) library(broom) library(broom.mixed) (purrr::map_dfr(list(nls=fit1, gnls=fit2), tidy, .id = "pkg") %>% select(pkg, term, estimate) %>% group_by(pkg) ## force common parameter names %>% mutate(across(term, ~ c("b", paste0("p", LETTERS[1:3])))) %>% pivot_wider(names_from = pkg, values_from = estimate) ) ```
47,629,259
I'm looking for a way to fit all views with the right zoom which in my app's instance is one annotation and userlocation and the whole polyline which signifies the route connecting the annotation and the userlocation. I have this code below which I call every time the map loads the mapview: ``` func mapViewDidFinishLoadingMap(_ mapView: MGLMapView) { if let location = mapView.userLocation?.location?.coordinate, let annotations = mapView.annotations { let coordinate = annotations.first?.coordinate mapView.setVisibleCoordinateBounds(MGLCoordinateBounds(sw: location, ne: coordinate!), edgePadding: UIEdgeInsetsMake(100, 50, 100, 200 ), animated: true) } } ``` This works well for coordinates where the routes are almost linear but when the routes are a bit more complicated and long it doesn't help.
2017/12/04
[ "https://Stackoverflow.com/questions/47629259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5328686/" ]
This method will give you the bounds on the polyline no matter how short or long it is. You need an array of locations somewhere in your VC being locationList: [CLLocation] in this example. ``` func setCenterAndBounds() -> (center: CLLocationCoordinate2D, bounds: MGLCoordinateBounds)? { let latitudes = locationList.map { location -> Double in return location.coordinate.latitude } let longitudes = locationList.map { location -> Double in return location.coordinate.longitude } let maxLat = latitudes.max()! let minLat = latitudes.min()! let maxLong = longitudes.max()! let minLong = longitudes.min()! let center = CLLocationCoordinate2D(latitude: (minLat + maxLat) / 2, longitude: (minLong + maxLong) / 2) let span = MKCoordinateSpan(latitudeDelta: (maxLat - minLat) * 1.3, longitudeDelta: (maxLong - minLong) * 1.3) let region = MKCoordinateRegion(center: center, span: span) let southWest = CLLocationCoordinate2D(latitude: center.latitude - (region.span.latitudeDelta / 2), longitude: center.longitude - (region.span.longitudeDelta / 2) ) let northEast = CLLocationCoordinate2D( latitude: center.latitude + (region.span.latitudeDelta / 2), longitude: center.longitude + (region.span.longitudeDelta / 2) ) return (center, MGLCoordinateBounds(sw: southWest, ne: northEast)) } ``` Then you can set the mapbox view like this: ``` func populateMap() { guard locationList.count > 0, let centerBounds = setCenterAndBounds() else { return } mapboxView.setCenter(centerBounds.center, animated: false) mapboxView.setVisibleCoordinateBounds(centerBounds.bounds, animated: true)} ```
66,569,955
I have the following data in a table: ``` GROUP1|FIELD Z_12TXT|111 Z_2TXT|222 Z_31TBT|333 Z_4TXT|444 Z_52TNT|555 Z_6TNT|666 ``` And I engineer in a field that removes the leading numbers after the '\_' ``` GROUP1|GROUP_ALIAS|FIELD Z_12TXT|Z_TXT|111 Z_2TXT|Z_TXT|222 Z_31TBT|Z_TBT|333 <- to be removed Z_4TXT|Z_TXT|444 Z_52TNT|Z_TNT|555 Z_6TNT|Z_TNT|666 ``` How can I easily query the original table for only GROUP's that correspond to GROUP\_ALIASES with only one Distinct FIELD in it? Desired result: ``` GROUP1|GROUP_ALIAS|FIELD Z_12TXT|Z_TXT|111 Z_2TXT|Z_TXT|222 Z_4TXT|Z_TXT|444 Z_52TNT|Z_TNT|555 Z_6TNT|Z_TNT|666 ``` This is how I get all the GROUP\_ALIAS's I don't want: ``` SELECT GROUP_ALIAS FROM (SELECT GROUP1,FIELD, case when instr(GROUP1, '_') = 2 then substr(GROUP1, 1, 2) || ltrim(substr(GROUP1, 3), '0123456789') else substr(GROUP1 , 1, 1) || ltrim(substr(GROUP1, 2), '0123456789') end GROUP_ALIAS FROM MY_TABLE GROUP BY GROUP_ALIAS HAVING COUNT(FIELD)=1 ``` Probably I could make the engineered field a second time simply on the original table and check that it isn't in the result from the latter, but want to avoid so much nesting. I don't know how to partition or do anything more sophisticated on my case statement making this engineered field, though. **UPDATE** Thanks for all the great replies below. Something about the SQL used must differ from what I thought because I'm getting info like: ``` GROUP1|GROUP_ALIAS|FIELD 111,222|,111|111 111,222|,222|222 etc. ``` Not sure why since the solutions work on my unabstracted data in db-fiddle. If anyone can spot what db it's actually using that would help but I'll also check on my end.
2021/03/10
[ "https://Stackoverflow.com/questions/66569955", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9682236/" ]
Here is one way, using analytic `count`. If you are not familiar with the `with` clause, read up on it - it's a very neat way to make your code readable. The way I declare column names in the `with` clause works since Oracle 11.2; if your version is older than that, the code needs to be re-written just slightly. I also computed the "engineered field" in a more compact way. Use whatever you need to. I used `sample_data` for the table name; adapt as needed. ``` with add_alias (group1, group_alias, field) as ( select group1, substr(group1, 1, instr(group1, '_')) || ltrim(substr(group1, instr(group1, '_') + 1), '0123456789'), field from sample_data ) , add_counts (group1, group_alias, field, ct) as ( select group1, group_alias, field, count(*) over (partition by group_alias) from add_alias ) select group1, group_alias, field from add_counts where ct > 1 ; ```
55,228,206
I followed threejs documentation in vuejs project to import image using : ``` texture.load( "./clouds" ) ``` This code is not working, I have to import image using require : ``` texture.load( require( "./clouds.png" ) ) ``` Now I want to use functions for sucess or error, so thank's to the internet i found that ``` texture.load( require( "./clouds.png" ), this.onSuccess, this.onProgress, this.onError ) ``` The problem is in success function, I want to create a cube with texture and nothing happened. I also tried on success function to add color in material but it didn't work. ``` onSuccess( image ) { this.material = new THREE.MeshLambertMaterial( { color: 0xf3ffe2, map: image } this.generateCube() } generateCube() { let geometry = new THREE.BoxGeometry( 100, 100, 100 ); this.forme = new THREE.Mesh( geometry, this.material ); this.forme.position.z = -200 this.forme.position.x = -100 this.scene.add( this.forme ); }, ```
2019/03/18
[ "https://Stackoverflow.com/questions/55228206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10380588/" ]
Your problem is not related to VueJS /ThreeJs (again ^^), you should learn how to use `this` inside a callback, here is a E6 fix : ``` texture.load( require( "./clouds.png" ), t => this.onSuccess(t), e => this.onProgress(e), e => this.onError(e) ) ``` <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions>
70,558,800
I want to change the content of a List with a class funcion. The class takes an item from the list as a parameter. Now I want to change this item in the list. How do I do that? I was only able to change the parameter in the instance but not the original list. ``` list = ["just", "an", "list"] class Test(): def __init__(self, bla): self.bla = bla def blupp(self): self.bla = "a" test = Test(list[1]) ``` If I run `test.blupp()` I want the list to be `["just", "a", "list"]` Thanks! (I hope nothing important is missing. This is my first question here)
2022/01/02
[ "https://Stackoverflow.com/questions/70558800", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17816849/" ]
`list[1]` is an expression that evaluates to `"an"` before `Test` is ever called. You have to pass the list and the index to modify separately, and let `blupp` make the assignment. ``` class Test: def __init__(self, bla, x): self.bla = bla self.x = x def blupp(self): self.bla[self.x] = "a" test = Test(list, 1) ``` Or, store a *function* that makes the assignment in the instance of `Test`: ``` class test: def __init__(self, f): self.f = f def blupp(self): self.f("a") test = Test(lambda x: list.__setitem__(1, x)) ```
11,521,178
I have an EditText view which I am using to display information to the user. I am able to append a String and it works correctly with the following method: ``` public void PrintToUser(String text){ MAIN_DISPLAY.append("\n"+text); } ``` The application is an RPG game which has battles, when the user is fighting I would like to display the String in RED. So I have attempted to use a SpannableString. (changed the method) ``` public void PrintToUser(String text, int Colour){ if(Colour == 0){ //Normal(Black) Text is appended MAIN_DISPLAY.append("\n"+text); }else{ //Colour text needs to be set. //Take the CurrentText String CurrentText = MAIN_DISPLAY.getText().toString(); CurrentText = CurrentText+"\n"; SpannableString SpannableText = new SpannableString(CurrentText + text); switch(Colour){ case 1: SpannableText.setSpan(new ForegroundColorSpan(Color.RED), CurrentText.length(), SpannableText.length(), 0); break; } //You cannot append the Spannable text (if you do you lose the colour) MAIN_DISPLAY.setText(SpannableText, BufferType.SPANNABLE); } ``` This new method works and the new line is displayed is red. **Problems** 1. Only the last line formatted is red. If a new line is set to be red the previous formatting is lost due to the way I retrieve the text > > String CurrentText = MAIN\_DISPLAY.getText().toString(); > > > 2. When I was ONLY appending Strings to the EditText it was displaying the bottom of the EditText box (the last input) now when using SetText the users see's the Top. **Finally My Question:** Is there a way to Append the formatted text? *OR...* Can I retrieve the formatted text from the EditText and then when I use .setText I can keep the current format? *AND if so...* Is there a way to focus the Display at the Bottom opposed to the Top? *Thank you! Please comment if additional information is needed I've been stuck on this for a while now.*
2012/07/17
[ "https://Stackoverflow.com/questions/11521178", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2474385/" ]
My suggestion would be to use the method: ``` myTextView.setText(Hmtl.fromHtml(myString)); ``` Where the myString could be of the format: ``` String myString = "Hello <font color=\'#ff0000\'>World</font>"; ```
7,863,936
I'm using a BYTE variable in assembler to hold partial statements before they're copied to a permanent location. I'm trying to figure out how I could clear that after each new entry. I tried moving an empty variable into it, but that only replaced the first character space of the variable. Any help would be much appreciated, thanks!
2011/10/23
[ "https://Stackoverflow.com/questions/7863936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/974953/" ]
Use XOR instead of MOV. It's faster. ``` XOR r1, r1 ```
55,376,694
So basically, i have a component "ShowTaskStatus" that will show how many tasks are open, how many closed and the total. This result i get by POSTing to my query server endpoint. In my dashboard, ShowTaskStatus can be rendered multiple times and the results will be visible per row in a table. There can be up to 50 different areas, and the query is quite complex. The result per row is presented as soon as the result is available, without waiting for the other areas to be fetched. **Dashboard** ============= Area | Open | Closed | Total ---------------------------- * Area1 | 10 | 20 | 30 * Area2 | 12 | 28 | 40 * AreaX | XX | YY | ZZ * ... So the problem is, that the process that handles the query cannot handle that many request and i want to limit therefore how many "active" HTTPMethods can be executed before fetching a new Area. ``` //initial queryProcs = 0 var that = this; var areaRows = areas.map(function(area) { //some other code isLoading[area] = true; this.setState({ isLoading : isLoading }); // so check how many requests are running if (that.state.queryProcs < 5) { // only after state is set, execute POST that.setState({ queryProcs: queryProcs + 1, }, () => { POST('/TastStatus', queryParameters, function(response) { // This code is executed when POST returns a response //dome something here isLoading[area] = false; //trigger a rerender by setting state with the query result //and also decrease the counter so another free query process is available that.setState(prevState => ({ queryProcs: prevState.queryProcs - 1, isLoading: isLoading //... })); }, function(error, errorText) { //some error handling //free up another query process self.setState(prevState => ({ queryProcs: prevState.queryProcs - 1, //... })); }); }) } }); ``` so obviously this is not working, as the state will never have the chance to be up-to-date during the map loop and the POST response anyway comes asynchronous. Well i guess i could just build up my data within the map and setState outside of it. The data will then hold the complete result of all areas, but i will loose my "line-by-line" result loading feature. Has someone a suggestion here?
2019/03/27
[ "https://Stackoverflow.com/questions/55376694", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9460865/" ]
You need to move the code inside a method. one of the solutions could be as follows ``` package application; public class Mathprocess { public static void main(String[] args){ int numberOne = 15; int numberTwo = 5; int answerNumbers; int ansSubtract = 0; int ansDivide = 0; int ansMultiply = 0; int ansAddition = 0; //Question 1 ansAddition = numberOne + numberTwo; String questionOne = numberOne + " + " + numberTwo +" = "; //Question 2 ansMultiply = numberOne * numberTwo; String questionTwo = numberOne + " * " + numberTwo +" = "; //Question 3 ansDivide = numberOne / numberTwo; //Question 4 ansSubtract = numberOne - numberTwo; // error happens here if (ansAddition > 0) { answerNumbers = ansAddition; } } } ``` However, it may differ as per your needs.
4,307,536
I am building a string to detect whether filename makes sense or if they are completely random with PHP. I'm using regular expressions. A valid filename = `sample-image-25.jpg` A random filename = `46347sdga467234626.jpg` I want to check if the filename makes sense or not, if not, I want to alert the user to fix the filename before continuing. Any help?
2010/11/29
[ "https://Stackoverflow.com/questions/4307536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/148718/" ]
I'm not really sure that's possible because I'm not sure it's possible to define "random" in a way the computer will understand sufficiently well. "umiarkowany" looks random, but it's a perfectly valid word I pulled off the Polish Wikipedia page for South Korea. My advice is to think more deeply about why this design detail is important, and look for a more feasible solution to the underlying problem.
36,401,911
**TL;DR** When I'm importing my existing Cordova project in Visual Studio and run the application in my browser (through Ripple) I'll get the following error: `PushPlugin.register - We seem to be missing some stuff :(` **Full explanation:** First of all apologies for the long post, I wanted to include as much information as possible! I have a working Cordova application that I run with Ionic, Cordova and Ripple. I use Ripple to emulate mobile devices in my browser. All of the features work perfectly when I test it in Sublime Text Editor and run with `ripple emulate`. When I try to import the project in Visual Studio, it doesn't run as smoothly. I'll explain what I did in steps, because perhaps I missed something in a particular step. Step 1 ------ This is my code from my config.xml in my Sublime project (not Visual Studio). ``` <gap:plugin name="cordova-plugin-file" source="npm" /> <gap:plugin name="cordova-plugin-file-transfer" source="npm" /> <gap:plugin name="cordova-plugin-device" source="npm" /> <gap:plugin name="cordova-plugin-inappbrowser" source="npm" /> <gap:plugin name="com.phonegap.plugins.pushplugin" version="2.4.0" /> ``` This is the config.xml in Visual Studio. Note the `com.phonegap.plugins.PushPlugin`. This is a plugin available on github, but I could only find a direct link to the `2.5` version. In managed to download the zip to the `2.4` version though, so I added it through this way. ``` <plugin name="cordova-plugin-file" version="4.1.1" /> <plugin name="cordova-plugin-file-transfer" version="1.5.0" /> <plugin name="cordova-plugin-device" version="1.1.1" /> <plugin name="cordova-plugin-inappbrowser" version="1.2.1" /> <plugin name="com.phonegap.plugins.PushPlugin" version="2.4.0" src="D:\Dev\A\VisualStudioApp\VisualStudioApp\local-plugins\PushPlugin-2.4.0" /> <plugin name="cordova-plugin-websql" version="0.0.10" /> ``` Step 2 ------ This is the folder structure in my Sublime Text Editor: ``` <DIR> fonts <DIR> icons <DIR> images <DIR> iscroll <DIR> jquery-mobile <DIR> js - <DIR> app - <DIR> lib <DIR> platforms <DIR> res <DIR> slickgrid <DIR> styles <DIR> testdata 27 295 MobileProject.jsproj 588 MobileProject.jsproj.user 4 115 config.xml 999 config.xml.bak 938 config.xml.vs 222 115 cordova.android.js 209 664 cordova.ios.js 60 180 cordova.js 2 cordova_plugins.js 1 142 footer.html 313 header.html 212 index.html 67 607 main.html ``` And here is the folder structure inside Visual Studio: ``` <DIR> bin <DIR> bld <DIR> local-plugins <DIR> merges <DIR> platforms <DIR> plugins <DIR> res <DIR> testdata <DIR> www - <DIR> fonts - <DIR> icons - <DIR> images - <DIR> iscroll - <DIR> jquery-mobile - <DIR> js - <DIR> app - <DIR> lib - <DIR> slickgrid - <DIR> styles - 1 142 footer.html - 313 header.html - 212 index.html - 67 607 main.html 131 .gitignore 75 bower.json 225 build.json 6 686 VisualStudioApp.jsproj 309 VisualStudioApp.jsproj.user 7 146 config.xml 122 package.json 124 250 Project_Readme.html 34 taco.json ``` Step 3 ------ Run the application on Android [![Run application](https://i.stack.imgur.com/qoLA3.png)](https://i.stack.imgur.com/qoLA3.png) This is what my console log gives me: `GET http://localhost:4400/config.xml 404 (Not Found) ripple.js:51` `No Content-Security-Policy meta tag found. Please add one when using the cordova-plugin-whitelist plugin. whitelist.js:24` [![Result](https://i.stack.imgur.com/J2dHN.png)](https://i.stack.imgur.com/J2dHN.png) Sidenotes --------- * When I add the plugins, but don't copy the code from Sublime to Visual Studio, no errors will be shown. * When I run the application on Windows-AnyCPU (Local Machine), the application will start and almost instantly shut down. * In debug mode I've bumped into an exception at the start of the run: `SCRIPT5022: Unhandled exception at line 59, column 13 in ms-appx://io.cordova.myapp4a33c5/www/cordova.js 0x800a139e - Runtime-fout JavaScript: module cordova/windows8/commandProxy not found cordova.js (59,13)` What is this `cordova/windows8/commandProxy`?
2016/04/04
[ "https://Stackoverflow.com/questions/36401911", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2664414/" ]
Just add a button at the top that deletes the selected rows. It looks like your using a `QTreeWidget` ``` def __init__(...) ... self.deleteButton.clicked.connect(self.deleteRows) def deleteRows(self): items = self.tree.selectedItems() for item in items: # Code to delete items in database self.refreshTable() ```
37,481,473
I'm setting the routes and I would like to pass a parameter to the delete method. I've tried this which doesn't work: ``` namespace :admin do resources :item do get 'create_asset' delete 'destroy_asset/:asset_id' end resources :asset end ``` I've done that, but it doesn't look like the proper solution... ``` delete 'admin/items/:frame_id/destroy-asset/:asset_id' => 'admin/frames#destroy_asset'2, as: :destroy_asset ``` How can I achieve it? I cannot understand where I'm wrong.
2016/05/27
[ "https://Stackoverflow.com/questions/37481473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1498118/" ]
I have log4net in my project from before I added identity server, it just works for me, I did not have to change anything that I had done. so in my case I had got the nuget package created the table and updated my web.config to use log4net before I added identity server. if you want a sample of my setup I can add it later.
41,786,278
I've tried adding JAVA\_HOME with the directory - C:\Program Files\Java\jdk1.8.0\_121 to my system variables, and then adding %JAVA\_HOME%/bin to Path variable and this didn't work and I receive > > 'java' is not recognized as an internal or external command, operable > program or batch file. > > > So I've tried adding C:\Program Files\Java\jdk1.8.0\_121; directly to the path variable but I still get the above error. Does anyone have any suggestions please? Thanks PS - The image shows me in the command prompt at C:\Program Files\Java\jdk1.8.0\_121 trying 'java -version' - I just moved up one dir to test the variable, entering 'java -version' in the bin directory returns the correct info, as you would expect. [![Link to the image](https://i.stack.imgur.com/nONVL.png)](https://i.stack.imgur.com/nONVL.png)
2017/01/22
[ "https://Stackoverflow.com/questions/41786278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6321773/" ]
Did you try closing that command prompt and reopening it?
44,161,916
Please can anyone help me, I am stuck, I have to extract data from JIRA web page and put it into EXCEL without using plugins that's way i am trying to do it with VBA but I don't how to proceed. I have tried several methods but it dosen't work for me, Is there anyone who has done that already ? Thank you
2017/05/24
[ "https://Stackoverflow.com/questions/44161916", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8054553/" ]
The piece of code you posted works , maybe in the rest of your code there is some html output before `header( )` , this can be also in some of included files if there is some . UPDATE : Some useful answers about the same issue could be found here : [php-header-redirect-not-working](https://stackoverflow.com/questions/423860/php-header-redirect-not-working)
37,516,491
I am running git commands remotely through the SSH protocol as the server doesn't accept HTTPS. I am running it through a bash script and would prefer if I could pass in a username and password as variables. More specifically, I am doing a migrate of repositories and am having issues when running ``` git remote add origin ssh://${username}:${password}@server.com/repo.git ``` I am running the script through a Jenkins job and am not able to easily prompt for passwords. Is my best option to copy keys to the remote server?
2016/05/30
[ "https://Stackoverflow.com/questions/37516491", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4727710/" ]
Assuming you're using a recent version of Git, you can use the `GIT_SSH_COMMAND` environment variable: > > > ``` > GIT_SSH, GIT_SSH_COMMAND > > If either of these environment variables is set then git fetch > and git push will use the specified command instead of ssh when > they need to connect to a remote system. The command will be > given exactly two or four arguments: the username@host (or just > host) from the URL and the shell command to execute on that > remote system, optionally preceded by -p (literally) and the port > from the URL when it specifies something other than the default > SSH port. > > $GIT_SSH_COMMAND takes precedence over $GIT_SSH, and is > interpreted by the shell, which allows additional arguments to be > included. $GIT_SSH on the other hand must be just the path to a > program (which can be a wrapper shell script, if additional > arguments are needed). > > Usually it is easier to configure any desired options through > your personal .ssh/config file. Please consult your ssh > documentation for further details. > > ``` > > So, before you call `git`, you can simply: ``` export GIT_SSH_COMMAND='ssh -i /path/to/key' ``` If you can't use an SSH key, you can use the the [Jenkins Credential Binding plugin](https://wiki.jenkins-ci.org/display/JENKINS/Credentials+Binding+Plugin).
1,201,312
$D: \begin{bmatrix}1&4.19\\2&3.40\\3&2.80\\4&2.30\\5&1.99\\6&1.70\\7&1.51\\8&1.34\\9&1.21\\10&1.09\end{bmatrix}$ In this table of data the first column is representing time (in minutes), and the second column is the mass of some element. * The element consists of two types of isotopes that decay rapidly. * The first isotope has a half-life of 3 minutes, and the second of 8 minutes. How can I figure out the initial mass of the two isotopes using least square method on this table of data? *I will use Wolfram Mathematica for the calculations*
2015/03/22
[ "https://math.stackexchange.com/questions/1201312", "https://math.stackexchange.com", "https://math.stackexchange.com/users/174557/" ]
**Hint 1:** $t \mapsto (1-x)/(1+x)$ > > $$\begin{equation}\displaystyle\int\frac{x-1}{(x+1)\sqrt{x+x^2+x^3}}\,\mathrm{d}x = 2\arccos\left(\frac{\sqrt{x}} {x+1}\right) + \mathcal{C}\end{equation}$$ > > > **Hint 2:** One can show that $t = (1-x)/(1+x)$ is it's own inverse. In other words $x = (1-t)/(1+t)$. Hence the derivative becomes. $\mathrm{d}x = -2t \,\mathrm{d}t/(t+1)^2$. Similarly we have $\sqrt{x^3+x^2+x} = \sqrt{(t^3+3)(1-t^2)}/(t+1)^2$ so we get a nice cancelation. Explicitly we have $$ \begin{align\*} \sqrt{x^3+x^2+x} & = \sqrt{ \left(\frac{1-t}{1+t}\right)^3 + \left(\frac{1-t}{1+t}\right)^2 + \left(\frac{1-t}{1+t}\right) } \\ & = \sqrt{ \frac{-t^3+t^2-3t+3}{(1+t)^3}} = \sqrt{ \frac{1+t}{1+t}\frac{(1-t)(t^2+3)}{(1+t)^3}} = \frac{\sqrt{(1-t^2)(t^3+3)}}{(t+1)^2} \end{align\*} $$ **Hint 3:** Use the substitution $\cos u \mapsto t$, what happens?
68,486,025
I'm trying to add validation to my route in a fastapi server, followed the instructions [here](https://fastapi.tiangolo.com/tutorial/path-params-numeric-validations/) and managed to have added validation on my int path parameters like so: ``` route1 = router.get("/start={start:int}/end={end:int}")(route1_func) ``` and my `route1_func`: ``` async def route1_func(request: Request, start: int = Path(..., title="my start", ge=1), end: int = Path(..., title="my end", ge=1)): if end <= start: raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST) else: return True ``` and this works great... but i would like to validate the `end > start` if possible as part of the definition, instead of checking this after going into `route1_func` is this possible?
2021/07/22
[ "https://Stackoverflow.com/questions/68486025", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14952079/" ]
You can put path params & query params in a Pydantic class, and add the whole class as a function argument with `= Depends()` after it. The FastAPI docs barely mention this functionality, but it does work. Then, once you have your args in a Pydantic class, you can easily use Pydantic validators for custom validation. Here's a rough pass at your use case: ``` class Route1Request(BaseModel): start: int = Query(..., title="my start", ge=1) end: int = Query(..., title="my end", ge=1) @root_validator def verify_start_end(cls, vals: dict) -> dict: assert vals.get("end", 0) > vals.get("start", 0) return vals @router.get("/") async def route1(route1_data: Route1Request = Depends()): return True ``` *Note: It wasn't clear to me if you meant to use path params or query params. I wrote this example for `Query` params, but it can work with `Path` params with only a few changes.*
42,088,715
I'm using word2vec model to build a classifier on training data set and wonder what are technics to deal with unseen terms (words) in the test data. Removing new terms doesn't seem like a best approach. My current thought is to recalculate word2vec on combined data set (training + test) and replace new terms with nearest word from training data set (or maybe some linear combination of 2-3 nearest). Sounds a bit tricky, but should be doable. Have you come across similar problem? Any idea/suggestion how to deal with unseen terms?
2017/02/07
[ "https://Stackoverflow.com/questions/42088715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6077279/" ]
To get document without having name is N3 of properties use [$ne](https://docs.mongodb.com/v3.2/reference/operator/query/ne/#ne) (*not equal*) operator ``` db.collectionName.find( { "properties.name": { $ne: "N3" } } ) ``` **Updated:** You need to use aggregate query to get all record with properties only discard properties element that contains N3 as name. ``` db.collectionName.aggregate([ {$unwind:"$properties"}, {$match:{"properties.name":{$ne:"N3"}}}, {$group:{ _id:"$_id", properties:{$push:"$properties"}, menu: {$first:"$menu"} } } ]) ```
92,711
I've read on a Twitter support page that when we block a user that user will be notified that he/she has been blocked. My question is: when I block a user, that user will still be able to see my profile? Is there a way to prevent users from viewing my profile permanently?
2016/05/11
[ "https://webapps.stackexchange.com/questions/92711", "https://webapps.stackexchange.com", "https://webapps.stackexchange.com/users/123448/" ]
> > How to change comma to dot? > > > Use Edit, Find and Replace... [![Find and Replace](https://i.stack.imgur.com/OzrSP.jpg)](https://i.stack.imgur.com/OzrSP.jpg) However the result is a text string, so you might need to substitute dot with comma if to calculate with the result.
117,945
I need to put a letter under the min symbol in the equation below but i couldn't do it,It now looks like this: ![enter image description here](https://i.stack.imgur.com/D0PIC.png) and I need it to look like this: ![enter image description here](https://i.stack.imgur.com/gC0tg.png) ``` \begin{document} \begin{equation} mina\sum^{N}_{i=1}\sum^{N}_{j=1}|y_i - y_j|^2 W_{ij} \label{eqn4} \end{equation} \end{document} ```
2013/06/06
[ "https://tex.stackexchange.com/questions/117945", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/28377/" ]
``` \begin{document} \begin{equation} \min_A\sum^{N}_{i=1}\sum^{N}_{j=1}|y_i - y_j|^2 W_{ij} \label{eqn4} \end{equation} \end{document} ```
27,351,064
I have a class that makes car objects. It has two instance variables: Make and Color. I am having an issue calling this method within the workspace (noted below) Class Method -Constructor ``` make: aMake color: aColor "Creates a new car object, sets its instance variables by the arguments" |car| car := self new. car setMake: aMake setColor: aColor. "accessor method below" ^car ``` Accessor Method ``` setMake: make setColor: color "sets the instance variables" Make := make. Color := color. ``` Workspace (calling code) ``` |car| car := Car make: 'toyota' color: 'red' ``` I get 'Message Not Understood' when calling this line. What is the issue here?
2014/12/08
[ "https://Stackoverflow.com/questions/27351064", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2249815/" ]
Everything looks alright. The likely gotcha would be that your "constructor" (which would more likely be called an "instance creation message" in Smalltalk) needs to be implemented on the class side, and you may have done so on the instance side. Conversely, your set... must be on the instance side. Which message is not understood (error details always help)? It should say in the debugger and that would help clarify.
41,601,636
When I try to run this Python script, the following happens: ``` $ python mlp_training.py Loading training data... (0, 38400) (0, 4) Loading image duration: 0.000199834 Training MLP ... Traceback (most recent call last): File "mlp_training.py", line 49, in <module> num_iter = model.train((train, ( train_labels ), ( params ))) TypeError: Required argument 'layout' (pos 2) not found ``` ### mlp\_training.py ``` __author__ = 'zhengwang' import cv2 import numpy as np import glob print 'Loading training data...' e0 = cv2.getTickCount() # load training data image_array = np.zeros((1, 38400)) label_array = np.zeros((1, 4), 'float') training_data = glob.glob('training_data/*.npz') for single_npz in training_data: with np.load(single_npz) as data: print data.files train_temp = data['train'] train_labels_temp = data['train_labels'] print train_temp.shape print train_labels_temp.shape image_array = np.vstack((image_array, train_temp)) label_array = np.vstack((label_array, train_labels_temp)) train = image_array[1:, :] train_labels = label_array[1:, :] print train.shape print train_labels.shape e00 = cv2.getTickCount() time0 = (e00 - e0)/ cv2.getTickFrequency() print 'Loading image duration:', time0 # set start time e1 = cv2.getTickCount() # create MLP layer_sizes = np.int32([38400, 32, 4]) model = cv2.ml.ANN_MLP_create() model.setLayerSizes(layer_sizes) criteria = (cv2.TERM_CRITERIA_COUNT | cv2.TERM_CRITERIA_EPS, 500, 0.0001) criteria2 = (cv2.TERM_CRITERIA_COUNT, 100, 0.001) params = dict(term_crit = criteria, train_method = cv2.ml.ANN_MLP_BACKPROP, bp_dw_scale = 0.001, bp_moment_scale = 0.0 ) print 'Training MLP ...' num_iter = model.train((train, ( train_labels ), ( params ))) # set end time e2 = cv2.getTickCount() time = (e2 - e1)/cv2.getTickFrequency() print 'Training duration:', time # save param model.save('mlp_xml/mlp.xml') print 'Ran for %d iterations' % num_iter ret, resp = model.predict(train) prediction = resp.argmax(-1) print 'Prediction:', prediction true_labels = train_labels.argmax(-1) print 'True labels:', true_labels print 'Testing...' train_rate = np.mean(prediction == true_labels) print 'Train rate: %f:' % (train_rate*100) ``` I got this from a [GitHub page](https://github.com/hamuchiwa/AutoRCCar) and copied the code and modified it here and there to fit my needs. What's going wrong?
2017/01/11
[ "https://Stackoverflow.com/questions/41601636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7405626/" ]
See code from [mlp\_training.py](https://github.com/hamuchiwa/AutoRCCar/blob/master/computer/mlp_training.py) ``` num_iter = model.train(train, train_labels, None, params = params) ``` It runs `train()` with 4 arguments but you run with only one - tuple ``` model.train( (train, ( train_labels ), ( params )) ) ``` It seems you put too many parethesis.
11,906,219
I have a question on my mind. Let's assume that I have two parameters passed to JVM: -Xms256mb -Xmx1024mb At the beginning of the program 256MB is allocated. Next, some objects are created and JVM process tries to allocate more memory. Let's say that JVM needs to allocate 800MB. Xmx attribute allows that but the memory which is currently available on the system (let's say Linux/Windows) is 600MB. Is it possible that OutOfMemoryError will be thrown? Or maybe swap mechanism will play a role? My second question is related to the quality of GC algorithms. Let's say that I have jdk1.5u7 and jdk1.5u22. Is it possible that in the latter JVM the memory leaks vanish and OutOfMemoryError does not occur? Can the quality of GC be better in the latest version?
2012/08/10
[ "https://Stackoverflow.com/questions/11906219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1275053/" ]
The quality of the GC (barring a buggy GC) does not affect memory leaks, as memory leaks are an artifact of the application -- GC can't collect what isn't actual garbage. If a JVM needs more memory, it will take it from the system. If the system can swap, it will swap (like any other process). If the system can not swap, your JVM will fail with a system error, not an OOM exception, because the system can not satisfy the request and and this point its effectively fatal. As a rule, you NEVER want to have an active JVM partially swapped out. GC event will crush you as the system thrashes cycling pages through the virtual memory system. It's one thing to have a idle background JVM swapped out as a whole, but if you machine as 1G of RAM and your main process wants 1.5GB, then you have a major problem. The JVM like room to breathe. I've seen JVMs in a GC death spiral when they didn't have enough memory, even though they didn't have memory leaks. They simply didn't have enough working set. Adding another chunk of heap transformed that JVM from awful to happy sawtooth GC graphs. Give a JVM the memory it needs, you and it will be much happier.
7,475,837
This is the code (corona SDK btw), it is calling a physicsdata (unimportant). ``` r = math.random(1,5) local scaleFactor = 1.0 local physicsData = (require "retro").physicsData(scaleFactor) physics.addBody( enemy, physicsData:get(r) ) ``` The r in ``` physicsData:get(r) ) ``` has to be inside speech marks to work (I tested). how can the r variable be string-ilised? ( :D )
2011/09/19
[ "https://Stackoverflow.com/questions/7475837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
If you need a string, ``` tostring(r) ``` For example, ``` physics.addBody( enemy, physicsData:get(tostring(r)) ) ``` If you really need quotes in the string (I doubt you do): ``` physics.addBody( enemy, physicsData:get('"' .. tostring(r) .. '"') ) ```
64,654,855
So I have the following 3 tables: ``` Table: Products Columns: id, name, description, price, currency Table: Orders Columns: id, firstName, lastName, phoneNumber Table: Order_Products Columns: orderId, productId, quantity ``` Now I'm trying to figure out where to put the total price of the order and I have 2 ideas: 1. Add a `totalPrice` column to the `Orders` table that will contain the sum of the `price * quantity` of all products in the order, or: 2. Add a `price` column to the `Order_Products` table that will contain the the `price * quantity` of that specific product, and then I'd have to get all `Order_Products` records for that order and sum their `price` columns. I'm not quite sure which option is better, hence why I'm asking for recommendations here.
2020/11/02
[ "https://Stackoverflow.com/questions/64654855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8618818/" ]
I would recommend that you store the order total in the `orders` table. Why? Basically, order totals are not necessarily the same as the sum of all the prices on the items: * The prices might change over time. * The order itself might have discounts. In addition, the order might have additional charges: * Discounts applied to the entire order. * Taxes. * Delivery charges. For these reasons, I think it is safer to store financial information on the order when the order is placed.
42,008,449
I am trying to see if an array contains each element of another array. Plus I want to account for the duplicates. For example: ``` array = [1, 2, 3, 3, "abc", "de", "f"] ``` array contains [1, 2, 3, 3] but does not contain [2, 2, "abc"] - too many 2's I have tried the below but obviously doesn't take into account the dupes. ``` other_arrays.each { |i| array.include? i } ```
2017/02/02
[ "https://Stackoverflow.com/questions/42008449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6449679/" ]
This method iterates once over both arrays. For each array, it creates a hash with the number of occurences of each element. It then checks that for every unique element in `subset`, there are at least as many elements in `superset`. ``` class Array def count_by each_with_object(Hash.new(0)) { |e, h| h[e] += 1 } end def subset_of?(superset) superset_counts = superset.count_by count_by.all? { |k, count| superset_counts[k] >= count } end end [1, 2, 3, 3, "abc", "de", "f"].count_by #=> {1=>1, 2=>1, 3=>2, "abc"=>1, "de"=>1, "f"=>1} [1, 2, 3, 3].count_by #=> {1=>1, 2=>1, 3=>2} [1, 2, 3, 3].subset_of? [1, 2, 3, 3, "abc", "de", "f"] #=> true [2, 2, "abc"].subset_of? [1, 2, 3, 3, "abc", "de", "f"] #=> false ``` If you don't want to patch the `Array` class, you could define : `count_by(array)` and `subset_of?(array1, array2)`.
29,144,832
I want to sequentially read each line of an input unsorted file into consecutive elements of the array until there are no more records in the file or until the input size is reached, whichever occurs first. but i can't think of a way to check the next line if its the end of the file? This is my code: ``` Scanner cin = new Scanner(System.in); System.out.print("Max number of items: "); int max = cin.nextInt(); String[] input = new String[max]; try { BufferedReader br = new BufferedReader(new FileReader("src/ioc.txt")); for(int i=0; i<max; i++){ //to do:check for empty record input[i] = br.readLine(); } } catch (IOException e){ System.out.print(e.getMessage()); } for(int i=0; i<input.length; i++){ System.out.println((i+1)+" "+input[i]); } ``` the file has 205 lines, if I input 210 as max, the array prints with five null elements like so.. ``` ..204 Seychelles 205 Algeria 206 null 207 null 208 null 209 null 210 null ``` Thanks for your responses in advance!
2015/03/19
[ "https://Stackoverflow.com/questions/29144832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4532762/" ]
From [the docs](http://docs.oracle.com/javase/7/docs/api/java/io/BufferedReader.html): > > public String readLine() > > > Returns: A String containing the contents of the line, not including > any line-termination characters, or null if the end of the stream has > been reached > > > In other words, you should do ``` String aux = br.readLine(); if(aux == null) break; input.add(aux) ``` I recomend you use a variable-size array (you can pre-allocated with the requested size if reasonable). Such that you get either the expected size or the actual number of lines, and can check later. (depending on how long your file is, you might want to look at [readAllLines()](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#readAllLines(java.nio.file.Path,%20java.nio.charset.Charset)) too.)
49,707
I was rewatching Stargate-SG1 and noticed something while I was watching "[Menace](http://stargate.wikia.com/wiki/Menace)" where we learn that the android Reese created the Replicators and sent them out in to the galaxy. We know that the Replicators integrate technology they consume to their own and lastly we know of no race that were capable of travelling between galaxies (and that lives in the Milky Way) aside from the ancients My question is, how did they end up in the [Asgard galaxy](http://stargate.wikia.com/wiki/Ida) (Ida) and why didn't they consume everything in the Milky Way long before the series began? Is is ever explained? ![enter image description here](https://i.stack.imgur.com/jJP0K.jpg)
2014/02/08
[ "https://scifi.stackexchange.com/questions/49707", "https://scifi.stackexchange.com", "https://scifi.stackexchange.com/users/22619/" ]
The short answer is that it's not explained in canon. Although the Asgard have had a presence in the Milky Way Galaxy for a very long time (and hence it would be logical to assume they encountered the Replicators there) Thor [explictly states](http://stargate-sg1-solutions.com/wiki/3.22_%22Nemesis_Part_1%22_Transcript#Transcript) that they were first encountered in the Ida Galaxy. > > **THOR :** ***They were discovered on an isolated planet in our home galaxy*** some years ago. The creators were not present. > > > **TEAL'C :** *Most likely destroyed by their own creation.* > > > **THOR :** *The Replicators were brought aboard an Asgard ship for study before the danger could be fully comprehended.* > > > **O'NEILL :** *We do that all the time. I kinda expected more from you guys.* > > > **THOR :** *Overconfidence in our technologies has been our undoing. The entities learned from the very means that were employed to stop > them. They have become a plague on our galaxy that is annihilating > everything in its path.* > > >
338,952
On top of [an answer](https://meta.stackexchange.com/a/63791/399694) describing a meme about pluralization bugs, there was a deprecation notice posted (from August 2018): > > This meme is officially deprecated. > > > Please do not use this meme. It remains here while links to it are > still quite 'out in the wild' as a reference to inform folks that they > shouldn't be using it, and should be flagging comments linking to it > for removal. > > > While at the time it was seen as light-hearted fun, that context (and > Jeff) are long gone; the use of this is just confusing and definitely > not in line with our Code of Conduct. > > > While I can understand the rationale of prohibiting jokes about violence, I want to clarify whether the prohibition of the meme solely covers jokes about violence, or also jokes about pluralization bugs in the Stack Exchange software. For example, is the prohibition intended to cover comments like > > We've seen this pluralization bug occur one time**s** this week in the chat software > > > or > > At least this [obviously incorrect] stack exchange software message has correct pluralization! > > >
2019/11/24
[ "https://meta.stackexchange.com/questions/338952", "https://meta.stackexchange.com", "https://meta.stackexchange.com/users/38765/" ]
It is possible that your post may be on-topic at the [Information Security](https://security.stackexchange.com) Stack Exchange site. They have quite a few questions and a lot of them do cover Internet censorship by governments.
5,303,118
i have a relative layout and i have two buttons in it with texts "hello" and "world" respectively. i want these two buttons to lie adjacent to each other and equally occupy the whole horizontal space available. i tried the following but didnt get expected output ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent"> <Button android:layout_height="wrap_content" android:layout_width="wrap_content" android:text="@string/world" android:id="@+id/world" android:layout_alignParentRight="true" android:layout_toRightOf="@+id/hello" android:layout_alignTop="@+id/hello" /> <Button android:id="@+id/hello" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/hello" android:layout_alignParentLeft="true" android:layout_alignParentBottom="true" /> </RelativeLayout> ``` i tried changing the android:layout\_width of both children to fill\_parent but that didnt work too. i have a working solution of using LinearLayout with layout\_weight set to 0.5 on both childs but i wanted to understand if there is way to do that in relative layout itself. thanks,
2011/03/14
[ "https://Stackoverflow.com/questions/5303118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41432/" ]
``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" > <Button android:id="@+id/world" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentRight="true" android:layout_alignTop="@+id/hello" android:layout_toRightOf="@+id/view" android:text="First" /> <View android:id="@+id/view" android:layout_width="0dp" android:layout_height="1dp" android:layout_centerHorizontal="true" /> <Button android:id="@+id/hello" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_toLeftOf="@+id/view" android:text="Second" /> </RelativeLayout> ``` ![Check](https://i.stack.imgur.com/AmEgj.jpg) ### Note: * Even if the `android:layout_width` was `fill_parent` the result will not change. * What actually matters here is `android:layout_alignParentRight` and `android:layout_alignParentLeft`
51,620,422
In Postgres, I have a table with many columns (e.g. t1(a, b, c, ..., z)). I need to obtain its subset through a select-from-where statement into a new table (e.g. t2), but this new table must have a `serial` attribute. So, t2 would like t2(id, a, b, c, ..., z), where id the `serial` attribute. In Postgres, this works: ``` INSERT INTO t2(a, b, c, d, ..., z) SELECT * FROM t1 WHERE <condition> ``` However, is it possible to achieve the same without writing all the attributes of t1?
2018/07/31
[ "https://Stackoverflow.com/questions/51620422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1959766/" ]
As suggested by people in the comment section, **your best bet for this type of task is using list comprehension** like so, ``` ['file_Path ' + i for i in List] ``` Now, I wanted to add an answer because I wanted to add that `List` is definitely not a good choice of naming for you `list` object. **I would go with something more meaningful and further from the `list` keyword** (eg. `sheet_names`) ``` sheet_names = ['test1', 'test2', 'test3'] sheet_names = ['file_Path ' + i for i in sheet_names] print(sheet_names) >>>>['file_Path test1', 'file_Path test2', 'file_Path test3'] ```
39,233,962
I want to submit a score to my leaderboard. Sometimes it works but sometimes i get the error: ``` Error Code 6: STATUS_NETWORK_ERROR_OPERATION_FAILED ``` I am connected to the internet and enabled multiplayer in the developer console. Any ideas? Here is my code: MainActivity: ``` if(isSignedIn()){ Games.Leaderboards.submitScoreImmediate(mGoogleApiClient, this.leaderboardId, targetScore).setResultCallback(new LeaderBoardSubmitScoreCallback(this)); } ``` LeaderBoardSubmitScoreCallback: ``` @Override public void onResult(Leaderboards.SubmitScoreResult res) { Log.d("mylog","leaderboard upload result "+res.getStatus().getStatusCode()+": "+res.getStatus().getStatusMessage()); if (res.getStatus().getStatusCode() == 0) { activity.showToast(activity.getApplicationContext().getString(R.string.score_submitted)); }else{ Toast.makeText(activity.getApplicationContext(),activity.getString(R.string.error)+": "+res.getStatus().getStatusMessage(),Toast.LENGTH_LONG).show(); } } ```
2016/08/30
[ "https://Stackoverflow.com/questions/39233962", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4835496/" ]
You can use this lazy regex: ``` (.*?) \((.*)\)[^()]*$ ``` [RegEx Demo](https://regex101.com/r/yQ8xI8/1) Examples: ``` >>> reg = r'(.*?) \((.*)\)[^()]*$' >>> s = 'Bell St/Oriel Rd (Bellfield (3081))' >>> re.findall(reg, s) [('Bell St/Oriel Rd', 'Bellfield (3081)')] >>> s = 'Stud Rd/(after) Ferntree Gully Rd (Scoresby)' >>> re.findall(reg, s) [('Stud Rd/(after) Ferntree Gully Rd', 'Scoresby')] ```
23,577,146
Haskell does not have loops like many other languages. I understand the reasoning behind it and some of the different approaches used to solve problems without them. However, when a loop structure is necessary, I am not sure if the way I'm creating the loop is correct/good. For example (trivial function): ``` dumdum = do putStrLn "Enter something" num <- getLine putStrLn $ "You entered: " ++ num dumdum ``` This works fine, but is there a potential problem in the code? A different example: ``` a = do putStrLn "1" putStrLn "2" a ``` If implemented in an imperative language like Python, it would look like: ```python def a(): print ("1") print ("2") a() ``` This eventually causes a maximum recursion depth error. This does not seem to be the case in Haskell, but I'm not sure if it might cause potential problems. I know there are other options for creating loops such as `Control.Monad.LoopWhile` and `Control.Monad.forever` -- should I be using those instead? (I am still very new to Haskell and do not understand monads yet.)
2014/05/10
[ "https://Stackoverflow.com/questions/23577146", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1993391/" ]
For general iteration, having a recursive function call itself is definitely the way to go. If your calls are in [tail position](https://en.wikipedia.org/wiki/Tail_call), they don't use any extra stack space and behave more like `goto`1. For example, here is a function to sum the first n integers using constant stack space2: ``` sum :: Int -> Int sum n = sum' 0 n sum' !s 0 = s sum' !s n = sum' (s+n) (n-1) ``` It is roughly equivalent to the following pseudocode: ``` function sum(N) var s, n = 0, N loop: if n == 0 then return s else s,n = (s+n, n-1) goto loop ``` Notice how in the Haskell version we used function parameters for the sum accumulator instead of a mutable variable. This is very common pattern for tail-recursive code. So far, general recursion with tail-call-optimization should give you all the looping power of gotos. The only problem is that manual recursion (kind of like gotos, but a little better) is relatively unstructured and we often need to carefully read code that uses it to see what is going on. Just like how imperative languages have looping mechanisms (for, while, etc) to describe most common iteration patterns, in Haskell we can use higher order functions to do a similar job. For example, many of the list processing functions like `map` or `foldl'`3 are analogous to straightforward for-loops in pure code and when dealing with monadic code there are functions in Control.Monad or in the [monad-loops](http://hackage.haskell.org/package/monad-loops) package that you can use. In the end, its a matter of style but I would err towards using the higher order looping functions. --- 1 You might want to check out ["Lambda the ultimate GOTO"](http://library.readscheme.org/page1.html), a classical article about how tail recursion can be as efficient as traditional iteration. Additionally, since Haskell is a lazy languages, there are also some situations where recursion at non-tail positions can still run in O(1) space (search for "Tail recursion modulo cons") 2 Those exclamation marks are there to make the accumulator parameter be eagerly evaluated, so the addition happens at the same time as the recursive call (Haskell is lazy by default). You can omit the "!"s if you want but then you run the risk of running into a [space leak](http://www.haskell.org/haskellwiki/Foldr_Foldl_Foldl%27). 3 Always use `foldl'` instead of `foldl`, due to the previously mentioned space leak issue.
31,494,001
I want to change this url from: ``` https://lh3.googleusercontent.com/-5EoWQXUJMiA/VZ86O7eskeI/AAAAAAADHGs/ej6F-va__Ig/s1600/i2Fun.com-helpful-dogs-015.gif ``` to this: ``` http://3.bp.blogspot.com/-5EoWQXUJMiA/VZ86O7eskeI/AAAAAAADHGs/ej6F-va__Ig/s1600/i2Fun.com-helpful-dogs-015.gif ``` This is my code, but it's not working as expected: ``` $link = preg_replace('#^https?://.*?/(.+?/)(s\d+/)?([\w_-]+\.[\w]{3,})?$#i','http://3.bp.blogspot.com/$1s0/$3',$url); ```
2015/07/18
[ "https://Stackoverflow.com/questions/31494001", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1201672/" ]
It's a simple string replace. Search for `"https://lh3.googleusercontent.com/"`. Replace with `"http://3.bp.blogspot.com/"`. `str_replace()` will do this. Am I missing something?
758,758
I am learning about radians in my current class and am totally confused. How does $\sin(x+\frac\pi 2)=\cos(x)$ when $\frac\pi 2<x$ < $\pi$. I drew the triangles and I got $\sin(x+\frac\pi 2)=\frac{-\mathrm{opposite}}{-\mathrm{hypotenuse}}=\frac{\mathrm{opp}}{\mathrm{hyp}}$ $\cos(x)=\frac{\mathrm{adjacent}}{\mathrm{hypotenuse}}$ If the adjacent equals the hypotenuse this should work however in most circumstances this isn't true. What is the major flaw in my work?? Here is what I drew out. ![enter image description here](https://i.stack.imgur.com/rmsY7.png)
2014/04/18
[ "https://math.stackexchange.com/questions/758758", "https://math.stackexchange.com", "https://math.stackexchange.com/users/90108/" ]
Your expression for $\sin(x)$ is correct. But recall that the cosine is the abscissa divided by the radius of the circle. So in your drawing, $\cos(x)=\frac a b$. ![enter image description here](https://i.stack.imgur.com/a1eN9.png)
58,648,255
`str_getcsv ()` has some odd behaviour. It removes **all** characters that match the enclosing character, instead of **just the enclosing ones**. I'm trying to parse a CSV string (contents of an uploaded file) in two steps: 1. split the CSV string into an array of lines 2. split each line into an array of fields with this code: ``` $whole_file_string = file_get_contents($file); $array_of_lines = str_getcsv ($whole_file_string, "\n", "\""); // step 1. split csv into lines foreach ($array_of_lines as $one_line_string) { $splitted_line = str_getcsv ($one_line_string, ",", "\""); // step 2. split line into fields }; ``` In the code example nothing is done with `$splitted_line` for clarity of example Then I feed this script a file with the following contents: `"text,with,delimiter",secondfield`. When step 1 is performed the first (and only) element of `$array_of_lines` is `text,with,delimiter,secondfield`. So when step 2 is performed, it splits the line into 4 fields, but that needs to be 2. I can't use `fgetcsv()` because some string conversion is done (checking BOM, converting encoding accordingly and stuff like that) after reading the file and before splitting it into lines in step 1. I'm at the point of writing my own string parser (which isn't that complicated for CSV format), but before I do so I want to make sure that that's the best approach. I'm a bit disappointed that the PHP functions are letting me down on this simple (and I guess quite common) use case: processing an uploaded csv file with varying encoding. Any tips?
2019/10/31
[ "https://Stackoverflow.com/questions/58648255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11036459/" ]
Create a branch at **exactly** the revision where the person who worked separately started working from. Then remove every single file from it (use `git rm` for removing).... then put there whatever the user code is.... then add all of that and commit (use `--author="batman forever"` with the name of the developer so that you know who really did it), and then you can use this work to be merged or whatever you consider should be done.