qid
int64
10
74.7M
question
stringlengths
15
26.2k
date
stringlengths
10
10
metadata
list
response_j
stringlengths
27
28.1k
response_k
stringlengths
23
26.8k
69,306,523
I have a dataset about start and end dates, and I want to expand them to consecutive dates in rows. The dataset looks like this (df1): ``` id deg from to 1 1 2010-03-01 2010-03-05 1 1 2010-03-20 2010-03-25 1 2 2010-06-01 2010-06-05 ``` And this is the result I want (df2): ``` id deg date 1 1 2010-03-01 1 1 2010-03-02 1 1 2010-03-03 1 1 2010-03-04 1 1 2010-03-05 1 1 2010-03-20 1 1 2010-03-21 1 1 2010-03-22 1 1 2010-03-23 1 1 2010-03-24 1 1 2010-03-25 1 2 2010-06-01 1 2 2010-06-02 1 2 2010-06-03 1 2 2010-06-04 1 2 2010-06-05 ``` Here's the different codes I've tried: ``` df2 = df1 %>% mutate(id= 1:nrow(.)) %>% rowwise() %>% do(data.frame(id=.$id, date=seq.Date(.$from, .$to, by="days"))) ``` But it keeps showing the error: wrong sign in 'by' argument Thank you all in advance!
2021/09/23
[ "https://Stackoverflow.com/questions/69306523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16634627/" ]
put this code in your Podfile ``` post_install do |installer| installer.pods_project.targets.each do |target| flutter_additional_ios_build_settings(target) target.build_configurations.each do |build_configuration| build_configuration.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = 'arm64 i386' end end end ```
Add the below lines to your podfile. Place the below lines in the post\_install do [installer] section at the bottom of the Podfile. Code : ``` target.build_configurations.each do |build_configuration| build_configuration.build_settings['EXCLUDED_ARCHS[sdk=iphonesimulator*]'] = 'arm64 i386' end ```
1,500,390
I am trying to serialize an extended UIComponent (com.esri.ags.layers.GraphicsLayer) to send and store in a MSSQL Server database using WebOrb. Apparently, these types of objects aren't meant to be serialized, and I haven't had much serializing/deserializing using the flash byteArray. I have also tried several other libraries(FlexXB,asx3m,JSONLite,as3corelib) with other formats (xml, json) with no luck. Before I write some ugly-ass function, I am hoping someone may know how to do this already. Any thoughts/suggestions would be greatly appreciated.
2009/09/30
[ "https://Stackoverflow.com/questions/1500390", "https://Stackoverflow.com", "https://Stackoverflow.com/users/163757/" ]
Corbin's answer is the best one here. [link text](http://developer.apple.com/mac/library/samplecode/DragNDropOutlineView/Introduction/Intro.html "DragNDropOutlineView")
I don't believe the action method is called when multiple rows are selected. What would probably be a lot easier would be to override the `menuForEvent:` method in `NSTableView`. You'd have to create a subclass of `NSTableView` to do this, but it would be a cleaner solution. You could also create an informal protocol (a category on `NSObject`) and have the `NSTableView` delegate return the appropriate menu. ``` @interface NSObject (NSCustomTableViewDelegate) - (NSMenu *)tableView:(NSTableView *)tableView menuForEvent:(NSEvent *)event; @end @implementation NSObject (NSCustomTableViewDelegate) - (NSMenu *)tableView:(NSTableView *)tableView menuForEvent:(NSEvent *)event { return nil; } @end ``` And in your `NSTableView` subclass: ``` - (NSMenu *)menuForEvent:(NSEvent *)event { return [[self delegate] tableView:self menuForEvent:event]; } ```
39,415,367
Bear with me as this is the first time I've used Spring Boot so this is only what I *think* is happening... I have a couple of methods which are annotated with `@Scheduled`. They work great, and I have all of the dependencies configured and injected. These dependencies are quite heavy weight, relying on internet connections etc. I've annotated them as `@Lazy`, so they're only instantiated at the very last minute. However, the classes which contain the scheduled methods need to be marked with `@Component` which means they're created on launch. This sets off a chain reaction which creates all of my dependencies whether I actually need them for the test I'm currently running. When I run my unit tests on our CI server, they fail because the server isn't auth'd with the database (nor should it be). The tests which test these `@Scheduled` jobs inject their own mocks, so they work fine. However, the tests which are completely unrelated are causing the problems as the classes are still created. I obviously don't want to create mocks in these tests for completely unrelated classes. How can I prevent certain a `@Component` from being created when the tests are running? Scheduled jobs class: ``` package example.scheduledtasks; @Component public class ScheduledJob { private Database database; @Autowired public AccountsImporter(Database database) { this.database = database; } @Scheduled(cron="0 0 04 * * *") public void run() { // Do something with the database } } ``` Config class: ``` package example @Configuration public class ApplicationConfig { @Bean @Lazy public Database database() { return ...;// Some heavy operation I don't want to do while testing. } ``` }
2016/09/09
[ "https://Stackoverflow.com/questions/39415367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/862410/" ]
Just add the following to your test class: ``` @MockBean public Database d; ```
Another alternative: use a in-memory database like h2 when testing. Create an `application-test.properties` with ``` spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password=password spring.jpa.database-platform=org.hibernate.dialect.H2Dialect ``` See e.g. <https://www.baeldung.com/spring-boot-h2-database> .
49,980,265
I am trying to optimize the following query : ``` Select distinct cadData.id FROM CAD_Data cadData INNER JOIN Sales_Data SD ON cadData.CAD_Acct=SD.CAD_Acct and SD.List_Date = ( select max(List_Date) from Sales_Data where Sales_Data.CAD_Acct=cadData.CAD_Acct ) where cadData.GMA_Tag = 101 AND SD.List_Status NOT IN('ACT','OP','PEND','PSHO','pnd') ORDER BY cadData.id asc limit 10 ``` Both the table has more than 10 millions rows. CAD\_Data table is indexed by CAD\_Acct and GMA\_Tag column. Besides Sales\_data is indexed by CAD\_Acct,GMA\_Tag,List\_Date,List\_Status columns. Explain shows [![enter image description here](https://i.stack.imgur.com/nqMeF.png)](https://i.stack.imgur.com/nqMeF.png) I need some suggestion for optimizing this query. Thanks in advance.
2018/04/23
[ "https://Stackoverflow.com/questions/49980265", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4600064/" ]
if you want to remove partition expiration completely, set `NULL` for `partition_expiration_days` option ``` ALTER TABLE `project-name`.dataset_name.table_name SET OPTIONS (partition_expiration_days=NULL); ```
we can try updating this way:- [set partition Expiration time on Table](https://i.stack.imgur.com/PzvS9.png)
29,077,104
I'm trying to configure a mapped class to use a sequence I defined in a postgres db. The ids are always zero when I try to persist any entities, if I use select nextval('item\_seq'), I'll get 1 (or the next val). I used intellij to regenerate the classes. The version of hibernate in this project is 3.6.0, if that might be part of my problem? ``` @Entity @Table(name = "item") public class Item { private int itemid; ... @Basic @Id @SequenceGenerator(name = "item_seq", sequenceName = "item_seq", allocationSize = 1) @GeneratedValue(strategy=GenerationType.SEQUENCE, generator = "item_seq") @Column(name = "itemid", unique = true, nullable = false, insertable = true, updatable = true) public int getItemid() { return itemid; } ... } ``` Usage ``` Item item = new Item(); item.setCreated(new Date()); item.setVendorId(vendorId); save(item); // essentially is getHibernateTemplate().save(Item.class.getName(), item); ``` -- EDIT -- I've been trying the suggestions below and everything seems to keep generating 0 as an id or throw the exception 'ids for this class must be manually assigned before calling save()'. This is where I am now, as a last ditch effort I tried moving the annotations to the variable declaration instead of the getter. Didn't help. ``` @Entity @Table(name = "item") public class Item { @Id //@SequenceGenerator(name = "item_seq", sequenceName = "item_seq", allocationSize = 1) @GeneratedValue(strategy = GenerationType.IDENTITY) //, generator = "item_seq") @Column(name = "itemid", unique = true, nullable = false) //, insertable = true, updatable = true) private Long itemid; ... public Long getItemid() { return itemid; } } ```
2015/03/16
[ "https://Stackoverflow.com/questions/29077104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/682059/" ]
This always works for me (Hibernate 4.x though): ``` @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; ``` `@Id` makes the column a primary key (unique, no nulls), so you don't need the `@Column(...)` annotation. Is something setting your `itemId` somewhere? You can remove its setter if you have one (Hibernate doesn't require).
what database u are using? can be possibly a database that does not support sequence?? try to use strategy=auto and see how does it work since 'select nextval(...)' works, your database (postgresql) is supporting sequence. so thats not it maybe for some reason hibernate is threating yout `int == 0` as an id and it is trying to update it instead of inserting a new record ( deafult value for int =0 ) just change your id type to `Integer` and see if it solve the problem
53,758,509
I'm trying to upload a csv. file I have on HDFS to mongoDB. I'm using a python script for that purpose: <https://i.imgur.com/G33sDaz.png> Using spark 2 and the command: spark-submit --packages org.mongodb.spark:mongo-spark-connector\_2.11:2.0.0 cities\_mongodb.py gets me the following error message: <https://i.imgur.com/91HgZff.png> I tried searching for missing collection name but didn't find a result. Please note I'm very new to python and don't know the language myself, I'm using a python script from a tutorial with only minor changes. The line .mode('append')\ (which is part of the error message) was already in the script without any changes on my part. Thanks for your help
2018/12/13
[ "https://Stackoverflow.com/questions/53758509", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10785117/" ]
It is possible, but a bit hack, because is necessary converting to `object`: ``` df3['T'] = np.array([int(x) if int(x) == x else x for x in df3['T']], dtype=object) print (df3) T v2 v3 v4 0 11 11.0 112.1 NaN 1 22 13.0 2.0 blue 2 11.23 55.1 2.1 1 3 20.03 33.0 366.0 2 print (df3['T'].tolist()) [11, 22, 11.23, 20.03] ``` If possible missing values: ``` df3 = pd.DataFrame({ 'T': [11.0,22.0,11.23,np.nan], 'v2': [11.0,13.0,55.1,33.0], 'v3' : [112.1,2.0,2.1,366.0], 'v4': [np.nan, "blue", 1.0, 2.0] }) df3['T'] = np.array([int(x) if x % 1 == 0 else x for x in df3['T']], dtype=object) print (df3) T v2 v3 v4 0 11 11.0 112.1 NaN 1 22 13.0 2.0 blue 2 11.23 55.1 2.1 1 3 NaN 33.0 366.0 2 print (df3['T'].tolist()) [11, 22, 11.23, nan] ```
Using the same idea of @jezrael but with [is\_integer](https://docs.python.org/3/library/stdtypes.html#float.is_integer): ``` import numpy as np import pandas as pd df3 = pd.DataFrame({ 'T': [11.0, 22.0, 11.23, 20.03], 'v2': [11.0, 13.0, 55.1, 33.0], 'v3': [112.1, 2.0, 2.1, 366.0], 'v4': [np.nan, "blue", 1.0, 2.0] }) df3['T'] = np.array([int(x) if float(x).is_integer() else x for x in df3['T']], dtype=object) print(df3) ``` **Output** ``` T v2 v3 v4 0 11 11.0 112.1 NaN 1 22 13.0 2.0 blue 2 11.23 55.1 2.1 1 3 20.03 33.0 366.0 2 ``` Or using [numpy.where](https://docs.scipy.org/doc/numpy-1.10.4/reference/generated/numpy.where.html) with [numpy.fmod](https://docs.scipy.org/doc/numpy/reference/generated/numpy.fmod.html#numpy.fmod): ``` mask = np.fmod(df3['T'].values, 1) == 0 df3['T'] = np.where(mask, df3['T'].values.astype(np.int), df3['T']).astype(dtype=object) print(df3) ```
70,059,204
I want to import numbers (40000 in total, space-separated) (format: 2.000000000000000000e+02) with "fscanf" and put it in a 1D-Array. I tried a lot of things, but the numbers I am getting are strange. What I've got until now: ``` int main() { FILE* pixel = fopen("/Users/xy/sample.txt", "r"); float arr[40000]; fscanf(pixel,"%f", arr); for(int i = 0; i<40000; i++) printf("%f", arr[i]); } ``` I hope somebody can help me, I am a beginner ;-) Thank you very much!!
2021/11/21
[ "https://Stackoverflow.com/questions/70059204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17474208/" ]
Instead of: ``` fscanf(pixel,"%f", arr); ``` which is the exact equivalent of this and which read only one single value: ``` fscanf(pixel,"%f", &arr[0]); ``` you want this: ``` for(int i = 0; i<40000; i++) fscanf(pixel,"%f", &arr[i]); ``` Complete code: ``` #include <stdio.h> #include <stdlib.h> int main() { FILE* pixel = fopen("/Users/xy/sample.txt", "r"); if (pixel == NULL) // check if file could be opened { printf("Can't open file"); exit(1); } float arr[40000]; int nbofvaluesread = 0; for(int i = 0; i < 40000; i++) // read 40000 values { if (fscanf(pixel,"%f", &arr[i]) != 1) break; // stop loop if nothing could be read or because there // are less than 40000 values in the file, or some // other rubbish is in the file nbofvaluesread++; } for(int i = 0; i < nbofvaluesread ; i++) printf("%f", arr[i]); fclose(pixel); // don't forget to close the file } ``` Disclaimer: this is untested code, but it should give you an idea of what you did wrong.
You need to call `fscanf()` in a loop. You're just reading one number. ``` int main() { FILE* pixel = fopen("/Users/xy/sample.txt", "r"); if (!pixel) { printf("Unable to open file\n"); exit(1); } float arr[40000]; for (int i = 0; i < 40000; i++) { fscanf(pixel, "%f", &arr[i]); } for(int i = 0; i<40000; i++) { printf("%f", arr[i]); } printf("\n"); } ```
649,019
I have a WSDL file for a web service. I'm using JAX-WS/wsimport to generate a client interface to the web service. I don't know ahead of time the host that the web service will be running on, and I can almost guarantee it won't be <http://localhost:8080>. How to I specify the host URL at runtime, e.g. from a command-line argument? The generated constructor `MyService(URL wsdlLocation, QName serviceName)` doesn't seem like what I want, but maybe it is? Perhaps one of the variants of `Service.getPort(...)`? Thanks!
2009/03/16
[ "https://Stackoverflow.com/questions/649019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40310/" ]
The constructor should work fine for your needs, when you create MyService, pass it the url of the WSDL you want i.e. <http://someurl:someport/service?wsdl>.
In your generated code (eg: say "HelloWorldWebServiceImplService" ) look in to the static block on the top which will have reference to the WSDL url or wsdl file which is under META-INF. ``` /* static { URL url = null; try { url = new URL("http://loclahost/HelloWorld/HelloWorldWebServiceImpl?wsdl"); } catch (MalformedURLException e) { java.util.logging.Logger.getLogger(HelloWorldWebServiceImplService.class.getName()) .log(java.util.logging.Level.INFO, "Can not initialize the default wsdl from {0}", "http://loclahost/HelloWorld/HelloWorldWebServiceImpl?wsdl"); } WSDL_LOCATION = url; } */ ``` Once you comment this you also need to comment out the default construtor and needless to say intialize the static WSDL\_LOCATION = null; (to null) So you will not have two constructors as shown below. ``` public final static URL WSDL_LOCATION = null; public HelloWorldWebServiceImplService(URL wsdlLocation) { super(wsdlLocation, SERVICE); } public HelloWorldWebServiceImplService(URL wsdlLocation, QName serviceName) { super(wsdlLocation, serviceName); } ``` **Calling Webservice :** Now in the client call where you instantiate this object Pass the webservice URL as an argument as shown ``` //You can read mywebserviceURL from property file as String. String mywebserviceURL = "http://myqamachine.com/HelloWorld/HelloWorldWebServiceImpl?wsdl" URL WsURL = new URL(mywebserviceURL); HelloWorldWebServiceImplService webService = new HelloWorldWebServiceImplService(WsURL); ``` So here you can point the webservice url dynamically.
35,070
Is there a single English word to describe when someone has appropriated property that doesn't belong to them unintentionally? For example, say I borrow a pen from someone and absentmindedly put it in my pocket after I finish writing. I discover the pen much later. Did I steal it, or is there a term with less harsh connotations?
2011/07/21
[ "https://english.stackexchange.com/questions/35070", "https://english.stackexchange.com", "https://english.stackexchange.com/users/10453/" ]
Unfortunately most terms I can think of are equally harsh. Even **misappropriate** (to steal something that you have been trusted to take care of and use it for your own good) implies misuse of someone else's property. However it does at least imply that you were originally given the pen by the original owner rather than just stealing it.
The word you are looking for is, "CONVERSION". Basically, the difference is, your intent wasn't to deprive the owner of his/her property. In an extreme case, taking a neighbors car to go joyriding with no intent to damage or cause any loss to its owner.
28,561,470
I have a table with multiple columns. In one of the column rows I want to add 2 elements which will be next to each other. One text element and one icon. The icon has a fixed with, the text element needs to be dynamic and has to be truncated with ... when the column cannot stretch anymore. This is the HTML: ``` <table> <tr> <td> </td> <td> <span>Truncated text goes here</span> <i class="icn sprite icn-name></i> </td> <td> </td> </tr> </table> ``` How do I do this? Using `display: table;` will make the HTML all buggy.
2015/02/17
[ "https://Stackoverflow.com/questions/28561470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2247819/" ]
Suppose `df` is your data.frame. The first thing is to convert all `factors` in `character`. Then replace with the wanted values - I do this with a deep functional programming approach, so no side effect on your `df` :) and convert wanted columns to `numeric`: ``` library(functional) df[] = lapply(df, as.character) f = function(df, u, target) {df[df==u]=target; df} fs = Map(function(x,y) Curry(f, u=x, target=y), c('P','A','M'),c('2','-2','0')) df1 = Reduce(Compose, fs)(df) df1 = transform(df1, V5=rowSums(apply(df1[,2:4], 2, as.numeric))) transform(df1, V6=ifelse(df1$V5>0, 'P', ifelse(df1$V5<0,'A','0'))) # V1 V2 V3 V4 V5 V6 #1 CCL5 2 0 0 2 P #2 CYP2A6 0 -2 -2 -4 A #3 CYP2E1 2 -2 2 2 P #4 DDR1 2 0 2 4 P ``` **Data** ``` df = data.frame(V1=c("CCL5","CYP2A6","CYP2E1","DDR1"), V2=c("P",'M','P','P'), V3=c('0','A','A','0'), V4=c('0','A','P','P')) ```
Have you tried ``` d1[d1 == "P"] <- 2 d1[d1 == "A"] <- -2 d1[d1 == "M"] <- 0 ``` Then you can take rowsums of d1[, 2:5] and place then in the last column. And finally replace again with ``` d1[,6][d1[,6] > 0] <- "P" d1[,6][d1[,6] < 0] <- "A" ```
62,963
Last year, Scott Guthrie [stated](http://weblogs.asp.net/scottgu/archive/2007/07/31/linq-to-sql-debug-visualizer.aspx) “You can actually override the raw SQL that LINQ to SQL uses if you want absolute control over the SQL executed”, but I can’t find documentation describing an extensibility method. I would like to modify the following LINQ to SQL query: ``` using (NorthwindContext northwind = new NorthwindContext ()) { var q = from row in northwind.Customers let orderCount = row.Orders.Count () select new { row.ContactName, orderCount }; } ``` Which results in the following TSQL: ``` SELECT [t0].[ContactName], ( SELECT COUNT(*) FROM [dbo].[Orders] AS [t1] WHERE [t1].[CustomerID] = [t0].[CustomerID] ) AS [orderCount] FROM [dbo].[Customers] AS [t0] ``` To: ``` using (NorthwindContext northwind = new NorthwindContext ()) { var q = from row in northwind.Customers.With ( TableHint.NoLock, TableHint.Index (0)) let orderCount = row.Orders.With ( TableHint.HoldLock).Count () select new { row.ContactName, orderCount }; } ``` Which *would* result in the following TSQL: ``` SELECT [t0].[ContactName], ( SELECT COUNT(*) FROM [dbo].[Orders] AS [t1] WITH (HOLDLOCK) WHERE [t1].[CustomerID] = [t0].[CustomerID] ) AS [orderCount] FROM [dbo].[Customers] AS [t0] WITH (NOLOCK, INDEX(0)) ``` Using: ``` public static Table<TEntity> With<TEntity> ( this Table<TEntity> table, params TableHint[] args) where TEntity : class { //TODO: implement return table; } public static EntitySet<TEntity> With<TEntity> ( this EntitySet<TEntity> entitySet, params TableHint[] args) where TEntity : class { //TODO: implement return entitySet; } ``` And ``` public class TableHint { //TODO: implement public static TableHint NoLock; public static TableHint HoldLock; public static TableHint Index (int id) { return null; } public static TableHint Index (string name) { return null; } } ``` Using some type of LINQ to SQL extensibility, other than [this one](http://blogs.msdn.com/mattwar/archive/2008/05/04/mocks-nix-an-extensible-linq-to-sql-datacontext.aspx). Any ideas?
2008/09/15
[ "https://Stackoverflow.com/questions/62963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5869/" ]
The ability to change the underlying provider and thus modify the SQL did not make the final cut in LINQ to SQL.
`DataContext x = new DataContext` Something like this perhaps? `var a = x.Where().with()`...etc It lets you have a much finer control over the SQL.
23,012,148
I have a query that produces one row. I would like to output this one row multiple times, determined by a constant in this query. The query is on the format: ``` select A.a, B.b, C.c from A inner join B .. inner join C .. where A.a =.. and B.b = .. and C.c = .. ``` This gives the result: ``` [A.a, B.b, C.c] ``` but what I want is, given that the constant is 3: ``` [A.a, B.b, C.c] [A.a, B.b, C.c] [A.a, B.b, C.c] ``` Is there an easy way to do this? Using UNION ALL with the query repeated doesn't work because I need to use a numeric value to specify the number of times the value should be repeated. This value will be a parameter for a report made with *iReport* with this query. If it could be done in *iReport* that would also work, but it has to be possible in a very old version of *iReport (3.0.0)*. Any help would be greatly appreciated, I've been googling this for hours but can't find a solution that works. It seems like it should be a simple task.
2014/04/11
[ "https://Stackoverflow.com/questions/23012148", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1731401/" ]
You will need to a table to use in a [Cartesian product](http://en.wikipedia.org/wiki/Cartesian%5fproduct). Using a Cartesian product will multiply your business data results by the number of rows in the table. I would generate the table as an in-memory table rather than a physical table. That way you don't have additional database objects to maintain. The only reason I would create the number table as a physical table is as a performance optimization so that you don't incur the cost of building the table in-memory all the time. But I'm not even sure that would help, so I'd have to take some measurements to evaluate. You could create that in-memory table in several ways: 1. Recursive SQL. 2. Declared Global Temporary Table, insert ? numbers into it. 3. Union a bunch of one row queries together. Of those options, recursive SQL would be the best option, since you could get the result you want with a single SQL statement, and it sounds like you want to use an application that may not have the flexibility to build some of these more complex processes. The other two would either require dynamically building a SQL statement (for a union all) or inserting using the program a number of times. For a recursive SQL in DB2, you would create a basic [Recursive CTE](http://publib.boulder.ibm.com/infocenter/dzichelp/v2r2/index.jsp?topic=/com.ibm.db2z10.doc.apsg/src/tpc/db2z%5fxmprecursivecte.htm) to generate the desired number of rows. Keep the recursive portion separate from your actual business query so that the code is as clear as possible. When you come back to this in six months and it's not fresh in your mind, you want to be able to see a clear delineation between the generated values, and your business data SQL. Add the recursive CTE at the top, and put a reference to it in the FROM clause of your original query. That's all you should need: ``` with genrows(num) as ( select 1 from sysibm.sysdummy1 union all select num+1 from genrows where num < ? ) select A.a, B.b, C.c from genrows /* and add genrows here to make the Cartesian product */ , A inner join B .. inner join C .. where A.a =.. and B.b = .. and C.c = .. ```
This is a little workaround, but you can make a table, that contains number from 1 to 10 for example. Then you can join your row with this table where number\_in\_aux\_table <= your constant.
26,796,159
I want to know about that how can we stream videos from one my one drive using Office 365 api, Is it possible or we have to download file first I am exploring the following api provided by Microsoft <http://msdn.microsoft.com/en-us/office/office365/howto/common-file-tasks-client-library#GetClient> Thanks is advance
2014/11/07
[ "https://Stackoverflow.com/questions/26796159", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1097149/" ]
No you can't stream it using the O365 REST API, you'll have to download the file first.
You could try HTTP progressive download mechanism that doesn't require full file to be downloaded prior to playback. The media player has to be capable of playing with buffered data. On most modern players that is supported.
426,537
I am writing a bash script to move all images into a central file. I create the list of image files with: ``` img_fil='/home/files/img_dump.txt' locate -i image | grep \.jpg > "$img_fil" locate -i image | grep \.jpeg >> "$img_fil" locate -i image | grep \.gif >> "$img_fil" locate -i image | grep \.tif >> "$img_fil" locate -i image | grep \.png >> "$img_fil" ``` But when I start processing the dump file for this, most of the paths contain blanks so this does not work: ``` while read -r fline do if [ ! -e "$fline" ]; then echo "F=> $fline" mv "$fline" "$img_dir" else fpath="$(dirname $fline)" fname="$(basename $fline)" echo "F=> $fname P=> $fpath" fi done ``` The dirname and basename always parse at the blanks so will not process right. How do I get this to work?
2018/02/25
[ "https://unix.stackexchange.com/questions/426537", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/72706/" ]
``` fpath="$(dirname $fline)" fname="$(basename $fline)" ``` Here, you need to quote `$fline` inside the command substitution. (Outside doesn't matter since it's in an assignment.) So: ``` fpath=$(dirname -- "$fline") ``` or ``` fpath=${fline%/*} ``` (Though note the minor differences between `dirname`/`basename` and the parameter expansions, see: [dirname and basename vs parameter expansion](https://unix.stackexchange.com/q/253524/170373) )
Where are you using `$img_fil` in your script? Shouldn't the line `done` be `done < "$img_fil"`?
1,676,723
I'm taking an analysis class and I'm a little confused about this question. Also I'm mostly a computer science guy so I'm not great at proof based math so I apologize if this is ignorant > > Let $A = \{x : x \in \mathbb Q,\ x^3 < 2\}$ > > > Prove that $\sup A$ exists. Guess the value of $\sup A$. > > > So from what I understand, if you're work in the set of rationals, you can't set a least upper bound but you can find the sup which in this case would be $2^{1/3}$ However, I'm not really sure how I could prove that. Any advice would be great. Thanks
2016/02/29
[ "https://math.stackexchange.com/questions/1676723", "https://math.stackexchange.com", "https://math.stackexchange.com/users/293481/" ]
Hint: Consider the limit of $\cos(1/x\_n)/x\_n$ as $n \to \infty$ with $x\_n = 1/(2n\pi)$ and $x\_n = 1/ (\pi/2 + 2n\pi)$.
**Not really an answer** but related: the function $$f(z) = \exp(1/z), z\in\mathbb{C}$$ is a famous example of a function having an **essential singularity** at $z = 0$. That means by the famous Casorati-Weierstrass and [Picard's theorems](https://en.wikipedia.org/wiki/Picard_theorem) it will take all possible complex values in every neighbourhood of $0$ and that behaviour will not change no matter how many times we multiply or divide with $z$.
2,369,939
Has anyone ever tried to combine the use of google guice with obfuscation (in particular proguard)? The obfuscated version of my code does not work with google guice as guice complains about missing type parameters. This information seems to be erased by the transformation step that proguard does, even when the relevant classes are excluded from the obfuscation. The stack trace looks like this: ``` com.google.inject.CreationException: Guice creation errors: 1) Cannot inject a Provider that has no type parameter while locating com.google.inject.Provider for parameter 0 at de.repower.lvs.client.admin.user.administration.AdminUserCommonPanel.setPasswordPanelProvider(SourceFile:499) at de.repower.lvs.client.admin.user.administration.AdminUserCommonPanel.setPasswordPanelProvider(SourceFile:499) while locating de.repower.lvs.client.admin.user.administration.AdminUserCommonPanel for parameter 0 at de.repower.lvs.client.admin.user.administration.b.k.setParentPanel(SourceFile:65) at de.repower.lvs.client.admin.user.administration.b.k.setParentPanel(SourceFile:65) at de.repower.lvs.client.admin.user.administration.o.a(SourceFile:38) 2) Cannot inject a Provider that has no type parameter while locating com.google.inject.Provider for parameter 0 at de.repower.lvs.client.admin.user.administration.AdminUserCommonPanel.setWindTurbineAccessGroupProvider(SourceFile:509) at de.repower.lvs.client.admin.user.administration.AdminUserCommonPanel.setWindTurbineAccessGroupProvider(SourceFile:509) while locating de.repower.lvs.client.admin.user.administration.AdminUserCommonPanel for parameter 0 at de.repower.lvs.client.admin.user.administration.b.k.setParentPanel(SourceFile:65) at de.repower.lvs.client.admin.user.administration.b.k.setParentPanel(SourceFile:65) at de.repower.lvs.client.admin.user.administration.o.a(SourceFile:38) 2 errors at com.google.inject.internal.Errors.throwCreationExceptionIfErrorsExist(Errors.java:354) at com.google.inject.InjectorBuilder.initializeStatically(InjectorBuilder.java:152) at com.google.inject.InjectorBuilder.build(InjectorBuilder.java:105) at com.google.inject.Guice.createInjector(Guice.java:92) at com.google.inject.Guice.createInjector(Guice.java:69) at com.google.inject.Guice.createInjector(Guice.java:59) ``` I tried to create a small example (without using guice) that seems to reproduce the problem: ``` package de.repower.common; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; class SomeClass<S> { } public class ParameterizedTypeTest { public void someMethod(SomeClass<Integer> param) { System.out.println("value: " + param); System.setProperty("my.dummmy.property", "hallo"); } private static void checkParameterizedMethod(ParameterizedTypeTest testObject) { System.out.println("checking parameterized method ..."); Method[] methods = testObject.getClass().getMethods(); for (Method method : methods) { if (method.getName().equals("someMethod")) { System.out.println("Found method " + method.getName()); Type[] types = method.getGenericParameterTypes(); Type parameterType = types[0]; if (parameterType instanceof ParameterizedType) { Type parameterizedType = ((ParameterizedType) parameterType).getActualTypeArguments()[0]; System.out.println("Parameter: " + parameterizedType); System.out.println("Class: " + ((Class) parameterizedType).getName()); } else { System.out.println("Failed: type ist not instance of ParameterizedType"); } } } } public static void main(String[] args) { System.out.println("Starting ..."); try { ParameterizedTypeTest someInstance = new ParameterizedTypeTest(); checkParameterizedMethod(someInstance); } catch (SecurityException e) { e.printStackTrace(); } } } ``` If you run this code unsbfuscated, the output looks like this: ``` Starting ... checking parameterized method ... Found method someMethod Parameter: class java.lang.Integer Class: java.lang.Integer ``` But running the version obfuscated with proguard yields: ``` Starting ... checking parameterized method ... Found method someMethod Failed: type ist not instance of ParameterizedType ``` These are the options I used for obfuscation: ``` -injars classes_eclipse\methodTest.jar -outjars classes_eclipse\methodTestObfuscated.jar -libraryjars 'C:\Program Files\Java\jre6\lib\rt.jar' -dontskipnonpubliclibraryclasses -dontskipnonpubliclibraryclassmembers -dontshrink -printusage classes_eclipse\shrink.txt -dontoptimize -dontpreverify -verbose -keep class **.ParameterizedTypeTest.class { <fields>; <methods>; } -keep class ** { <fields>; <methods>; } # Keep - Applications. Keep all application classes, along with their 'main' # methods. -keepclasseswithmembers public class * { public static void main(java.lang.String[]); } # Also keep - Enumerations. Keep the special static methods that are required in # enumeration classes. -keepclassmembers enum * { public static **[] values(); public static ** valueOf(java.lang.String); } # Also keep - Database drivers. Keep all implementations of java.sql.Driver. -keep class * extends java.sql.Driver # Also keep - Swing UI L&F. Keep all extensions of javax.swing.plaf.ComponentUI, # along with the special 'createUI' method. -keep class * extends javax.swing.plaf.ComponentUI { public static javax.swing.plaf.ComponentUI createUI(javax.swing.JComponent); } # Keep names - Native method names. Keep all native class/method names. -keepclasseswithmembers,allowshrinking class * { native <methods>; } # Keep names - _class method names. Keep all .class method names. This may be # useful for libraries that will be obfuscated again with different obfuscators. -keepclassmembers,allowshrinking class * { java.lang.Class class$(java.lang.String); java.lang.Class class$(java.lang.String,boolean); } ``` Does anyone have an idea of how to solve this (apart from the obvious workaround to put the relevant files into a seperate jar and not obfuscate it)? Best regards, Stefan
2010/03/03
[ "https://Stackoverflow.com/questions/2369939", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4497/" ]
With the current version of Proguard (4.7) I was able to get it working by adding the following:- ``` -keepattributes *Annotation*,Signature -keep class com.google.inject.Binder -keep public class com.google.inject.Inject # keeps all fields and Constructors with @Inject -keepclassmembers,allowobfuscation class * { @com.google.inject.Inject <fields>; @com.google.inject.Inject <init>(...); } ``` In addition to explicitly keeping any class that is created by Guice eg ``` -keep class com.example.Service ```
Following code works for me, having had the same problem. `-keepattributes Signature` was the fix. ``` -optimizationpasses 5 -dontusemixedcaseclassnames -dontskipnonpubliclibraryclasses -dontpreverify #-dontobfuscate -repackageclasses '' -keepattributes *Annotation* -keepattributes Signature -verbose -optimizations !code/simplification/arithmetic,!field/*,!class/merging/* -keep public class * extends android.app.Activity -keep public class * extends android.app.Application -keep public class * extends android.app.Service -keep public class * extends android.content.BroadcastReceiver -keep public class * extends android.content.ContentProvider -keep public class * extends android.app.backup.BackupAgentHelper -keep public class * extends android.preference.Preference -keep public class com.android.vending.licensing.ILicensingService -keepclasseswithmembernames class * { native <methods>; } -keepclasseswithmembernames class * { public <init>(android.content.Context, android.util.AttributeSet); } -keepclasseswithmembernames class * { public <init>(android.content.Context, android.util.AttributeSet, int); } -keepclassmembers enum * { public static **[] values(); public static ** valueOf(java.lang.String); } -keepattributes Signature -keep class * implements android.os.Parcelable { public static final android.os.Parcelable$Creator *; } -keep class com.google.inject.Binder -keepclassmembers class * { @com.google.inject.Inject <init>(...); } -keep public class * extends android.view.View { public <init>(android.content.Context); public <init>(android.content.Context, android.util.AttributeSet); public <init>(android.content.Context, android.util.AttributeSet, int); public void set*(...); } # I didn't need this one, maybe you need it. #-keep public class roboguice.** -keepclassmembers class **.R$* { public static <fields>; } ```
35,775,080
We're currently working on a query for a report that returns a series of data. The customer has specified that they want to receive 5 rows total, with the data from the previous 5 days (as defined by a start date and an end date variable). For each day, they want the data from the row that's closest to 4am. I managed to get it to work for a single day, but I certainly don't want to union 5 separate select statements simply to fetch these values. Is there any way to accomplish this via CTEs? ``` select top 1 'W' as [RecordType] , [WellIdentifier] as [ProductionPtID] , t.Name as [Device Name] , t.RecordDate --convert(varchar, t.RecordDate, 112) as [RecordDate] , TubingPressure as [Tubing Pressure] , CasingPressure as [Casing Pressure] from #tTempData t Where cast (t.recorddate as time) = '04:00:00.000' or datediff (hh,'04:00:00.000',cast (t.recorddate as time)) < -1.2 order by Name, RecordDate desc ```
2016/03/03
[ "https://Stackoverflow.com/questions/35775080", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2228526/" ]
assuming that the #tTempData only contains the previous 5 days records ``` SELECT * FROM ( SELECT *, rn = row_number() over ( partition by convert(date, recorddate) order by ABS ( datediff(minute, convert(time, recorddate) , '04:00' ) ) FROM #tTempData ) WHERE rn = 1 ```
Try something like this: ``` select 'W' as [RecordType] , [WellIdentifier] as [ProductionPtID] , t.Name as [Device Name] , t.RecordDate --convert(varchar, t.RecordDate, 112) as [RecordDate] , TubingPressure as [Tubing Pressure] , CasingPressure as [Casing Pressure] from #tTempData t Where exists (select 1 from #tTempData t1 where ABS(datediff (hh,'04:00:00.000',cast (t.recorddate as time))) < ABS(datediff (hh,'04:00:00.000',cast (t1.recorddate as time))) and GETDATE(t.RecordDate) = GETDATE(t1.RecordDate) )dt and t.RecordDate between YOURDATERANGE order by Name, RecordDate desc; ```
4,963,881
I have an aspx page which allows a user to submit modified entries into the database, but when the user clicks `Submit` to fire the stored procedure I want to first run a check to see if a modified row with the same relationship exists. I am passing the results of the following query: ``` SELECT SwitchRoom.ModifiedID FROM SwitchRoom WHERE SwitchRoomID = @ChkSwitchRmID", constring; ``` into a `DataReader` to determine if that relationship exists. I need it to determine whether the reader returns `NULL` to allow the procedure to execute, if it doesn't, then don't allow the user to save the information. I've tried the following: ``` if (dbreader = NULL) { Fire Procedure } else { "Error Message" } ``` and I've even tried passing the reader into a `datatable` and running it against that without any luck. How do I check the restults of a DataReader for `null`?
2011/02/10
[ "https://Stackoverflow.com/questions/4963881", "https://Stackoverflow.com", "https://Stackoverflow.com/users/606736/" ]
Try `if (!dbReader.Read() || dbreader.IsDbNull(field)} { .. }`
You're looking for the DBNull type. Databases don't send actual null-references, they send a special datatype in C# to represent a database NULL value.
6,273,931
The table view works fine however when I leave the view and come back to it the second time, I get a memory leak. Probably something in the viewDidLoad just not sure. I am running the leaks tool and am getting the following notification: ``` Leaked Object # Address Size Responsible Library Responsible Frame NSCFString 631 < multiple > 20192 Foundation -[NSCFString copyWithZone:] NSCFString 0x8339c80 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8339af0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8339960 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x83397d0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8339640 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x83394b0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8339320 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8339190 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8339000 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8338e70 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8338ce0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8338b50 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x83389c0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8338830 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x83386a0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8338510 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8338380 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x83381f0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8338060 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8337ed0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8337d40 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8337bb0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8337a20 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x83378b0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8337720 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8337590 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8337400 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8337270 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x83370b0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8336f40 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8336dd0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8336c50 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8336ae0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8336960 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x83367e0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8336660 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x83364f0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8336360 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x83361e0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8336070 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8335ee0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8335d60 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8335be0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8335a60 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x83358f0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8335760 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8335470 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8335180 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8334e80 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8334d10 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8334b90 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8334a10 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8334890 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x83344a0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8334310 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8334180 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8333e10 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8333c80 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8333af0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8333970 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8333800 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8333670 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8323220 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8320160 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x831eef0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x831e5e0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x831d710 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8312e80 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x83119c0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x830e1c0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x83055c0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8031900 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8031770 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8031470 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8031300 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8031190 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8031010 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8030ea0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8030d20 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8030ba0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8030a20 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x80308b0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8030720 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x80305a0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x80302a0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802ffa0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802fe80 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802fb90 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802fa20 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802f8b0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802f730 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802f5c0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802f2d0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802ef10 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802ed80 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802ebd0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802ea50 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802e8e0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802cbe0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802cb40 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802c9c0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802c840 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802c6d0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802c560 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802c3e0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802c270 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802c100 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802bf90 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802bdf0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802bdd0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802bc60 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802bb90 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802b9e0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x802b870 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8028080 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x8027fe0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6f5e0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6f450 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6f150 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6efd0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6ee50 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6ece0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6eb60 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6e9e0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6e870 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6e700 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6e580 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6e400 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6e280 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6e100 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6df80 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6de00 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6dc80 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6db10 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6d930 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6d7c0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6d640 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6d420 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6d3b0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6d220 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6d090 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6cf00 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6cd70 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6cbe0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6ca50 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6c8c0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6c730 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6c5a0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6c410 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6c280 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6c0f0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6bf60 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6be10 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6bca0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6bb30 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6b9c0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6b850 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6b6e0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6b550 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6b3c0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6b230 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6b0c0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6af50 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6ae00 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6ac90 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6ab20 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6a9d0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6a880 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6a6f0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6a560 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6a3e0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6a260 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e6a0e0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e69f50 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e69de0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e69c60 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e69af0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e69980 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e69800 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e69680 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e69500 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e69380 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e69200 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e69090 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e68f20 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e68da0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e68c30 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e68ab0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e68930 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e687b0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e68640 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e684c0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e68340 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e681d0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e68040 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e67ec0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e67d40 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e67bc0 32 Foundation -[NSCFString copyWithZone:] NSCFString 0x4e67a50 32 Foundation -[NSCFString copyWithZone:] ``` when i click on the first line in extended view I get: ``` 14 CFNetwork URLConnectionClient::_clientDidFinishLoading(URLConnectionClient::ClientConnectionEventQueue*) 15 CFNetwork URLConnectionClient::ClientConnectionEventQueue::processAllEventsAndConsumePayload(XConnectionEventInfo<XClientEvent, XClientEventParams>*, long) 16 CFNetwork URLConnectionClient::processEvents() 17 CFNetwork MultiplexerSource::perform() ``` Here is the code: ``` #import "AddRemoteRecipientsTableViewController.h" #import "MyManager.h" #import "FaxRecipient.h" @implementation AddRemoteRecipientsTableViewController @synthesize lastIndexPath; @synthesize delegate=_delegate; @synthesize faxRecipient; /* -(IBAction) btnSave{ } -(IBAction) btnDone{ } */ -(void) loadRemoteRecipients{ activityIndicator.startAnimating; [remoteRecipientItems removeAllObjects]; [[self tableView] reloadData]; NSString * uName=[[NSUserDefaults standardUserDefaults]objectForKey:@"userNameKey"]; NSString * pWord = [[NSUserDefaults standardUserDefaults]objectForKey:@"passwordKey"]; NSURL *url = [NSURL URLWithString: @"https://someurl"]; NSString *xmlString = [NSString stringWithFormat: @"<?xml version=\"1.0\" encoding=\"utf-8\" ?>" "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">" "<soap:Body>" "<GetContactsWithId xmlns=\"http://tempuri.org/\">" "<uid>%@</uid>" "<pwd>%@</pwd>" "</GetContactsWithId>" "</soap:Body>" "</soap:Envelope>",uName,pWord ]; NSData *data = [xmlString dataUsingEncoding:NSUTF8StringEncoding]; NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url]; //---set the headers--- NSString *msgLength = [NSString stringWithFormat:@"%d", [xmlString length]]; [request addValue:@"text/xml; charset=utf-8" forHTTPHeaderField:@"Content-Type"]; [request addValue:@"http://someurl" forHTTPHeaderField:@"SOAPAction"]; [request addValue:msgLength forHTTPHeaderField:@"Content-Length"]; //---set the HTTP method and body--- [request setHTTPMethod:@"POST"]; [request setHTTPBody: data]; if (connectionInprogress) { [connectionInprogress cancel]; [connectionInprogress release]; } //instantiate object to hold incoming data [xmlData release]; xmlData = [[NSMutableData alloc]init]; connectionInprogress = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES]; } -(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{ [xmlData appendData:data]; } - (void) connectionDidFinishLoading:(NSURLConnection *)connection{ NSXMLParser *parser = [[NSXMLParser alloc]initWithData:xmlData]; [parser setDelegate:self]; [parser parse]; [parser release]; [[self tableView] reloadData]; activityIndicator.stopAnimating; [connectionInprogress release]; connectionInprogress = nil; [xmlData release]; xmlData = nil; } #pragma mark - #pragma Parser Methods -(void)parser:(NSXMLParser *)parser didStartElement:(NSString *) elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName attributes:(NSDictionary *)attributeDict { if ([elementName isEqual:@"ContactId"]) { faxRecipient =[[FaxRecipient alloc]init]; remoteRecipientString = [[NSMutableString alloc]init]; } else if ([elementName isEqual:@"Name"]) { remoteRecipientString = [[NSMutableString alloc]init]; }else if ([elementName isEqual:@"Fax"]) { remoteRecipientString = [[NSMutableString alloc]init]; } else if ([elementName isEqual:@"Company"]) { remoteRecipientString = [[NSMutableString alloc]init]; } } -(void) parser:(NSXMLParser *)parser foundCharacters:(NSString *)string{ [remoteRecipientString appendString:string]; } -(void)parser:(NSXMLParser *)parser didEndElement:(NSString *) elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName{ if ([elementName isEqual:@"ContactId"]) { faxRecipient.contactID = remoteRecipientString; [remoteRecipientString release]; remoteRecipientString = nil; } if ([elementName isEqual:@"Name"]) { faxRecipient.name = remoteRecipientString; [remoteRecipientString release]; remoteRecipientString = nil; } if ([elementName isEqual:@"Fax"]) { faxRecipient.fax = remoteRecipientString; [remoteRecipientString release]; remoteRecipientString = nil; } if ([elementName isEqual:@"Company"]) { faxRecipient.company = remoteRecipientString; [remoteRecipientItems addObject:faxRecipient]; [faxRecipient release]; faxRecipient = nil; [remoteRecipientString release]; remoteRecipientString = nil; } } -(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{ [connectionInprogress release]; connectionInprogress = nil; [xmlData release]; xmlData = nil; NSString *errorString = [NSString stringWithFormat:@"Remote Recipient Fetch Failed %@",[error localizedDescription]]; UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:errorString delegate:nil cancelButtonTitle:@"OK" destructiveButtonTitle:nil otherButtonTitles:nil]; [actionSheet showInView:[[self view]window]]; [actionSheet autorelease]; } #pragma mark - #pragma mark Initialization /* - (id)initWithStyle:(UITableViewStyle)style { // Override initWithStyle: if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad. self = [super initWithStyle:style]; if (self) { // Custom initialization. } return self; } */ #pragma mark - #pragma mark View lifecycle - (void)viewDidLoad { [super viewDidLoad]; remoteRecipientItems = [[NSMutableArray alloc]init]; remoteRecipientID = [[NSMutableArray alloc]init]; // add activity indicator activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray]; activityIndicator.center = CGPointMake(self.view.bounds.size.width / 2.0f, self.view.bounds.size.height / 2.0f); activityIndicator.hidesWhenStopped = YES; [self.view addSubview:activityIndicator]; } - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; [self loadRemoteRecipients]; /* self.navigationController.toolbarHidden=NO; UIBarButtonItem *saveItem; UIBarButtonItem *doneItem; saveItem = [[ UIBarButtonItem alloc ] initWithTitle: @"Save" style: UIBarButtonItemStyleBordered target: self action: @selector( btnSave ) ]; doneItem = [[ UIBarButtonItem alloc ] initWithTitle: @"Done" style: UIBarButtonItemStyleBordered target: self action: @selector( btnDone ) ]; self.toolbarItems = nil ; self.toolbarItems = [ NSArray arrayWithObjects: saveItem,doneItem,nil ]; [saveItem release]; [doneItem release]; */ } /* - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; } */ - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; /* self.navigationController.toolbarHidden=YES; */ } /* - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; } */ /* // Override to allow orientations other than the default portrait orientation. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations. return (interfaceOrientation == UIInterfaceOrientationPortrait); } */ #pragma mark - #pragma mark Table view data source - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { // Return the number of sections. return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { // Return the number of rows in the section. return [remoteRecipientItems count]; } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *CellIdentifier = @"RemoteRecipientItem"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; if (cell == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease]; } NSUInteger row = [indexPath row]; NSUInteger oldRow = [lastIndexPath row]; // Configure the cell... FaxRecipient *faxObject= [remoteRecipientItems objectAtIndex:indexPath.row]; [[cell textLabel]setText:faxObject.name]; cell.accessoryType = (row == oldRow && lastIndexPath !=nil)? UITableViewCellAccessoryCheckmark : UITableViewCellAccessoryNone; cell.imageView.image = [UIImage imageNamed:@"contact.png"]; return cell; } #pragma mark - #pragma mark Table view delegate - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { int newRow = [indexPath row]; int oldRow = (lastIndexPath !=nil)?[lastIndexPath row]:-1; if (newRow != oldRow) { UITableViewCell *newCell = [tableView cellForRowAtIndexPath:indexPath]; newCell.accessoryType = UITableViewCellAccessoryCheckmark; UITableViewCell *oldCell = [tableView cellForRowAtIndexPath:lastIndexPath]; oldCell.accessoryType = UITableViewCellAccessoryNone; // lastIndexPath = indexPath; lastIndexPath = [indexPath retain]; } [tableView deselectRowAtIndexPath:indexPath animated:YES]; FaxRecipient *faxObject= [remoteRecipientItems objectAtIndex:[indexPath row]]; [self.delegate getRemoteRecipient:faxObject]; [self.navigationController popViewControllerAnimated:YES]; } #pragma mark - #pragma mark Memory management - (void)didReceiveMemoryWarning { // Releases the view if it doesn't have a superview. [super didReceiveMemoryWarning]; // Relinquish ownership any cached data, images, etc. that aren't in use. } - (void)viewDidUnload { // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand. // For example: self.myOutlet = nil; remoteRecipientItems = nil; remoteRecipientID = nil; lastIndexPath = nil; faxRecipient = nil; } - (void)dealloc { [remoteRecipientItems release]; [remoteRecipientID release]; [lastIndexPath release]; [faxRecipient release]; [super dealloc]; } @end ```
2011/06/08
[ "https://Stackoverflow.com/questions/6273931", "https://Stackoverflow.com", "https://Stackoverflow.com/users/323698/" ]
I see most of your statement are ready for leak, e.g in the viewDidUnload method , you are not releasing any instance member properly. you need to call release on the object which you either alloced, init or retain. ``` (void)viewDidUnload { // Relinquish ownership of anything that can be recreated in viewDidLoad or on demand. // For example: self.myOutlet = nil; [remoteRecipientItems release]; remoteRecipientItems = nil; [remoteRecipientID release]; remoteRecipientID = nil; .................. .................. } ``` Would suggest you to spend some time to read [Memory Management Programming Guide](http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/MemoryMgmt.html)
I heard the > > [UIImage imageNamed:@"contact.png"]; > > > is a memory occurring line. It will create an autorelease object as the returned object. May be that can also be a problem.
65,702,197
I am retrieving data from firebase and storing it into list items. But I want to reverse the order, which will bring new posts at the top. What should I add to make it work that way? [JsFiddle of my code](https://jsfiddle.net/g0eadwkL/) This is my function for retrieving the data ``` const dbRef = firebase.database().ref(); const usersRef = dbRef.child('users'); readUserData(); // READ function readUserData() { const userListUI = document.getElementById("user-list"); usersRef.on("value", snap => { userListUI.innerHTML = "" snap.forEach(childSnap => { let key = childSnap.key, value = childSnap.val() let $li = document.createElement("li"); // edit icon let editIconUI = document.createElement("span"); editIconUI.class = "edit-user"; editIconUI.innerHTML = " ✎"; editIconUI.setAttribute("userid", key); editIconUI.addEventListener("click", editButtonClicked) // delete icon let deleteIconUI = document.createElement("span"); deleteIconUI.class = "delete-user"; deleteIconUI.innerHTML = " ☓"; deleteIconUI.setAttribute("userid", key); deleteIconUI.addEventListener("click", deleteButtonClicked) $li.innerHTML = value.name; $li.append(editIconUI); $li.append(deleteIconUI); $li.setAttribute("user-key", key); $li.addEventListener("click", userClicked) userListUI.append($li); }); }) } ```
2021/01/13
[ "https://Stackoverflow.com/questions/65702197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13475348/" ]
This worked for me `Modifier.height(IntrinsicSize.Min)` ``` @Composable fun content() { return Row( modifier = Modifier .height(IntrinsicSize.Min) ) { Box( modifier = Modifier .width(8.dp) .fillMaxHeight() .background(Color.Red) ) Column { Text("Hello") Text("World") } } } ``` source: <https://www.rockandnull.com/jetpack-compose-fillmaxheight-fillmaxwidth/>
Have a look at the Layout Composable or Modifier. You can measure the defining element first and then provide modified constraints to the dependent element. If you want to use this as a modifier you should add a size check for the list. ```kotlin Layout(content = { Box(modifier = Modifier .size(width = 30.dp, height = 50.dp) .background(Color.Green)) Box( contentAlignment = Alignment.Center, modifier = Modifier .background(color = Color.Yellow) .fillMaxHeight() ) { CircularProgressIndicator() } }) { measurables: List<Measurable>, constraints: Constraints -> val heightDef = measurables[0].measure(constraints) val other = measurables[1].measure( constraints.copy( maxHeight = heightDef.height, maxWidth = constraints.maxWidth - heightDef.width) ) layout( width = heightDef.width + other.width, height = heightDef.height ) { other.placeRelative(0,0) heightDef.placeRelative(other.width,0) } } ```
273,290
Any idea's how to prevent the title from moving in promoted links webpart and instead remain stationary? Preferably using CSS, but willing to look at other options. using the below code i can somewhat get it to keep in the same location but it still pops up first. ``` <style type="text/css"> /* This section turns the Arrows on or off. For responsive design purposes, I would keep this and maybe left justify it, or at least move around the webpart to make it look good, but retain the functionality you're looking for. */ #WebPartWPQ9 .ms-promlink-header{ display:none; } </style> <style type="text/css"> /* BG was larger than image by "right" class, this removes it */ #WebPartWPQ9 .ms-promlink-body img{ right:inherit!important; } </style> <style type="text/css"> /* Body, keep big enough for the amount of tiles you want on a line - 3 lines. If your tiles are 150px by 150px, and you want 3 per row, set the width to 450(PLUS your padding set below-- so like... 475px) and height to 150. */ #WebPartWPQ9 .ms-promlink-body { height: 118px; width: 354px; } </style> <style type="text/css"> /*change the size of the tile canvas*/ #WebPartWPQ9 .ms-tileview-tile-root { width: 118px! important; height: 118px !important; } </style> <style type="text/css"> /*change the size of the tile*/ #WebPartWPQ9 .ms-tileview-tile-content { width: 118px !important; height: 118px !important; margin-bottom: -40px !important; } </style> <style> /*change the size of the image on the tile*/ #WebPartWPQ9 div.ms-tileview-tile-content > a > div > img { height: 118px !important; width: 118px !important; } </style> <style type="text/css"> /*remove the top margin from the details box after hovering with your mouse*/ #WebPartWPQ9 .ms-tileview-tile-detailsBox:hover { margin-top: 0px; /* addtional, Color change hover effect */ background-color: rgba(0,0,0,0.0); /*additional, underline hover effect */ text-decoration: underline; </style> <style type="text/css"> /* Changes Webpart Background Color */ #WebPartWPQ9 { background-color: #007ab8; } </style> <style type="text/css"> /* Set Bottom Border Style Cyan Thick */ #WebPartWPQ9 { border-bottom-width: 45px; border-bottom-color: #00a3f5; } </style> <style type="text/css"> /* Set Top Border Style None */ #WebPartWPQ9 { border-top-style: none; } </style> <style type="text/css"> /* Set Left Border Style None */ #WebPartWPQ9 { border-left-style: none; } </style> <style type="text/css"> /* Set Right Border Style None */ #WebPartWPQ9 { border-right-style: none; } </style> <style type="text/css"> /* Tiles, alter color of individual backgrounds. Setup for WebPartWPQ9 Navigation Menu */ #WebPartWPQ9 .ms-promlink-body img[alt*='High Fives'] { background-color: #0084c7; } .ms-promlink-body img[alt*='Documents'] { background-color: #007fbf; } .ms-promlink-body img[alt*='Videos'] { background-color: #0084c7; } .ms-promlink-body img[alt*='Forms'] { background-color: #007fbf; } .ms-promlink-body img[alt*='Policies'] { background-color: #0084c7; } .ms-promlink-body img[alt*='FOCI'] { background-color: #007fbf; } .ms-promlink-body img[alt*='CI Briefings'] { background-color: #0084c7; } .ms-promlink-body img[alt*='Suggestions'] { background-color: #007fbf; } .ms-promlink-body img[alt*='Quick Links'] { background-color: #0084c7; } </style> <style> /*changes height of text on overlay*/ #WebPartWPQ9 .ms-tileview-tile-titleMediumCollapsed { height: 20px !important; } </style> <style type="text/css"> /*change the size and position of the overlay box*/ #WebPartWPQ9 .ms-tileview-tile-detailsBox { width: 118px !important; height: 118px !important; margin-top: -15px; /* addtional, remove overlay color */ background-color: rgba(0,0,0,0); } </style> <style type="text/css"> /*remove the top margin from the details box after hovering with your mouse*/ #WebPartWPQ9 .ms-tileview-tile-detailsBox:hover { margin-top: 0px; /* addtional, Color change hover effect */ background-color: rgba(0,0,0,0.0); /*additional, underline hover effect */ text-decoration: underline; </style> <style type="text/css"> /* Tile hover color change */ #WebPartWPQ9 .ms-promlink-body img:hover { background-color: #0099e6 !important; } </Style> <style type="text/css"> /* Center Text */ #WebPartWPQ9 .ms-tileview-tile-titleMedium { display: block; text-align: center; font-size: 14px; } </style> <style type="text/css"> /* Center Text */ #WebPartWPQ9 .ms-tileview-tile-titleMediumCollapsed { display: block; text-align: center; font-size: 14px; } </style> <style type="text/css"> /* Center Text */ #WebPartWPQ9 .ms-tileview-tile-titleMediumExpanded { display: block; text-align: center; font-size: 14px; padding-top: 85px; } </style> <style type="text/css"> /* Center Text */ #WebPartWPQ9 .ms-tileview-tile-titleSmall { display: block; text-align: center; } </style> <style type="text/css"> /* Center Text */ #WebPartWPQ9 .ms-tileview-tile-titleSmallCollapsed { display: block; text-align: center; } </style> <style type="text/css"> /* Center Text */ #WebPartWPQ9 .ms-tileview-tile-titleSmallExpanded { display: block; text-align: center; } </style> <style type="text/css"> /* Center Text */ #WebPartWPQ9 .ms-tileview-tile-descriptionMedium { display: block; text-align: center; } </style> <style type="text/css"> /* Remove Overlay to not interfere with background color change */ /*need different solution breaks title underline ability*/ #WebPartWPQ9 .ms-tileview-tile-detailsBox { background-color: transparent; pointer-events: none; } </Style> ```
2019/12/09
[ "https://sharepoint.stackexchange.com/questions/273290", "https://sharepoint.stackexchange.com", "https://sharepoint.stackexchange.com/users/87908/" ]
You can create a view with the below filter options, 1. `Assigned To` is equal to `[ME]` **OR** 2. `Created By` is equal to `[ME]` So in this view, only the items in which the current logged in user is in "Assigned To" column or "Created By" column will only be displayed. This is a simple way to display item in which current logged in user is related to. There is another drawback too, if I know other items ID, then I can use them in the URL and access that item.
You can use [Audience Targeting](https://support.office.com/en-us/article/target-files-news-and-pages-to-specific-audiences-33d84cb6-14ed-4e53-a426-74c38ea32293) to hide the other views. This will allow you to create views where you can use meta data in the list to hide list items only viewed by certain users. This includes attachments and Document Library options as well. Create security groups for the List/Library, and use those to set up your target audiences. This will help with the other views you have not using the `[Me]` filter as listed above.
30,925,268
I am having trouble with bash\_completion. When I expand variables, I am fine, but when I use a commands completion (such as `git` or `vim-addon-manager`), then the completion throws random characters in there. This didn't use to happen to me, I can't figure out what it is. This is an example of what happens when I type `git``Tab``Tab``y` ``` [11:11] me@my_computer:~ $ git Display all 131 possibilities? (y or n) ^[[01;31m^[[K c^[[m^[[Kheckout delete-tag f^[[m^[[Kmt-merge-msg i^[[m^[[Knit-db notes rm a^[[m^[[Kdd c^[[m^[[Kheckout-index d^[[m^[[Kaemon f^[[m^[[Kor-each-ref i^[[m^[[Knstaweb obliterate setup a^[[m^[[Klias c^[[m^[[Kheck-ref-format d^[[m^[[Kelete-branch f^[[m^[[Kormat-patch info p4 shortlog a^[[m^[[Km c^[[m^[[Kherry d^[[m^[[Kelete-merged-branches f^[[m^[[Ksck line-summary pull show a^[[m^[[Knnotate c^[[m^[[Kherry-pick d^[[m^[[Kelete-submodule f^[[m^[[Ksck-objects l^[[m^[[Kog pull-request show-branch a^[[m^[[Kpply c^[[m^[[Klean d^[[m^[[Kescribe fresh-branch l^[[m^[[Ks-files push show-tree a^[[m^[[Krchive c^[[m^[[Klone d^[[m^[[Kiff g^[[m^[[Kc l^[[m^[[Ks-remote rebase squash a^[[m^[[Krchive-file c^[[m^[[Kolumn d^[[m^[[Kiff-files g^[[m^[[Ket-tar-commit-id l^[[m^[[Ks-tree refactor stage b^[[m^[[Kack c^[[m^[[Kommit d^[[m^[[Kiff-index g^[[m^[[Krep local-commits reflog stash b^[[m^[[Kisect c^[[m^[[Kommits-since d^[[m^[[Kifftool graft mergetool release status b^[[m^[[Klame c^[[m^[[Kommit-tree d^[[m^[[Kiff-tree h^[[m^[[Kash-object m^[[m^[[Kailinfo relink submodule b^[[m^[[Kranch c^[[m^[[Konfig effort h^[[m^[[Kelp m^[[m^[[Kailsplit remote subtree b^[[m^[[Kug c^[[m^[[Kontrib extras h^[[m^[[Kttp-backend m^[[m^[[Kerge rename-tag summary b^[[m^[[Kundle c^[[m^[[Kount feature h^[[m^[[Kttp-fetch m^[[m^[[Kerge-base repack tag c^[[m^[[Kat-file c^[[m^[[Kount-objects f^[[m^[[Kast-export h^[[m^[[Kttp-push m^[[m^[[Kerge-file repl touch c^[[m^[[Khangelog c^[[m^[[Kreate-branch f^[[m^[[Kast-import ignore m^[[m^[[Kerge-index replace undo c^[[m^[[Kheck-attr c^[[m^[[Kredential f^[[m^[[Ketch i^[[m^[[Kmap-send m^[[m^[[Kerge-octopus request-pull whatchanged c^[[m^[[Kheck-ignore c^[[m^[[Kredential-cache f^[[m^[[Ketch-pack i^[[m^[[Kndex-pack mv reset c^[[m^[[Kheck-mailmap c^[[m^[[Kredential-store f^[[m^[[Kilter-branch i^[[m^[[Knit name-rev revert ``` --- --- Another example is `vam tetris` (`vam tet``Tab``Tab`): ``` ^[[01;31m^[[Kaddon: tet^[[m^[[Kris ``` --- --- For `vam install tet``Tab``Tab`, it actually renders it an invalid argument (it's also quite difficult to read), so how can I fix this?
2015/06/18
[ "https://Stackoverflow.com/questions/30925268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3772603/" ]
The fundamental difference between mock and stub is that mock can make your test fail. Stub can't. Stub is used to guarantee correct program flow. It is never part of assert. Note that mock can also be used to guarantee flow. In other words, every mock is also a stub, and stub is never a mock. Because of such overlapping responsibilities nowadays you don't see much distinction between mock and stub and framework designers go for more general terms (like [fake](https://github.com/FakeItEasy/FakeItEasy/wiki/Creating-Fakes), [substitute](https://github.com/nsubstitute/NSubstitute#basic-use) or [catch-all mock](https://github.com/Moq/moq4#moq)). This realization (mock - assert, stub - flow) helps us narrow down some usage scenarios. To start with the easier one... ### Mock As I mentioned mocks are used in asserts. When the **expected behavior** of your component is that *it should talk to this other component* - use mock. All those ``` emailSender.SendEmail(email); endOfDayRunner.Run(); jobScheduler.ScheduleJob(jobDetails); ``` can be only tested by asking *"Did it call `ScheduleJob` with such and such parameters?"* This is where you go for mock. Usually this will be mock's only usage scenario. ### Stub With stub it's a bit different. Whether to use stub or not is a **design question**. Once you follow regular loosely coupled, dependency injection-based design, eventually you will end up with **a lot of interfaces**. Now, when in test, how do return value from interface? You either stub it or use real implementation. Each approach has its pros and cons: * with library-generated stubs, your tests will be less brittle but might require more up-front work (setting up stub and such) * with real implementations, setup work is already done but when `Angle` class changes `CoordinateSystem` might fail... Is such behavior desirable or not? Is it? Which one to use? Both! It all depends on... ### Unit of work We arrived at final and the actual part of the problem. What is the scope of your unit test? What is the ***unit***? Can `CoordinateSystem` be detached from its inner workings and dependencies (`Angle`, `Point`, `Line`) and can they be stubbed? Or more importantly, should they be? You always need to **identify what your unit is**. Is it `CoordinateSystem` alone or perhaps `Angle`, `Line` and `Point` play important part of it? In many, many cases, the unit will be formed by both method and its **surrounding ecosystem**, including domain objects, helper classes, extensions or sometimes even other methods and other classes. Naturally, you can separate them and stub all the way around but then... is it really your unit?
As a rule of thumb, use Mocks when you need to simulate behavior, and stubs when the only thing that matters in your test is the state of the object you're communicating with. Taking into consideration the edit you made to your post, when you need to receive an immutable object use a stub, but when you need to call operations that object exposes then go for a mock, this way you are not prone to failing tests due to errors in another class implementation.
16,884,746
I have the following relationship set up in my Core Data model, in my shopping cart app. `Menu` ->> `Product` <<- `Cart` (See picture below). ![enter image description here](https://i.stack.imgur.com/lqcPS.png) And a Objective-C category with the following code: ``` + (Cart *)addProductToCartWithProduct:(Product *)product inManagedObjectContext:(NSManagedObjectContext *)context { Cart *cart = [NSEntityDescription insertNewObjectForEntityForName:@"Cart" inManagedObjectContext:context]; NSManagedObjectID *retID = [product objectID]; [(Product *)[context objectWithID:retID] setInCart:cart]; [cart addProductsObject:(Product *)[context objectWithID:retID]]; return cart; } ``` When the user pushes the "add to cart" button in the app, this method is fired (the method above). I now want to fetch these products (which is added to the cart by the user), in my other class, where the "cart" is located. I want these products to be shown in my `UITableView` in that class, I therefore use an FRC. *But I can't figure out how to fetch the relationship and thereby show the products. How would I manage to do this?* I have the following code right now. ``` - (void)loadCart { NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init]; fetchRequest.entity = [NSEntityDescription entityForName:@"Cart" inManagedObjectContext:_theManagedObjectContext]; NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"id" ascending:YES]; fetchRequest.sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil]; [NSFetchedResultsController deleteCacheWithName:@"cartproducts"]; self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_theManagedObjectContext sectionNameKeyPath:nil cacheName:@"cartproducts"]; _fetchedResultsController.delegate = self; NSError *error = nil; if (![_fetchedResultsController performFetch:&error]) { NSLog(@"Fetch Failed"); } } ``` My `UITableview` `cellForRowAtIndexPath:` method. ``` - (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *plainCellIdentifier = @"OrderCell"; ProductsCell *cell = (ProductsCell *)[aTableView dequeueReusableCellWithIdentifier:plainCellIdentifier]; if (!cell) { cell = [[ProductsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:plainCellIdentifier]; } Cart *ret = (Cart *)[self.fetchedResultsController objectAtIndexPath:indexPath]; // How to show the product names using the relationship? cell.title = ret.products ??; [cell setNeedsDisplay]; return cell; } ```
2013/06/02
[ "https://Stackoverflow.com/questions/16884746", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1723514/" ]
To display product for one specific cart, you would create the fetched results controller as follows *(not compiler checked, there may be syntax errors!)* : ``` Cart *theCart = ... the cart that you want display products for ... // Fetch request for "Product": NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Product"]; // Fetch only products for the cart: NSPredicate *predicate = [NSPredicate predicateWithFormat:@"inCart = %@", theCart]; [fetchRequest setPredicate] = predicate; // Assuming that you want to sort by "navn": NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"navn" ascending:YES]; [fetchRequest setSortDescriptors:@[sortDescriptor]]; self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:_theManagedObjectContext sectionNameKeyPath:nil cacheName:nil]; _fetchedResultsController.delegate = self; ``` The fetched objects are now `Product` objects, therefore in `cellForRowAtIndexPath:` you would do for example: ``` ... Product *product = [self.fetchedResultsController objectAtIndexPath:indexPath]; cell.title = product.navn; ``` *Remark:* The fetched results controller uses a cache (as far as I know) only for section information, so there is no need to specify a `cacheName:` here.
I think your new model is good. Now that I understand your approach better, I think you do need to do a fetch kind of like your original code. I mistakenly assumed you'd want to have more than one cart - I'm thinking like a server engineer I guess. ``` + (Cart *)addProductToCart:(Product *)theProduct inManagedObjectContext:(NSManagedObjectContext *)context { Cart *cart = nil; NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Cart"]; NSError *error = nil; NSArray *carts = [context executeFetchRequest:request error:&error]; if (!carts || ([carts count] > 1)) { // handle error } else if (![carts count]) { cart = [NSEntityDescription insertNewObjectForEntityForName:@"Cart" inManagedObjectContext:context]; } else { // they already have a cart started cart = [carts lastObject]; } [cart addProductsObject:theProduct]; return cart; } ``` You don't need this: `NSManagedObjectID *retID = [product objectID];`. Just refer to the product by the Product object. You don't need to round-trip it by its ID in this case. You don't need this: `[(Product *)[context objectWithID:retID] setInCart:cart];`. With the inverses properly configured, adding theProduct to the cart automatically sets theProduct.inCart. The other answer is good for how to do the fetched results controller.
38,257,142
I know some similar issues exist ([Find the field names of inputtable form fields in a PDF document?](https://stackoverflow.com/questions/3310533/find-the-field-names-of-inputtable-form-fields-in-a-pdf-document)) but my question is different: I have all the field names (in fdf file). I wish I could visually identify directly on the PDF. With acrobat I should be able to right click on a field and then select "display the name of the field" but I can find no such thing. Can someone help me ?
2016/07/08
[ "https://Stackoverflow.com/questions/38257142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2267379/" ]
Ok. I have found pdf editor where this is possible. Probably acrobat pro too... <http://www.pdfescape.com/> Right click on the field : unlock. Right click again : get properties.
If you're using [Apache PDFBox](https://pdfbox.apache.org/) to fill the form automatically, you can use it to fill all text fields with their name: ``` final PDDocument document = PDDocument.load(in); final PDAcroForm acroForm = document.getDocumentCatalog().getAcroForm(); final Iterator<PDField> it = acroForm.getFieldIterator(); for (PDField f : acroForm.getFields()) { System.out.println(f.toString()); if (f instanceof PDTextField) { f.setValue(f.getFullyQualifiedName()); } }; document.save(...); ``` When you open the generated PDF, you'll be able to identify each field immediately like you asked. [![example](https://i.stack.imgur.com/32Wgn.png)](https://i.stack.imgur.com/32Wgn.png)
75,202
I attached 4 10GB disks to MySQL Server and I used RAID 0: ![enter image description here](https://i.stack.imgur.com/7LMDp.png) but still MySQL performance is the same. Do I have to change configuration in `my.cnf` to let MySQL know about RAID 0? This are my `mount` results: ![enter image description here](https://i.stack.imgur.com/YOD78.png) This is not development box, it is my production server. I used to have MySQL server on AWS but now I am using Azure, and I/O really hurts MySQL. I am not a server admin expert, but I am trying to solve here my problem, a consultant recommended to me to do RAID 0. I am using newrelic to test my performance. It shows how bad is MySQL, my server is 8 cores and 14 GB Azure server.
2014/08/28
[ "https://dba.stackexchange.com/questions/75202", "https://dba.stackexchange.com", "https://dba.stackexchange.com/users/46416/" ]
You should perform an `UPDATE LEFT JOIN` and set `enabled` based on the right side being `NULL` ``` UPDATE table1 A LEFT JOIN table2 B ON A.code = B.id SET A.enabled = 1 - ISNULL(B.id); ``` Why should this work ? * If [ISNULL(B.id)](https://dev.mysql.com/doc/refman/5.6/en/comparison-operators.html#function_isnull) is 0, that means `A.enabled` is set to 1 (1 - 0) because it is in `table2` * If [ISNULL(B.id)](https://dev.mysql.com/doc/refman/5.6/en/comparison-operators.html#function_isnull) is 1, that means `A.enabled` is set to 0 (1 - 1) because it is not in `table2` @ypercube suggested ``` UPDATE table1 A LEFT JOIN table2 B ON A.code = B.id SET A.enabled = (B.id IS NOT NULL); ``` GIVE IT A TRY !!! =================
You should test it on you system and compare the the execution data and plans. But the database systems I know only optimize statement by statement and not pairs and groups of statements. And for an optimal optimizer that possesses enough information about the data and optimizes statement by statement I would expect that he can create a better plan if the work is contained in one statement instead of distributed over two statements. For your statement it is possible that the optimizer for each of the three statements reads the whole table table2 and then scans the whole table table1 and changes the values according to the update clause. So the variant with two updates then will need to scans of table table1 and table table2 and only one scan of table table1 and table table2 for the second variant.
1,107,858
I have the 'luck' of develop and enhance a legacy python web application for almost 2 years. The major contribution I consider I made is the introduction of the use of unit test, nosestest, pychecker and CI server. Yes, that's right, there are still project out there that has no single unit test (To be fair, it has a few doctest, but are broken). Nonetheless, progress is slow, because literally the coverage is limited by how many unit tests you can afford to write. From time to time embarrassing mistakes still occur, and it does not look good on management reports. (e.g. even pychecker cannot catch certain "missing attribute" situation, and the program just blows up in run time) I just want to know if anyone has any suggestion about what additional thing I can do to improve the QA. The application uses WebWare 0.8.1, but I have expermentially ported it to cherrypy, so I can potentially take advantage of WSGI to conduct integration tests. Mixed language development and/or hiring an additional tester are also options I am thinking. Nothing is too wild, as long as it works.
2009/07/10
[ "https://Stackoverflow.com/questions/1107858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/58129/" ]
Feather's [great book](https://rads.stackoverflow.com/amzn/click/com/0131177052) is the first resource I always recommend to anybody in your situation (wish I had it in hand before I faced it my first four times or so!-) -- not Python specific but a lot of VERY useful general-purpose pieces of advice. Another technique I've been happy with is [fuzz testing](http://en.wikipedia.org/wiki/Fuzz_testing) -- low-effort, great returns in terms of catching sundry bugs and vulnerabilitues; check it out! Last but not least, if you do have the headcount & budget to hire one more engineer, please do, but make sure he or she is a "software engineer in testing", NOT a warm body banging at the keyboard or mouse for manual "testing" -- somebody who's rarin' to write and integrate all sorts of *automated* testing approaches as opposed to spending their days endlessly repeating (if they're lucky) the same manual testing sequences!!! I'm not sure what you think mixed language dev't will buy you in terms of QA. WSGI OTOH *will* give you nice bottlenecks/hooks to exploit in your forthcoming integration-test infrastructure -- it's good for that (AND for sundry other things too;-).
Since it is a web app, I'm wondering whether browser-based testing would make sense for you. If so, check out [Selenium](http://seleniumhq.org/ "Selenium"), an open-source suite of test tools. Here are some items that might be interesting to you: * automatically starts and stops browser instances on major platforms (linux, win32, macos) * tests by emulating user actions on web pages (clicking, typing), Javascript based * uses assertions for behavioral results (new web page loaded, containing text, ...) * can record interactive tests in firefox * can be driven by Python test scripts, using a simple communication API and running against a coordination server (Selenium RC). * can run multiple browsers on the same machine or multiple machines It has a learning curve, but particularly the Selenium RC server architecture is very helpful in conducting automated browser tests.
73,816,832
I'm new in the unit testing. and I had an issue about asynchronous function testing. ``` func test_Repository() { let properEmail = "" let properPassword = "" let improperEmail = "" let improperPassword = "" let testArray = [(username : "", password : ""), // both empty (username : "", password : properPassword), // empty email (username : properEmail, password : ""), // empty password (username : improperEmail, password : properPassword), // wrong email (username : properEmail, password : improperPassword) // wrong password ] let repo = UserRepository() let exp = expectation(description: "Wait for async signIn to complete") for data in testArray { print(data.username) print(data.password) repo.createNewUser(data.username, password: data.password) {[weak self] email, error in XCTAssertNotNil(error) exp.fulfill() } sleep(5) } wait(for: [exp], timeout: 200.0) } ``` as you can see, I want to test all improve possibilities but it didn't work. and also my asynchronous create function is here ``` func createNewUser(_ email : String, password : String,result: @escaping (_ email : String, _ error : Error?)->()) { auth.createUser(withEmail: email, password: password) { [weak self] authResult, error in if let error = error { self?.userCreationError = true self?.userCreationErrorText = error.localizedDescription result("",error) } else { if let authresult = authResult { self?.user.email = authresult.user.email ?? "" self?.createNewUserTable(user: self!.user) result((self?.user.email)!,nil) } } } } ```
2022/09/22
[ "https://Stackoverflow.com/questions/73816832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19480198/" ]
A solution using parameter expensions. ```bash $ filename="03 - Artist name first-middle name - Title of the Track (Original Version - Long Edit)" $ filename="${filename#* - * - }" $ echo "$filename" Title of the Track (Original Version - Long Edit) ```
Using `sed` ``` $ title=$(sed -E 's/.*- ([[:alpha:] ]+(\([^)]*\))?\..*)/\1/' input_file) $ echo "$title" Retrowave Mix.mp3' Astral Dive.mp3' Deathtouch.mp3' A Synthwave Mix.mp3' Eastbound Plane Mattaei (Original - Long Mix).mp3' ```
416,391
I'm trying to use the [Windows 7 USB/DVD Download Tool](http://www.microsoftstore.com/store/msstore/html/pbPage.Help_Win7_usbdvd_dwnTool) from the Microsoft Store to make my new 16 GB USB Flash drive bootable to install Windows. It worked the first time that I did this (for Windows 7 Pro 32-bit), but now it keeps failing at the end. (I'm trying to make it bootable with the Windows 7 Pro 64-bit installation DVD ISO.) I've tried to do this on two different computers (Windows XP Pro 32-bit & Windows 7 Pro 32-bit) with the same error: > > Files copied successfully. However, we were unable to run bootsect to make the USB device bootable. If you need assistance with bootsect, please click the "Online Help" link above for more information. > > > Clicking the link just takes me to the Microsoft store homepage, and a search for `bootsect` from there yields no search results. I've tried to burn a DVD twice using Sonic RecordNow!, but even though it finishes without "errors," the disk is unreadable. :( Does anyone know why this keeps failing and how I may fix it?
2012/04/24
[ "https://superuser.com/questions/416391", "https://superuser.com", "https://superuser.com/users/35950/" ]
The following description is taken from the tool's [online help](http://www.microsoftstore.com/store/msusa/html/pbPage.Help_Win7_usbdvd_dwnTool): **When creating a bootable USB device, I am getting an error about bootsect** To make the USB device bootable, you need to run a tool named bootsect.exe. In some cases, this tool needs to be downloaded from your Microsoft Store account. This may happen if you're trying to create a 64-bit bootable USB device from a 32-bit version of Windows. To download bootsect: 1. Login to your Microsoft Store account to view your purchase history 2. Look for your Windows 7 purchase. 3. Next to Windows 7, there is an "Additional download options" drop-down menu. 4. In the drop-down menu, select "32-bit ISO." 5. Right-click the link, and then save the bootsect.exe file to the location where you installed the Windows 7 USB/DVD Download Tool (e.g. `%UserProfile%\AppData\Local\Apps\Windows 7 USB DVD Download Tool`). 6. Once the file has been saved, go back to the Windows 7 USB/DVD Download tool to create your bootable USB device. Archive.org link: <https://web.archive.org/web/20130130224114/http://www.sevenforums.com/attachments/installation-setup/47060d1263222191-32-bit-bootsect-bootsect7600x86.zip>
Try to format (FAT32) your USB drive but not using quick option ! You can then check again (using explorer or chkdsk) to see if all sectors are readable. After formating (from Windows 7) the USB drive will have proper Windows 7 MBR and PBR. Never had problems with Windows 7 USB/DVD Download Tool. Help for bootsect.exe - [http://technet.microsoft.com/en-us/library/cc749177(v=ws.10).aspx](http://technet.microsoft.com/en-us/library/cc749177%28v=ws.10%29.aspx)
167,248
Opportunity attacks have a long history in the world of tabletop games and D&D in particular. 3.5e/PF both had an exhaustive list of actions which can or can not trigger an OA. Various games have their own OA mechanics, but one trigger always remains the same. * 5th edition simplified things a lot. Only the [one single trigger left](https://rpg.stackexchange.com/questions/44402/): > > You can make an opportunity attack when a hostile creature that you can see moves out of your reach. > > > * [Starfinder](https://paizo.com/starfinder) also reduces the list of AoO triggers greatly, comparing to its ancestor, to three points only, and "an enemy goes away" trigger is still there: > > When you threaten a space and the opponent moves out of that space in any way other than a guarded step > > > * [Open Legend](https://openlegendrpg.com/core-rules/07-combat), a game influenced by but not directly derived from D&D, has the same only one trigger: > > If you are wielding a melee weapon, and an enemy moves from a space within your reach to a space that is not within your reach, you may make a free attack against the enemy. > > > It seems the game developers consider this particular trigger as the most important one. To my knowledge, many wargames uses the similar rule. So what happens if we remove it? Why do we need it, in the first place? **Is there a substantial problem with turn-based gameplay, which OAs solve**? The reason I ask is because there are 5e-based games which do not have OAs at all (Five Torches Deep, for instance). I want to know what changes I should expect within basic 5e gameplay (no feats, no variant rules) if the DM introduces a "no opportunity attacks" house rule. I'm more interested in base mechanics, rather than particular OA-dependent 5e spells or features (like Rogue's Cunning Action becomes less useful, etc.)
2020/04/06
[ "https://rpg.stackexchange.com/questions/167248", "https://rpg.stackexchange.com", "https://rpg.stackexchange.com/users/27377/" ]
This is a question I've thought about a lot because I'm making my own d20 game with the aim of keeping rules as light as possible. To that end I've done away with OAs. My play testers have responded positively because they are more mobile on the battlefield. **Play Expeerience** With OAs in force, positioning tactics stop after round 1 or 2 because after that everyone is locked in place on the spot and melee becomes a slog. Without them, they can reposition more easily, switch up their tactics if they're failing, or even retreat if things are going badly without fear of a TPK. Fighting is more fluid and keeps you paying attention while waiting for your turn. This makes for very 'cinematic' fights where opponents dance around trees, chase through buildings, jump on tables. I compare typical D&D fights to Rock 'em, Sock 'em Robots with dice, where as the games I'm testing feel more like dynamic movie fights. As for melee fighters protecting ranged fighters, I find that ranged fighters do just fine. They tend to maximise Dexterity which gives them high AC. They also do more hiding and think more tactically themselves, rather than leaving that to the meatheads at the front. Together with carefully chosen healing options and other options like the Tough or Mobile feat, they don't do so badly. This might prevent them from taking things which would enhance their attacks, which is a trade off which that I'll come to dislike later in this post, but I think it's less severe here. **OAs exist because...** As for why OAs exists at all, my guess has always been that it's supposed to be a simulation of something. I think the idea is that if you turn your back to run then you expose yourself to attack. I think this is wrong. Consider that ALL self defence advice begins with 'run away'. I think that the Disengage action is easier than the designers think and should be free, where as the OA action requires much more whit and agility and should be the action that requires the learning of a new skill. **Other Thoughts** From a game design perspective, starting with this false notion that fleeing is hard creates a rules arms race to help players Not Suck, rather than Be Awesome. It just creates more default rules to read and remember and bloats out Feat and Class Feature options with stuff that is just there to overcome a problem that you created, not build on the cool stuff you can already do. If OAs exist at all it should be as a bonus, not a penalty. (And don't get me started on shooting into combat!). Theik also makes the great point that suffering one or two OAs is not a big deal for any melee creature above about level 3, so why not suffer it and do what you like anyway!? I think that the aversion to incurring OAs is more psychological than tactical. This psychological deterrent against running wherever you want seems to be the only real value I can see, but it's value crumbles when you realise the dull static combat that it encourages. I said earlier that ranged players might have to take some options to buff their defences, I don't think these fall into the Options to Not Suck category, but rather make the player feel more powerful than not-weak.
If we remove opportunity attacks from the game, the following scenarios can occur: * If two creatures are the same speed, and only have melee, one can keep away from the other guaranteed with no chance for the other to continue attacking them. * Melee rogues can now kite any creature they are faster than with their bonus action dash. The creature's only option is to ready a melee attack, which drastically reduces their output if they have multiple attacks by default. * Enemies now have no reason not to run straight past your front line Barbarian/Paladin and dog pile onto your squishy Wizard/Sorcerer. * Enemies and players alike have zero reason to fight the person in front of them. A little opinion leaking in here, but this **kills** the cinematic aspect of melee combat. Duels never really happen. After all, why would a barbarian ever attack the opposing barbarian when they could just hit the wizard? The main consequence here is that front-line no longer serves a purpose unless they can physically block a passageway, or grapple. Monsters with low movement speed (gelatinous cubes, for example) become useless, and difficult terrain becomes a HUGE deal. If you're melee without high movement speed in this scenario, you're pretty much dead in the water (especially if you're actually in the water, and don't have a swimming speed).
25,525,226
I have a table `news` with 48 columns The table has some values like so: ``` ID|title |date |....... 1|Apple iphone 6 |2014-08-23 2|Samsung Galaxy s5|2014-08-23 3|LG G3 |2014-08-25 4|Apple iphone 6 |2014-08-25 5|HTC One m8 |2014-08-27 ``` The "title" value is duplicated in id `1` and `4` (`Apple iphone 6`) I want to keep the just last ID row in news table and delete the other older rows. So in the above example I want to delete row with the ID `1`, keep the last id (`4`) which has the same title column value.
2014/08/27
[ "https://Stackoverflow.com/questions/25525226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3982563/" ]
``` delete from news where id not in ( select * from ( select max(id) from news group by title ) tmp ) ``` This query groupy by the title and selects the latest `id` for every unique title. Then it deletes all records that have NOT that `id`. I added another subquery because in MySQL you can't select from a table you are deleting at the same time.
In MySQL, I would do this using a `join`: ``` delete n from news n join (select title, max(id) as keepid from news group by title ) ti on ti.title = n.title and ti.id < keepid; ``` MySQL is finicky in `delete` and `update` statements about referring to the table being modified. Unfortunately, the typical way to do this in ANSI SQL (and other databases) doesn't quite work: ``` delete from news where id < (select max(id) from news n2 where n2.title = n.title); ``` You can get around this with a MySQL hack of using an extra layer of subqueries.
127,357
I’m trying to build a world for a short story where the protagonist increasingly finds truths in Fortean-type phenomena. He witnesses proof of mythical creatures, for example. He begins investigating these things after his wife mysteriously disappears. The issue that I have is, I need her to disappear in such a way where one minute he sees her, but then she’s gone. I was thinking about her getting on a plane, but then never getting off, but other passengers do. I’ve thought about incorporating some kind of parallel universe she may fall into, or something of the sort. Would it be possible for a single person on a plane full of people to fall into such a universe?
2018/10/12
[ "https://worldbuilding.stackexchange.com/questions/127357", "https://worldbuilding.stackexchange.com", "https://worldbuilding.stackexchange.com/users/56242/" ]
Since your protagonist is investigating Fortean phenomena is appropriate that the disappearance of his wife into parallel universe happens with that most Fortean of phenomena teleportation. > > Examples of the odd phenomena in Fort's books include many occurrences of the sort variously referred to as occult, supernatural, and paranormal. Reported events include teleportation (a term Fort is generally credited with inventing);[11][12] falls of frogs, fishes, inorganic materials of an amazing range;[1](https://en.wikipedia.org/wiki/Charles_Fort) spontaneous human combustion;[1](https://en.wikipedia.org/wiki/Charles_Fort) ball lightning[1](https://en.wikipedia.org/wiki/Charles_Fort) (a term explicitly used by Fort); poltergeist events; unaccountable noises and explosions; levitation; unidentified flying objects; unexplained disappearances; giant wheels of light in the oceans; and animals found outside their normal ranges (see phantom cat). He offered many reports of out-of-place artifacts (OOPArts), strange items found in unlikely locations. He was also perhaps the first person to explain strange human appearances and disappearances by the hypothesis of alien abduction and was an early proponent of the extraterrestrial hypothesis, specifically suggesting that strange lights or objects sighted in the skies might be alien spacecraft. > > > Source: [Charles Fort](https://en.wikipedia.org/wiki/Charles_Fort) Charles Fort has been credited with inventing the term "teleportation". Therefore, it would be fitting if she was teleported from this universe into another. Why not go the full mile and have her disappear right in front of his eyes while surrounded by a crowd of people? Then he would have seen her vanish and this would be for him an incontrovertible fact. While, yes, it is conceivably possible for someone to be teleported from an aircraft in flight, there is the small problem of compensating for her state of motion. For example, if the airliner is flying at 600 km/hr, then she will arrive at her destination moving at the same speed. There are two solutions to this problem. Either teleportation mechanism can compensate automatically so the person arrives at their destination at its state of motion or she is teleported onto an aircraft moving at 600 km/hr in the parallel universe. In conclusion, Charles Fort this sort of disappearance happened all the time. So disappearing by teleportation into parallel universe is very Fortean. What better way to send her husband on the trail of investigating Fortean phenomena.
To me the best sci-fi stories are those which feature fantastical worlds with fantastical features, but with some basis in science. Some good examples are most of Dan Simmons' work especially Hyperion and Ilium. So I would suggest you start with "Let's assume parallel universes exist. How would I portray someone slipping into another universe?" From what I've read about parallel universe theories I would say it is most likely if someone "jumps universes" they would swap bodies with their counterpart in the other universe. On the other hand, someone just disappearing could mean that they do not have a counterpart in the universe they traveled to.
4,852,650
I was wondering if binding a single `change()` event on form fields is enough to correctly perform a action when the value of the field changes. Or should I bind all possible events? like this: ``` $(this).bind('change keyup focus click keydown', function(){ // ... }).change(); ``` Also, does binding multiple events affect performance?
2011/01/31
[ "https://Stackoverflow.com/questions/4852650", "https://Stackoverflow.com", "https://Stackoverflow.com/users/376947/" ]
`change` will only fire when the field loses focus (for most inputs). If you want something a little more real time, use the HTML 5 `oninput` event. This will pretty much catch any type of value change for an input element (and it bubbles, too!). It's not supported in Internet Explorer 8 and lower, though, but [I wrote a plugin](http://whattheheadsaid.com/projects/input-special-event) that maps to `onpropertychange` for those browsers. See also: * [Effectively detecting user input in JavaScript](http://whattheheadsaid.com/2010/09/effectively-detecting-user-input-in-javascript) For the performance side of things, each event you described fires at different times so performance shouldn't be an issue unless.
Only listening to the `change` event *might* be sufficient for you (see also [@Andy E's answer](https://stackoverflow.com/questions/4852650/jquery-binding-multiple-events-on-input-fields/4852726#4852726)). From the [documentation](http://api.jquery.com/change/): > > The `change` event is sent to an element when its value changes. This event is limited to `<input>` elements, `<textarea>` boxes and `<select>` elements. For select boxes, checkboxes, and radio buttons, the event is fired immediately when the user makes a selection with the mouse, but for the other element types the event is deferred until the element loses focus. > > >
121,361
Can Google Analytics and Google Search Console coexist without issues for the same website if the Google account that is used for Google Analytics is not the same as the account used for Google Search Console? Context: I'm building a site for a client and would like to monitor the site's performance on google while letting him use his own analytics account. I would like to avoid any trouble with google and don't want my Google account to get banned.
2019/03/04
[ "https://webmasters.stackexchange.com/questions/121361", "https://webmasters.stackexchange.com", "https://webmasters.stackexchange.com/users/98711/" ]
Not an issue at all. They are different tools and verified differently. Info on linking together: Each account is not tied to only one user account. In GA you can add other users will full access at the account or property level. In SC you can add other *owners*. Therefore, if any of the accounts have the same user in both, you can link them together in GA.
Should not be an issue, however you wont be able to link the two products together though, as doing so requires the same Google Account be used.
240,850
I am having an issue when using `LoadControl( type, Params )`. Let me explain... I have a super simple user control (ascx) ``` <%@ Control Language="C#" AutoEventWireup="True" Inherits="ErrorDisplay" Codebehind="ErrorDisplay.ascx.cs" EnableViewState="false" %> <asp:Label runat="server" ID="lblTitle" /> <asp:Label runat="server" ID="lblDescription" /> ``` with code ( c# ) behind of: ``` public partial class ErrorDisplay : System.Web.UI.UserControl { private Message _ErrorMessage; public ErrorDisplay() { } public ErrorDisplay(Message ErrorMessage) { _ErrorMessage = ErrorMessage; } protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); if (_ErrorMessage != null) { lblTitle.Text = _ErrorMessage.Message; lblDescription.Text = _ErrorMessage.Description; } } } ``` Elsewhere in my web application I am adding an instance of the usercontrol to the page using the following code: ``` divValidationIssues.Controls.Add(LoadControl(typeof(ErrorDisplay), new object[] { MessageDetails })); ``` I am using the overloaded version of LoadControl because I want to pass the Message parameter to the constructor. All this *appears* to work ok. However, when the `OnPreRender()` is fired on the ErrorDisplay usercontrol the lblTitle and lblDescription variables are both `null`, despite them having a markup equivalent. The message variable has been correctly populated. Can anyone shed any light on why this may be happening? Thanks **EDIT:** Just for clarity I'll also add that the code which is programatically adding the usercontrol to the page is running in response to a button press, so the 'hosting page' has progressed through Init, Page\_Load and is now processing the event handlers. I cannot add the usercontrols at an earlier asp lifecycle stage as they are being created in response to a button click event.
2008/10/27
[ "https://Stackoverflow.com/questions/240850", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31128/" ]
I had a similar issue with the Calendar control DayRender event, in that I wanted to add a user control to the e.Cell.Controls collection. After trying a couple of failed approaches with the user control page\_load not firing or the listbox on the ascx throwing a null exception, I found that if I initialized my control on the form with LoadControl(ascx) and then start accessing the markup controls on the ascx, everything worked fine. This approach does not depend upon the Page\_Load event on the ascx at all. ASCX markup code behind Public Class CPCalendarCell Inherits System.Web.UI.UserControl ``` Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load End Sub Public Sub Add(txt As String) Dim li As New ListItem(txt, txt) lstDay.Items.Add(li) End Sub ``` End Class page ASPX markup code behind Calendar DayRender event on the form ``` Private Sub Calendar1_DayRender(sender As Object, e As System.Web.UI.WebControls.DayRenderEventArgs) Handles Calendar1.DayRender Dim div As CPCalendarCell = LoadControl("~/UserControls/CPCalendarCell.ascx") div.ID = "dv_" & e.Day.Date.ToShortDateString.Replace(" ", "_") **e.Cell.Controls.Add(div)** div.Add(e.Day.Date.Month.ToString & "/" & e.Day.Date.Day.ToString) div.Add("Item 1") div.Add("Item 2") e.Cell.Style.Add("background-color", IIf(e.Day.IsWeekend, "whitesmoke", "white").ToString) End Sub ```
Per the asp.net page lifecycle your controls are not fully added in pre-render, why don't you just load the values in page\_load?
34,762,238
I am looking to create a set of dates as follows. For example, if today's date is 12/01/2016. I need: ``` A ``` 1 Jan 2016 2 Dec 2015 3 Nov 2015 4 Oct 2015 5 Sep 2015 6 August 2015 and so on. I would appreciate all the help I can get on this matter. Thank you.
2016/01/13
[ "https://Stackoverflow.com/questions/34762238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5750344/" ]
If you got `12 Jan 2016` in cell `A1` you could then use the following formula in cell `A2` and drag down the formula down for as long as needed. ``` =EDATE(A1,-1) ``` This continues to give you the previous date minus 1 month. You could then format the cell values as `mmmm yyyy` which will give you the date format that you are looking for.
This code will iterate over the cells from A1 to A100, and fill them with the current month and year, and for each cell, it will subtract one month: ``` Sub test() MyMonth = Date For i = 1 To 100 Range("A" & i).Value = MyMonth Range("A" & i).NumberFormat = "[$-406]mmmm yyyy;@" MyMonth = DateAdd("m", -1, MyMonth) Next i End Sub ```
27,013,044
I am attempting to retrieve a `ListItemCollection` from a `List` of controls. This `List` contains many controls of different types - `DropDownList`, `Label`, `TextBox`. I would like to retrieve all `ListItem` from all the `DropDownList` controls contained in the original `List` of controls. My thought process so far has been to extract all of the `DropDownList` controls into a new list, and iterate though this to pull out each `ListItem` - however, every `DropDownList` control is coming up with 0 items ``` ControlCollection cList = pnlContent.Controls; List<DropDownList> ddlList = new List<DropDownList>(); foreach (Control c in cList) { if (c.GetType() == new DropDownList().GetType()) { ddlList.Add((DropDownList)c); } } ListItemCollection itemCollection = new ListItemCollection(); foreach (DropDownList ddl in ddlList) { foreach(ListItem li in ddl.Items) { itemCollection.Add(li); } } ``` I'm sure this is the wrong (and massively inefficient) way of doing this. Any help would be appreciated.
2014/11/19
[ "https://Stackoverflow.com/questions/27013044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3797366/" ]
This will do: ``` public IEnumerable<ListItem> GetListItems(ControlCollection controls) { return controls.OfType<DropDownList>().SelectMany(c => c.Items.OfType<ListItem>()); } ```
Try this: ``` var ddlList = cList.OfType<DropDownList>(); ListItemCollection itemCollection = new ListItemCollection(); // option 1 var temp = ddlList.Select(ddl => ddl.Items.Cast<ListItem>()).SelectMany(li => li).ToArray(); itemCollection.AddRange(temp); // or option 2 var temp = ddlList.Select(ddl => ddl.Items.Cast<ListItem>()).SelectMany(li => li); foreach (var listItem in temp) { itemCollection.Add(listItem); } ```
554
Working in highly regulated environments data is classified in different ways depending on the sensitivity. In some cases, this is legally enforced and must be treated differently. Examples of a data classification policy are: * **Highly Restricted** Data, such as Passwords, Private Keys, SAML Tokens, and Credit Card Numbers. * **Restricted** Data, such as Usernames and Customer IDs. * **Unrestricted** Data, pretty much anything else. This classification comes with certain obligations: * Any data that is **Highly Restricted** must never be made available in log file under any circumstances. * **Restricted** data could be made available in log files under specific conditions. For example, if an incident were to occur with a service then the on-call engineer would be able to enact a [Break-Glass](http://security-architect.com/how-to-balance-assurance-and-availability-in-pam-systems/) procedure to access this data to diagnose the problem. The Break-Glass procedure would, in turn, trigger a review, an audit, and possibly temporary revocation of privilege from that engineer. What strategies can be employed to achieve this, particularly given that there are a broad range of logging, monitoring and instrumentation tools available on the market that don't provide a direct answer to this problem? For example, both Splunk and AppDynamics have the ability to impose different access controls upon conditions of the telemetry being exposed; this means you can create a filter that masks out `<customerId>NNNNNNNNNNNN</customerId>`. However, neither of these tools give you the capability automatically identify credit card numbers and mask them automatically. **Note**: I believe this is related to DevOps because in a traditional tiered support model a relatively small group of people could have access to the data and filter it manually, by devolving responsibility for operating platforms to development teams this data is potentially exposed to a far wider audience.
2017/03/18
[ "https://devops.stackexchange.com/questions/554", "https://devops.stackexchange.com", "https://devops.stackexchange.com/users/397/" ]
I think the solution comes down to a broad spectrum of approaches that ensures data protection: * **Data Classification**: The most efficient technical strategy is to categorise the data at the point of creation rigorously. At its core, the developers are responsible for ensuring that all logged information is assigned a category. Categorization can, for example, be achieved through [Splunk Metadata](https://docs.splunk.com/Documentation/Splunk/6.5.2/SearchReference/Metadata) which, in turn, can be used to direct log entries to different buckets based upon their data categorization. * **Event Partitioning**: There is often a desire to log sensitive information along side non-sensitive information. For example, if a new user was to sign up you may log: + Customer ID (Restricted) + Customer Type (Restricted) + Aquisition Source (Unrestricted) + Correlation ID (Unrestricted)It is possible to split this one "Event" into two parts, one containing the *Restricted* information and one containing th *Unrestricted* information. This aligns with the first point by allowing filtering rules to direct to different buckets. * **Data Masking**: In specific circumstances it may not be possible to categorise the data at source, in my experience logging solutions do allow for [Masking Rules](https://answers.splunk.com/answers/211998/masking-sensitive-data.html) to X out sensitive data. In the linked example a `sed` command is used to apply a regular expression to all data from a specific source. Once the restricted data has been masked out then the event can be considered to be Unrestricted. Care must be taken with the rule to ensure that information critical to an event such as a correlation ID doesn't match the Regular Expression used to match sensitive data. * **Event Filtering**: As a last resort it may be necessary to filter all events of a particular type or source into a separate bucket if they contain sensitive data that cannot be categorised or masked. In this case the information in a restricted bucket could only be accessed through a [Break-Glass mechanism](https://security.stackexchange.com/questions/14430/in-healthcare-it-is-a-break-glass-mode-to-bypass-access-controls-commonly-req) to bypass access controls under the provisions of an incident. With each of these solutions, testing is key to ensuring that nothing slips through the cracks. Logging and Event Management must be considered to be a first class Non-functional Requirement with the same level of development rigour applied to a solution - including peer review and tests to ensure that data is properly categorised and partitioned in the tool of choice.
It depends on what you mean by "log files" I supposed. If you mean the telemetry data you use to verify your system is operating correctly I would say "Don't log sensitive fields." You don't need that kind of information to alert you to high or low transaction rates, response times to your dependent services, etc. If you mean data for billing or audit purposes I would suggest you establish a write-only pipeline where the data is written but can't be read by the writer. Then your billing and auditing pipeline kicks in and you have the controls there to audit who looked at individual records. In the end security comes down to documented processes with their own secure log files, etc. At some point you have to trust someone or some process since all data is written so that it can later be read.
23,938,711
I have a problem with connection with Google maps API V2 and Android. I' ve enabled services: * Google Maps Android API v2 * Places API Also I've added sha1 fingerprint. ![enter image description here](https://i.stack.imgur.com/mi1qu.png) But I still get this message: **This IP, site or mobile application is not authorized to use this API key** I'm calling service from Android. Do you know where might be the problem, cause I don't know where to search.
2014/05/29
[ "https://Stackoverflow.com/questions/23938711", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1483810/" ]
You must be creating a browser key instead of an android key. I faced similar problem when I accidentely created an android key for Google Cloud Messaging instead of a server key. Please check which key is required for your purpose. For google maps v2 you need android key and for google places api you need a server key(searched google but not so sure on this one never used it). So basically you need two keys. Update: You need server key for places api.
You don't need to create a key for using Google place API, instead just use "**Key for browser apps (with referers)**". But if you want to use Google Map API, you need to generate a Android Key, and you could find instruction here :<https://developers.google.com/maps/documentation/android/start>. Good luck.
37,796,453
I'm having a hard time to understand how to work with functions - I can make then but after that I don't know how to use them. My question is how can I print this code with a function? ``` string = "Hello" reverse = string[::-1] print(reverse) ``` I tried putting it in a function but I cannot make it print Hello. ``` def reverse_a_string(string): string = "Hello" reverse = string[::-1] print(reverse) ``` also tried this ``` def reverse_a_string(string): string = "Hello" reverse = string[::-1] print(reverse) ``` Nothing seems to work. I'm having same problem with this as well. ``` total = 0 def length(words): for i in words: total += 1 return total ```
2016/06/13
[ "https://Stackoverflow.com/questions/37796453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6461005/" ]
Functions without a return value ================================ Functions that just take action or do something without returning a value (for example, `print`). Functions that don't return a value can be defined like that: ``` def sayHello(): print "Hello!" ``` And can be used (called) like that: ``` sayHello() ``` And the output will be: > > Hello! > > > Function parameters =================== A function can also receive parameters (type of variables) from the caller. It's better to demonstrate it with an example. A function that receives a name and greets this name: ``` def sayHelloTo(name): print "Hello", name ``` It can be called like that: ``` sayHelloTo("Yotam") ``` And the output will be: > > Hello Yotam > > > The parameters are the function's input. Functions with a return value ============================= Other functions, unlike `sayHello()` or `sayHelloTo(name)` (that just do something) can return a value. For example, let's make a function that rolls a dice (returns a random number between 1 and 6). from random import randint ``` def rollDice(): result = randint(1, 6) return result ``` The `return` keyword just sets the `output value` of the function and exits the function. An example use of the `rollDice` function will be: ``` dice = rollDice() print "The dice says", dice ``` When the function hits a `return` keyword, it finishes and the return value (in our case, the variable `result`) will be placed instead of the function call. Let's assume `randint(1, 6)` has produced the number 3. Result becomes 3. Result is returned. Now, instead of the line: ``` dice = rollDice() ``` We can treat the line as: ``` dice = 3 ``` (`rollDice()` was replaced with `3`) Functions with parameters and a return value ============================================ Some functions (for example, math functions) can take inputs AND produce outputs. For example, let's make a function that receives 2 numbers and outputs the greater one. ``` def max(a,b): if a > b: return a else: return b ``` What it does is pretty clear, isn't it? If `a` is greater, it returns the value of it. Otherwise, returns the value of `b`. It can be used like that: ``` print max(4, 6) ``` And the output will be: > > 6 > > > Now, your case ============== What you want to do is a function that reverses a string. It should take 1 parameter (input) - the string you want to reverse, and output 1 value - the reversed string. This can be accomplished like that: ``` def reverse_a_string(my_text): return my_text[::-1] ``` now you can do something like that: ``` s = raw_input("Please enter a string to be reversed\n") #input in Python3 r = reverse_a_string(s) print r ``` r will contain the reversed value of s, and will be printed. About your second function - well, I assume that based on this answer you can make it yourself, but comment me if you need assistance with the second one. Local variables =============== About your 3rd example: ``` def reverse_a_string(string): string = "Hello" reverse = string[::-1] print(reverse) ``` This is something that is really worth delaying and understanding. the variable `reverse` is first used **inside the function**. This makes it a **local variable**. This means that the variable is stored in the memory when the function is called, and when it finishes, it is removed. You can say it's lifetime is from when the function is called to when the function is done. This means that even if you called `reverse_a_string(string)`, you wouln't be able to use the `reverse` variable outside of the function, because it would be **local**. If you do want to pass a value like that, you have to "declare" your variable outside of the function and to use the **global** keyword, like that: ``` reverse = "" #This makes reverse a global variable def reverse_a_string(string): global reverse #Stating that we are going to use the global variable reverse reverse = string[::-1] # Then you can call it like that: reverse_a_string("Hello") print reverse ``` The output will be > > olleH > > > Although it's **strongly not recommended** to do it in Python, or in any other language.
``` # defines the 'Reverse a String' function and its arguments def reverse_a_string(): print(string) reverse = string[::-1] print(reverse) print("Type a string") # asks the user for a string input string = input() # assigns whatever the user input to the string variable reverse_a_string() # simply calls the function ``` for functions, you have to define the function, then simply call it with the function name i.e. funtion() In my example, I ask for a string, assign that to the variable, and use it within the function. If you just want to print hello (I'm a little unclear from your question) then simply including the print("hello") or w/ variable print(string) will work inside the function as well.
1,342,540
I implemented a fonction in Visual Basic 2008 that takes the content of all the controls from a System.Winows.Form object and return a hash value corresponding to this content. The use of this function is to detect whether or not the user modified the content of the page and determine if I have to display a message box asking to save. I tried to do this in WPF but I can't seem to get all the controls in the form. Is there any way to do this, or better, is there a function that does what I need? Thanks,
2009/08/27
[ "https://Stackoverflow.com/questions/1342540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/164377/" ]
None of us here have the same insight into your project the way you do, the best answer in this (and so many other cases) is - "It Depends", rarely are there any cut & dry, universally accepted answers to questions like this. You have to make your choice based upon what you're objective is and what is *reasonable* to do. Polling the community is a great way to find out what your options are and what pitfalls could lie ahead should you choose a particular course of action, but definitive answers are probably beyond our reach. As several people here have pointed out if you go down the road of storing multiple measurement types then you have the added responsibility of keeping track of how to convert between them and if you can accept rounding errors when converting between those values. Storing everything in a standard unit is certainly desirable from a maintenance standpoint because it makes things simpler on both the front & back ends - should you need to represent the data differently you can always convert it when drawing it out from the database or convert it before it goes in...But does it meet your users requirements?
First, don't store information inside a field name, I don't think it's best practice I would create a lookup table and do ``` buildings ----------------------------- building_id INT date_built DATE date_unit INT reported_area DOUBLE reported_unit INT ``` Why lookup table, very simple. Why would you want to duplicate 1000x meters while you can just use the number 1
28,393,123
For the past couple of days I've been playing with Ember CLI, using the SANE stack. After getting everything working and making a todo application like the one from the todo MVC website (todomvc.com), I'm now trying to validate data on my server (a sails js server). For example, when a new todo is saved ('Do shopping on Tuesday'), Ember saves the new record in the todo model in the Ember data store. Ember data then updates the todo model back in the sails server, by sending a POST request to '<http://localhost:4000/api/v1/todos>'. How do I tell Ember data that it needs to call a controller on the backend like '<http://localhost:4000/api/v1/todos/addTodo>', instead of directly inserting the data into the backend's model? Maybe it's me but does Ember data only talk to a backend's model. If so, how on earth do you validate data past into the server from the client side. I can only see validation being performed on the client side through the controllers, which is always going to be insecure. I just want to validate data on the backend...
2015/02/08
[ "https://Stackoverflow.com/questions/28393123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3982479/" ]
Had similar problems after I reset my phone. Twice. And a reset for my router. Even more, couldn't open gmail folders or receive Skype notifications on time. Long story short, in "Menu>Security>Apps with usage access" I had Google Play Services unchecked. So, make sure that Google Play Services is active.
I came across this spending hours searching. Almost identical problems on my S4. I downloaded "[ROOT] Disable IPv6" from the app store and it fixed my issues.
52,218,465
I have a dataset like this: ``` # test data test.table <- data.frame( id = seq(1,3), sequence = c('HELLOTHISISASTRING','STRING|IS||18|LONG','SOMEOTHERSTRING!!!') ) ``` Each sequence has the same length (18). Now I want to create a table like this: ``` #id position letter #1 1 H #1 2 E #1 3 L #.....etc ``` Although I know I can split the strings using `strsplit`, like so: ``` splitted <- strsplit(as.character(test.table$sequence), '') ``` I can't figure out how this should be converted to my preferred format?
2018/09/07
[ "https://Stackoverflow.com/questions/52218465", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7885426/" ]
You can use `tidyverse` tools: ```r test.table <- data.frame( id = seq(1,3), sequence = c('HELLOTHISISASTRING','STRING|IS||18|LONG','SOMEOTHERSTRING!!!') ) library(tidyverse) test.table %>% mutate(letters = str_split(sequence, "")) %>% unnest %>% group_by(id, sequence) %>% mutate(position = row_number()) #> # A tibble: 54 x 4 #> # Groups: id, sequence [3] #> id sequence letters position #> <int> <fct> <chr> <int> #> 1 1 HELLOTHISISASTRING H 1 #> 2 1 HELLOTHISISASTRING E 2 #> 3 1 HELLOTHISISASTRING L 3 #> 4 1 HELLOTHISISASTRING L 4 #> 5 1 HELLOTHISISASTRING O 5 #> 6 1 HELLOTHISISASTRING T 6 #> 7 1 HELLOTHISISASTRING H 7 #> 8 1 HELLOTHISISASTRING I 8 #> 9 1 HELLOTHISISASTRING S 9 #> 10 1 HELLOTHISISASTRING I 10 #> # ... with 44 more rows ``` Created on 2018-09-07 by the [reprex package](http://reprex.tidyverse.org) (v0.2.0).
There are some good answers here already, but here is another way to do it using `tidyverse`. ``` test.table <- data.frame( id = seq(1,3), sequence = c('HELLOTHISISASTRING','STRING|IS||18|LONG','SOMEOTHERSTRING!!!') ) library(tidyverse) library(reshape2) test.table %>% separate(col=sequence, into=as.character(1:18), sep=1:17) %>% melt('id', value.name = 'letter', variable.name='position') %>% arrange(id, position) ``` In the above code, the `separate` function from `tidyr` separates the `sequence` column into 18 separate columns (naming them 1 to 18) and then those are melted into the `letter` and `position` columns.
9,116,395
How to write `$('label.someClass').attr('valid', true);` in Java Script with out using jQuery?
2012/02/02
[ "https://Stackoverflow.com/questions/9116395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/144140/" ]
``` Array.prototype.forEach.call(document.querySelectorAll('label.someClass'), function( label ) { label.setAttribute('someAttribute', 'someValue'); }); ``` which implies that the browser is capable of ES5. An alternative for `.querySelectorAll` could be `.getElementsByClassName` too here.
``` document.getElementById("myimage").setAttribute("src","another.gif") ``` [Try this Tutorial](http://www.javascriptkit.com/dhtmltutors/domattribute.shtml)
7,244,331
I want to build a small Silverlight application that will save a Canvas (and it's child objects) as a high-resolution JPG or PNG. I'm not understanding how to work with the units in silverlight since they're based on pixels. How would I go about specifying the size of the Canvas object in pixels if my goal is to save it as a JPG or PNG with the exact measurements of 5" x 7" ??? In other words, how can we specify measurement values in Silverlight that will print out in exact inches since different monitors have different DPI values. Thanks!!
2011/08/30
[ "https://Stackoverflow.com/questions/7244331", "https://Stackoverflow.com", "https://Stackoverflow.com/users/919834/" ]
Try this, Click on "Fetch upstream" to sync your forked repo from upstream master. [![enter image description here](https://i.stack.imgur.com/GPkH4.png)](https://i.stack.imgur.com/GPkH4.png)
If you want to keep your GitHub forks up to date with the respective upstreams, there also exists this probot program for GitHub specifically: <https://probot.github.io/apps/pull/> which does the job. You would need to allow installation in your account and it will keep your forks up to date.
49,859,734
So at work we all share the same stash were we push and pull our branches and all that good git stuff. So i usually do my pull and push from egit in eclipse (I am not the only one most people here do it this way). but some of my branches have started giving me the [lock fail] "couldn't lock local tracking ref for update". But the thing is there are 75+ people doing it the same way and no one has seen this error. I have done some research and most of it says it is based off name conflicts for example Foo and foo. Egit would get confused on which one to pull because the only difference is a capital letter, but other people are having no issues. I don't know what is going on. Any help would be greatly appreciated.
2018/04/16
[ "https://Stackoverflow.com/questions/49859734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9269932/" ]
``` git remote prune origin ``` solved it for me.
For me, I encountered the lock fail problem in tags, so I do following steps: 1. Reset current branch 2. Delete all local tags. 3. Fetch 4. Pull. It solves the problem.
2,695,202
If you have an HTML `<select multiple>` of a certain width and height (set in CSS), if there are more values then you can possibly fit in that height, then the browser adds a vertical scroll bar. Now if the text is longer than the available width, is it possible to instruct the browser to add a horizontal scrollbar?
2010/04/22
[ "https://Stackoverflow.com/questions/2695202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5295/" ]
I think jtolle's response addressed the question best - the small reference to Application.Run may be the answer. The questioner doesn't want to use simply func1 or Module1.func1 - the reason one would want to use CallByName in the first place is that the desired function.sub name is not known at compile time. In this case, Application.Run does work, e.g.: ``` Dim ModuleName As String Dim FuncName As String Module1Name = "Module1" FuncName = "func1" Application.Run ModuleName & "." & FuncName ``` You can also prepend the Project Name before the ModuleName and add another period ".". Unfortunately, Application.Run does not return any values, so while you can call a function, you won't get its return value.
Modules in VB6 and VBA are something like static classes, but unfortunately VB doesn't accept Module1 as an object. You can write Module1.Func1 like C.Func1 (C being an instance of some Class1), but this is obviously done by the Compiler, not at runtime. Idea: Convert the Module1 to a class, Create a "Public Module1 as Module1" in your Startup-module and "Set Module1 = New Module1" in your "Sub Main".
656,273
Take a look at [this video](https://youtu.be/Cg73j3QYRJc). It shows that when 2 springs in series are transformed into 2 springs in parallel the attached mass goes up. But I'm interested in what happens in that split-second after cutting the blue cord but before the green and red ropes become taut (i.e. when the springs are pulling their respective ropes but the latter are still slack). Does the attached mass go up during that time? Down? Or does it maybe depend on the actual springs used (their pulling strength or something)?
2021/07/30
[ "https://physics.stackexchange.com/questions/656273", "https://physics.stackexchange.com", "https://physics.stackexchange.com/users/59692/" ]
### Summary **We do not know if the hanging weight will have a an instant of going downward or not** It depends on the mass and spring constant of the lower spring and mass of the hanging weight. ### Logic We cut the rope. There is gravitational force on the weight. The springs begin to contract rapidly and contract until the strings are tight. (John Hunter’s answer assumes the mass has to descend to make the strings taut, but the contracting springs do most of the moving to tighten the strings). Assume the strings have no mass. After cutting but before tight strings, the [lower spring / hanging weight] is a free system not affected by the upper spring or weightless un-taut strings. Let’s consider this system during that time: The system **as a whole** is only acted on by gravity so as mentioned by alephzero it will fall - it’s center of mass will accelerate downward at F/M = g, the acceleration of gravity, where M = m\_spr + m\_hw (spring and hanging weight). In addition to that, the spring (which has mass) will contract. As alephzero said, if the hanging weight has a much much higher mass than the lower spring, the mass will go down as this system falls (until the strings are tight). But what if the spring doesn’t have a mass that is negligible compared to the hanging weight? There are cases where the spring constant and/or spring mass are high enough that the mass never (even instantaneously) has a downward acceleration of velocity. The spring contracts with enough inertial force that it’s instantaneous force on the weight is greater than m\_hw g. To be sure there are such cases, take an extreme case where the mass of the hanging weight is negligible compared to the spring’s mass and the spring constant is high. The spring will begin to fall under its own weight while contracting rapidly about its center and its lower end will go up (hence the hanging weight will)
When the blue cord is cut, several things happen very rapidly. At the instant the blue cord is cut, the two springs in series become unloaded, and they rapidly contract up until the red and green cords become taut. At that point, the springs become loaded again and their rate of contraction would change in a complicated way based on what the weight does. While the springs are contracting and before the red and blue cords become taut, the weight is free falling, so it is moving down under the acceleration of gravity. When the red and blue cords become taut, the springs "catch" the weight that is falling. Because the time interval for this catch is so short, the weight has a very low downward velocity, and this velocity must still be stopped and reversed to pull the weight upward. Because the weight has inertia, this means that for an instant, the upward contraction of the springs is reversed by a very small amount. After that instant, the two springs will continue contracting upward at a rate that is somewhat slower than when the weight was in free fall. Note that it would take high speed video (e.g., 100,000 frames per second) to observe these changes in the cords, springs, and weight, so these changes are not observable in the posted video.
2,253,304
What rarely used debugging tools you found useful ? My recent debugging situation on Visual Studio required trapping the breakpoint on fresh built 32-bit DLL, which was loaded by GUI-less executable, which was spawned by COM+ server on remote x64 machine, which was called through RPC from actual GUI. As usual, all worked well on all 32 bit machine, but kept failing on "machine other than development one". So remote debugging was inevitable. So after scratching the head beaten against wall for 2 days, I have added 10 sec delay into DLL attach entry point and used Microsoft Remote Debugger wich I never used before. It saved my day. Another favorite: Java JMX console as a performance "debugging" tool. You can see all threads, memory chart, have a snapshot of any thread stack any time you click. Clicking several times helps to find what exactly is slow in J2EE application.
2010/02/12
[ "https://Stackoverflow.com/questions/2253304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
A logic analyzer plugged to CPU pins and able to disassemble executed code. I tracked a bug in the boot sequence of an embedded system.
WinDbg and other lower level debuggers are the ultimate weapon if you know the tricks and tips.
39,397,904
We have an MVC web application that I inherited that loads, let's call it MyCategory and all of its children into a webform, takes edit, then saves on save clicked. The way the application works is to first delete all data for the parent level entity in the model, then add everything back. We have pretty low concurrent user base on this, no more than twenty people saving at most every dew minutes each. We are unable to reproduce this error locally, but when the offshore team starts work we have started seeing the > > [SqlException (0x80131904): Timeout expired. The timeout period > elapsed prior to completion of the operation or the server is not > responding. The statement has been terminated.] > > > error show up. This is happening when calling a delete from LINQ on the parent table (it has no data at this point, nor do child tables). It is intermittent, but has happened quite a few times in the past week, in which there was a ramp up in work on this portion of the project. From the Stack Trace, it looks to be failing on System.Data.SqlClient.SqlCommand.FinishExecuteReader which appears to be going for 109+ minutes. This should be deleting at most tqo records from the table, and anyone loading data from this table should be retrieving at most two in a very short time span. Any ideas on where to start would be appreciated. Unfortunately, I do not have permissions to run SQL Query Analyzer or Activity Monitor on the production database. Call Stack is: ``` [SqlException (0x80131904): Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated.] System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction) +388 System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose) +717 System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean&amp; dataReady) +4515 System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString) +6557561 System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task&amp; task, Boolean asyncWrite, SqlDataReader ds) +6560327 System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task&amp; task, Boolean asyncWrite) +586 System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite) +742 System.Data.SqlClient.SqlCommand.ExecuteNonQuery() +287 System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult) +789 System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries) +188 System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query) +500 System.Data.Linq.StandardChangeDirector.DynamicDelete(TrackedObject item) +71 System.Data.Linq.StandardChangeDirector.Delete(TrackedObject item) +258 System.Data.Linq.ChangeProcessor.SubmitChanges(ConflictMode failureMode) +622 System.Data.Linq.DataContext.SubmitChanges(ConflictMode failureMode) +932 WebAppData.MyCategory.MyCategoryData.DeleteAll(Int32 id, Guid gid) +1053 WebAppServices.MyCategory.MyCategoryService.DeleteMyCategoryParentItems(Int32 id, Guid gId) +1632 WebAppServices.MyCategory.MyCategoryService.UpdateMyCategory(Int32 id, Guid gId, MyCategoryEntity mce) +51 WebAppUI.Areas.Documents.Categories.Sections.MyCategory.MyCategoryController.Save(Int32 Id, Guid gId, MyCategoryModel model) +93 ``` EDIT: Connection String: ``` <add name="Data" connectionString="Data Source=myserver;Initial Catalog=mydatabase;User ID=myuser;Password=mypassword /> ```
2016/09/08
[ "https://Stackoverflow.com/questions/39397904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4926084/" ]
Make sure you didn't **forgot** to ***commit/rollback transaction***. **Transaction makes** your **table lock** from selecting/updating/deleting. And because of it, **your accessing** to delete **will be time out** just because for **waiting** when the **table being unlock** again.
For a specific query, you can write the below code ``` context.Database.CommandTimeout =60*3; ``` `context` is the database connection object name `60*3` means `180` seconds, because `CommandTimeout` accepts value in `seconds`.
10,261
When there is one rectangular beam like below image, [![enter image description here](https://i.stack.imgur.com/3kce0.png)](https://i.stack.imgur.com/3kce0.png) I would like to know how the beam is deflected according to thicknesses of top plate and bottom plate. My concerning cross section patterns are like below. [![enter image description here](https://i.stack.imgur.com/L7HG3.png)](https://i.stack.imgur.com/L7HG3.png) The conditions are as below. Thicknesses of both side plates are same. Type 1 : thickness of top < thickness of bottom Type 2 : thickness of top = thickness of bottom Type 3 : thickness of top > thickness of bottom Which type is less deformed? and Why?
2016/06/10
[ "https://engineering.stackexchange.com/questions/10261", "https://engineering.stackexchange.com", "https://engineering.stackexchange.com/users/4624/" ]
There are two things going on. First, even if this "actuator" can produce constant torque, the torque required to keep the load spinning will be at least in part a function of the spinning speed. There will be some friction and other forces that increase with increased speed. *Viscous friction* increases linearly with speed, and other effects, like air resistance, increase even more strongly with speed. Therefore, even with constant torque, eventually the friction forces rise to exactly oppose the torque and the object no longer speeds up. Second, your "actuator" probably can't supply constant torque, even over its rated speed range. For a electric motor, for example, torque decreases with speed at a fixed applied voltage. The motor has a finite unloaded speed that is mostly proportional to applied voltage. That is the speed at which it's externally available mechanical torque drops to 0.
The torque rating for the actuator depends on the speed it's running at - as it approaches its "top speed" it can't deliver the full rated torque. The reasons depend a lot on the actuator type. For example with a DC electric motor the coil induces a back-EMF at higher speeds causing a tail off on the torque curve. For other actuator types there will be other losses which affect their performance. (All in addition to friction in bearings, etc.)
24,718,071
I'm can't seem to build a working NSTextView programmatically. Starting from a new project template I have this code (mostly coming from Apple's "Text System User Interface Layer Programming Guide"): ``` - (void)applicationDidFinishLaunching:(NSNotification *)aNotification { NSString *string = @"Here's to the ones who see things different."; NSTextStorage *textStorage = [[NSTextStorage alloc] initWithString:string]; NSLayoutManager *layoutManager = [[NSLayoutManager alloc] init]; [textStorage addLayoutManager:layoutManager]; NSTextContainer *textContainer = [[NSTextContainer alloc] initWithContainerSize:NSMakeSize(300, 300)]; [layoutManager addTextContainer:textContainer]; NSTextView *textView = [[NSTextView alloc] initWithFrame:NSMakeRect(50, 50, 300, 300) textContainer:textContainer]; [textContainer setWidthTracksTextView:YES]; [textView setVerticallyResizable:YES]; [textView setHorizontallyResizable:NO]; [textView setAutoresizingMask:NSViewWidthSizable]; [[self.window contentView] addSubview:textView]; } ``` Running the app, a window opens with a white square in it that's supposed to be the NSTextView, but there's no text, and there's no way to interact with the text view. Moreover, I tried adding text to the text view in code after the view is created using `[textView setString:@"Some string."]`, but that doesn't work either. (Incidentally, I've also tried putting it in a NSScrollView first, in case that somehow was the issue, but that didn't help.) I can't for the life of me figure out what the problem is. What am I missing?
2014/07/12
[ "https://Stackoverflow.com/questions/24718071", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3833236/" ]
The result of your `$.merge` is `[Array[2], 6, 7, 8, 9]` `function.apply()` takes an array of items, and divide it into a number of **separate** arguments - one for each element of the array. The first argument `item` is therefore [1,2] because that is the first element of the array you passed. apply() did take the rest of elements and passed them as additional arguments which you would see by declaring your function as prependArgs(item, item2, item3, item4, etc..), or by doing this: `function prependArgs(item) { console.log(arguments) // prints [Array[2], 6, 7, 8, 9] }` `function.call()` would pass the entire array as the single argument `item` without splitting it.
To get the whole array inside the function call **using `apply()`**, try this ``` var orig = [1, 2], add = [6,7,8,9]; prependArgs.apply(orig, [$.merge([orig], add)]); function prependArgs(item) { console.log(item) //--- this prints [[1, 2], 6, 7, 8, 9] var a = item.slice(0); for (var i = 0; i < a.length; i++) { this.unshift(item[i]); } } ``` as pointed out in the comments, if you want to use `apply()` you need to pass an array as the second argument, see documentation [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply)
301,775
I have the option to open groups of files in same window setting turned on, and this works for pictures. However, for PDFs this setting does not seem to work. I know opening multiple PDFs in the same window was possible at least in Sierra, I have no idea if they changed anything for High Sierra that caused this to fail. I went through ~/Library/Containers/com.apple.preview/..../com.apple.Preview.plist and found PVImageOpeningMode = 1 so this should be the correct setting, at least from what I know. I tried getting my old ~/Library/Containers/com.apple.preview/fluff and replaced whatever setting I have right now ( it worked before ), and unfortunately I still cannot view multiple PDFs in the same window ( without using tabs ). This is pretty vexing, right now im leaning on the conclusion that apple had some how changed how preview app works, unless there is another hidden preview setting location some where. Has anybody found a solution to opening multiple PDFs in the same window in High Sierra?
2017/10/11
[ "https://apple.stackexchange.com/questions/301775", "https://apple.stackexchange.com", "https://apple.stackexchange.com/users/259197/" ]
If you have multiple PDF files that you want to open in ONE window as ONE file that you can scroll down you can do this: 1. Open ONLY ONE pdf file in previev. 2. Use Alt+Cmd+2 (it will open miniatures on the left side). 3. Select all OTHER pdf files and drag them manually into miniatures sidebar. Now you have old view in which you can move pages up or down, delete them, add other files, save all as one pdf etc.
You can combine pdf pages into one preview document by: 1. Open one of the docs. 2. View the thumbnail sidebar. 3. Select where you wish to add additional pdf file. (in the thumbnail sidebar) 4. Select "Edit" from menu then "Insert" and "Page from File" 5. Click on the file you wish to add. 6. Save the resulting pdf file that you have added pages to. Hope this helps.
18,168,484
I was just wondering how I could find out what the last character of the user input was using Python. I need to know whether it was an S or not. Thanks in advance.....
2013/08/11
[ "https://Stackoverflow.com/questions/18168484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2671605/" ]
You can use the built-in function [`str.endswith()`](http://docs.python.org/2/library/stdtypes.html#str.endswith): ``` if raw_input('Enter a word: ').endswith('s'): do_stuff() ``` Or, you can use [Python's Slice Notation](https://stackoverflow.com/questions/509211/the-python-slice-notation): ``` if raw_input('Enter a word: ')[-1:] == 's': # Or you can use [-1] do_stuff() ```
Strings can be treated like lists of characters, and to get the last item of a list you can use `-1`, so after you convert the string to lowercase (just in case you have an uppercase s), your code will look like: ``` if (user_input.lower()[-1] == 's'): #Do Stuff ```
146,316
What number of classes do you think is ideal per one namespace "branch"? At which point would one decide to break one namespace into multiple ones? Let's not discuss the logical grouping of classes (assume they are logically grouped properly), I am, at this point, focused on the maintainable vs. not maintainable number of classes.
2008/09/28
[ "https://Stackoverflow.com/questions/146316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15497/" ]
"42? No, it doesn't work..." Ok, let's put our programming prowess to work and see what is Microsoft's opinion: ``` # IronPython import System exported_types = [ (t.Namespace, t.Name) for t in System.Int32().GetType().Assembly.GetExportedTypes()] import itertools get_ns = lambda (ns, typename): ns sorted_exported_types = sorted(exported_types, key=get_ns) counts_per_ns = dict( (ns, len(list(typenames))) for ns, typenames in itertools.groupby(sorted_exported_types, get_ns)) counts = sorted(counts_per_ns.values()) print 'Min:', counts[0] print 'Max:', counts[-1] print 'Avg:', sum(counts) / len(counts) print 'Med:', if len(counts) % 2: print counts[len(counts) / 2] else: # ignoring len == 1 case print (counts[len(counts) / 2 - 1] + counts[len(counts) / 2]) / 2 ``` And this gives us the following statistics on number of types per namespace: ``` C:\tools\nspop>ipy nspop.py Min: 1 Max: 173 Avg: 27 Med: 15 ```
With modern IDEs and other dev tools, I would say that if all the classes belong in a namespace, then there is no arbitrary number at which you should break up a namespace just for maintainability.
10,975,898
I want to do CRUD operations on xml docs stored in Marklogic Server. Can anybody tell me please how can I perform CRUD operations in Marklogic Server ?
2012/06/11
[ "https://Stackoverflow.com/questions/10975898", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1326229/" ]
How are you connecting to the MarkLogic database? This may make a big difference in how you go about doing CRUD. If you are pushing data in using an HTTP service you can use an existing REST endpoint such as the [Corona project](https://github.com/marklogic/Corona) or make your own using XQuery. If you are using Java or .Net you can connect through the XCC library, which have functions for CRUD without having to write XQuery. In pure XQuery the following commands may be useful to read up on in the MarkLogic XQuery function documentation on the MarkLogic web site: * [`xdmp:document-insert()`](http://community.marklogic.com/pubs/3.2/apidocs/UpdateBuiltins.html#document-insert) + this will do the Create and Update of CRUD * `fn:doc-available()` + if you want to test to see if a document exists. Some people doing CRUD want this in order to make Create and Update different . Other's don't care. * [`xdmp:document-delete()`](http://community.marklogic.com/pubs/3.2/apidocs/UpdateBuiltins.html#document-delete) + the Delete in CRUD * `fn:doc()` + the Read in CRUD
Once the document is stored, you use functions like `xdmp:node-replace()`, `xdmp:node-insert-child()` etc. to manipulate the document node-by-node. Alternatively, you can change a document by saving a new version to the same URI via `xdmp:document-insert()`, or delete a document via `xdmp:document-delete()`. Note that the transactional semantics in MarkLogic are truly functional, so the document never changes during execution of a transaction. You need to complete the transaction and get the document from the database to see the changes.
1,693,412
What can you tell about speed of couchdb and mysql databases? I mean, very simple requests like getting one row (or one document) by unique id and simple requests like getting the 20 ids/rows/documents with the biggest date (of course, using indexes and views etc - don't really know how it works in CouchDB but I'm pretty sure there is something. Please don't send me learn how CouchDB works: I'm going to learn it, but I need a perfomance comparison anyway). Thanks! --- As I realized from the links in the first answer, while I have only one server for DB, it's a lot better to use MySQL?
2009/11/07
[ "https://Stackoverflow.com/questions/1693412", "https://Stackoverflow.com", "https://Stackoverflow.com/users/145357/" ]
I found [this article](http://en.wikipedia.org/wiki/Apples_and_oranges) linked to in another SO question about MySQL vs CouchDB performance, but I don't know if it counts.
Exactly. The main diference is that: Relational vs Non Relational. And it depends of what you need. There is a movement about this: <http://en.wikipedia.org/wiki/NoSQL> And, another good no-relational db: www.mongodb.org
380,752
Let $K/F$ be a finite extension of local fields (of characteristic 0). Is it true that the quotient group $K^\times/ F^\times$ is always compact? I understand that if the extension is cyclic, it is compact by Hilbert 90. But does it hold in general?
2021/01/09
[ "https://mathoverflow.net/questions/380752", "https://mathoverflow.net", "https://mathoverflow.net/users/32746/" ]
Let $K\subset L$ be a finite extension of normed non-discrete locally compact fields. Let $r>1$ be the norm of some element of $K$. Then every nonzero element of $L$ can be written as $r^nw$ with $\|w\|\in [1,r]$ and $n\in\mathbf{Z}$. Since $\{w\in L:\|w\|\in [1,r]\}$ is compact, it immediately follows that $K^\*/L^\*$ is compact. (Actually, this shows that for every locally compact normed field $L$ and $w\in L$ with $\|w\|>1$, $L^\*/\langle w\rangle$ is compact. In particular, in the above setting with $w\in K$, the group $L^\*/K^\*$ is a quotient of $L^\*/\langle w\rangle$ and inherits compactness.)
N.B. The result is true without the assumption that the characteristic of $F$ is $0$. You moreover have to assume that $F$ is *locally compact*. The standard proof is reuns's one. If you already know that the projective space ${\mathbb P}(F^n )$ is compact for any $n\geqslant 0$, you can observe that $K^\times /F^\times$ identifies to ${\mathbb P}(F^n )$, where $n=[K:F]$, as a topological space.
21,905,534
I want to display and order a number of results to my webpage. I'm still a starter with PHP but I have the following code to echo (all) data and that works pretty fine but I don't know if the code is good if I only want to show for example 5 results. And if that would work, how could I order them? (Like a top 5 for quickest time scores) ``` $dbhost = 'host'; $dbuser = 'user'; $dbpass = 'pass'; $conn = mysql_connect($dbhost, $dbuser, $dbpass); if(! $conn ) { die('Could not connect: ' . mysql_error()); } $sql = 'SELECT name, company, time FROM tablename'; mysql_select_db('databasename'); $retval = mysql_query( $sql, $conn ); if(! $retval ) { die('Could not get data: ' . mysql_error()); } while($row = mysql_fetch_array($retval, MYSQL_NUM)) { echo "name: {$row[0]} <br> ". "company: {$row[1]} <br> ". "time: {$row[3]} <br> " ; } mysql_free_result($retval); mysql_close($conn); ``` I should somewhere add ORDER BY but can't find the right solution.
2014/02/20
[ "https://Stackoverflow.com/questions/21905534", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2086716/" ]
Try this, ``` $sql = 'SELECT name, company, `time` FROM tablename ORDER BY name ASC LIMIT 5'; ```
`$sql = SELECT name, company, time FROM tablename ORDERBY columnname LIMIT n;` Here n refers to number of records to be shown.
10,102,456
I am trying to get all the images with class `front` and display their src attribute. Looking at the console it's working, but it returns images with class front and also images with class back along with the entire img code. I only want the src attribute. How can I o about doing this? **HTML** ``` <div id="results"></div> <div id="mm_grid"> <!-- Grid contents written dynamically --> <div class="mm_row"> <div class="mm_window" id="tile0" onclick="flipImage(this)"><img class="front" src="public/images/mm_image5.jpg" alt="" /><img class="back" src="public/images/mm_back.jpg" alt="" /></div> <div class="mm_window" id="tile1" onclick="flipImage(this)"><img class="front" src="public/images/mm_image5.jpg" alt="" /><img class="back" src="public/images/mm_back.jpg" alt="" /></div> <div class="mm_clearfix"></div> </div> <div class="mm_row"> <div class="mm_window" id="tile2" onclick="flipImage(this)"><img class="front" src="public/images/mm_image8.jpg" alt="" /><img class="back" src="public/images/mm_back.jpg" alt="" /></div> <div class="mm_window" id="tile3" onclick="flipImage(this)"><img class="front" src="public/images/mm_image0.jpg" alt="" /><img class="back" src="public/images/mm_back.jpg" alt="" /></div> <div class="mm_clearfix"></div> </div> <div class="mm_row"> <div class="mm_window" id="tile4" onclick="flipImage(this)"><img class="front" src="public/images/mm_image3.jpg" alt="" /><img class="back" src="public/images/mm_back.jpg" alt="" /></div> <div class="mm_window" id="tile5" onclick="flipImage(this)"><img class="front" src="public/images/mm_image2.jpg" alt="" /><img class="back" src="public/images/mm_back.jpg" alt="" /></div> <div class="mm_clearfix"></div> </div> </div>​ ``` **jQuery** ``` var linkArray = $("img.front").map(function() { return $(this).parent().html(); }).get(); console.log(linkArray); ``` ​ **Results** ``` ["<img class="front" src="public/images/mm_image5.jpg" alt=""><img class="back" src="public/images/mm_back.jpg" alt="">", "<img class="front" src="public/images/mm_image5.jpg" alt=""><img class="back" src="public/images/mm_back.jpg" alt="">", "<img class="front" src="public/images/mm_image8.jpg" alt=""><img class="back" src="public/images/mm_back.jpg" alt="">", "<img class="front" src="public/images/mm_image0.jpg" alt=""><img class="back" src="public/images/mm_back.jpg" alt="">", "<img class="front" src="public/images/mm_image3.jpg" alt=""><img class="back" src="public/images/mm_back.jpg" alt="">", "<img class="front" src="public/images/mm_image2.jpg" alt=""><img class="back" src="public/images/mm_back.jpg" alt="">"] ```
2012/04/11
[ "https://Stackoverflow.com/questions/10102456", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1320596/" ]
Replace ``` return $(this).parent().html(); ``` With ``` return $(this).attr('src'); ``` In your example you are getting the HTML code of the image parent element (i.e. the div element). This way you get the `src` attribute of the `front` img element alone.
if you want the SRC attribute only, you have to do the following: ``` $("img.front").each(function (index, element){ alert($("img.front").eq(index).attr("src")); }); ``` this will print out the SRC of each image with FRONT class.
8,388,130
I am facing a complex situation of SQL queries. The task is to update multiple rows, with multiple values and multiple conditions. Following is the data which I want to update; Field to update: 'sales', condition fields: 'campid' and 'date': ``` if campid = 259 and date = 22/6/2011 then set sales = $200 else if campid = 259 and date = 21/6/2011 then set sales = $210 else if campid = 260 and date = 22/6/2011 then set sales = $140 else if campid = 260 and date = 21/6/2011 then set sales = $150 ``` I want to update all these in one query.
2011/12/05
[ "https://Stackoverflow.com/questions/8388130", "https://Stackoverflow.com", "https://Stackoverflow.com/users/927924/" ]
Try this: ``` UPDATE your_table SET sales = CASE WHEN campid = 259 AND date = 22/6/2011 THEN 200 WHEN campid = 259 AND date = 21/6/2011 THEN 210 WHEN campid = 259 AND date = 22/6/2011 THEN 140 WHEN campid = 259 AND date = 21/6/2011 THEN 150 ELSE sales END ``` Naturally I don't know if date field is really DATE or DATETIME, so I left query showing what you can do, but maybe you have to fix dates comparison according to data type. If date field is DATE (as it should) you can write `AND date = '2011-06-22'` and so on. Note `ELSE` condition: it's necessary to avoid records not falling inside other cases will be set to NULL.
You certainly should not do these in a single query. Instead, if what you aim for is to update them atomically, all at the same time, you should issue several `UPDATE` statements in a single *transaction*. You do not say which MySQL version you use, and not which storage engine. Assuming InnoDB - which is the standard in recent versions of MySQL and should generally be used for transactional systems - and also assuming you are doing this from the command line client, you would ``` mysql> set autocommit=0; mysql> UPDATE ....; mysql> UPDATE ....; mysql> ... mysql> commit; ``` You can then reenable autocommit if you like by repeating the first line, but with a value of `1`: ``` mysql> set autocommit=1; ```
62,783,101
I'm new to PowerShell, I need to create traces on several steps of the script below. Here is the csv example (the real one is about a million lines) I erased a value in the first column in order to do test ``` UCB63_DATENUM;U6618_FILENAME;UF6E8_CANAL;U65B8_IDRP 7/8/19 22:27;;ML;1367091; 9/11/19 23:03;49453878_ZN_LIQRLVPR_A_V_ML.pdf;ML;106440 9/24/19 21:04;497E585B_ZN_LIQRLVPR_A_V_CS.pdf;CS;1536658 2/12/20 22:12;58453B75_ZN_LIQRLVPR_A_V_ML.pdf;ML;1406091 ``` First check would be on the whole CSV, to check the right number and names of the column Then check of an exception or an error during treatment (I think a try/catch) I've changed things, some of them work other not (I can't find why) I still have to do a first check on my document (number of columns and name of the column) If you try the code you'll see in the result of the TITLE (in my xml) I get a ')' which I was not expecting And if I erase a value in U65B8\_IDRP column the error is not catch and goes into the xml Here is the code ``` #vARIABLES EN DUR $FREQUENCE_DECOMPTE = 'Nom="FREQUENCE_DECOMPTE" Valeur="MENS"' $LIBELLE_ORGANISME = 'Nom="LIBELLE_ORGANISME" Valeur="HUMANIS CCN OG"' $MONTANT_TOTAL = 'Nom="MONTANT_TOTAL" Valeur="0"' $POLE = 'Nom="POLE" Valeur="1ADP"' $CODE_ORGANISME = 'Nom="CODE_ORGANISME" Valeur="1ADP"' # Paramètre nombre item par xml VALEUR A MODIFIER A 5000 $maxItemsPerXml = 3 #Import du csv et création des différentes collections $liste = Import-Csv -path 'c:\temp\testH.csv' -Delimiter ';' [System.Collections.ArrayList] $DateErrors = @() [System.Collections.ArrayList] $FileNameErrors = @() [System.Collections.ArrayList] $CanalErrors = @() [System.Collections.ArrayList] $NumAssureErrors = @() #Initiation booléen foreach($item in $liste) { #Initiation variables booléennes $MyDateIsCorrect = $true $MyFileNameIsCorrect = $true $MyCanalIsCorrect = $true $MyNumAssureIsCorrect = $true #Transformations données $date = $($item.UCB63_DATENUM -split " ")[0] $renommage = % {$item.U6618_FILENAME.Split('.')[0]} if([System.String]::IsNullOrEmpty($item.UCB63_DATENUM)) { $MyDateIsCorrect = $false $DateErrors.Add($item) } else { if($date -notmatch "[0-9]{1,2}[\/][0-9]{1,2}[\/][0-9]{1,2}") { $MyDateIsCorrect = $false $DateErrors.Add($item) } } if([System.String]::IsNullOrEmpty($item.U6618_FILENAME)) { $MyFileNameIsCorrect = $false $FileNameErrors.Add($item) } else { if($item.U6618_FILENAME -notmatch ".+[\.]pdf") { $MyFileNameIsCorrect = $false $FileNameErrors.Add($item) } } if([System.String]::IsNullOrEmpty($item.UF6E8_CANAL)) { $MyCanalIsCorrect = $false $CanalErrors.Add($item) } if([System.String]::IsNullOrEmpty($item.U65B8_IDRP)) { $MyNumAssureIsCorrect = $false $NumAssureErrors.Add($item) } #Génération output XML if($MyDateIsCorrect -and $MyFileNameIsCorrect -and $MyCanalIsCorrect -and $MyNumAssureIsCorrect) { @" <Document> <Index Nom="TITLE" Valeur="$renommage"/> <Index Nom="NO_ASSURE" Valeur="$($item.U65B8_IDRP)"/> <Index Nom="DEBUT_PERIODE" Valeur="$RecupDateFinTraitement"/> <Index Nom="FIN_PERIODE" Valeur="$RecupDateFin30"/> <Index $FREQUENCE_DECOMPTE/> <Index $LIBELLE_ORGANISME/> <Index $MONTANT_TOTAL/> <Index Nom="DATE_GENERATION_DECOMPTE"$RecupDateFinTraitement/> <Index $POLE/> <Index $CODE_ORGANISME/> <Index Nom="ALERTE_MAIL" Valeur="$fin"/> <Fichier Nom="$($item.U6618_FILENAME)"/> </Document> "@ # création fichier $xmlFile = "C:\Temp\MIG_ERELEVE_MM_$(get-date -f dd-MM-yyyy)_{0:D3}.xml" -f $xmlFileCount # création fichier ok $CsvColonneEnPlus = import-csv -path 'c:\temp\testH.csv' -Delimiter ';' | Select-Object *,@{Name='Etat';Expression={'OK'}} # création contenant xml, décla du root node et écriture dans fichier @" <?xml version="1.0" encoding="utf-8"?> <Documents Origine="ERELEVE_HUM"> $($XMLItems -join "`r`n") </Documents> "@ | Set-Content -Path $xmlFile -Encoding UTF8 # Création fichier OK suite traitement #$CsvColonneEnPlus = import-csv -path 'c:\temp\testH.csv' -Delimiter ';' | Select-Object *,@{Name='Etat';Expression={'OK'}} | Export-Csv -path c:\temp\FichierOK.csv -NoTypeInformation } else { #ECRIRE DANS LE 5eme FICHIER RECAP AVEC ;KO } } $DateErrors.ToArray() | Export-Csv -Path c:\temp\DateErrors.csv -NoTypeInformation $FileNameErrors.ToArray() | Export-Csv -Path c:\temp\FileNameErrors.csv -NoTypeInformation $CanalErrors.ToArray() | Export-Csv -Path c:\temp\CanalErrors.csv -NoTypeInformation $NumAssureErrors.ToArray() | Export-Csv -Path c:\temp\NumAssureErrors.csv -NoTypeInformation ``` And as well I would like to catch all the "good treatment and export it" into a csv file like my first csv file with the command : ``` $CsvColonneEnPlus = import-csv -path 'c:\temp\testH.csv' -Delimiter ';' | Select-Object *,@{Name='Etat';Expression={'OK'}} ``` It works but I don't know where in the code to put it in to catch the right values Here the result I'm obtaining (which catch everything) ``` "UCB63_DATENUM","U6618_FILENAME","UF6E8_CANAL","U65B8_IDRP","Etat" "08/07/201","457E6659_ZN_LIQRLVPR_A_V_ML.pdf","ML","","OK" "11/09/2019 22:04","49453878_ZN_LIQRLVPR_A_V_ML.pdf","ML","106440","OK" "24/09/2019 00:00","497E585B_ZN_LIQRLVPR_A_V_CS","CS","1536658","OK" "12/02/2020 00:00","","ML","1406091","OK" "","3D517878_ZN_LIQRLVPR_A_V_ML.pdf","ML","1282640","OK" ```
2020/07/07
[ "https://Stackoverflow.com/questions/62783101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13853879/" ]
You have to create a new dictionary: ``` d_original = {'2,449': 1, '11,821': 2, '26,153': 3} sorted_items = sorted(d_original.items(), key=lambda item: int(item[0].replace(',', '')), reverse=True) # from collections import OrderedDict # d_new = OrderedDict(sorted_items) d_new = dict(sorted_items) for k,v in d_new.items(): print(f'{k}: {v}') ``` Prints: ``` 26,153: 3 11,821: 2 2,449: 1 ``` **Update** Or in your case: ``` sorted_items = sorted(self.likeposts.items(), key=lambda item: int(item[0].replace(',', '')), reverse=True) self.likeposts = dict(sorted_items) for k,v in slef.likeposts.items(): print(f'{k}: {v}') ``` Since Python 3.6 regular `dict` objects maintain insertion order. If your are using Python 2 or Python < 3.6, then use a `collections.OrderedDict` rather than a `dict`.
Dictionaries in Python are unordered. If you want to access by sorted keys you could do something like this: ``` d = {"a": 4, "c": 10, "b": 11, "d" : 6} for key in sorted(d.keys()): print(f'{key} {d[key]}') ``` EDIT: You can't edit the dictionary while you iterate over it. So store the values sorted in a new dictionary, and overwrite the existing. ``` tmp = {} for key in sorted(d.keys(), key=lambda x: int(x.replace(",",""))): tmp[key] = d[key] print(f'{key} {d[key]}') self.likeposts = tmp ```
19,562,695
``` private static final byte[] BitPMC1 = { 56, 48, 40, 32, 24, 16, 8, 0, 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 60, 52, 44, 36, 28, 20, 12, 4, 27, 19, 11, 3 }; byte[] outData= new byte[] { 0, 0, 0, 0, 0, 0, 0 }; for (int i = 0; i < 56; i++) { if ((inData[BitPMC1[i] >> 3] & (1 << (7 - (BitPMC1[i] & 0x07)))) != 0) { outData[i >> 3] |= (1 << (7 - (i & 0x07))); } } ``` --- ``` java outData[i >> 3] and c# different ```
2013/10/24
[ "https://Stackoverflow.com/questions/19562695", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915051/" ]
Your input values are all in the range 0..127 so there's no problem there. On the output, but *only* after all the calculations are done, you need to convert the `byte` values into `int` values, whilst also converting the twos-complement negative values to positive: ``` int unsigned_value = ((int)byte_value) & 0xff; ``` If you output each element of the array per the above, you *should* find that the values you get out match your C# code.
You don't describe what your code should do (e.g. giving some example numbers) thus I can only guess. Having unsigned data, it does not make sense to use an operation taking care of the sign bit (`>>`), probably the operation you need is a logical shift (`>>>`) More details here: [Difference between >>> and >>](https://stackoverflow.com/questions/2811319/difference-between-and)
57,333,896
I successfully installed Laravel and Laravel Nova in live server but when I tried to view Nova login page, I get index of/nova page and the page does not redirect any css. Below is the screenshot of the page rendering: [![Laravel Nova login page fails to render correctly in live server](https://i.stack.imgur.com/Dyd7B.jpg)](https://i.stack.imgur.com/Dyd7B.jpg) In the config/nova.php the path is correctly set to: ``` config/nova.php ``` I need help to get this page to display correctly.
2019/08/02
[ "https://Stackoverflow.com/questions/57333896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9205751/" ]
This is due to shallow comparison, in fact the solution is listed in the documentation here: <https://developer.microsoft.com/en-us/fabric#/controls/web/detailslist> From the docs: > > My List is not re-rendering when I mutate its items! What should I do? > ---------------------------------------------------------------------- > > > To determine if the List within DetailsList should re-render its > contents, the component performs a referential equality check within > its `shouldComponentUpdate` method. This is done to minimize the > performance overhead associating with re-rendering the virtualized > List pages, as recommended by the React documentation. > > > As a result of this implementation, the inner List will not determine > it should re-render if the array values are mutated. To avoid this > problem, we recommend re-creating the items array backing the > `DetailsList` by using a method such as `Array.prototype.concat` or > ES6 spread syntax shown below: > > > > ``` > public appendItems(): void { > const { items } = this.state; > > this.setState({ > items: [...items, ...['Foo', 'Bar']] > }) > } > > public render(): JSX.Element { > const { items } = this.state; > > return <DetailsList items={items} />; > } > > ``` > > By re-creating the items array without mutating the values, the inner > List will correctly determine its contents have changed and that it > should re-render the new values. > > >
There is no issue with `DetailsList`. The table should update properly, as you indicated that when you resize the page the items show up but before that it doesn't. It's definitely because the render function isn't being called again. Which means that when you do `this.setState` you are not updating the states of your present component. As Mirage, in the comments suggested try checking if you have the correct `this` and you are updating the correct component.
17,493,988
I have connected to an SQL Server database and can perform simple CRUD operations. Now I want to make my app show a second `Form` *(a reminder form)* when a person in my database has a birthday today, but nothing happens when I run my app. EDIT: My reminder form is now showing properly, but when I try to close that form I get this error message: > > Cannot access a disposed object. Object name: 'Form2'. > > > Here is my code: ``` public partial class Form1 : Form { Timer timer = new Timer(); Form2 forma = new Form2(); public Form1() { InitializeComponent(); var data = new BirthdayEntities(); dataGridView1.DataSource = data.Tab_Bday.ToList(); timer.Tick += new EventHandler(timer_Tick); timer.Interval = (1000) * (1); timer.Enabled = true; timer.Start(); } private void timer_Tick(object sender, EventArgs e) { Boolean flag = false; IQueryable<Tab_Bday> name; using (var data2 = new BirthdayEntities()) { name = (from x in data2.Tab_Bday select x); foreach (var x in name) { if (x.Datum.Day == System.DateTime.Now.Day && x.Datum.Month == System.DateTime.Now.Month) { flag = true; break; } } } if (flag == true) forma.Show(); } ```
2013/07/05
[ "https://Stackoverflow.com/questions/17493988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2554389/" ]
FYI: For Mac users: Following the link that @Bertrand Moreau shared, this worked on Mac OS X 10.7.5 and R 3.0.1: ``` cd /Users/xx/Downloads/rpy2-2.3.7 export LDFLAGS="-Wl,-rpath,/Library/Frameworks/R.framework/Resources/lib" sudo python3.3 setup.py build --r-home /Library/Frameworks/R.framework/Resources install sudo python3.3 setup.py install ``` I would have shared this as a comment to the above, but formatting was lost. SO newbie here!
A solution under `ubuntu 14.04` using `anaconda` and `python2.7` is the following: `conda install -c https://conda.anaconda.org/r rpy2` This works on the command line, and also from `pycharm` terminal for me. **However, still does not work under `pycharm`, and I get the same error as OP.** The fact that it does now work on `pycharm`, but works on the `pycharm` terminal is a bit weird.
10,031,756
I am using Axlsx to create an excel file. For a small dataset, it works fine. But once the dataset gets big, it just hangs. I ran strace on the process, it was doing a lot brk. ``` a = Axlsx::Package.new book = a.workbook book.add_worksheet(:name => "test") do |sheet| input_array.each do |input_data| ...# covert input_data to row_data sheet.add_row(row_data) end end File.open("testfile", 'w') { |f| f.write(p.to_stream().read) } ``` My input\_array size is about 400,000, so the worksheet has 400,000 rows, quite large. It got stuck at `p.to_stream().read`. Any help would be great. Thanks.
2012/04/05
[ "https://Stackoverflow.com/questions/10031756", "https://Stackoverflow.com", "https://Stackoverflow.com/users/612308/" ]
Looks like I need to start paying attention to SO! This is randym (the author of axlsx) There are a couple of things I'd like to point out that should help you get what you need done, well... done! 1. If you are writing to a file, consider Package#serialize - not because it is faster, but because it is less code for you to maintain. p.serialize 'filename.xlsx' 2. Major performance improvements have been made over the last few weeks. Please upgrade to 1.1.1 The gem no longer depends on RMagic, and use\_autowidth = false is no longer required. <https://github.com/randym/axlsx> Benchmarks for master: ``` Benchmarks w/40k rows: user system total real axlsx_noautowidth 68.130000 1.690000 69.820000 ( 80.257108) axlsx 61.520000 2.290000 63.810000 ( 78.187423) axlsx_shared 53.280000 1.170000 54.450000 ( 62.880780) axlsx_stream 52.110000 1.360000 53.470000 ( 61.980672) csv 10.670000 0.930000 11.600000 ( 14.901387) Benchmarks w/4k rows: user system total real axlsx_noautowidth 4.880000 0.120000 5.000000 ( 5.314383) axlsx 5.470000 0.110000 5.580000 ( 5.853739) axlsx_shared 5.720000 0.080000 5.800000 ( 6.135263) axlsx_stream 4.840000 0.090000 4.930000 ( 5.194801) csv 1.090000 0.090000 1.180000 ( 1.484763) ``` Here is the benchmarking file: <https://gist.github.com/2411144> Hope this helps
You can try to disable RMagick, which handles column autowidth feature, since it's quite heavy process AFAIK. ``` a = Axlsx::Package.new a.use_autowidth = false ```
28,995,757
I am getting the following exception when calling OData from my Kendo ListView: > > "A binary operator with incompatible types was detected. Found operand > types 'Edm.Guid' and 'Edm.String' for operator kind 'Equal'" > > > **DECODED FILTER:** $filter=OrganizationId eq '4c2c1c1e-1838-42ca-b730-399816de85f8' **ENCODED FILTER:** %24filter=OrganizationId+eq+%274c2c1c1e-1838-42ca-b730-399816de85f8%27 **HAVE ALSO UNSUCESSFULLY TRIED THESE FILTERS:** $filter=OrganizationId eq guid'4c2c1c1e-1838-42ca-b730-399816de85f8' $filter=OrganizationId eq cast('4c2c1c1e-1838-42ca-b730-399816de85f8', Edm.Guid) **MY WEB API CALL LOOKS LIKE:** ``` // GET: odata/Sites [HttpGet] [EnableQuery] public IHttpActionResult GetSites(ODataQueryOptions<Site> queryOptions) { IQueryable<Site> sites = null; try { queryOptions.Validate(_validationSettings); sites = _siteService.GetAll().OrderBy(x => x.SiteName); if (sites == null) return NotFound(); } catch (ODataException ex) { TraceHandler.TraceError(ex); return BadRequest(ex.Message); } return Ok(sites); } ``` **MY JAVASCRIPT KENDO DATASOURCE LOOKS LIKE:** ``` var dataSource = new kendo.data.DataSource({ filter: { field: "OrganizationId", operator: "eq", value: that.settings.current.customer.id }, schema: { data: function (data) { return data.value; }, total: function (data) { return data.length; } }, serverFiltering: true, serverPaging: true, transport: { parameterMap: function (options, type) { var paramMap = kendo.data.transports.odata.parameterMap(options); // Remove invalid Parameters that Web API doesn't support delete paramMap.$inlinecount; // <-- remove inlinecount delete paramMap.$format; // <-- remove format delete paramMap.$callback; // <-- remove callback // PLEASE NOTICE: That I have tried reformatting unsuccessfully //paramMap.$filter = paramMap.$filter.replace("OrganizationId eq ", "OrganizationId eq guid"); //paramMap.$filter = "OrganizationId eq cast('81de6144-987c-4b6f-a9bd-355cb6597fc1', Edm.Guid)"; return paramMap; }, read: { url: buildRoute('odata/Sites') , dataType: 'json' } }, type: 'odata' }); ```
2015/03/11
[ "https://Stackoverflow.com/questions/28995757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/312317/" ]
If the OData service is of protocol version V4, the correct query URL should be: ``` $filter=OrganizationId eq 4c2c1c1e-1838-42ca-b730-399816de85f8 ``` No single quotes is required.
I ran into this error querying OData 4.0 through Microsoft Dynamics. The other answers here didn't help unfortunately, even though they are exactly right. My issue was more with handing EntityReference's in filters. I ended up having to adjust my filter to something like this, to target the foreign key properly. In the example below 'parentaccountid' is the foreign key in the entity I was querying. 'accountid' is the primary key in the accounts entity. ``` /opportunities?$select=opportunityid&$filter=parentaccountid/accountid eq 5e669180-be01-e711-8118-e0071b6af2a1 ```
30,058,904
I'm not familiar with DataGridViews, but I need to work with one in this case. Basically, I have a method I want to call anytime the state of the DataGridView is changed in ANY way (cells added, removed, changed, etc). There seem to be many events, but I'm not sure which ones are relevant (I'm assuming I'll use more that one).
2015/05/05
[ "https://Stackoverflow.com/questions/30058904", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2957232/" ]
You can temporary disable it. ``` mPullToRefreshLayout.setEnabled(false); ```
Version 1.2.0-alpha01 now respects requestDisallowInterceptTouchEvent()
3,828,907
Is there any way to inline just some selective calls to a particular function not all of them? cause only form I know is declaring function as such at beginning and that's supposed to effect all calls to that function.
2010/09/30
[ "https://Stackoverflow.com/questions/3828907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/388056/" ]
please note that if you use the inline keyword, this is only a hint for the compiler. You cannot really control what the compiler inlines and what not. If your compiler would follow your hints you could do: ``` inline void doItInline() {...} void doItNonInline() {doItInline();} ``` Now you can call the method either inline'd or not.
You can try to force it the other way around. even though if you ask the compiler to inline, it can't do so if the definition is not available in the current compilation unit and has to create a call. if you make sure the definition IS available, the compiler MIGHT inline it.
20,931,859
What I'm trying to do is, load a Text file, then take the values from each line and assign them to a variable in my program. Every two lines, I will insert them into a `LinkedHashMap` (As a pair) The problem with a buffered reader is, all I can seem to do is, read one line at a time. Here is my current code: ``` public static void receiver(String firstArg) {// Receives // Input // File String cipherText; String key; String inFile = new File(firstArg).getAbsolutePath(); Path file = new File(inFile).toPath(); // File in = new File(inFile); try (InputStream in = Files.newInputStream(file); BufferedReader reader = new BufferedReader( new InputStreamReader(in))) { String line = null; while ((line = reader.readLine()) != null) { // System.out.println(line); String[] arrayLine = line.split("\n"); // here you are // splitting // with whitespace cipherText = arrayLine[0]; // key = arrayLine[1]; System.out.println(arrayLine[0] + " " + arrayLine[1]); cipherKeyPairs.put(arrayLine[0], arrayLine[1]); } } catch (IOException x) { System.err.println(x); } ``` The problem is, it can't find the `arrayLine[1]` (for obvious reasons). I need it to read two lines at a time without the array going out of bounds. Any idea how to do this, so that I can store them into my `LinkedHashMap`, two lines at a time as separate values.
2014/01/05
[ "https://Stackoverflow.com/questions/20931859", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1877059/" ]
You can overcome this issue by inserting in the List every 2 lines reading. A description for this code is that: "Bold is the true case" 1. Read the first line (count is 0) * **If (secondLine is false) ==> Save the line to CipherText variable, make secondLine = true** * Else If (secondLine is true) ==> Add to list (CipherText, line), make secondLine = false 2. Read the second line (count is 1) * If (secondLine is false) ==> Save the line to CipherText variable, make secondLine = true * **Else If (secondLine is true) ==> Add to list (CipherText, line), make secondLine = false** --- ``` String cipherText; boolean secondLine = false; String inFile = new File(firstArg).getAbsolutePath(); Path file = new File(inFile).toPath(); try { InputStream in = Files.newInputStream(file); BufferedReader reader = new BufferedReader(new InputStreamReader(in))) { String line = null; while ((line = reader.readLine()) != null) { if (!secondLine) //first line reading { cipherText = line; secondLine = true; } else if (secondLine) //second line reading { cipherKeyPairs.put(cipherText, line); secondLine = false; } } } catch (IOException x) { System.err.println(x); } ```
See if this works for you. I just edited your code. it might not be the best answer. ``` public static void receiver(String firstArg) {// Receives // Input // File String cipherText; String key; String inFile = new File(firstArg).getAbsolutePath(); Path file = new File(inFile).toPath(); // File in = new File(inFile); try (InputStream in = Files.newInputStream(file); BufferedReader reader = new BufferedReader( new InputStreamReader(in))) { String line = null; List<String> lines = new ArrayList(); while ((line = reader.readLine()) != null) { lines.add(line);//trim line first though and check for empty string } for(int i=1;i<lines.size();i++){ cipherText = arrayLine[i]; // key = arrayLine[1]; System.out.println(arrayLine[i] + " " + arrayLine[i-1]); cipherKeyPairs.put(arrayLine[i-1], arrayLine[i]); } } catch (IOException x) { System.err.println(x); } } ```
4,773,646
If in the process of moving my prodiuct categories out of the main table into seperate tables. At the moment its stored like this: ``` ProductId Product Name Cat1 Cat2 Cat3 ---------------------------------------------------------------------- 1 Something One Y N N 2 Another N Y N 3 Product Three Y N Y 4 Final One N N Y ``` My new tables look like this: ``` CatID CatName --------------------------- 1 Cat1 2 Cat2 3 Cat3 ID CatID ProductID ----------------------------------- 1 1 1 2 2 2 3 1 1 4 1 3 5 3 4 ``` My question is; is it possible to transfer this information from the main table to the new table using SQL? I have over 500 products and don't fancy doing it by hand.
2011/01/23
[ "https://Stackoverflow.com/questions/4773646", "https://Stackoverflow.com", "https://Stackoverflow.com/users/263960/" ]
Sure, assuming your tables are Category, Product and CategoryXProduct (with ID definned as identity): ``` INSERT CategoryXProduct ( CatID, ProductID ) SELECT 1, ProductId FROM Product WHERE Cat1 = 'Y' INSERT CategoryXProduct ( CatID, ProductID ) SELECT 2, ProductId FROM Product WHERE Cat2 = 'Y' INSERT CategoryXProduct ( CatID, ProductID ) SELECT 3, ProductId FROM Product WHERE Cat3 = 'Y' ```
Yes, it is possible. there is sth like INSERT from SELECT: ``` INSERT into table1(id, name, fname) SELECT id, lname, fname FROM authors WHERE somecondiction ```
33,589,211
So I made this java file A.java, ``` package alphabet; public class A{ private String private_A; String _A; protected String protected_A; public String public_A; public A(){ private_A="Private A"; _A="Package Private A"; protected_A="Protected A"; public_A="Public A"; } public static void main(String[] args) { } } ``` and another class in the same package, ``` package alphabet; import alphabet.A; public class B{ void methodB1(){ } public static void main(String[] args) { A AinB = new A(); } } ``` When I compile `B` I can't instantiate `A`. Why is that? `A` is a public class, and `B` belongs to the same package? Shouldn't `B` be able to make an instance of `A`? This pretty noobish, but thanks. **EDIT:** Got these errors, ``` *@*:~/rand$ javac B.java B.java:3: error: cannot find symbol import alphabet.A; ^ symbol: class A location: package alphabet B.java:9: error: cannot find symbol A AinB = new A(); ^ symbol: class A location: class B B.java:9: error: cannot find symbol A AinB = new A(); ^ symbol: class A location: class B 3 errors ``` **EDIT**: Removed the import statement still getting these errors ``` B.java:9: error: cannot find symbol A AinB = new A(); ^ symbol: class A location: class B B.java:9: error: cannot find symbol A AinB = new A(); ^ symbol: class A location: class B 2 errors ```
2015/11/07
[ "https://Stackoverflow.com/questions/33589211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4539308/" ]
Problem is you are compiling it wrong. Since you are using package, while compiling you need to be outside the package. So instead of `javac B.java` Make a folder/directory named same as package name i.e. `alphabet` and move the java files to it. Use `javac alphabet/B.java`
Remove the import statement in class B. You don't need to import from the same package.
7,524,715
The same code ran in TURBO C. ``` struct details { char name[20]; int year; float price; }my_str; details book1[10]; ``` This error is produced. How can this be fixed? ``` ram.c: In function ‘main’: ram.c:11:1: error: ‘details’ undeclared (first use in this function) ram.c:11:1: note: each undeclared identifier is reported only once for each function it appears in ```
2011/09/23
[ "https://Stackoverflow.com/questions/7524715", "https://Stackoverflow.com", "https://Stackoverflow.com/users/940510/" ]
There are two ways to fix this: Change second line to this: ``` struct details book1[10]; ``` Or you can change the declaration to: ``` typedef struct{ char name[20]; int year; float price; } details; ``` C is slightly different from C++, so you can't declare structs quite the same way.
This is a a bit more correct in terms of C: ``` typedef struct _detailstype { char name[20]; int year; float price; } details; details book1[10]; ```
21,627,629
I am new to servlet and making my first servlet using eclipse.I have made Index.html, Login.java and WelcomeServlet.java. But whenever I am trying to access the using ``` localhost:8080/ServletExample/ ``` It shows 404 error.Here are the codes.. **Index.html** ``` <form action="Login" method="post"> Name:<input type="text" name="userName"/><br/> Password:<input type="password" name="userPass"/><br/> <input type="submit" value="login"/> </form> ``` **Login.java** ``` public class Login extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); String p=request.getParameter("userPass"); if(p.equals("servlet")) { RequestDispatcher rd=request.getRequestDispatcher("WelcomeServlet"); rd.forward(request, response); } else { out.print("Sorry UserName or Password Error!"); RequestDispatcher rd=request.getRequestDispatcher("/index.html"); rd.include(request, response); } } } ``` **WelcomeServlet.java** ``` package java.io; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class WelcomeServlet extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String n=request.getParameter("userName"); out.print("Welcome "+n); } } ``` **web.xml** ``` <?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>Login</servlet-name> <servlet-class>Login</servlet-class> </servlet> <servlet> <servlet-name>WelcomeServlet</servlet-name> <servlet-class>WelcomeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Login</servlet-name> <url-pattern>/Login</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>WelcomeServlet</servlet-name> <url-pattern>/WelcomeServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.html</welcome-file> </welcome-file-list> </web-app> ```
2014/02/07
[ "https://Stackoverflow.com/questions/21627629", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1707351/" ]
package java.io; why u put this line in WelcomeServlet.java.
Make sure ur projrct name is ServletExample. localhost:8080/ServletExample/index.html
669,298
I had Linux Ubuntu and Windows dual booting from my computer. I used partition manager to remove the Linux Ubuntu partitions, now I can't get into Windows. The machine loads in to a command prompt ( GRUB ) I think I may need to remove GRUB from the MBR and install windows Boot loader using the windows repair option Could you please tell me how to do it ? Furthermore, I have Windows7 Ultimate installed in the machine. Ihave lost the CD and now I have Windows7 Home Premium.
2013/11/04
[ "https://superuser.com/questions/669298", "https://superuser.com", "https://superuser.com/users/65953/" ]
While @sgtbeano already answers the question, I'd like to provide some information on why this happens. When you have a dual-boot for linux & windows, then it's linux bootloader, that's loaded when you start the computer. Now when you un-install linux, that bootloader is gone and hence, you need to rebuilt/re-instantiate the windows bootloader. But now, another question can be `Can I ignore doing it and instead use windows 7 bootloader in the dual-boot` The answer is simply NO, you can't use windows bootloader because it doesn't recognize the linux system/os. It's also the major reason why we install linux after windows so that linux's bootloader can take-over and we can have a dual-boot with windows & linux.
sgtbeano's solution is likely to work; however, I want to provide another couple of options, which work only on EFI-based computers. (The vast majority of machines that shipped with Windows 8 or later are EFI-based.) These solutions are: * **Re-order the boot list** -- EFI-based computers store a list of boot entries in NVRAM, along with an order in which these entries are tried. You can change this boot order using tools like `efibootmgr` in Linux or [EasyUEFI](http://www.easyuefi.com/index-us.html) in Windows. If you delete the Linux entry (`ubuntu` for Ubuntu) or re-order the list so that Windows comes before Ubuntu, the system will begin booting normally. Part of the trick to this approach is likely to be to boot to an environment that permits making this change. The easiest solution is likely to be to do a one-time boot to Windows, which you can usually accomplish by hitting a special key at boot time to access a boot menu that will enable booting Windows. The trouble is that the key to do this varies from one computer to another. It's *usually* a high-numbered function key (F8 or above), but it can be Enter, Esc, or something else. Typing `exit` at the `grub>` prompt may also cause Windows to boot. Also, some EFI setup utilities enable changing the boot order, so entering the setup tool may enable you to re-order the boot list. * **Delete the Linux boot loader** -- On an EFI-based computer, boot loaders reside on the [EFI System Partition (ESP),](http://en.wikipedia.org/wiki/EFI_System_partition) which is a FAT partition with a particular type code. You can boot an emergency system (like an Ubuntu installation disc in its "try before installing" mode), mount the ESP, and delete the `EFI/{distname}` directory, where `{distname}` is a name associated with the distribution -- for instance, Ananth would delete `EFI/ubuntu`, since the distribution is Ubuntu. Once this directory is gone, GRUB will be gone, so the computer *should* skip over the GRUB entry (which is no longer valid) and boot Windows. These solutions don't really have equivalents on BIOS-based computers, but they're perfectly valid approaches on EFI-based computers that boot in EFI mode. (Most EFI-based computers *can* boot in BIOS mode, and if that's how your system is configured to boot, these options won't work on it.)
57,155,636
I need to generate random division problems for an educational game that I am building. Generating random addition, subtraction, and multiplication problems is not too difficult. But I want my division problems to not have any remainders. With addition, subtraction and multiplication, I could just do [random number] times or plus or subtract [random number]. It is not so easy if I want to do division problems. Can anyone help? Thanks in advance
2019/07/23
[ "https://Stackoverflow.com/questions/57155636", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11003015/" ]
x/y = z y\*z = x Generate y and z as integers, then calculate x.
You can simply generate the divisor and quotient randomly and then compute the dividend. Note that the divisor must be nonzero (thanks to @o11c's remind).
1,208,338
In my ongoing effort to quench my undying thirst for more programming knowledge I have come up with the idea of attempting to write a (at least for now) simple programming language that compiles into bytecode. The problem is I don't know the first thing about language design. Does anyone have any advice on a methodology to build a parser and what the basic features every language should have? What reading would you recommend for language design? How high level should I be shooting for? Is it unrealistic to hope to be able to include a feature to allow one to inline bytecode in a way similar to gcc allowing inline assembler? Seeing I primarily code in C and Java which would be better for compiler writing?
2009/07/30
[ "https://Stackoverflow.com/questions/1208338", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33911/" ]
There are so many ways... You could look into stack languages and Forth. It's not very useful when it comes to designing other languages, but it's something that can be done very quickly. You could look into functional languages. Most of them are based on a few simple concepts, and have simple parsing. And, yet, they are very powerful. And, then, the traditional languages. They are the hardest. You'll need to learn about lexical analysers, parsers, LALR grammars, LL grammars, EBNF and regular languages just to get past the parsing. Targeting a bytecode is not just a good idea – doing otherwise is just insane, and mostly useless, in a learning exercise. Do yourself a favour, and look up books and tutorials about compilers. Either C or Java will do. Java probably has an advantage, as object orientation is a good match for this type of task. My personal recommendation is Scala. It's a good language to do this type of thing, and it will teach you interesting things about language design along the way.
I recommend reading the following books: [ANTLR](http://www.pragprog.com/titles/tpantlr/the-definitive-antlr-reference) [Language Design Patterns](http://www.pragprog.com/titles/tpdsl/language-design-patterns) This will give you tools and techniques for creating parsers, lexers, and compilers for custom languages.
16,658,040
I got this HTML tags that I've pulled from a website: ``` <ul><li>Some Keys in the UL List</li> </ul> <li>HKEY_LOCAL_MACHINE\SOFTWARE\Description</li> <li>HKEY_LOCAL_MACHINE\SOFTWARE\Description\Microsoft</li> <li>HKEY_LOCAL_MACHINE\SOFTWARE\Description\Microsoft\Rpc</li> <li>HKEY_LOCAL_MACHINE\SOFTWARE\Description\Microsoft\Rpc\UuidTemporaryData</li> </ul></ul> <ul><li>Some objects in the UL LIST</li> </ul> <li>_SHuassist.mtx</li> <li>MuteX.mtx</li> <li>Something.mtx</li> <li>Default.mtx</li> <li>3$5.mtx</li> </ul></ul> ``` How can I get the lines(text beteween `<li>` tags) between the `<ul>` tags. They don't have any class to diff then. I don't know too much about BeautifulSoup and Regex. I want this result as example: ``` <li>_SHuassist.mtx</li> <li>MuteX.mtx</li> <li>Something.mtx</li> <li>Default.mtx</li> <li>3$5.mtx</li> ```
2013/05/20
[ "https://Stackoverflow.com/questions/16658040", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2403166/" ]
With `BeautifulSoup`: ``` >>> html = textabove >>> from bs4 import BeautifulSoup as BS >>> soup = BS(html) >>> for ultag in soup.findAll('ul'): ... for litag in ultag.findAll('li'): ... print litag.text ``` Which prints: ``` Some Keys in the UL List Some objects in the UL LIST ``` --- To get the latter `<li>` tags: ``` >>> for litag in soup.findAll('li'): ... if litag.text.endswith('.mtx'): ... print litag ... <li>_SHuassist.mtx</li> <li>MuteX.mtx</li> <li>Something.mtx</li> <li>Default.mtx</li> <li>3$5.mtx</li> ```
you do not need regular expressions to do that take a look at python's [HTMLParser](http://docs.python.org/2/library/htmlparser.html)
2,670,012
I've ported the non-blocking queue psuedocode [here](http://www.cs.rochester.edu/research/synchronization/pseudocode/queues.html#nbq) to C#. The code below is meant as a near verbatim copy of the paper. What approach would you take to test the implementation? Note: I'm running in VS2010 so I don't have CHESS support yet. Edit: I've removed the code in question so some unsuspecting developer doesn't use it -- it required quite a few changes to get it bug free... and I still wasn't 100% confident that it was bug free. With brute force testing I could not get it to perform better than a lock based solution. Also, since I'm targeting 3.5 I thought I was SOL with the 4.0 concurrent queue. The 3.5 RX framework includes a ConcurrentQueue so this was indeed just a fun little programming exercise and nothing more.
2010/04/19
[ "https://Stackoverflow.com/questions/2670012", "https://Stackoverflow.com", "https://Stackoverflow.com/users/55952/" ]
Since `.apk` is a `.jar` file by another name (in other words it is a zip file with some specific definitions of where configuration files are stored inside the directory) then look at [ZipInputStream](http://java.sun.com/j2se/1.5.0/docs/api/java/util/zip/ZipInputStream.html) to read the file and walk through the contents and write them out as files.
Thank you very much Yishai... this was the Hint I was waiting for :) Probably is sb out there, who needs the to do a same thing, therefore... here is my code: ``` public static boolean copyApkFile(File outputFile){ try { FileInputStream fis = new FileInputStream(this.getClass().getResource("/resources/myApkFile.apk").getFile()); ZipInputStream zis = new ZipInputStream(fis); FileOutputStream fos = new FileOutputStream(outputFile)); ZipOutputStream zos = new ZipOutputStream(fos); ZipEntry ze = null; byte[] buf = new byte[1024]; while ((ze = zis.getNextEntry()) != null) { System.out.println("Next entry "+ze.getName()+" "+ze.getSize()); zos.putNextEntry(ze); int len; while ((len = zis.read(buf)) > 0) { zos.write(buf, 0, len); } } zos.close(); fos.close(); zis.close(); fis.close(); return true; } catch (IOException ex) { Logger.getLogger(SetUpNewDevice.class.getName()).log(Level.SEVERE, null, ex); return false; } } ```
9,932,678
Given the following array `a`: ``` a = [1, 2, 3, 4, 5] ``` How do I do: ``` a.map { |num| num + 1 } ``` using the short notation: ``` a.map(&:+ 1) ``` or: ``` a.map(&:+ 2) ``` where 1 and 2 are the arguments?
2012/03/29
[ "https://Stackoverflow.com/questions/9932678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1301770/" ]
You can't do it like this. The `&` operator is for turning symbols into procs. ``` a = [1, 2, 3, 4, 5] puts a.map(&:to_s) # prints array of strings puts a.map(&:to_s2) # error, no such method `to_s2`. ``` `&` is a shorthand for [`to_proc`](http://ruby-doc.org/core-2.0/Symbol.html#method-i-to_proc): ``` def to_proc proc { |obj, *args| obj.send(self, *args) } end ``` It creates and returns new proc. As you see, you can't pass any parameters to this method. You can only call the generated proc.
If you really need that you can use [Ampex](https://github.com/rapportive-oss/ampex) library, but I don't know if it is still maintained.
60,516,539
I am new to the MS Azure. I am trying to download Microsoft Academic Graph for various analysis, and they don't offer bulk-downloading the structured dataset. External sources such as openacademicgraph weren't really useful, so I thought I could try downloading the data through Azure. Luckily, there were manuals for just that - "Get Microsoft Academic Graph on Azure storage - learn.microsoft.com/en-us/academic-services/graph/get-started-setup-provisioning". I followed the steps in the manual to create a Azure account for MAG, getting a following email from Academic Knowledge API - --- *Welcome to the Microsoft Academic Graph (MAG) Azure Storage (AS) Distribution preview. Please be advised that this distribution is in free preview stage. Pricing structure is subject to change.* *Your Azure Storage is successfully setup to receive MAG update through Azure Data Factory. Each MAG dataset is provisioned to a separate container named "mag-yyyy-mm-dd". The 2020-02-14 dataset was pushed to your Azure Storage.* *As MAG comes with ODC-BY license, you are granted the rights to add values and redistribute the derivatives based on the terms of the open data license, e.g., the attribution to MAG in your products, services or community events.* *Each snapshot of MAG will show up in your Azure Storage as a distinct container. In Microsoft Academic Graph documentation, you could find a sample to extract knowledge from MAG for your application using Azure Databricks. Also there is a sample using U-SQL, a member of Azure Data Lake Analytic Framework.* *We also put together great Analytics and visualization samples that we used for our WWW Conference Analytics blog post. We hope this can help accelerate your development process and spark imagination!* --- Next step was "Set up Azure Databricks for Microsoft Academic Graph - learn.microsoft.com/en-us/academic-services/graph/get-started-setup-databricks", which I followed. I was able to create an Azure Databricks for MAG (I have no idea what they are as I'm new to this), but now I cannot get it to run. Following is the error message I get: --- *Message* *Cluster terminated. Reason: Cloud Provider Launch Failure* *A cloud provider error was encountered while launching worker nodes. See the Databricks guide for more information.* *Azure error code: OperationNotAllowed* *Azure error message: Operation could not be completed as it results in exceeding approved Total Regional Cores quota. Additional details - Deployment Model: Resource Manager, Location: centralus, Current Limit: 4, Current Usage: 4, Additional Required: 4, (Minimum) New Limit Required: 8. Submit a request for Quota increase at <https://aka.ms/ProdportalCRP/?#create/Microsoft.Support/Parameters/~~~> by specifying parameters listed in the ‘Details’ section for deployment to succeed. Please read more about quota limits at <https://learn.microsoft.com/en-us/azure/azure-supportability/regional-quota-requests>.* --- I'm not sure what I'm supposed to do. "Total Regional Cores quota" is exceeded, not my personal subscription etc. How would I ask to increase the quota for the whole region? They say I need to apply for a larger quota, which cannot be done with the free trial account I created as per the manual. Does this mean that the manual is wrong, and I have to become Pay-As-You-Go? "Current Usage: 4" but I am not using anything at the moment. All I have is an Azure storage and a Databrick cluster which aren't running. I re-tried starting the cluster, and the second time it was successfully started, only to deactivated a couple of minutes later with the same error message. I'm not going to do any complex querying and stuff - it's going to be pretty expensive. Being the poor research and such, all I am looking to get is the dataset following the MAG schema; I will run whatever analysis on them on my desktop which would be free, while slower. Any help would be really appreciated.
2020/03/03
[ "https://Stackoverflow.com/questions/60516539", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10649974/" ]
You can try most of the examples with databricks community edition : <https://community.cloud.databricks.com/login.html>
Using free Azure subscription and trial tier for databricks I got the same error while doing this module <https://learn.microsoft.com/en-us/learn/modules/describe-azure-databricks/> When creating the cluster I modified the cluster mode from 'standard' to 'none', problem solved; I could run the python notebook.
15,269,051
I'm reading that I should use worker object and move it to thread by moveToThread instead of inherit from QThread directly. But I can't find solution how to stop loop in my object worker. For example I have test loop: ``` void CollectionWorker::doWork() { for (int i = 0; i < 10; ++i) { sleep(1); emit ping(i); } } ``` Now I'm moving this object to thread: ``` worker->moveToThread(mTh); ``` This is working fine. But when I call mTh.quit() then thread is waiting until loop in doWork is end. When I inherit from QThread directly then on each loop I can check thread status and break loop when thred is finished but don't know how to do it in worker object. Can I just create some flag in worker object and switch it from main thread? Or maybe can I find thread owner and check it status? Or maybe better before starting thread, set thread pointer in worker object and then check status? What is the best thread safe solution? Regards
2013/03/07
[ "https://Stackoverflow.com/questions/15269051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/764914/" ]
I have the same problem as Dibo had. I'm running a long calculation loop inside my `doWork()` function and need to be able to stop it from my main thread. Chadick Robbert's answers didn't do the trick for me. The first suggestion behaved just like what he describes for member functions. That is, although we're using signals and slots, calling `setTerminationFlag` slot from a signal emitted in the main thread, properly connected to it, only gets executed after the loop ends. But maybe I did something wrong with the implementation. If it really is supposed to work please let me know, because it seems like the deal breaker. His second alternative of using `QThread::currentThread()->isInterruptionRequested()` to tell the thread to stop would work great if it weren't for the fact that you can't reset this flag if you plan on reusing the thread and worker for some similar processing intensive loop, if not the same. Surely you can get it done by stopping and starting the thread, but I'm not sure if it wouldn't have adverse effects like clearing execution queues on it. This issue was actually posted as a [bug report](https://bugreports.qt.io/browse/QTBUG-40400) and Thiago Macieira (key developer for Qt) mentions there, if I may quote him: > > The purpose of the requestInterruption function is to finish the thread. > > > Which makes `requestInterruption` inadequate for the job, as it is reset only on thread start and finish. A solution that I found, that doesn't seem all that clean to me, is to include `QCoreApplication` in the worker class and call `QCoreApplicaton::processEvents()` from time to time, to process those queued signals in Chadick Robbert's first suggestion or update the worker's class awareness of flag variables shared between threads. Because calling `QCoreApplicaton::processEvents()` within your loop can slow it dramatically what I do is something like: ``` for(unsigned long int i=0; i<800000000 && !*stop; i++){ f += (double)i * .001; // dummy calculation if(i%10000000 == 0) // Call it only from time to time QCoreApplication::processEvents(); // update *stop according to main Thread } ``` As you can see, with this solution the loop will only break at integer multiples of '10000000' which may not be adequate for some use cases. If anyone knows of a killer solution to this I'd love to hear.
The idiomatic way in Qt to destroy a worker thread is using the signal/slot interface: ``` CollectionWorker *worker = new CollectionWorker; QThread *workerThread = new QThread(this); connect(workerThread, SIGNAL(started()), worker, SLOT(doWork())); connect(workerThread, SIGNAL(finished()), worker, SLOT(deleteLater())); worker->moveToThread(workerThread); ``` In order for this to work CollectionWorker must inherit from a QObject class and declare the Q\_OBJECT macro.
42,371,783
I know this is a duplicate question and I've tried every possible solution but not succeeded. I am using a panel in which my excel data is showing and I wanna fix the column in other words header. Every css I've tried break the panel settings and I didn't succeed. I'm using bootstrap css & have more than 1000 rows that's why I need a fixed header. This is my HTML ``` <div class="panel panel-primary"> <div class="panel-heading">Excel Sheet</div> <div class="panel-body"> <?php echo '<table class="table table-striped table-hover table-condensed">'; echo "<thead class='thead'>"; echo "<tr class='info'>"; for ($column = 'A'; $column < $lastcol; $column++) { echo "<th>"; echo $worksheet->getCell($column . '1')->getFormattedValue(); echo "</th>"; } echo "</tr>"; echo '</thead>'; echo '<tbody>'; for ($row = 2; $row <= $lastrow; $row++) { echo "<tr>"; for ($column = 'A'; $column < $lastcol; $column++) { echo "<td>"; echo $worksheet->getCell($column . $row)->getFormattedValue(); echo "</td>"; } echo "</tr>"; } echo '</tbody>'; echo "</table>"; ?> </div> </div> ``` Here is column and row 1 are for loop, which will give the header. I have used integrated php-html. Other rows will appear in row for loop. this is my css and commented code is last code i have tried. ``` .panel-heading{ font-size: 15px; } .panel-body{ overflow:auto; height:400px; } tr{ border: 1px solid black; } th{ border: 1px solid black; } td{ border: 1px solid black; } ``` example fiddle is [Here](https://jsfiddle.net/adeel1992/286zcrhs/1/) P.S : Please dont forget to place a comment in case of negative vote for helping me . Cheers !
2017/02/21
[ "https://Stackoverflow.com/questions/42371783", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7013297/" ]
If you want to associate multiple values with a key, you could just make the value part of the pair a list: ``` var dict = new Dictionary<char, List<int>>(); char key = 'D'; int value = 5; if (!dict.ContainsKey(key)) dict[key] = new List<int>(); dict[key].Add(value); ```
Like Adam Houldsworth said you can use `Lookup`. Here is a snippet based on Adam Houldsworth's answer. ``` var str = @"A=1|B=2|C=3|D=4|D=5|D=5"; string[] t = str.Split(new[] { '|', '|' }, StringSplitOptions.RemoveEmptyEntries); var message = t.ToLookup(s => s.Split('=')[0], s => Convert.ToInt32(s.Split('=')[1])); var res = message.ToDictionary(i=>i.Key, x=>x.LastOrDefault()); ``` Edit: After reading your question again I understand you want the D=4 value also. ``` var res = message.SelectMany(i => i.Select((x, y) => new { Key = i.Key, Value = x })).GroupBy(q=>q.Value) .SelectMany(x=>x.ToLookup(xx=>xx.Key, xx=>xx.Value)); ```
47,987,068
I am very new to Swift. I am creating a register page and applying validation to it. I want to validate the email and password. I am using outlet collection and I also want to know how to get a value from outlet collection. Here is the code. ``` if senderTag == 0 // Name { } else if senderTag == 1 // Email { func validateEmail(candidate: String) -> Bool { let emailRegex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,6}" return NSPredicate(format: "SELF MATCHES %@", emailRegex).evaluate(with: candidate) } if validateEmail(candidate:How to use this?) } else if senderTag == 2 { func isPasswordValid(_ password : String) -> Bool{ let passwordTest = NSPredicate(format: "SELF MATCHES %@", "^(?=.*[A-Z].*[A-Z])(?=.*[!@#$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{8}$") return passwordTest.evaluate(with: password) } } else if senderTag == 3 { func isPasswordValid(_ password : String) -> Bool{ let passwordTest = NSPredicate(format: "SELF MATCHES %@", "^(?=.*[A-Z].*[A-Z])(?=.*[!@#$&*])(?=.*[0-9].*[0-9])(?=.*[a-z].*[a-z].*[a-z]).{8}$") return passwordTest.evaluate(with: password) } } ``` I want to know what is wrong in here in email validation and how can I use password validation? Thanks in advance
2017/12/27
[ "https://Stackoverflow.com/questions/47987068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9117534/" ]
``` Actually the issue was, in the String resource if we write `<b>` its will be converted to string itself. And when Html.fromHtml() tries to convert they found no tags, So, For < we have to use &lt; For > we have to use &gt; For & we have to use &amp; ``` Retrieve the text as spanned text and pass it to drawtext(). It worked !! Anyway thanks for the efforts.
You can do this by setting pint style to BOLD for specific characters and also the start and end index of the string i.e. to be bold should be known you can do this as- Suppose the string is ``` <string name="bold_text">This is the Bold text</string> ``` Following is the to be done in view class ``` //create two paints one is regular and another is bold private Paint mPaintText; private Paint mPaintTextBold; private String textToDraw; // initialize them mPaintText = new Paint(); mPaintText.setColor(Color.WHITE); mPaintText.setStyle(Style.FILL); mPaintText.setTextSize(32f); mPaintTextBold= new Paint(); mPaintTextBold.setColor(Color.WHITE); mPaintTextBold.setStyle(Style.FILL); mPaintTextBold.setTextSize(32f); mPaintTextBold.setTypeface(Typeface.DEFAULT_BOLD); textToDraw = getString(R.string.bold_text); // Now in on draw method of view draw the following text if you are drawing // text on canvas it means you already have start point let it be be // startX and startY, index of the bold string be boldStart and boldEnd in // our case it will be 12 and 16 String normalStartString = mTextToDraw.substring(0, boldStart); String normalEndString = mTextToDraw.substring(boldEnd); String boldString = mTextToDraw.substring(boldStart, boldEnd); Paint.FontMetrics fm = mPaintText.getFontMetrics(); float height = -1 * (fm.ascent + fm.descent); // drawing start string canvas.drawText(normalStartString, startX, startY - height, mPaintText); // drawing bold string float width = mPaintText.measureText(normalStartString) + startX; canvas.drawText(boldString, width, startY - height, mPaintTextBold); // drawing end string width += mPaintTextBold.measureText(boldString); canvas.drawText(normalEndString, width, startY - height, mPaintText); ```
150,414
Using alphabetical ordering for authors' names is a long established tradition in mathematics. In the situations of extremely unequal contributions, is it reasonable to break from this tradition? Has there been any examples? If it is common, what is the threshold for breaking from alphabetical ordering?
2020/06/12
[ "https://academia.stackexchange.com/questions/150414", "https://academia.stackexchange.com", "https://academia.stackexchange.com/users/-1/" ]
*Edit: this answer is about pure math.* It’s not common. In 25 years of reading math papers I‘ve only ever seen one example of a paper that had a nonalphabetical author ordering. It was an English translation of a Russian paper from the 1970s written by a PhD student and his advisor. I don’t know what the story was behind this unconventional author order, but all I know is that the advisor’s name appears first even though alphabetically he comes second. > > In the situations of extremely unequal contributions, is it reasonable to break from this tradition? > > > No. Since you’re going against the overwhelming norm in math publishing, no one will have a clear sense of what exactly you’re trying to say. Also, consider the fact that it could be that the author order that reflects the actual author contributions might coincide with the alphabetical order (for example in the paper I mentioned, it was competely random that the PhD advisor came second alphabetically and could easily have been the other way around). In that case the signal will be lost entirely. My conclusion is that the idea of forcing this signaling mechanism on a math publication culture that isn’t adapted to it is illogical, ineffective, and will lead to inconsistent results that are only very weakly correlated with the effect you’re trying to achieve. If I were a journal editor and I received a submission that tries to use this mechanism, I would tell the authors to find a different way to say what they want to say about the author contributions.
In the answers and comments, it's suggested that it's extremely rare in pure math, and there are only one or two such papers. I'd suggest that while it is rare, it's not as rare as Dan Romik's answer and a couple of comment's suggest. I myself have noticed a number of papers where the author list is non-alphabetical (and in fact I'm a co-author on one). My impression is that the two most common reasons for these situations are: * there was some confusion about the alphabetical ordering, typically with non-English names (maybe unRomantic names is better?) as in paul garrett's comment and as seems to be the case in Dan Romik's example * the contributions to the paper were highly unbalanced among co-authors (e.g., the RSA paper---at least from A's perspective) That said, just by seeing such a situation, it's probably not clear why the author order is non-alphabetical, and people will wonder why when they notice it. So unless some of the authors feel strongly about it, I wouldn't recommend doing this as a matter of course, and especially not unless all authors agree. Here are some alternative suggestions for how to handle a situation like this: 1. Break the project up into two (or more) different papers, using different subsets of authors to better represent author contributions. 2. Instead of making separate papers, have 1 paper but with appendices with different sets of authors. 3. Include a comment in the introduction about each author's contributions. 4. Be generous (or thankful, depending on which party you are), and don't worry about it. (This is the probably the most common solution to this rather frequent situation, and unless the paper is really groundbreaking, sharing credit shouldn't be too much of a burden.)
12,992
We know four trainers started in Pallet town. Three with one of the three original starters and Ash with his Pikachu. Apart from Gary, were the other two trainers ever revealed in the anime? And was it ever revealed who got which specific starter Pokemon?
2014/07/22
[ "https://anime.stackexchange.com/questions/12992", "https://anime.stackexchange.com", "https://anime.stackexchange.com/users/6166/" ]
### The Four Trainers of Pallet Town Theory *Pokémon: Indigo League*, episode 10 "Bulbasaur And The Hidden Village": Bulbasaur protects a "spa resort for pokémon" village in which the only human there, a girl by the name of Melanie, takes care of them. By theory, we conclude that Melanie does not want to be a trainer but more of a caretaker for pokémon and may have "abandoned" or set free Bulbasaur to choose his own path. But there is speculation that she might be too old to have recently left Pallet town considering she is as tall as Brock. He falls for her and is older than Ash and Misty. *Pokémon: Indigo League*, episode 11 "The Stray": Charmander is left on a rock and his trainer said he'd be back for him. His original owner's name is Damian. Oddly enough he brags about how many pokémon he has on a table in pokéballs - over the 6 pokéball legal limit. By theory, he is one of the new pokémon trainers from Pallet town and chose the Charmander as his first. Starter pokémon are associated with "beginner" which in turn translates to some as "weak". A pokémon you catch and earned is less likely to be discarded because of work you put into it unlike the freely given pokémon at the start. This may be what Damian was thinking of Charmander at the time. *Pokémon: Johto League*, episode 269 (or S3E152) "The Ties That Bind": Professor Oak bragged to Ash that Gary had chosen the best starter pokémon in the first episode without revealing which one this might have been. Gary Oak reveals his third pokémon in a match against Ash to be the evolved form of his starter pokémon, Blastoise (originally Squirtle). Gary Oak was the only other trainer apart from Ash from Pallet town that was carried on through the anime series to be his rival. The other two were simply written off by Professor Oak (ep64) who stated that the other two flunked out of Pokémon Training. --- Sources: [Bulbapedia](http://bulbapedia.bulbagarden.net) * [Ep.10: Bulbasaur](http://bulbapedia.bulbagarden.net/wiki/EP010) * [Ep.11:Charmander](http://bulbapedia.bulbagarden.net/wiki/EP011) * [Ep.269: Squirtle/Blastoise](http://bulbapedia.bulbagarden.net/wiki/EP269) * [Melanie](http://bulbapedia.bulbagarden.net/wiki/Melanie) * [Damian](http://bulbapedia.bulbagarden.net/wiki/Damian) * [Gary Oak](http://bulbapedia.bulbagarden.net/wiki/Gary_Oak) * [Ep.1: Prof. Oak bragging](http://bulbapedia.bulbagarden.net/wiki/EP001) * [Ep.63: Earth Badge](http://bulbapedia.bulbagarden.net/wiki/EP063) * [Ep.64: consulting Prof. Oak](http://bulbapedia.bulbagarden.net/wiki/EP064)
I think Damian, the original owner of Ash's Charmander (now Charizard), was one of the Pokemon trainers from Pallet Town. Firstly, because he wasn't seen at the Pokemon League. Secondly, wild Charmanders weren't seen in the anime much or maybe at all. So it's reasonable to say that he got it as his starter. I don't know about Bulbasaur, though. It probably belonged to a girl who quit in episode 30 something, because she wanted her Pokemon to just be her companions.
9,380
For the moment we protect a directory on our site with .htaccess and .htpasswd. But I was wondering how secure this is? Are there things I should watch for or can do make it more secure? I don't know why but it don't feel really confident about it. I have the feeling this kind of security is easy to crack. From what I have read there are ways to just download the .htpasswd file and decrypt the passwords.
2011/12/02
[ "https://security.stackexchange.com/questions/9380", "https://security.stackexchange.com", "https://security.stackexchange.com/users/6144/" ]
If all the access is via SSL, then it's reasonably secure. Basic authentication without SSL only sends the username/password as base64 encoded - so it's trivial to extract the tokens via MITM or sniffing. Digest authentication without SSL is a lot better (a challenge based mechanism) but still not as secure as an encrypted connection. However there are few cues to the user that the authentication is being implemented as Digest rather than Basic. Also proxy authentication challenges look very similar. The built-in authentication mechanisms don't provide for a good user experience. If this is for a site with a small, defined user group, then using the built-in methods are a quick solution (but you might consider client-side certificate auth instead). But for a public facing website you should think about implementing somethnig a bit more sophisticated. You should configure your webserver appropriately to prevent direct access to the htaccess file and password database. Either by putting the config outside of the document root (obviously this isn't going to work for htaccess files - but they are just a local extension to the webserver config) or by blocking access to the files. Every Apache distribution I've ever come across blocks access to files with names starting '.ht' While you can prevent direct access to the password db, there's not a great deal of scope for limiting brute force attacks on the server over HTTP - another reason for considering a forms based approach.
I would check out this resource to make sure that htaccess is properly protected: <http://www.symantec.com/connect/articles/hardening-htaccess-part-one> And I would check out a WAF or mod\_security if you want greater operational control: <http://www.askapache.com/htaccess/modsecurity-htaccess-tricks.html>
69,147,230
[updated error image](https://i.stack.imgur.com/Jix0u.png) For some reason I can't call my commands. RuntimeError: Event loop is closed. I need help to fix it, I'm new in python programming. I want to learn how to create bots for discord on python, so I'm asking for help ! ``` import discord from discord.ext import commands TOKEN = "TOKEN-HERE" client = commands.Bot(command_prefix = '!') @client.command() async def embed(ctx): em = discord.Embed(title="Title",description ="This is a description",color=0x20B2AA) em.set_footer(text='This is a footer.') em.set_image(url='') em.set_thumbnail(url='https://cdn.discordapp.com/attachments/823480191493210113/886011319688527892/Screenshot_808.png') em.set_author(name='Author Name', icon_url='https://cdn.discordapp.com/attachments/823480191493210113/886011319688527892/Screenshot_808.png') em.add_field(name='Field Name', value='Field Value', inline=False) em.add_field(name='Field Name', value='Field Value', inline=True) em.add_field(name='Field Name', value='Field Value', inline=True) await ctx.send(embed=em) @client.command() async def asnwer(ctx): await ctx.send("Hi !") client.run(TOKEN) ``` Exception ignored in: <function \_ProactorBasePipeTransport.**del** at 0x0000020AAF885040> Traceback (most recent call last): File "C:\Users\wital\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor\_events.py", line 116, in **del** self.close() File "C:\Users\wital\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor\_events.py", line 108, in close self.\_loop.call\_soon(self.\_call\_connection\_lost, None) File "C:\Users\wital\AppData\Local\Programs\Python\Python39\lib\asyncio\base\_events.py", line 746, in call\_soon self.\_check\_closed() File "C:\Users\wital\AppData\Local\Programs\Python\Python39\lib\asyncio\base\_events.py", line 510, in \_check\_closed raise RuntimeError('Event loop is closed') RuntimeError: Event loop is closed Exception ignored in: <function \_ProactorBasePipeTransport.**del** at 0x0000020AAF885040> Traceback (most recent call last): File "C:\Users\wital\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor\_events.py", line 116, in **del** File "C:\Users\wital\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor\_events.py", line 108, in close File "C:\Users\wital\AppData\Local\Programs\Python\Python39\lib\asyncio\base\_events.py", line 746, in call\_soon File "C:\Users\wital\AppData\Local\Programs\Python\Python39\lib\asyncio\base\_events.py", line 510, in \_check\_closed RuntimeError: Event loop is closed
2021/09/11
[ "https://Stackoverflow.com/questions/69147230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16780766/" ]
You didn't enable `Intents`. Remember to do it both in code and on your bot's dashboard on the Discord developers site if you need privileged intents enabled. This includes things like wanting access to the members in a Guild, etc. ```py intents = discord.Intents.default() client = commands.Bot(command_prefix="!", intents=intents) ``` More info here: <https://discordpy.readthedocs.io/en/stable/intents.html> Also you just leaked your bot token, generate a new one.
Are you sure, that your bot is running? I'm getting this error everytime I stop my bot.
666,872
I'm working in Photoshop CS6 and multiple browsers a lot. I'm not using them all at once, so sometimes some applications are minimized to taskbar for hours or days. The problem is, when I try to maximize them from the taskbar - it sometimes takes longer than starting them! Especially Photoshop feels really weird for many seconds after finally showing up, it's slow, unresponsive and even sometimes totally freezes for minute or two. It's not a hardware problem as it's been like that since always on all on my PCs. Would I also notice it after upgrading my HDD to SDD and adding RAM (my main PC holds 4 GB currently)? Could guys with powerful pcs / macs tell me - does it also happen to you? I guess OSes somehow "focus" on active software and move all the resources away from the ones that run, but are not used. Is it possible to somehow set RAM / CPU / HDD priorities or something, for let's say, Photoshop, so it won't slow down after long period of inactivity?
2013/10/29
[ "https://superuser.com/questions/666872", "https://superuser.com", "https://superuser.com/users/267835/" ]
### Summary The immediate problem is that the programs that you have minimized are being paged out to the "page file" on your hard disk. This symptom can be improved by installing a Solid State Disk (SSD), adding more RAM to your system, reducing the number of programs you have open, or upgrading to a newer system architecture (for instance, Ivy Bridge or Haswell). Out of these options, adding more RAM is generally the most effective solution. ### Explanation The default behavior of Windows is to give active applications priority over inactive applications for having a spot in RAM. When there's significant memory pressure (meaning the system doesn't have a lot of free RAM if it were to let every program have all the RAM it wants), it starts putting minimized programs into the page file, which means it writes out their contents from RAM to disk, and then makes that area of RAM free. That free RAM helps programs you're actively using -- say, your web browser -- run faster, because if they need to claim a new segment of RAM (like when you open a new tab), they can do so. This "free" RAM is also used as *page cache*, which means that when active programs attempt to read data on your hard disk, that data might be cached in RAM, which prevents your hard disk from being accessed to get that data. By using the majority of your RAM for page cache, and swapping out unused programs to disk, Windows is trying to improve responsiveness of the program(s) you are actively using, by making RAM available to them, and caching the files they access in RAM instead of the hard disk. The downside of this behavior is that minimized programs can take a while to have their contents copied from the page file, on disk, back into RAM. The time increases the larger the program's footprint in memory. This is why you experience that delay when maximizing Photoshop. RAM is *many* times faster than a hard disk (depending on the specific hardware, it can be up to several orders of magnitude). An SSD is considerably faster than a hard disk, but it is still slower than RAM by orders of magnitude. Having your page file on an SSD will *help*, but it will also wear out the SSD more quickly than usual if your page file is heavily utilized due to RAM pressure. ### Remedies Here is an explanation of the available remedies, and their general effectiveness: * **Installing more RAM**: This is the recommended path. If your system does not support more RAM than you already have installed, you will need to upgrade more of your system: possibly your motherboard, CPU, chassis, power supply, etc. depending on how old it is. If it's a laptop, chances are you'll have to buy an entire new laptop that supports more installed RAM. When you install more RAM, you reduce *memory pressure*, which reduces use of the page file, which is a good thing all around. You also make available more RAM for page cache, which will make all programs that access the hard disk run faster. As of Q4 2013, my personal recommendation is that you have at least 8 GB of RAM for a desktop or laptop whose purpose is anything more complex than web browsing and email. That means photo editing, video editing/viewing, playing computer games, audio editing or recording, programming / development, etc. all should have at least 8 GB of RAM, if not more. * **Run fewer programs at a time**: This will only work if the programs you are running do not use a lot of memory on their own. Unfortunately, Adobe Creative Suite products such as Photoshop CS6 are known for using an enormous amount of memory. This also limits your multitasking ability. It's a temporary, free remedy, but it can be an inconvenience to close down your web browser or Word every time you start Photoshop, for instance. This also wouldn't stop Photoshop from being swapped when minimizing it, so it really isn't a very effective solution. It only helps in some specific situations. * **Install an SSD**: If your page file is on an SSD, the SSD's improved speed compared to a hard disk will result in generally improved performance when the page file has to be read from or written to. Be aware that SSDs are not designed to withstand a very frequent and constant random stream of writes; they can only be written over a limited number of times before they start to break down. Heavy use of a page file is not a particularly good workload for an SSD. You should install an SSD *in combination with* a large amount of RAM if you want maximum performance while preserving the longevity of the SSD. * **Use a newer system architecture**: Depending on the age of your system, you may be using an out of date system architecture. The "system architecture" is generally defined as the "generation" (think generations like children, parents, grandparents, etc.) of the motherboard and CPU. Newer generations generally support faster I/O (input/output), better memory bandwidth, lower latency, and less contention over shared resources, instead providing dedicated links between components. For example, starting with the "Nehalem" generation (around 2009), the Front-Side Bus (FSB) was eliminated, which removed a common bottleneck, because almost all system components had to share the same FSB for transmitting data. This was replaced with a "point to point" architecture, meaning that each component gets its own dedicated "lane" to the CPU, which continues to be improved every few years with new generations. You will generally see a more significant improvement in overall system performance depending on the "gap" between your computer's architecture and the latest one available. For example, a Pentium 4 architecture from 2004 is going to see a much more significant improvement upgrading to "Haswell" (the latest as of Q4 2013) than a "Sandy Bridge" architecture from ~2010. ### Links Related questions: [How to reduce disk thrashing (paging)?](https://superuser.com/questions/32860/how-to-reduce-disk-thrashing-paging) [Windows Swap (Page File): Enable or Disable?](https://superuser.com/questions/14795/windows-swap-page-file-enable-or-disable) Also, just in case you're considering it, you really shouldn't disable the page file, as this will only make matters worse; see here: <http://lifehacker.com/5426041/understanding-the-windows-pagefile-and-why-you-shouldnt-disable-it>
> > when I try to maximize them from the taskbar - it sometimes takes longer than starting them > > > That's because *both* when you start it and when you maximize it from them taskbar you are reading the application from *disk* (as explained by all the others), but an application which ran for a while (opening files and doing stuff) might have taken more RAM space than a newly started one, and all that memory was swapped out to disk to make space for active applications (again, as explained by the others) so now that you are maximizing it, *more* data has to be read from disk than for a fresh start.
3,173
As my company begins its first agile project, I'm wondering if it would be easier to have separate tasks for QA and development for each story/requirement. Is it a cleaner process or will the lack of insight into development tasks be hazardous for QA since their tasks will be separate. Any feedback would be greatly appreciated.
2012/05/24
[ "https://sqa.stackexchange.com/questions/3173", "https://sqa.stackexchange.com", "https://sqa.stackexchange.com/users/2520/" ]
My company has been using Agile for a while so I can provide some answers. First of all we do only black-box testing, we don't have the access to the code. Therefore each story has some technical sub-tasks defined and these tasks are handled only by developers. We don't test them. As for the rest - we share all the tasks/stories (whatever you call it). There are reasons for that. One is that you mentioned - the lack of insight, lack of the "big picture" may become a problem. There is a difference between testing and quality assurance. You need the big picture, you need to monitor everything that's happening in a project, so you can see the risks early. I don't only report bugs to developers. My duty is also to report about the possible risks to project manager. While developers often work on just a part of the application, someone is needed to look at it as a whole. That's why I think separating tasks is simply not a good idea. Another thing is that working on common tasks seems just easier and simpler to me. You asked if separating tasks is "cleaner" process. Well, I don't think so, I'd say just opposite. It would be much easier for everyone to define states (like implemented/tested/resolved etc.) for every task and implement a proper workflow. Last thing - common tasks = better planning. If you are implementing the Agile you must have heard about colored cards on the wall (if not - google for 'color cards agile'). This is great idea - it lets me see what is currently being developed (or waiting in development queue). Thanks to that I can better plan my work (for instance - I can see that even if I don't have too much to do at the moment, things might get hectic soon (because there are lots of tasks being implemented so they will be assigned to me next day)). I hope this helps. Good luck with transition to Agile. It may be difficult in the beginning but eventually things will get smooth. :)
On a true agile project the line between development and testing can become very, very blurry. A team that is properly implementing behavior driven development (BDD) will be automating acceptance tests as part of each feature. There are pros and cons with this approach as each feature is not done until the automation is written, however the tests are typically at a lower level than a tester would right. The other thing is that typically, they are not actually testing, they are checking instead. For actual testing you need someone with a testers mindset to research and apply sapience and utilize heuristics to find bugs in a typically exploratory manner.
74,519,777
Given a file tree with much dept like this: ``` ├── movepy.py # the file I want use to move all other files └── testfodlerComp ├── asdas │   └── erwer.txt ├── asdasdas │   └── sdffg.txt └── asdasdasdasd ├── hoihoi.txt ├── hoihej.txt └── asd ├── dfsdf.txt └── dsfsdfsd.txt ``` **How can I then move all items recursively into the current working directory:** ``` ├── movepy.py │── erwer.txt │── sdffg.txt ├── hoihoi.txt ├── hoihej.txt ├── dfsdf.txt └── dsfsdfsd.txt ``` *The file tree in this question is an example, in reality I want to move a tree that has many nested sub folders with many nested files.*
2022/11/21
[ "https://Stackoverflow.com/questions/74519777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5558126/" ]
Adding to xlab's solutions, you could also disable STRICT\_TRANS\_TABLES. This is particularly useful when you already have the code written and you can "allow" not to use strict inputs (if you understand the implications). Check the accepted solution here: [How to turn on/off MySQL strict mode in localhost (xampp)?](https://stackoverflow.com/questions/40881773/how-to-turn-on-off-mysql-strict-mode-in-localhost-xampp)
Actually I made a typo: False: ``` public function store(Request $request) { $storeData = $request->validate([ 'name' => 'required|max:255', 'name' => 'required|max:255', 'email' => 'required|max:255', 'phone' => 'required|numeric', 'password' => 'required|max:255', ]); ``` True: ``` public function store(Request $request) { $storeData = $request->validate([ 'name' => 'required|max:255', '**nickname**' => 'required|max:255', 'email' => 'required|max:255', 'phone' => 'required|numeric', 'password' => 'required|max:255', ]); ```
501,845
1. I like to create a color change in vertical direction of the "*pump Symbol*" in the following example from black to blue to black again. 2. The symbol itself should NOT be filled with color. ONLY the drawing lines. My mini Example doesn't work. Any ideas? Mini Example or MWE =================== ``` \documentclass[tikz,border=10pt]{standalone} \usetikzlibrary{fadings} \tikzfading[name=fade gradient, top color=black!80, bottom color=black!80, middle color=blue!100] %% Pumpe Symbol \tikzset{ pump/.style={ circle, draw, thick, minimum size=0.5cm, path picture={ \draw [thick] (path picture bounding box.north) -- (path picture bounding box.east) -- (path picture bounding box.south); }, node contents={} } } %%% \begin{document} \begin{tikzpicture} \node at (0,0)[ pump, path fading=fade gradient, align = left ]; \end{tikzpicture} \end{document} ```
2019/07/28
[ "https://tex.stackexchange.com/questions/501845", "https://tex.stackexchange.com", "https://tex.stackexchange.com/users/193587/" ]
IMHO you need neither the `shadings` nor the `fadings` library here. ``` \documentclass[tikz,border=10pt]{standalone} \usetikzlibrary{calc} %% Pumpe Symbol \tikzset{ pump/.style={ circle, thick, minimum size=0.5cm, path picture={ \path[top color=black!80, bottom color=black!80, middle color=blue!100,even odd rule] ([xshift={-0.5pt}]path picture bounding box.north) -- (path picture bounding box.east) -- ([xshift={-0.5pt}]path picture bounding box.south) -- cycle ([xshift=0.5pt,yshift={-(1+sqrt(2))*1pt}]path picture bounding box.north) -- ([xshift={-sqrt(2)*1pt}]path picture bounding box.east) -- ([xshift=0.5pt,yshift={(1+sqrt(2))*1pt}]path picture bounding box.south)-- cycle; \path[top color=black!80, bottom color=black!80, middle color=blue!100,even odd rule] let \p1=($(path picture bounding box.north)-(path picture bounding box.center)$) in (path picture bounding box.center) circle[radius=\y1] (path picture bounding box.center) circle[radius=\y1-1pt]; }, node contents={} } } %%% \begin{document} \begin{tikzpicture} \node at (0,0)[ pump, align = left ]; \end{tikzpicture} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/uv94l.png)](https://i.stack.imgur.com/uv94l.png)
Using `shadings` library instead of `fadings`, following code might be used. ``` \documentclass[tikz,border=10pt]{standalone} \usetikzlibrary{shadings} \pgfdeclareverticalshading{rainbow}{100bp} {color(0bp)=(black); color(40bp)=(black); color(50bp)=(blue); color(60bp)=(black); color(100bp)=(black)} %\tikzfading[name=fade gradient, top color=black!80, bottom color=black!80, %middle color=blue!100] %% Pumpe Symbol \tikzset{ pump/.style={ circle, draw, thick, minimum size=0.5cm, path picture={ \draw [shading=rainbow,thick] (path picture bounding box.north) -- (path picture bounding box.east) -- (path picture bounding box.south); }, node contents={} } } %%% \begin{document} \begin{tikzpicture} \node at (0,0)[ pump, %path fading=fade gradient, align = left ]; \end{tikzpicture} \end{document} ``` [![enter image description here](https://i.stack.imgur.com/IId33.png)](https://i.stack.imgur.com/IId33.png)
64,843,459
SOLVED/NOTE: I have accepted the answer of adding the "accept=" option to the HTML code as a solution to the problem. It should be noted that although this does work as as a work around, the root cause is likely a Safari bug - it should NOT be a requirement to add this to your HTML to make this functionality work. ORIGINAL PROBLEM DESCRIPTION & INFO: My mac received an update this morning, now running macOS Mojave 10.14.6 (18G6042). It looks like Safari must have received an update as part of this, although Apple didn't give the update specifics, just the usual "You need to Restart" with no extra info, followed by 20 mins of waiting. Safari is now Version 14.0.1 (14610.2.11.51.10). Since the update, I find that I can no longer submit files through HTML forms in Safari. The "Choose File" button is displayed, but clicking it results in nothing. I'll post my code below, but I also verified this using the w3schools example at <https://www.w3schools.com/tags/att_input_type_file.asp> (it won't work in Safari now either), and my code works fine in Chrome & Firefox on the same laptop. Does anyone have any info on this? Are extra directives required for this to work in Safari now? Is it blocked due to some security issue? Is this just a bug? Here's my test code in case it is relevant, although it's more or less the same as the w3schools example, with some added PHP to display the file info. ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional/EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="UTF-8"> <meta http-equiv="Content-type" content="text/html; charset=UTF-8"> <title>Upload File Test</title> </head> <body> <br/> <?php if (isset($_POST["UploadFile"])) { if ($_FILES["myfile"]["error"] > 0) { echo "No file was selected.<br/>\n"; } else { echo "Upload: " . $_FILES["myfile"]["name"] . "<br/>\n"; echo "Type: " . $_FILES["myfile"]["type"] . "<br/>\n"; echo "Size: " . ($_FILES["myfile"]["size"] / 1024) . " kB<br/>\n"; echo "Stored in: " . $_FILES["myfile"]["tmp_name"] . "<br/>\n"; } } ?> <FORM NAME="file_upload" METHOD="POST" ACTION="file-test.php" enctype="multipart/form-data" accept-charset="UTF-8"> <label for="file">Upload File:</label> <input type="file" name="myfile" id="myfile" /> <INPUT type="Submit" name="UploadFile" value="Upload" /> </FORM> <br/> </body> </html> ``` MORE INFO: So the problem continues, and sometimes the dialog opens now, but sometimes it doesn't. Previously, the dialog would always open in the last directory you loaded or saved files from, I just saved a bunch of pages as PDF (via Print) for some work, and now when I go to Choose File again, it shows the dialog below (unfortunately the screenshot doesn't capture the full path, but you get the idea). So it looks like this is an issue within Safari, but I'm still not sure exactly what or how to rectify it. Plus, while the dialog opens on my local test page, it's not opening for web based pages (my sites, w3schools, etc). [![Default Choose File Directory](https://i.stack.imgur.com/DXFRm.png)](https://i.stack.imgur.com/DXFRm.png) MORE INFO: Safari just defaulted again to the "inaccessible" directory it keeps defaulting to sometimes, here's a screen shot, in case the additional info helps anyone further (probably just the guys at Apple in fixing the bug I'm guessing)... Normally you can't browse to this folder from Safari, which I'm guessing is part of this bug - Safari is trying to default to this directory for file upload, when it can't jump to the last previously used directory for whatever reason. [![enter image description here](https://i.stack.imgur.com/vHIsR.png)](https://i.stack.imgur.com/vHIsR.png)
2020/11/15
[ "https://Stackoverflow.com/questions/64843459", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4241666/" ]
I have run into the same issue yesterday. Having looking into it I have found it working elsewhere and fixed it on the site I'm working on by adding an *accept* attribute with a file types list to the *input* tag. (e.g. `<input type="file" accept=".xls,.xlsx,.xlsb,.txt,.csv,.tsv"/>`) Works fine now in Safari version 14.0.1 (14610.2.11.51.10) on Mojave 10.14.6
Giving Safari Full Disk Access will NOT fix the problem. I have a [test page with different attributes](https://dusty-manager.surge.sh) Click file input 1, 3, 4 is fine. Once clicked file input 2 with accept="image/\*;capture=camera" it will kill all file upload on the page. But not any other page in the same domain. [See a clone of the page here](https://dusty-manager.surge.sh/2.html) need to quit safari in order to be able to select any file again with file input 1,3,4.
227,130
Ok, so I have tried this quite a few times and I'm sure this is very trivial but: I am trying to SSH via command line on Ubuntu into my VM (Centos6) with an RSA key-pair I created using key-gen. I have created the key-pair and appended the public key to authorized\_keys file and changed the permissions to `600`. After I SCP'ed the private key to Ubuntu and tried to SSH using it and I always get: ``` Permission denied (publickey,gssapi-keyex,gssapi-with-mic). ``` I have tried this 3x already and no luck. I can ping it but I can't seem to figure out why it's not taking the key I made. Any suggestions?
2015/09/02
[ "https://unix.stackexchange.com/questions/227130", "https://unix.stackexchange.com", "https://unix.stackexchange.com/users/72902/" ]
First generate the key-pair on your Ubuntu machine. After, copy the contents of the generated `.pub` file in your ssh folder (`~/.ssh/id_rsa`) and paste it to the `username/.ssh/id_rsaauthorized_keys` file, on a new line, on your CentOS for the specific user you are logging in with.
If you `tailf /var/log/auth.log` on the server and login again, you should see the reason for the failure get logged. If not, kick up the verbosity in the SSH daemon config file to DEBUG and retry again. Often times it's related to file permissions.
49,834,251
I have a styled component that is extending a third-party component: ``` import Resizable from 're-resizable'; ... const ResizableSC = styled(Resizable)``; export const StyledPaneContainer = ResizableSC.extend` flex: 0 0 ${(props) => props.someProp}px; `; const PaneContainer = ({ children, someProp }) => ( <StyledPaneContainer someProp={someProp} > {children} </StyledPaneContainer> ); export default PaneContainer; ``` This resulted in the following error in the browser console: > > Warning: React does not recognize the `someProp` prop on a DOM > element. If you intentionally want it to appear in the DOM as a custom > attribute, spell it as lowercase `someProp` instead. If you > accidentally passed it from a parent component, remove it from the DOM > element > > > So, I changed the prop to have a `data-*` attribute name: ``` import Resizable from 're-resizable'; ... const ResizableSC = styled(Resizable)``; export const StyledPaneContainer = ResizableSC.extend` flex: 0 0 ${(props) => props['data-s']}px; `; const PaneContainer = ({ children, someProp }) => ( <StyledPaneContainer data-s={someProp} > {children} </StyledPaneContainer> ); export default PaneContainer; ``` This works, but I was wondering if there was a native way to use props in the styled component without them being passed down to the DOM element (?)
2018/04/14
[ "https://Stackoverflow.com/questions/49834251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3111255/" ]
2020 UPDATE: Use transient props -------------------------------- With the [release 5.1.0](https://styled-components.com/releases#v5.1.0) you can use [transient props](https://styled-components.com/docs/api#transient-props). This way you do not need an extra wrapper i.e. unnecessary code is reduced: > > Transient props are a new pattern to pass props that are explicitly consumed only by styled components and are not meant to be passed down to deeper component layers. Here's how you use them: > > > ``` const Comp = styled.div` color: ${props => props.$fg || 'black'}; `; render(<Comp $fg="red">I'm red!</Comp>); ``` > > Note the dollar sign ($) prefix on the prop; this marks it as transient and styled-components knows not to add it to the rendered DOM element or pass it further down the component hierarchy. > > > The new answer should be: ------------------------- styled component: ``` const ResizableSC = styled(Resizable)``; export const StyledPaneContainer = ResizableSC.extend` flex: 0 0 ${(props) => props.$someProp}px; `; ``` parent component: ``` const PaneContainer = ({ children, someProp }) => ( <StyledPaneContainer $someProp={someProp} // '$' signals the transient prop > {children} </StyledPaneContainer> ); ```
You can try with **defaultProps**: ``` import Resizable from 're-resizable'; import PropTypes from 'prop-types'; ... const ResizableSC = styled(Resizable)``; export const StyledPaneContainer = ResizableSC.extend` flex: 0 0 ${(props) => props.someProp}px; `; StyledPaneContainer.defaultProps = { someProp: 1 } const PaneContainer = ({ children }) => ( <StyledPaneContainer> {children} </StyledPaneContainer> ); export default PaneContainer; ``` We can also pass props using '**attrs**'. This helps in attaching additional props (Example taken from styled components official doc): ``` const Input = styled.input.attrs({ // we can define static props type: 'password', // or we can define dynamic ones margin: props => props.size || '1em', padding: props => props.size || '1em' })` color: palevioletred; font-size: 1em; border: 2px solid palevioletred; border-radius: 3px; /* here we use the dynamically computed props */ margin: ${props => props.margin}; padding: ${props => props.padding}; `; render( <div> <Input placeholder="A small text input" size="1em" /> <br /> <Input placeholder="A bigger text input" size="2em" /> </div> ); ```
10,739,867
``` select * from StudySQL.dbo.id_name n inner join StudySQL.dbo.id_sex s on n.id=s.id and s.sex='f' select * from StudySQL.dbo.id_name n inner join StudySQL.dbo.id_sex s on n.id=s.id where s.sex='f' ``` The result are identical. So any difference between them? Add --- I made several more interesting tries. ``` select * from StudySQL.dbo.id_name n 1 | baby 3 | alice select * from StudySQL.dbo.id_class c 1 | math 3 | physics 3 | english 4 | chinese select * from StudySQL.dbo.id_name n left join StudySQL.dbo.id_class c on n.name='alice' name id id class baby 1 NULL NULL alice 3 1 math alice 3 3 physics alice 3 3 english alice 3 4 chinese select * from StudySQL.dbo.id_name n left join StudySQL.dbo.id_class c on n.name='baby' name id id class baby 1 1 math baby 1 3 physics baby 1 3 english baby 1 4 chinese alice 3 NULL NULL select * from StudySQL.dbo.id_name n left join StudySQL.dbo.id_class c on n.name<>'' name id id class baby 1 1 math baby 1 3 physics baby 1 3 english baby 1 4 chinese alice 3 1 math alice 3 3 physics alice 3 3 english alice 3 4 chinese ``` So I thinnk it's reasonable to say, the on clause decides **which rows should be joined**. While the where clause decides **which rows should be returned**. If this is true, **I think it's better to write detailed restrictions in the on clause so that fewer rows needs to be joined.** Becuase the join is an expensive operation.
2012/05/24
[ "https://Stackoverflow.com/questions/10739867", "https://Stackoverflow.com", "https://Stackoverflow.com/users/264052/" ]
There's no difference while this is an `INNER JOIN` but the results would be very different if you used an `OUTER JOIN`. Used with an `LEFT OUTER JOIN` the second query would implicitly become an `INNER JOIN`. By using `AND` the predicate is identifying when a row from s should be joined to n. In an inner join, a negative result here would prevent both the n and s sides to be omitted.
Some interesting discussion of this topic is found here: [INNER JOIN ON vs WHERE clause](https://stackoverflow.com/questions/1018822/inner-join-on-vs-where-clause) They should always return the same results, but may result in slightly different query plans and performance due to when the filtered rows are being removed. This behaviour will depend on exactly what server you are using.
18,965,503
I need some help. I write little app using ASP.NET MVC4 with JavaScript and Knockout and I can't send data from javascript to MVC Controller and conversely. For example, the part of JS looks like that: JavaScript ---------- ```js self.Employer = ko.observable(); self.AboutEmployer = function (id) { $.ajax({ Url.Action("GetEmployer", "Home") cache: false, type: 'GET', data: "{id:" + id + "}", contentType: 'application/json; charset=utf-8', dataType: "json", success: function (data) { self.Employer(data); } }).fail( function () { alert("Fail"); }); }; ``` In ASP.NET MVC Home Controller I'm getting employer by ID and return it as Json: C# -- ```cs public JsonResult GetEmployer(int id) { var employer = unit.Repository<Employer>().GetByID(id); return Json(employer, JsonRequestBehavior.AllowGet); } ``` My View return another Controller (Home/KnockOutView). My View also gets another objects and depending what recieve, has different look: HTML ---- ```html ... <b>About Company: </b><a href="#" data-bind="click: $root.AboutEmployer.bind($data, Vacancy().EmployerID)"> <span data-bind=" text: Vacancy().Employer"></span></a> <div data-bind="if: Vacancy"> <div id="VacancyDescription"><span data-bind="text:DescriptionShort"></span> </div> </div> <div data-bind="if: Employer"> <div data-bind="text: Employer().EmployerDescription"></div> </div> ``` Everything works great, I receive Vacancy and Employer objects in JS and show it in HTML using Knockout, but my URL all time still the same!!! **But I want to change URL all time, when i'm getting Vacancy or Employer.** For example, if I want to get Employer, using method GetEmployer, URL should looks like that: ~/Home/GetEmployer?id=3 If I change this string of Code `Url.Action("GetEmployer", "Home")` at `url: window.location.href = "/home/GetEmployer?id=" + id` URL will be changed, but Controller returns me an Json object and shows it in window in Json format. Help me, please, to change URL and get information in Controller from URL. Thanks.
2013/09/23
[ "https://Stackoverflow.com/questions/18965503", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2702323/" ]
Try below code, hope helps you This code works %100 , please change below textbox according to your scenario HTML ``` <input type="text" id="UserName" name="UserName" /> <input type="button" onclick="MyFunction()"value="Send" /> <div id="UpdateDiv"></div> ``` Javascript: ``` function MyFunction() { var data= { UserName: $('#UserName').val(), }; $.ajax({ url: "/Home/GetEmployer", type: "POST", dataType: "json", data: JSON.stringify(data), success: function (mydata) { $("#UpdateDiv").html(mydata); history.pushState('', 'New URL: '+href, href); // This Code lets you to change url howyouwant }); return false; } } ``` Controller: ``` public JsonResult GetEmployer(string UserName) { var employer = unit.Repository<Employer>().GetByID(id); return Json(employer, JsonRequestBehavior.AllowGet); } ```
Here is my controller action. ``` [HttpPost] public ActionResult ActionName(string x, string y) { //do whatever //return sth :) } ``` and my post action is here. ``` <script type="text/javascript"> function BayiyeCariEkle(){ var sth= $(#itemID).text(); var sth2= $(#itemID2).text(); $.post("/ControllerName/ActionName", { x: sth, y: sth2}); } </script> ```
41,487,473
I got this Python Code, and somehow I get the Error Message: > > > ``` > File "/app/identidock.py", line 13, in mainpage > if request.method == 'POST': > NameError: name 'request' is not defined > > ``` > > But I really can't find my mistake. Can someone please help me with that? ``` from flask import Flask, Response import requests import hashlib app = Flask(__name__) salt = "UNIQUE_SALT" default_name = 'test' @app.route('/', methods=['GET', 'POST']) def mainpage(): name = default_name if request.method == 'POST': name = request.form['name'] salted_name = salt + name name_hash = hashlib.sha256(salted_name.encode()).hexdigest() header = '<html><head><title>Identidock</title></head><body>' body = '''<form method="POST"> Hallo <input type="text" name="name" value="{0}"> <input type="submit" value="Abschicken"> </form> <p> Du siehst aus wie ein: </p> <img src="/monster/{1}"/> '''.format(name, name_hash) footer = '</body></html>' return header + body + footer @app.route('/monster/<name>') def get_identicon(name): r = requests.get('http://dnmonster:8080/monster/' \ + name + '?size=80') image = r.content return Response(image, mimetype='image/png') if __name__ == '__main__': app.run(debug=True, host='0.0.0.0') ```
2017/01/05
[ "https://Stackoverflow.com/questions/41487473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6817996/" ]
You appear to have forgotten to import the `flask.request` [*request context*](http://flask.pocoo.org/docs/0.12/reqcontext/) object: ``` from flask import request ```
This is because you missed the import statement ``` from flask import request ```
30,483,121
This little section is still a problem. ``` if (card.suit == Suit.DIAMOND || card.suit == Suit.HEART) { g.setColor(Color.red); } else { g.setColor(Color.black); } ``` The error I am getting is "**cannot find symbol**" and the symbol is "**Suit**". And when I change it to. ``` if (card.suit == PlayingCard.DIAMOND || card.suit == PlayingCard.HEART) { g.setColor(Color.red); } else { g.setColor(Color.black); } ``` I still get the error "**cannot find symbol**" and the symbols are the "**.DIAMOND**" and "**.HEART**" My **PlayingCard** Class ``` public class PlayingCard { // Instance Data - all things common to all cards private String cardFace; // king, q, j, 10 - 2, A private int faceValue; // numberic value of the card private char cardSuit; // hold suit of the card private char suits[] = {(char)(003), (char)(004), (char)(005), (char)(006)}; Suit suit; Rank rank; // Constructor public PlayingCard(int value, int suit) { faceValue = value; setFace(); setSuit(suit); } // helper setFace() public void setFace() { switch(faceValue) { case 1: cardFace = "A"; faceValue = 14; break; case 11: cardFace = "J"; break; case 12: cardFace = "Q"; break; case 0: cardFace = "K"; faceValue = 13; break; default: cardFace = ("" + faceValue); } } public void setSuit(int suit) // suit num between 0 and 3 { cardSuit = suits[suit]; } // other helpers public int getFaceValue() { return faceValue; } public String getCardFace() { return cardFace; } public String toString() { return (cardFace + cardSuit); } public static enum Suit { CLUB, DIAMOND, SPADE, HEART } public static enum Rank { TWO("2"), THREE("3"), FOUR("4"), FIVE("5"), SIX("6"), SEVEN("7"), EIGHT("8"), NINE("9"), TEN("10"), JACK("J"), QUEEN("Q"), KING("K"), ACE("A"); private final String symbol; Rank(String symbol) { this.symbol = symbol; } public String getSymbol() { return symbol; } } } ``` This is also the full class where I indicated there was a problem in. Which is my **GUI** class. ``` public class BlackjackGUI extends Applet { public void init() { // The init() method lays out the applet using a BorderLayout. // A BlackjackCanvas occupies the CENTER position of the layout. // On the bottom is a panel that holds three buttons. The // HighLowCanvas object listens for ActionEvents from the buttons // and does all the real work of the program. setBackground( new Color(130,50,40) ); setLayout( new BorderLayout(3,3) ); BlackjackCanvas board = new BlackjackCanvas(); add(board, BorderLayout.CENTER); Panel buttonPanel = new Panel(); buttonPanel.setBackground( new Color(220,200,180) ); add(buttonPanel, BorderLayout.SOUTH); Button hit = new Button( "Hit!" ); hit.addActionListener(board); hit.setBackground(Color.lightGray); buttonPanel.add(hit); Button stay = new Button( "Stay!" ); stay.addActionListener(board); stay.setBackground(Color.lightGray); buttonPanel.add(stay); Button newGame = new Button( "New Game" ); newGame.addActionListener(board); newGame.setBackground(Color.lightGray); buttonPanel.add(newGame); } // end init() public Insets getInsets() { // Specify how much space to leave between the edges of // the applet and the components it contains. The background // color shows through in this border. return new Insets(3,3,3,3); } } // end class HighLowGUI class BlackjackCanvas extends Canvas implements ActionListener { // A class that displays the card game and does all the work // of keeping track of the state and responding to user events. DeckOfCards BJDeck = new DeckOfCards(); // A deck of cards to be used in the game. BlackjackHand dealerHand; // Hand containing the dealer's cards. BlackjackHand playerHand; // Hand containing the user's cards. String message; // A message drawn on the canvas, which changes // to reflect the state of the game. boolean gameInProgress; // Set to true when a game begins and to false // when the game ends. Font bigFont; // Font that will be used to display the message. Font smallFont; // Font that will be used to draw the cards. BlackjackCanvas() { // Constructor. Creates fonts and starts the first game. setBackground( new Color(0,120,0) ); smallFont = new Font("SansSerif", Font.PLAIN, 12); bigFont = new Font("Serif", Font.BOLD, 14); doNewGame(); } public void actionPerformed(ActionEvent evt) { // Respond when the user clicks on a button by calling // the appropriate procedure. Note that the canvas is // registered as a listener in the BlackjackGUI class. String command = evt.getActionCommand(); if (command.equals("Hit!")) doHit(); else if (command.equals("Stand!")) doStand(); else if (command.equals("New Game")) doNewGame(); } void doHit() { // This method is called when the user clicks the "Hit!" button. // First check that a game is actually in progress. If not, give // an error message and exit. Otherwise, give the user a card. // The game can end at this point if the user goes over 21 or // if the user has taken 5 cards without going over 21. if (gameInProgress == false) { message = "Click \"New Game\" to start a new game."; repaint(); return; } playerHand.addCard( BJDeck.getTopCard() ); if ( playerHand.getBlackjackValue() > 21 ) { message = "You've busted! Sorry, you lose."; gameInProgress = false; } else if (playerHand.getCardCount() == 5) { message = "You win by taking 5 cards without going over 21."; gameInProgress = false; } else { message = "You have " + playerHand.getBlackjackValue() + ". Hit or Stand?"; } repaint(); } void doStand() { // This method is called when the user clicks the "Stand!" button. // Check whether a game is actually in progress. If it is, // the game ends. The dealer takes cards until either the // dealer has 5 cards or more than 16 points. Then the // winner of the game is determined. if (gameInProgress == false) { message = "Click \"New Game\" to start a new game."; repaint(); return; } gameInProgress = false; while (dealerHand.getBlackjackValue() <= 16 && dealerHand.getCardCount() < 5) dealerHand.addCard( BJDeck.getTopCard() ); if (dealerHand.getBlackjackValue() > 21) message = "You win! Dealer has busted with " + dealerHand.getBlackjackValue() + "."; else if (dealerHand.getCardCount() == 5) message = "Sorry, you lose. Dealer took 5 cards without going over 21."; else if (dealerHand.getBlackjackValue() > playerHand.getBlackjackValue()) message = "Sorry, you lose, " + dealerHand.getBlackjackValue() + " to " + playerHand.getBlackjackValue() + "."; else if (dealerHand.getBlackjackValue() == playerHand.getBlackjackValue()) message = "Sorry, you lose. Dealer wins on a tie."; else message = "You win, " + playerHand.getBlackjackValue() + " to " + dealerHand.getBlackjackValue() + "!"; repaint(); } void doNewGame() { // Called by the constructor, and called by actionPerformed() if // the use clicks the "New Game" button. Start a new game. // Deal two cards to each player. The game might end right then // if one of the players had blackjack. Otherwise, gameInProgress // is set to true and the game begins. if (gameInProgress) { // If the current game is not over, it is an error to try // to start a new game. message = "You still have to finish this game!"; repaint(); return; } DeckOfCards BJDeck = new DeckOfCards(); // Create the deck and hands to use for this game. dealerHand = new BlackjackHand(); playerHand = new BlackjackHand(); BJDeck.shuffleDeck(); dealerHand.addCard( BJDeck.getTopCard() ); // Deal two cards to each player. dealerHand.addCard( BJDeck.getTopCard() ); playerHand.addCard( BJDeck.getTopCard() ); playerHand.addCard( BJDeck.getTopCard() ); if (dealerHand.getBlackjackValue() == 21) { message = "Sorry, you lose. Dealer has Blackjack."; gameInProgress = false; } else if (playerHand.getBlackjackValue() == 21) { message = "You win! You have Blackjack."; gameInProgress = false; } else { message = "You have " + playerHand.getBlackjackValue() + ". Hit or stay?"; gameInProgress = true; } repaint(); } // end newGame(); public void paint(Graphics g) { // The paint method shows the message at the bottom of the // canvas, and it draws all of the dealt cards spread out // across the canvas. g.setFont(bigFont); g.setColor(Color.green); g.drawString(message, 10, getSize().height - 10); // Draw labels for the two sets of cards. g.drawString("Dealer's Cards:", 10, 23); g.drawString("Your Cards:", 10, 153); // Draw dealer's cards. Draw first card face down if // the game is still in progress, It will be revealed // when the game ends. g.setFont(smallFont); if (gameInProgress) drawCard(g, null, 10, 30); else drawCard(g, dealerHand.getCard(0), 10, 30); for (int i = 1; i < dealerHand.getCardCount(); i++) drawCard(g, dealerHand.getCard(i), 10 + i * 90, 30); // Draw the user's cards. for (int i = 0; i < playerHand.getCardCount(); i++) drawCard(g, playerHand.getCard(i), 10 + i * 90, 160); } // end paint(); void drawCard(Graphics g, PlayingCard card, int x, int y) { // Draws a card as a 80 by 100 rectangle with // upper left corner at (x,y). The card is drawn // in the graphics context g. If card is null, then // a face-down card is drawn. (The cards are // rather primitive.) if (card == null) { // Draw a face-down card g.setColor(Color.blue); g.fillRect(x,y,80,100); g.setColor(Color.white); g.drawRect(x+3,y+3,73,93); g.drawRect(x+4,y+4,71,91); } else { g.setColor(Color.white); g.fillRect(x,y,80,100); g.setColor(Color.gray); g.drawRect(x,y,79,99); g.drawRect(x+1,y+1,77,97); if (card.suit == PlayingCard.DIAMOND || card.suit == PlayingCard.HEART) { g.setColor(Color.red); } else { g.setColor(Color.black); } } } // end drawCard() } // end class BlackjackCanvas ```
2015/05/27
[ "https://Stackoverflow.com/questions/30483121", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4920432/" ]
Try to replace to this line of code: **Swift 2** ``` UIApplication.sharedApplication().keyWindow?.rootViewController?.presentViewController(refreshAlert, animated: true, completion: nil) ``` **Swift 3** ``` UIApplication.shared.keyWindow?.rootViewController?.present(refreshAlert, animated: true, completion: nil) ```
Leo's solution worked for me. I've used it to present an AlertView from a Custom collection view cell. Update for Swift 3.0: ``` extension UIView { var parentViewController: UIViewController? { var parentResponder: UIResponder? = self while parentResponder != nil { parentResponder = parentResponder!.next if parentResponder is UIViewController { return parentResponder as! UIViewController! } } return nil } } ``` Hope it helps.
2,050,306
I have three c# projects in my solution. One is a console app that simply calls into a class library project. The class library project does all the processing for the application. Then there is a WinForm project that displays a form and then when a button is pressed, calls the same logic in the class library project. As a result, there are two ways to run the logic, via the Console or via a Windows UI (WinForm). My problem is that part way through the class library logic, if the UI app is being used, I want a custom WinForm form to appear to ask the user a question. In the Console app, I want the same place in the logic to simply write out to the Console. In my understanding of architecture, you don't want the class library project to contain WinForm logic and require it to have references to all the WinForm references. But how do I make a call to the WinForms project (or something else) to display the custom WinForm form? There would be a circular reference where the class library would reference the main WinForm app and the WinForm app would reference the class library project. What is the standard way of doing this?
2010/01/12
[ "https://Stackoverflow.com/questions/2050306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/54064/" ]
You could raise an event in the class library that is listened to/registered from whatever your UI/Console layer is. That way it can decide to act on the event if it is deemed necessary in as many places as you desire. It really depends on how your architecture is setup.
While the interface answers are probably better solutions, if it's just *one* method you could just use a delegate to pass the Console or WinForm method to the class library.
44,535,888
I am attempting to log the current tracker info to the console as per the Analytics documentation: ``` (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-80990893-7', 'auto'); ga('send', 'pageview'); ga(function(tracker) { // Logs the tracker created above to the console. console.log('test'); console.log(tracker); }); ``` Nothing is actually outputted to the console. It's as if the function is not even executing. Why is this not working when I've literally copy and pasted from their docs?
2017/06/14
[ "https://Stackoverflow.com/questions/44535888", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5645843/" ]
Please install and enable **Google** Tag Assistant from [here](https://chrome.google.com/webstore/detail/tag-assistant-by-google/kejbdjndbnbjgmefkgdddjlbokphdefk?hl=en) and start record. Two things always remember. * put your **ga** code in always `<head></head>` tag. * don't put your **ga** code any core function like create one php function and define `<script>ga code is here</script>` and exicute it later. >> **It's totaly wrong way because exicution is skip your ga code.** Let's go with your question. * I have noticed your analytics code working fine. * Google Tag Assistance result as per follow for your code. * One page view event or tracks found. [![enter image description here](https://i.stack.imgur.com/1SUqw.png)](https://i.stack.imgur.com/1SUqw.png)
Don't forget to disable ad/tracking blockers ;) I know that this is an old thread, however, it was the only one I found about this issue and as the others stated the code is actually correct. However, the reason it did not work for me was that I forgot to disable tracking protection.