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 |
|---|---|---|---|---|---|
119,444 | For one and a half years, I have been keeping my eyes on the git community in hopes of making the switch away from SVN. One particular issue holding me back is the inability to lock binary files. Throughout the past year I have yet to see developments on this issue. I understand that locking files goes against the fundamental principles of distributed source control, but I don't see how a web development company can take advantage of git to track source code and image file changes when there is the potential for binary file conflicts.
To achieve the effects of locking, a "central" repository must be identified. Regardless of the distributed nature of git, most companies will have a "central" repository for a software project. We should be able to mark a file as requiring a lock from the governing git repository at a specified address. Perhaps this is made difficult because git tracks file contents not files?
Do any of you have experience in dealing with git and binary files that should be locked before modification?
NOTE: It looks like Source Gear's new open source distributed version control project, Veracity, has locking as one of its goals. | 2008/09/23 | [
"https://Stackoverflow.com/questions/119444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/472/"
] | [Git LFS 2.0](https://github.com/blog/2328-git-lfs-2-0-0-released) has added support for file locking.
>
> With Git LFS 2.0.0 you can now lock files that you're actively working on, preventing others from pushing to the Git LFS server until you unlock the files again.
>
>
> This will prevent merge conflicts as well as lost work on non-mergeable files at the filesystem level. While it may seem to contradict the distributed and parallel nature of Git, file locking is an important part of many software development workflows—particularly for larger teams working with binary assets.
>
>
> | In response to Mario's additional concern with changes happening in multiple places on the binaries. So the scenario is Alice and Bob are both making changes to the same binary resource at the same time. They each have their own local repo, cloned from one central remote.
This is indeed a potential problem. So Alice finishes first and pushes to the central `alice/update` branch. Normally when this happens, Alice would make an announcement that it should be reviewed. Bob sees that and reviews it. He can either (1) incorporate those changes himself into his version (branching from `alice/update` and making his changes to that) or (2) publish his own changes to `bob/update`. Again, he makes an announcement.
Now, if Alice pushes to `master` instead, Bob has a dilemma when he pulls `master` and tries to merge into his local branch. His conflicts with Alice's. But again, the same procedure can apply, just on different branches. And even if Bob ignores all the warnings and commits over Alice's, it's always possible to pull out Alice's commit to fix things. This becomes simply a communication issue.
Since (AFAIK) the Subversion locks are just advisory, an e-mail or instant message could serve the same purpose. But even if you don't do that, Git lets you fix it.
No, there's no locking mechanism per se. But a locking mechanism tends to just be a substitute for good communication. I believe that's why the Git developers haven't added a locking mechanism. |
64,176 | Can anyone help me identify the year, make and model of this car?
I would greatly appreciate anyone that can help me. Please!
Thank you so much for anyone that is looking.
[](https://i.stack.imgur.com/h2Ssh.jpg) | 2019/03/03 | [
"https://mechanics.stackexchange.com/questions/64176",
"https://mechanics.stackexchange.com",
"https://mechanics.stackexchange.com/users/46216/"
] | I'd say it's a first-generation BMW X3 (E83) - the ridge along the top of the doors is different to the Volvos, and you can see the distinctive upsweep to the bottom of the rearmost window. | Without a much clearer and larger picture I have to take an educated guess. It looks like a Volvo SUV XC model. As for the year hard to say. |
63,802,194 | Consider following 4 lines of code:
```
Mono<Void> result = personRepository.findByNameStartingWith("Alice")
.map(...)
.flatMap(...)
.subscriberContext()
```
**Fictional Use Case which I hope you will immediately map to your real task requirement:**
How does one adds "Alice" to the context, so that after `.map()` where "Alice" is no longer `Person.class` but a `Cyborg.class` (assuming irreversible transformation), in `.flatMap()` I can access original "Alice" `Person.class`. We want to compare the strength of "Alice" person versus "Alice" cyborg inside `.flatMap()` and then send them both to the moon on a ship to build a colony.
* I've read about 3 times:
<https://projectreactor.io/docs/core/release/reference/#context>
* I've read dozen articles on `subscriberContext`
* I've looked at colleague code who uses subscriberContext but only for Tracing Context and MDM which are statically initialised outside of pipelines at the top of the code.
So the conclusion I am coming to is that something else was named as "context" , what majority can't use for the overwhelming use case above.
Do I have to stick to tuples and wrappers? Or I am totally dummy and there is a way. I need this context to work in entirely opposite direction :-), unless "this" context is not the context I need. | 2020/09/08 | [
"https://Stackoverflow.com/questions/63802194",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/873139/"
] | This was achieved as proposed in the question.
The finished sample flow looks like this:
[](https://i.stack.imgur.com/FUiEu.jpg)
Add the Mule Java Module dependency, and Apache POI for handling the Microsoft xls file:
```
<dependency>
<groupId>org.mule.module</groupId>
<artifactId>mule-java-module</artifactId>
<version>1.2.5</version>
<classifier>mule-plugin</classifier>
</dependency>
<!-- https://mvnrepository.com/artifact/org.apache.poi/poi -->
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
```
The file was then read by a `On New or Updated` file reader with **no** mime type or encoding configured. This is because we are trying to avoid Mule knowing anything about the file type. The file could be received in any way of course - e.g. over FTP.
At this point the payload just looks like a pile of gobbledygook (the raw xls file).
The source (file reader) is then immediately followed by a transform converting the payload to plain text and base64 encoding it:
```
%dw 2.0
import * from dw::core::Binaries
output text/plain
---
toBase64(payload as Binary)
```
This is done because initially we had a lot of trouble passing the raw file to Java, with issues like (however if you have a better solution let me know!):
* Cannot convert so and so to object
* invalid end of file
Which make perfect sense because Java doesn't know what we are passing it and so how would it know to transform it to a specific object type.
Next we instantiate the Java class with Mule's Java 'New' event. The class itself looks like:
```
public class Transformer {
public String transform(String file) {
String cellValue = "";
try {
// Decode base64:
byte[] decoded = Base64.getDecoder().decode(file);
// Steam decoded file to an input stream (as if we were reading it from disk)
InputStream targetStream = new ByteArrayInputStream(decoded);
// Create the .xls Apache POI object
HSSFWorkbook workbook = new HSSFWorkbook(targetStream);
// Process the rows/cells etc...
HSSFSheet sheet = workbook.getSheetAt(0);
// For example...
cellValue = sheet.getRow(0).getCell(0).getStringCellValue();
} catch (Exception e) {
System.out.println("FAIL" + e.getMessage());
}
return cellValue;
}
}
```
Next we pass the payload to this method with Mule's Java Invoke event with the following configuration:
* Instance: vars.instanceName
* Args: `{arg0: payload as String}`
* Class: package and class name of the Java class
* Method: the method to invoke, ours was transform(java.lang.String)
It is passed as a `String` because Java knows how to handle the `String` object, and basically we are hiding the fact that it is a file.
From the there Java does the following (see the above Java file):
* Decodes the file:
* Reads it to an InputStream:
* Creates the Apache POI class:
* performs transformation:
In the sample above we are just returning the value of one cell as a String to Mule. But you can also create a CSV type String such as `a,b,c\nd,e,f` (\n for new line)and then transform it to a CSV with a Transform event:
```
%dw 2.0
output application/java
---
write( (read(payload,"application/csv",{"header" : false})),"application/csv",{"quoteValues" : "false","header" : false})
```
which would output a csv file like this:
```
a,b,c
d,e,f
```
And there you have it. Mule can now process a Microsoft Excel xls file. | Yes, You can pass an InputStream to Java module method invocation and use for example Apache POI (capable of reading xls and xlsx as well) for Your stream to csv conversion. |
30,041,551 | I have a class user which contains a boolean field, I want to sort a list of users, I want the users who have the boolean field equals true to be in the top of the list and than I want sort them by their names.
Here is my class :
```
public class User{
int id;
String name;
boolean myBooleanField;
public User(int id, String name, boolean myBooleanField){
this.id = id;
this.name = name;
this.myBooleanField = myBooleanField;
}
@Override
public boolean equals(Object obj) {
return this.id == ((User) obj).id;
}
}
```
Here is an example to clear what I want :
lets say that I have this collection of users :
```
ArrayList<User> users = new ArrayList<User>();
users.add(new User(1,"user1",false));
users.add(new User(2,"user2",true));
users.add(new User(3,"user3",true));
users.add(new User(4,"user4",false));
Collections.sort(users, new Comparator<User>() {
@Override
public int compare(User u1, User u2) {
//Here i'm lookin for what should i add to compare the two users depending to the boolean field
return u1.name.compareTo(u2.name);
}
});
for(User u : users){
System.out.println(u.name);
}
```
I want to sort users to get this result :
```
user2
user3
user1
user4
``` | 2015/05/04 | [
"https://Stackoverflow.com/questions/30041551",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3578325/"
] | Something along these lines perhaps?
```
Collections.sort(users, new Comparator<User>() {
public int compare(User u1, User u2) {
String val1 = (u1.myBooleanField ? "0" : "1") + u1.name;
String val2 = (u2.myBooleanField ? "0" : "1") + u2.name;
return val1.compareTo(val2);
}
});
``` | You can use `Collectors.groupingBy` to seperate top users from the rest
```
Map<Boolean, List<User>> list = users.stream()
.collect(
Collectors.groupingBy(
Info::getMyBooleanField);
```
Select top users and sort them by name
```
List<User> topUsers = list.get(true);
topUsers.sort((u1, u2) -> u1.getName().compareTo(u2.getName()));
```
Select of the rest of users and sort them by name:
```
List<User> restUsers = list.get(false);
restUsers.sort((u1, u2) -> u1.getName().compareTo(u2.getName()));
```
And here is the final list
```
topUsers.addAll(restUsers );
users=(ArrayList<User>)topUsers;
``` |
50,557,099 | I'm trying to parse strings like this: *aa bb first item ee ff*
I need separate prefix '*aa bb*', keyword:'*first item*' and suffix '*ee ff*'
Prefix and suffix can be several words or even doesn't exist. Keyword is list of predefined values.
this is what I tried but it didn't work:
```
a = ZeroOrMore(Word(alphas)('prefix')) & oneOf(['first item', 'second item'])('word') & ZeroOrMore(Word(alphas)('suffix'))
``` | 2018/05/27 | [
"https://Stackoverflow.com/questions/50557099",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9855931/"
] | First issue is your use of the '&' operator. In pyparsing, '&' produces `Each` expressions, which are like `And`s but accept the subexpressions in any order:
```
Word('a') & Word('b') & Word('c')
```
would match 'aaa bbb ccc', but also 'bbb aaa ccc', 'ccc bbb aaa', etc.
In your parser, you'll want to use the '+' operator, which produces `And` expressions. `And`s match several sub expressions, but only in the given order.
Secondly, one of the reasons for using pyparsing is to accept varying whitespace. Whitespace is an issue for parsers, especially when using `str.find` or regexes - in regexes, this usually manifests as lots of `\s+` fragments throughout your match expressions. In your pyparsing parser, if the input string contains `'first item'` (two spaces between 'first' and 'item'), trying to match a literal string 'first item' will fail. Instead you should match the multiple words separately, probably using pyparsing's `Keyword` class, and let pyparsing skip over any whitespace between them. To simplify this, I wrote a short method `wordphrase`:
```
def wordphrase(s):
return And(map(Keyword, s.split())).addParseAction(' '.join)
keywords = wordphrase('first item') | wordphrase('second item')
print(keywords)
```
prints:
```
{{"first" "item"} | {"second" "item"}}
```
indicating the each word will be parsed individually, with any number of spaces between the words.
Lastly, you have to write pyparsing parsers knowing that pyparsing does not do any lookahead. In your parser, the prefix expression `ZeroOrMore(Word(alphas))` will match *all* the words in "aa bb first item ee ff" - then there is nothing left to match the keywords expression, so the parser fails. To code this in pyparsing, you have to write an expression in your `ZeroOrMore` for the prefix words that translates to "match every word of alphas, but first make sure we are not about to parse a keyword expression". In pyparsing, this kind of negative lookahead is implemented using `NotAny`, which you can create using the unary `~` operator. For readabiity we'll use `keywords` expression from above:
```
non_keyword = ~keywords + Word(alphas)
a = ZeroOrMore(non_keyword)('prefix') + keywords('word') + ZeroOrMore(Word(alphas))('suffix')
```
Here is a complete parser, and results using runTests against different sample strings:
```
def wordphrase(s):
return And(map(Keyword, s.split())).addParseAction(' '.join)
keywords = wordphrase('first item') | wordphrase('second item')
non_keyword = ~keywords + Word(alphas)
a = ZeroOrMore(non_keyword)('prefix') + keywords('word') + ZeroOrMore(Word(alphas))('suffix')
text = """
# prefix and suffix
aa bb first item ee ff
# suffix only
first item ee ff
# prefix only
aa bb first item
# no prefix or suffix
first item
# multiple spaces in item, replaced with single spaces by parse action
first item
"""
a.runTests(text)
```
Gives:
```
# prefix and suffix
aa bb first item ee ff
['aa', 'bb', 'first item', 'ee', 'ff']
- prefix: ['aa', 'bb']
- suffix: ['ee', 'ff']
- word: 'first item'
# suffix only
first item ee ff
['first item', 'ee', 'ff']
- suffix: ['ee', 'ff']
- word: 'first item'
# prefix only
aa bb first item
['aa', 'bb', 'first item']
- prefix: ['aa', 'bb']
- word: 'first item'
# no prefix or suffix
first item
['first item']
- word: 'first item'
# multiple spaces in item, replaced with single spaces by parse action
first item
['first item']
- word: 'first item'
``` | If I understood your question correctly this should do the trick:
```
toParse='aa bb first item ee ff'
keywords=['test 1','first item','test two']
for x in keywords:
res=toParse.find(x)
if res>=0:
print('prefix='+toParse[0:res])
print('keyword='+x)
print('suffix='+toParse[res+len(x)+1:])
break
```
Gives this result:
```
prefix=aa bb
keyword=first item
suffix=ee ff
``` |
48,240,039 | When I try to localize my app and I create a new Main.strings file for the target language, everything I have created in interface builder (labels, buttons, ...) is added to the new Main.strings files (base and language versions) and I can localize the text accordingly.
But when I later add a label or a button to a ViewController in interface builder, it is not automatically added to the Main.strings files for the base and language version.
So, how can I find out what the ObjectID for the button/label is so that I can add it to the strings files?
Or is there another way to force Xcode to add newly added labels and buttons to those files automatically? | 2018/01/13 | [
"https://Stackoverflow.com/questions/48240039",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6852849/"
] | Easy XIB and Storyboard Localization - Very efficient and simple method
This repository serves as an example on how to localize some UIKit controls:
UILabel,
UIButton,
UITextField placeholder,
UISegmentedControl,
UIBarItem for tab bar items and navigation bar items,
UINavigationItem,
Review Localizable.swift to check it.
<https://github.com/emenegro/xib-localization>
[](https://i.stack.imgur.com/thZ0m.png)
[](https://i.stack.imgur.com/7AdeJ.png) | Use `ObjectID.text` for `UILabel`
Use `ObjectID.normalTitle` for `UIButton`
**Example:**
```
/* Object ID of UILabel */
"GWb-TZ-iGk.text" = "I am label";
/* Object ID of UIButton */
"H6f-pG-K8Z.normalTitle" = "I am button";
``` |
2,763,091 | As the title says, I want to parse some Java source code in Java. I'm pretty sure there are other java libraries that already perform this, but I couldn't find any. | 2010/05/04 | [
"https://Stackoverflow.com/questions/2763091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/133973/"
] | [Janino](http://docs.codehaus.org/display/JANINO/Home) can parse, compile and execute Java code. | JavaCC has a Java 1.5 grammar including generics.
>
> the tokens are probably more
> fine-grained then what I want
>
>
>
Your first requirement is to get an accurate parse, and you will realistically only get that from an existing parser. What you do with the result is up to you. |
38,601,746 | I have a spring boot application where I am creating `Datasource` and `JdbcTemplate` manually in my config because I need to decrypt datasource password.
I am using tomcat `DataSource` (`org.apache.tomcat.jdbc.pool.DataSource`) as recommended in spring boot docs since I am configuring connection properties.
I am excluding autoconfiguration for datasource (see `Application.java`) since I am creating one manually.
**Application.java**
```
// exclude datasourceAutoConfiguration since we are creating manaully creating datasource bean in AppConfig
@SpringBootApplication
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
```
Here is my `application.properties` file
```
jdbc.hostdb.url=jdbc:jtds:sqlserver://hello-world:1122/foobar
host.jdbc.hostdb.username=foo
host.jdbc.hostdb.password=encryptedPassword
host.jdbc.hostdb.driver=net.sourceforge.jtds.jdbc.Driver
secret=afasdfansdfsdfsd
```
**AppConfig.java**
```
import org.apache.tomcat.jdbc.pool.DataSource;
@ComponentScan("com.company.foo")
public class AppConfig {
@Value("${jdbc.hostdb.driver}")
private String driver;
@Value("${jdbc.hostdb.url}")
private String url;
@Value("${jdbc.hostdb.username}")
private String user;
@Value("${jdbc.hostdb.password}")
private String pass;
@Value("${secret}")
private String secret;
@Bean
public DataSource datasource_mydb(Encryption encryption) {
DataSource ds = new DataSource();
ds.setDriverClassName(hostdb_driver);
ds.setUrl(hostdb_url);
ds.setUsername(hostdb_user);
ds.setPassword(encryption.decrypt(hostdb_pass));
return ds;
}
@Bean
Encryption encryption() {
return new Encryption(secret);
}
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
```
**MyRepository.java**
```
@Repository
public class MyRepository {
JdbcTemplate jdbcTemplate;
@Autowired
public MyRepository(JdbcTemplate jdbcTemplate){
this.jdbcTemplate=jdbcTemplate;
}
}
```
when I start spring container, I get the following error
```
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'MyRepository' defined in file [/Users//Documents/codebase/my-service/build/classes/main/com/company/foo/MyRepository.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.springframework.jdbc.core.JdbcTemplate]: No qualifying bean of type [org.springframework.jdbc.core.JdbcTemplate] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.jdbc.core.JdbcTemplate] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:749) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:185) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1143) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1046) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:510) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:482) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:772) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:839) ~[spring-context-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:538) ~[spring-context-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:118) ~[spring-boot-1.3.6.RELEASE.jar:1.3.6.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:760) [spring-boot-1.3.6.RELEASE.jar:1.3.6.RELEASE]
at org.springframework.boot.SpringApplication.createAndRefreshContext(SpringApplication.java:360) [spring-boot-1.3.6.RELEASE.jar:1.3.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:306) [spring-boot-1.3.6.RELEASE.jar:1.3.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1185) [spring-boot-1.3.6.RELEASE.jar:1.3.6.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1174) [spring-boot-1.3.6.RELEASE.jar:1.3.6.RELEASE]
at com.concur.cognos.authentication.Application.main(Application.java:14) [main/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_102]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_102]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_102]
at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_102]
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144) [idea_rt.jar:na]
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.springframework.jdbc.core.JdbcTemplate] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1373) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1119) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1014) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:813) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:741) ~[spring-beans-4.2.7.RELEASE.jar:4.2.7.RELEASE]
... 24 common frames omitted
2016-07-26 1
``` | 2016/07/27 | [
"https://Stackoverflow.com/questions/38601746",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1988876/"
] | The problem is with the arguments of your bean definitions. Where would their values come from? For example -
```
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
```
Here you haven't specified where would value of `dataSource` argument come from. Same case of `datasource_mydb` bean. Use `@Autowire` on bean definitions acception other beans as input arguments.
```
@Bean
@Autowired
public DataSource datasource_mydb(Encryption encryption) {
DataSource ds = new DataSource();
ds.setDriverClassName(hostdb_driver);
ds.setUrl(hostdb_url);
ds.setUsername(hostdb_user);
ds.setPassword(encryption.decrypt(hostdb_pass));
return ds;
}
@Bean
Encryption encryption() {
return new Encryption(secret);
}
@Bean
@Autowired
@Qualifier("datasource_mydb")
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
``` | It's possible...
You might not have added JdbcTemplate dependency in project configuration file(.xml file). |
60,458,870 | Is it possible to call POST actions from an Azure Resource Manager (ARM) template? I have custom resource provider where I can create resources and call actions using POST as follows:
POST
/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomResourceProvider/resource/{resourceName}/actionName
Is there a way to call this action from a template? | 2020/02/28 | [
"https://Stackoverflow.com/questions/60458870",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12970037/"
] | No, there is none. ARM Templates can only do PUT calls, not POST. | I'm not sure whether I understand the question. I try to answer.
>
> The operations available for each Azure Resource Manager resource
> provider. These operations can be used in custom roles to provide
> granular role-based access control (RBAC) to resources in Azure.
>
> Refer to: [Azure Resource Manager resource provider operations](https://learn.microsoft.com/en-us/azure/role-based-access-control/resource-provider-operations)
>
>
>
It is desgined for RBAC to grant access. It seems can not be used for calling in ARM template. |
27,671,748 | I'm creating very simple charts with matplotlib / pylab Python module. The letter "y" that labels the Y axis is on its side. You would expect this if the label was longer, such as a word, so as not to extend the outside of the graph to the left too much. But for a one letter label, this doesn't make sense, the label should be upright. My searches have come up blank. How can I print the "y" horizontally? | 2014/12/27 | [
"https://Stackoverflow.com/questions/27671748",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3275196/"
] | It is very simple. After plotting the label, you can simply change the rotation:
```py
import matplotlib.pyplot as plt
plt.ion()
plt.plot([1, 2, 3])
plt.ylabel("y", rotation=0)
# or
# h = plt.ylabel("y")
# h.set_rotation(0)
plt.draw()
``` | Expanding on the accepted answer, when we work with a particular axes object `ax`:
```
ax.set_ylabel('abc', rotation=0, fontsize=20, labelpad=20)
```
Note that often the `labelpad` will need to be adjusted manually too — otherwise the "abc" will intrude onto the plot.
From brief experiments I'm guessing that `labelpad` is the offset between the bounding box of the tick labels and the y-label's centre. (So, not quite the padding the name implies — it would have been more intuitive if this was the gap to the label's bounding box instead.) |
11,072 | Is it possible to build a CNC whose Linear motion system does not contain any timing belt(pulley) or lead screw(threaded rod).
I was wondering whether I could directly control the Linear motion by securing wheels of a slider onto aluminum rails & directly connecting the wheels to a stepper motor.
The main objective of this question is to find the cheapest method for controlled Linear motion. | 2016/11/17 | [
"https://robotics.stackexchange.com/questions/11072",
"https://robotics.stackexchange.com",
"https://robotics.stackexchange.com/users/15322/"
] | CNC controllers, in most cases, control rotary motion and the model of how this rotary motion is tranformed, by the mechanism attached to the motor, to a translational motion is implemented in the controller.
You can use any method of transforming rotary motion to a linear motion as long as the model for it is pre-implemented in the CNC controller or you can implement it to the CNC. Moreover, it does not even has to be a decoupled translational motion. E.g. LinuxCNC can controll multiple axes to achive 1 decoupled linear motion. On a parellel mechanism, moving all axes results in a Z translation. Video of this [here](https://www.youtube.com/watch?v=O7pc1B3rnMY).
The only limit to what mechanism can you put on the end of the motor of a CNC is what are you able to model and integrate to the CNC controller. If you do not have the possibility to implement a model, then the question becomes what pre-implemented models are there and how can you adjust their parameters to make them refelct your mechanism.
Needles to say the accuracy of the model will affect the accuracy of the CNC. | Interesting question. Some degree of precision is required. There are two ways to do this:
a) use an encoder associated with a wheel which reports the rotary position. That value is then related to the wheel circumference to obtain the distance travelled. Perhaps a wifi transmitter on each carriage would be more practical than wiring.
b) use an absolute positioning measurement system. Your dimensions of 100m x 50m are very large and clearly any traditional belt drive/screw drive is impractical. As an example of absolute positioning, a laser rangefinder (+/- 1-2mm) at each corner would locate the gantry. How a commercial product would be interfaced with the PID/control system is a homework exercise. |
516,236 | I'm sure there's a more specific word/phrase for moments like in a soccer match when the loser team which is, say, two scores behind, scores 3 points in the last ten minutes to turn an almost certain defeat into a great victory to everyone's surprise.
PS: An alternative context can be a legal dispute or even a military battle. | 2019/10/23 | [
"https://english.stackexchange.com/questions/516236",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/91410/"
] | When a competitor is beaten by a small margin and at the last moment they have been **pipped at the post**.
There's a question specifically about this phrase: [What is the origin of "Pipped at the post"?](https://english.stackexchange.com/questions/193600/what-is-the-origin-of-pipped-at-the-post) | Alternatively to Glorfindel's answer, from the losing team's point of view it could be described as a **throw**, which means "to intentionally lose a game" (Wiktionary) but used colloquially means to play so badly as to be almost indistinguishable from purposely losing. Also consider **upset**, which means "an unexpected victory of a competitor or candidate that was not favored to win" (Wiktionary) but is more typically used when the winning team was already favored to lose prior to the game. |
81,062 | Data input validation always was quite an internal struggle to me.
On the verge of adding a real security framework and code to our legacy application rewrite project (which so far pretty much keeps the card-castle-strong legacy security code and data validation), I'm wondering again about how much should I validate, where, etc.
Over my 5 years as professional Java developer, I created and refined my personal rules for data input validation and security measures. As I like to improve my methods, I'd like some hear some ideas from you guys. General rules and procedures are fine, and Java-specific ones too.
Summarized, these are my guidelines (exposed on a 3-tier web application style), with brief explanations:
* 1st tier client side (browser): minimal validation, only invariable rules (mandatory email field, must select one item, and the like); use of additional validation like "between 6 and 20 characters" less frequent, as this increases maintenance work on changes (may be added once the business code is stable);
* 1st tier server side (web communication handling, "controllers"): I don't have a rule for this one, but I believe only data manipulation and assembly/parsing errors should be handled here (birthday field is not a valid date); adding further validation here easily makes it a really boring process;
* 2nd tier (business layer): rock solid validation, no less; input data format, ranges, values, internal state checking if method cannot be called anytime, user roles/permissions, and so on; use as little user input data as possible, retrieve it again from database if needed; if we consider retrieved database data as input too, I would only validate it if some specific data is known to be unreliable or corrupted enough on the DB - strong typing does most of the job here, IMHO;
* 3rd tier (data layer/DAL/DAO): never believed much validation is needed here, as only the business layer is supposed to access the data (validate maybe on some case like "param2 must not be null if param1 is true"); notice however, that when I mean "here" I mean "code that access the database" or "SQL-executing methods", the database itself is completely the opposite;
* the database (data model): needs to be as well thought, strong and self-enforcing as to avoid incorrect and corrupt data on the DB as much as possible, with good primary keys, foreign keys, constraints, data type/length/size/precision and so on - I'm leaving triggers out of this, as they have their own private discussion.
I know early data validation is nice and performance-wise, but repeated data validation is a boring process, and I admit that data validation itself is quite annoying. That's why so many coders skip it or do it halfway. Also, every duplicated validation is a possible bug if they are not synchronized all the times. Those are the main reasons that I'm nowadays preferring let most of the validations up to the business layer, at the expense of time, bandwidth and CPU, exceptions handled on a case-by-case basis.
So, what do you think about this? Opposite opinions? Do you have other procedures? A reference to such topic? Any contribution is valid.
Note: if you are thinking the Java way of doing things, our app is Spring based with Spring MVC and MyBatis (performance and bad database model rule out ORM solutions); I plan to add Spring Security as our security provider plus JSR 303 (Hibernate Validator?)
Thanks!
---
Edit: some extra clarification on the 3rd layer. | 2011/06/02 | [
"https://softwareengineering.stackexchange.com/questions/81062",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/15017/"
] | >
> •3rd tier (data layer/DAL/DAO): never
> believed much validation is needed
> here, as only the business layer is
> supposed to access the data (validate
> maybe on some case like "param2 must
> not be null if param1 is true").
>
>
>
This is so wrong. The most important place to have the validation is in the database itself. The data is almost always affected by more than the application (even when you think it won't be) and it is irresponsible at best to not put proper controls into the database. There is more loss of data integrity from a decision not to do this than any other factor. Data integrity is critical to the long term use of the database. I have never seen any database that failed to enforce integrity rules at the database level that contained good data (and I have seen the data in literally thousands of databases).
He says it better than I do:
<http://softarch.97things.oreilly.com/wiki/index.php/Database_as_a_Fortress> | All the above make the assumption that developers and maintainers are perfect and write perfect code that always runs perfectly. The future software releases know about all the assumptions you made and never documented, and users and hackers who put data into the system in ways you never imagined.
Sure, too much validation is a bad thing, but assuming programs, networks and OS's are perfect, hackers won't get through your firewall, an DBAs won't manually "tweak" the database is probably worse.
Draw boundary circles around things, identify the failure modes it's protecting against and implement an appropriate level of checking for that boundary. For instance, your database should never see invalid data, but how could it happen and what if it does? Who is your user, whats the cost of failure?
Study physical world security models, security should be in layers, like an onion. One thick wall is considered poor security. Data validation should be considered the same way. |
554,540 | My father was colorblind, and I always wondered if colors were a matter of physics or if different colors are just a human way of describing and differentiating our visual perception of the world?
For example, is the color blue by nature blue, or is it just what we see? | 2020/05/24 | [
"https://physics.stackexchange.com/questions/554540",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/74945/"
] | Our eyes are receptors, and have evolved so that they are most sensitive for visible wavelength photons, something called tricolor vision, with three types of receptors, each for Red, Green, and Blue wavelength. Now our receptors have naturally evolved for Sunlight, and Sunlight is made up of a combination of several different wavelength light (including non visible too, but our eyes are only sensitive for visible wavelength photons).
The receptors in our eyes, are sensitive for these three types of RGB wavelength photons. Each receptor sends information to the brain, and the brain perceives the combination of these photons as certain color light.
>
> The normal explanation of trichromacy is that the organism's retina contains three types of color receptors (called cone cells in vertebrates) with different absorption spectra.
>
>
>
<https://en.wikipedia.org/wiki/Trichromacy>
In this sense, the answer to your question is that color is a perception in our brain. Of course in a physical sense, the color of light (based on natural Sunlight) is a combination of different wavelength photons. Thus, certain color light (the one that our brain perceives as a certain color) can be produced many ways. It can be made of just certain wavelength photons, or it can be made up of different combinations. Yes, two different combinations can sometimes combine into light that our brain could perceive as (approximately) the same color.
[](https://i.stack.imgur.com/TPAaj.png)
<https://en.wikipedia.org/wiki/Color_vision>
Now in the visible wavelength, we made arbitrary (based on how our brain would perceive those photons alone) decisions to call certain wavelengths certain color.
In your case blue color light can be produced in different combinations, certain shades of blue can include other wavelength photons, but we call them all blue based on our brain's ability to perceive them all as shades of blue.
Yes, theoretically, there can exist blue light that is made purely of blue wavelength photons, and our brain would see that kind of light blue as well. In that case, in our eyes, only the blue receptors (the receptors that are sensitive for blue wavelength photons) would be activated.
>
> White is not a spectral color. It's a perceived color.
>
>
>
[How much red, blue, and green does white light have?](https://physics.stackexchange.com/questions/128785/how-much-red-blue-and-green-does-white-light-have)
In case some of the receptors in our eyes are not sensitive enough for certain wavelength photons, the color vision will be different, because our brain can only work with information it actually receives, but if the receptors do not send certain information (they are not sensitive for certain wavelength photons) to the brain, the brain perceives only the information it receives, and that will create a different color vision. | Colors can be described at three different levels.
The first two; electromagnetic frequency and neural signalling, have been well addressed in other answers. These are both objective measures of color, and it is even becoming possible to measure what color someone is seeing - or even imagining - in realtime, via non-invasively monitoring the pattern of their brain waves.
The third aspect or level is subjective. Why does blue feel "blue" and red "red"? Why don't they feel the other way around? Do all of us "feel" the same colors when similar neural signals arise? What about color-blind people, or other sentient creatures with different color vision, do they still see our blue as blue, or what? The problem is, it is impossible to find out. No physical theory, be it quantum physics, relativity, statistical mechanics, or of any emergent properties of matter arising from these, has anything at all to say about the subjective qualities of conscious experience. It is no longer the domain of physics but of philosophy, and even there it is simply known as "the hard problem". |
1,322,934 | I have a Python list of strings, e.g. initialized as follows:
```
l = ['aardvark', 'cat', 'dog', 'fish', 'tiger', 'zebra']
```
I would like to test an input string against this list, and find the "closest string below it" and the "closest string above it", alphabetically and case-insensitively (i.e. no phonetics, just `a<b` etc). If the input exists in the list, both the "below" and "above" should return the input.
Several examples:
```
Input | Below | Above
-------------------------------
bat | aardvark | cat
aaa | None | aardvark
ferret | dog | fish
dog | dog | dog
```
What's the neatest way to achieve this in Python? (currently I'm iterating over a sorted list using a for loop)
To further clarify: I'm interested in simple dictionary alphabetical comparison, not anything fancy like Levenshtein or phonetics.
Thanks | 2009/08/24 | [
"https://Stackoverflow.com/questions/1322934",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/103532/"
] | A very naive implementation, good only for short lists: you can pretty easily iterate through the list and compare your choice against each one, then break the first time your choice is 'greater' than the item being compared.
```
for i, item in enumerate(l):
if lower(item) > lower(input):
break
print 'below: %s, above, %s' % (l[i-1], item)
``` | Are these relatively short lists, and do the contents change or are they fairly static?
If you've got a large number of strings, and they're relatively fixed, you might want to look into storing your data in a Trie structure. Once you build it, then it's quick & easy to search through and find your nearest neighbors the way you'd like. |
71,232,214 | VS code and Android Studio is recognizing my connected android device.
My device is showing up on file explorer though. I have turned on USB debugging from settings too.
[](https://i.stack.imgur.com/pjY9D.png)
Below is the result of `flutter doctor`
```dart
Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.8.1, on Microsoft Windows [Version 10.0.22000.493], locale en-US)
[√] Android toolchain - develop for Android devices (Android SDK version 30.0.2)
[√] Android Studio (version 4.0)
[√] VS Code (version 1.64.2)
[!] Connected device
! No devices available
! Doctor found issues in 1 category.
```
**What I have tried**
<https://github.com/Dart-Code/Dart-Code/issues/1634#issuecomment-485071966>
<https://developer.android.com/studio/run/oem-usb#Win10> | 2022/02/23 | [
"https://Stackoverflow.com/questions/71232214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7290043/"
] | Please check link below. It might solve your problem of not showing devices (Message "flutter run: No connected devices"):-
[Message "flutter run: No connected devices"](https://stackoverflow.com/questions/49045393/message-flutter-run-no-connected-devices) | Once check the output of the command
```
adb devices
```
If the list is empty then the system has recognized your device as a storage device. Then you need to install android SDK from the Android Studio IDE and try again. |
20,056,458 | A reasonably common operation is to filter one `list` based on another `list`. People quickly find that this:
```
[x for x in list_1 if x in list_2]
```
is slow for large inputs - it's O(n\*m). Yuck. How do we speed this up? Use a `set` to make filtering lookups O(1):
```
s = set(list_2)
[x for x in list_1 if x in s]
```
This gives nice overall O(n) behavior. I however often see even veteran coders fall into *The Trap*™:
```
[x for x in list_1 if x in set(list_2)]
```
Ack! This is again O(n\*m) since python builds `set(list_2)` *every* time, not just once.
---
I thought that was the end of the story - python can't optimize it away to only build the `set` once. Just be aware of the pitfall. Gotta live with it. Hmm.
```
#python 3.3.2+
list_2 = list(range(20)) #small for demonstration purposes
s = set(list_2)
list_1 = list(range(100000))
def f():
return [x for x in list_1 if x in s]
def g():
return [x for x in list_1 if x in set(list_2)]
def h():
return [x for x in list_1 if x in {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19}]
%timeit f()
100 loops, best of 3: 7.31 ms per loop
%timeit g()
10 loops, best of 3: 77.4 ms per loop
%timeit h()
100 loops, best of 3: 6.66 ms per loop
```
Huh, python (3.3) *can* optimize away a set literal. It's even faster than `f()` in this case, presumably because it gets to replace a `LOAD_GLOBAL` with a `LOAD_FAST`.
```
#python 2.7.5+
%timeit h()
10 loops, best of 3: 72.5 ms per loop
```
Python 2 notably doesn't do this optimization. I've tried investigating further what python3 is doing but unfortunately `dis.dis` cannot probe the innards of comprehension expressions. Basically everything interesting turns into `MAKE_FUNCTION`.
So now I'm wondering - why can python 3.x optimize away the set literal to only build once, but not `set(list_2)`? | 2013/11/18 | [
"https://Stackoverflow.com/questions/20056458",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2581969/"
] | In order to optimize `set(list_2)`, the interpreter needs to prove that `list_2` (and all of its elements) does not change between iterations. This is a hard problem in the general case, and it would not surprise me if the interpreter does not even attempt to tackle it.
On the other hand a set literal cannot change its value between iterations, so the optimization is known to be safe. | The basic reason is that a literal really can't change, whereas if it's an expression like `set(list_2)`, it's possible that evaluating the target expression or the iterable of the comprehension could change the value of `set(list_2)`. For instance, if you have
```
[f(x) for x in list_1 if x in set(list_2)]
```
It is possible that `f` modifies `list_2`.
Even for a simple `[x for x in blah ...]` expression, it's theoretically possible that the `__iter__` method of `blah` could modify `list_2`.
I would imagine there is some scope for optimizations, but the current behavior keeps things simpler. If you start adding optimizations for things like "it is only evaluated once if the target expression is a single bare name and the iterable is a builtin list or dict..." you make it much more complicated to figure out what will happen in any given situation. |
51,906,882 | Consider **abc.com** is my main website using nameservers **ns1.testnameserver.com** & **ns2.testnameserver.com**.
I would like to redirect multiple domains as below:
```
def.com to abc.com/products/def
ghi.com to abc.com/products/ghi
jkl.com to abc.com/products/jkl
mno.com to abc.com/products/mno
```
*I tried the below:*
i set the same testnameserver for def.com,ghi.com,jkl.com,mno.com.
tried some combination in **RewriteCond** and **.htaccess** but i couldn't solve it.
Anyone guide me to move further.
Thanks all.
Note:
I can't use domain forwarding / host all the domains because it's should be dynamic (like 3500+ domains to 3500+ products) | 2018/08/18 | [
"https://Stackoverflow.com/questions/51906882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/755084/"
] | The `DataColumn` class doesn't have an `Item` property. If you want to iterate through the items of the 8th row, you can do so using the `ItemArray` property of the DataRow:
```
For Each item In myDataTable.Rows(7).ItemArray
MessageBox.Show(item.ToString)
Next
``` | ```
Dim dt As New DataTable()
Dim eightRow = dt.Rows(7)
For x = 0 To dt.Columns.Count - 1
MessageBox.Show(eightRow(x).ToString())
Next
``` |
3,447,545 | What's the easiest way to get a string with the value of "76.10" into an int rounded to 76?
I've tried a few different ways using Convert.ToInt32 and Decimal but I can't seem to get it right?
Edit: Here's the code Jon helped me with:
```
decimal t = Math.Round(decimal.Parse(info.HDDStatus));
int v = (int)t;
``` | 2010/08/10 | [
"https://Stackoverflow.com/questions/3447545",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/218638/"
] | The simplest way would be to use `Decimal.Parse` to parse it, and then [`Math.Round`](http://msdn.microsoft.com/en-us/library/aa340225.aspx) (or potentially [`Math.Floor`](http://msdn.microsoft.com/en-us/library/k7ycc7xh.aspx) depending on how you want numbers like "76.7" to be handled) to round it. *Then* convert to an integer just by casting.
I would suggest using `decimal` rather than `double` as you're inherently talking about a *decimal* number (as that's how it's represented in text).
The exact method of parsing will depend on culture - would you expect text of "76,10" to appear in a European context, or will it always use "." as the decimal point, for example? | 1. Convert it to double first and use Math.Floor()
2. Extract the substring (76) first .
```
string s = "76.7";
int n = int.Parse(s.Substring(0, s.IndexOf('.')));
``` |
4,270,657 | I was wonder is a there a web service or a database out there that let us programmatically check if the user input is an valid ISBN number before storing it in the database. Or is there a algorithm that allow the programmer to do that | 2010/11/24 | [
"https://Stackoverflow.com/questions/4270657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/240337/"
] | [Gory details](http://isbntools.com/details.html) here. So you can check the check digit and have a go at deducing what the country (and maybe publisher) are, but I don't see any way of checking there's a real book with that number | As others have suggested in my quick searches on SO try: [idbndb](http://isbndb.com/docs/api/index.html) |
56,814,489 | Following some tutorials, on Windows 7, I installed the Heroku CLI (first Git, then Heroku-x64). Git has several options to select during installation, I kept it default for most of them, except the editor and the interface: my choice is mintty. In mintty I changed my Git username and email.
After installing Heroku-x64, mintty still does not support the `heroku` command. And there's nothing to run in Heroku-x64's folder, so I use system's `cmd.exe` instead, and it supports the `heroku` command.
Now, following tutorials, I run `heroku container:login`, several seconds later it says
```
! not logged in
```
Shouldn't it ask me to input my Heroku username and password? | 2019/06/29 | [
"https://Stackoverflow.com/questions/56814489",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2650501/"
] | Ensure you are logged in on your Heroku CLI first:
```
heroku auth:login
```
Then you can login to your Heroku container registry:
```
heroku container:login
```
Running heroku/7.47.\* on Ubuntu 20+ (WSL) might require `sudo` for both commands listed above.
Before all these, I installed `gnupg2` and `pass`, following the answer here [Cannot login to Docker account](https://stackoverflow.com/questions/50151833/cannot-login-to-docker-account) by [Anish Varghese](https://stackoverflow.com/users/8516780/anish-varghese) | I had problem login with the other methods, but this worked fine:
```
docker login --username=_ --password=$(heroku auth:token) registry.heroku.com
``` |
18,083 | I read the result that every compact $n$-manifold is
a compactification of $\mathbb{R}^n$.
Now, for surfaces, this seems clear: we take
an n-gon, whose interior (i.e., everything in
the n-gon except for the edges) is homeo. to $\mathbb{R}^n$,
and then we identify the edges to end up with
a surface that is closed and bounded.
We can do something similar with the $S^n$'s ; by
using a "1-gon" (an n-disk), and identifying
the boundary to a point. Or we can just use the
stereo projection to show that $S^n-\{{\rm pt}\}\sim\mathbb{R}^n$;
$S^n$ being compact (as the Alexandroff 1-pt. -compactification
of $\mathbb{R}^n$, i.e., usual open sets + complements of compact subsets of
$\mathbb{R}^n$). And then some messy work helps
us show that $\mathbb{R}^n$ is densely embedded in $S^n$.
But I don't see how we can generalize this statement
for any compact n-manifold. Can someone suggest any
ideas?
Thanks in Advance. | 2011/01/19 | [
"https://math.stackexchange.com/questions/18083",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/6008/"
] | Assuming $M$ is a *differentiable* manifold, this can be shown by choosing normal coordinates about any point $P\in M$. The following is expanding on the method suggested by Jason DeVito in the comments.
Putting a metric on the manifold, we can define the exponential map $\exp\_P\colon T\_PM\to M$ and then, choosing an orthonormal basis $e\_1,\ldots,e\_n$ for $T\_PM$, we get a map
$$
\begin{align}
f\colon\mathbb{R}^n&\to M,\\
(x^1,\ldots,x^n)&\mapsto\exp\_P(x^ie\_i)
\end{align}
$$
(using the summation convention). As the manifold is compact, this is an onto mapping (only completeness is required). The idea, then, is that there is a [circled](http://en.wikipedia.org/w/index.php?title=Balanced_set&oldid=392602385) open subset $U\subseteq\mathbb{R}^n$ on which this becomes a coordinate map with dense image. That $U$ is circled (aka balanced) means that the line segment joining any point $x\in U$ to the origin is in $U$. It can be seen that any circled open set is diffeomorphic to $\mathbb{R}^n$ (also see [star domain](http://en.wikipedia.org/w/index.php?title=Star_domain&oldid=392602248)).
Let $D$ be the set of $x\in\mathbb{R}^n$ such that $[0,1]\to M$, $t\mapsto f(tx)$ is a minimizing geodesic. Equivalently, $D$ is the set of $x\in\mathbb{R}^n$ with $d(P,f(x))=\Vert x\Vert$, from which we see that it is closed. Also, let $U$ be the interior of $D$. The set $\partial D\equiv D\setminus U$ is called the [cut locus](http://en.wikipedia.org/w/index.php?title=Cut_locus_%28Riemannian_manifold%29&oldid=370670320) (more precisely, the cut locus is the subset of $T\_PM$ corresponding to $\partial D$).
Fixing some $x\in\mathbb{R}^n\setminus\{0\}$, let us consider the line $t\mapsto f(tx)$ for $t\ge0$. Define $r > 0$ to be the maximum real number with $rx\in D$. For any $0 < r\_0 < r$, we can show the following.
1. On $[0,r\_0]$, $t\mapsto f(tx)$ is the *unique* minimizing geodesic joining $P$ to $f(r\_0x)$.
2. The derivative of $f$ at $r\_0x$ is invertible, so $f$ is nonsingular at $r\_0x$.
3. $r\_0x$ is in $U$.
4. $f(D)=M$ and $f(\partial D)\subseteq M$ has zero measure.
Property (3) implies that $U$ is circled, so it is diffeomorphic to $\mathbb{R}^n$. Property (1) says that $f$ is one-to-one on $U$ and, by (2), it is a diffeomorphism. Then, by (4), $f(U)\supseteq M\setminus f(\partial D)$ is dense, so $f$ gives a diffeomorphism from $U$ to a dense subset of $M$.
I'll give proofs of these statements now, although they do seem quite standard. See also [these notes](http://www.google.co.uk/url?sa=t&source=web&cd=12&ved=0CBsQFjABOAo&url=http%3A%2F%2Fwww.math.zju.edu.cn%2Fswm%2FRG_Section_5.pdf&rct=j&q=exponential%20map%20cut%20locus&ei=vDo6TY_9GMyxhAeyvJHkCg&usg=AFQjCNE8XiGGsLnDCTDP4EUhosaxHSCnNg&cad=rja) and, in particular, Lemma 5.3 for the proofs of (1) and (2) and Lemma 5.4 for the proof of (4).
Proof of (1): Consider a minimizing geodesic $\gamma\colon[0,r\_0]\to M$ joining P to $f(r\_0x)$, which will have length no more than $r\_0\Vert x\Vert$. Then, we can extend $\gamma(t)$ to $r\_0\le t\le r$ by setting $\gamma(t)=f(tx)$. As this curve joins $P$ to $f(rx)$ and is of length no more than $r\Vert x\Vert$, it must be a geodesic. So, $\gamma(t)=f(tx)$ for all $t\le r$, and $t\mapsto f(tx)$ is a unique minimizing geodesic on $[0,r\_0]$.
Proof of (2): Choose a nonzero $y\in\mathbb{R}^n$ and consider the vector field $t\mapsto Y\_t$ given by $Y\_t=t\nabla\_y f(tx)=\frac{\partial}{\partial s}f(t(x+sy))\vert\_{s=0}$. By geodesic deviation, this is a [Jacobi field](http://en.wikipedia.org/w/index.php?title=Jacobi_field&oldid=385149512). Also, $Y\_0=0$ so, if $\nabla\_yf(tx)$ was zero, $P$ and $f(r\_0x)$ would be conjugate points along $t\mapsto f(tx)$. Then, it is a standard result that $t\mapsto f(tx)$ is *not* a minimizing geodesic on $[0,r]$ for any $r > r\_0$ (see [characterization of the cut locus](http://en.wikipedia.org/w/index.php?title=Cut_locus_%28Riemannian_manifold%29&oldid=370670320#Characterization)), contradicting the choice of $r$. So, $\nabla\_yf(r\_0x)\not=0$, and $f$ is nonsingular at $r\_0x$.
Proof of (3): If not, then there would be a sequence $x\_i\not\in D$ tending to $r\_0x$. By the definition of $D$, there exist $y\_i\in\mathbb{R}^n$ with $f(y\_i)=f(x\_i)$ and $\Vert y\_i\Vert < \Vert x\_i\Vert$. Passing to a subsequence, we can suppose that $y\_i$ tends to a limit $y$. So, by continuity, $\Vert y\Vert\le r\_0\Vert x\Vert$ and $f(y)=f(r\_0x)$. By (1), this means that $y=r\_0x$. But, then, setting $a\_i=\Vert y\_i-x\_i\Vert$, (2) contradicts the limit $\nabla\_{(y\_i-x\_i)/a\_i}f(r\_0x)\sim (f(y\_i)-f(x\_i))/a\_i=0$.
Proof of (4): By completeness, for any $Q\in M$, there is at least one minimizing geodesic joining $P$ to $Q$. So, $f(x)=Q$ for some $x\in D$, and $f(D)=M$. Next, (3) implies that, for any $x\in\mathbb{R}^n\setminus\{0\}$, the radial line $t\mapsto tx$ ($t\ge0$) intersects $\partial D$ at a single point. This means that $\partial D$ has zero measure. As $f$ is locally Lipschitz, it maps zero measure sets to zero measure sets, so $f(\partial D)$ has zero measure.
Finally, I'll admit that the details are a bit trickier than I initially thought when I commented that the method can be made to work "without too much trouble". | My guess it that you could generalize your example of the n-gon to any triangulation (with higher simplices, instead of only triangles) of your manifold. Any manifold admits a triangulation. |
13,833,566 | I have the following code to create a container which pretends to behave like the set of all prime numbers (actually hides a memoised brute-force prime test)
```
import math
def is_prime(n):
if n == 2 or n == 3:
return True
if n == 1 or n % 2 == 0:
return False
else:
return all(n % i for i in xrange(3, int(1 + math.sqrt(n)), 2))
class Primes(object):
def __init__(self):
self.memo = {}
def __contains__(self, n):
if n not in self.memo:
self.memo[n] = is_prime(n)
return self.memo[n]
```
That seems to be working so far:
```
>>> primes = Primes()
>>> 7 in primes
True
>>> 104729 in primes
True
>>> 100 in primes
False
>>> 100 not in primes
True
```
But it's not playing nicely with `argparse`:
```
>>> import argparse as ap
>>> parser = ap.ArgumentParser()
>>> parser.add_argument('prime', type=int, choices=primes, metavar='p')
_StoreAction(option_strings=[], dest='prime', nargs=None, const=None, default=None, type=<type 'int'>, choices=<__main__.Primes object at 0x7f4e21783f10>, help=None, metavar='p')
>>> parser.parse_args(['7'])
Namespace(prime=7)
>>> parser.parse_args(['11'])
Namespace(prime=11)
>>> parser.parse_args(['12'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/argparse.py", line 1688, in parse_args
args, argv = self.parse_known_args(args, namespace)
File "/usr/lib/python2.7/argparse.py", line 1720, in parse_known_args
namespace, args = self._parse_known_args(args, namespace)
File "/usr/lib/python2.7/argparse.py", line 1929, in _parse_known_args
stop_index = consume_positionals(start_index)
File "/usr/lib/python2.7/argparse.py", line 1885, in consume_positionals
take_action(action, args)
File "/usr/lib/python2.7/argparse.py", line 1778, in take_action
argument_values = self._get_values(action, argument_strings)
File "/usr/lib/python2.7/argparse.py", line 2219, in _get_values
self._check_value(action, value)
File "/usr/lib/python2.7/argparse.py", line 2267, in _check_value
tup = value, ', '.join(map(repr, action.choices))
TypeError: argument 2 to map() must support iteration
```
The [docs](http://docs.python.org/dev/library/argparse.html#choices) just say that
>
> Any object that supports the in operator can be passed as the choices
> value, so dict objects, set objects, custom containers, etc. are all
> supported.
>
>
>
Obviously I don't want to iterate the infinite "set" of primes. So why the heck is `argparse` trying to `map` my primes? Doesn't it just need `in` and `not in`? | 2012/12/12 | [
"https://Stackoverflow.com/questions/13833566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/674039/"
] | It was a documentation bug. This was [issue16468](https://bugs.python.org/issue16468), fixed in August 2019 by [PR 15566](https://github.com/python/cpython/pull/15566/files).
The library as written requires the `choices` argument to be not just a container but also iterable, It tries to list the available options, which isn't going to work for your case. You could try to hack it by giving it a fake `__iter__` that just returns some informational string. | `choices` are for arguments that you can enumerate all allowed values (a finite (small) set). The docs should be more clear about it.
`primes` is an infinite set. You could set `type` parameter to raise ValueError for non-primes. |
246,512 | AlexNet architecture uses zero-paddings as shown in the pic. However, there is no explanation in the paper why this padding is introduced.
[](https://i.stack.imgur.com/oJVjf.png)
Standford CS 231n course teaches we use padding to preserve the spatial size:
[](https://i.stack.imgur.com/dtybe.png)
**I am curious if that is the only reason for zero padding?
Can anyone explain the rationale behind zero padding? Thanks!**
**Reason I am asking**
Let's say I don't need to preserve the spatial size. Can I just remove padding then w/o loss of performance? I know it results in very fast decrease in spatial size as we go to deeper layers, but I can trade-off that by removing pooling layers as well. | 2016/11/17 | [
"https://stats.stackexchange.com/questions/246512",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/96608/"
] | Elaborating on keeping information at the border, basically, the pixel at the corner (green shaded) when done convolution upon would just be used once whereas the one in the middle, like shaded red, would contribute to the resulting feature map multiple times.Thus, we pad the image See figure: [2](https://i.stack.imgur.com/08Y21.png). | I'll try to tell from the regard of information that when is it okay to pad and when it is not.
Let's for base case take the example of tensorflow padding functionality. It provides two scenarios, either "Valid" or "same". Same will preserve the size of the output and will keep it the same as that of the input by adding suitable padding, while valid won't do that and some people claim that it'll lead to loss of information, but, here's the catch.
This information loss depends on the size of the kernel or the filter you're using. For example, let's say you have a 28x28 image and the filter size is 15x15(let's say). The output should have dimension 16x16, but if you pad using "same" in tensorflow it will be 28x28. Now the 12 rows and 12 columns in themselves don't carry any meaningful information but are still there as a form of noise.
And we all know how much susceptible deep learning models are towards the noise. This can degrade the training a lot. So if you're using big filters, better not go with padding. |
53,938,761 | I've been working in a geodjango app to include a map for a search function in a spatial table, learning from tutorials, so far I know of a method to load serialized data in leaflet by creating a function based view assigning an url and importing that url as a GeoJSON.AJAX variable, I've been trying to change that method to then try to figure out a way to pass the data in my search function:
Views file:
```
def map_dide(request):
return render(request, 'b_dide_uv/map_did.html')
def info_uvs(request):
uv = serialize('geojson', D_uvs.objects.all())
return HttpResponse(uv, content_type='json')
```
Template:
```
function uvs(map,options){
var dataset = new L.GeoJSON.AJAX("{% url 'info_uvs' %}",{
});
dataset.addTo(map);
}
```
I've been trying to insert the serializing and passing it as context in the map\_dide function:
```
def map_dide(request):
uv = serialize('geojson', D_uvs.objects.all())
return render(request, 'b_dideco_uv/mapa_did.html', {'uv':uv})
```
but when I assign it in the javascript in the template it gives me an error, so far I tried:
```
var uv_data = JSON.parse('{{uv|safe}}')
function uvs(map,options){
var dataset = new L.GeoJSON.AJAX(uv_data,{
});
dataset.addTo(map);
}
```
but I got an "SyntaxError: missing ) after argument list" in the console
I also tried the L.geoJson, and the L.GeoJSON function but it the same result
what others methods to insert serialized data in a template are there?, besides a separated function, in the case of a search function I asume it needs to be inside the same function to pass the result of the query, but it seems javascript doesnt recognize this data
Thanks | 2018/12/27 | [
"https://Stackoverflow.com/questions/53938761",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8303509/"
] | **1. First of all let’s plug our smartphone to the USB port of our computer and get a list of the installed packages and their namespaces:**
```
adb shell pm list packages
```
**2. This will list all packages on your smartphone, once you’ve found the namespace of the package you want to reverse** (`com.android.systemui in` this example), **let’s see what its physical path is:**
```
adb shell pm path com.android.systemui
```
**3. Finally, we have the APK path:**
```
package:/system/priv-app/SystemUIGoogle/SystemUIGoogle.apk
```
**4. Let’s pull it from the device:**
```
adb pull /system/priv-app/SystemUIGoogle/SystemUIGoogle.apk
```
=====> And here you go, you have the APK! | Thanks for your Answers. Finally i solved this problem and like to share with you. The steps to Download APK from Emulator to Desktop are given as follows ...
```
1. check the package list
adb shell pm list packages
adb shell pm list packages -f -3
2. find actual path
adb shell pm path [your_package_path]
Example: adb shell pm path com.android.certinstaller
3. output should look like
{your_path}/[your_apk].apk
Example: system/app/CertInstaller/CertInstaller.apk
4. actual execution command
adb pull /data/app/[your_package_name]-1/[your_apk].apk [local download path]
Example: adb pull /data/app/io.crash.air-1/base.apk /Documents/APK/
``` |
566,396 | I need a word or phrase which can be used to describe someone or something challenging a general idea of belief. Here are some examples:
>
> They **challenge** the ethos of their particular eras and in turn, inflict personal and political change.
>
>
> In these sources, they investigate the intricacies of human interaction, and how the distribution of power can be altered through **challenging** the zeitgeists of the same country at two distinct points, one filled with racism and the latter with chaos.
>
>
>
I need terms to replace the word "challenge" in these examples. Any help will be strongly appreciated. | 2021/05/04 | [
"https://english.stackexchange.com/questions/566396",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/422276/"
] | "To contend *against*" is a close synonym.
>
> (SOED)**4** *v.i.* Argue (*with, against, etc.*)
>
>
>
They contend against the ethos of their particular eras and in turn, inflict personal and political change.
[Here](https://www.google.com/search?q=%22contend%20against%22&tbm=bks&tbs=cdr:1,cd_min:1909,cd_max:2008&lr=lang_en) can be perused plenty of examples; by doing so a truer feel of the term can be gained.
[A telling sample](https://www.google.fr/books/edition/Passages_for_Translation_Into_French_and/UgFKAQAAMAAJ?hl=en&gbpv=1&bsq=%22contend+against%22&dq=%22contend+against%22&printsec=frontcover) The classical student has only to contend against other students who are and have been situated very much as he is situated himself.
This can be worded as follows.
* The classical student has only to challenge other students who are and have been situated very much as he is situated himself. | I looked through the thesaurus, and two words you may find useful are ‘contest’ and ‘denounce’.
Contest carries the meaning of arguing and questioning, similar to challenge:
>
> to struggle or fight for, as in battle.
>
>
>
>
> to argue against; dispute:
> to contest a controversial question; to contest a will.
>
>
>
>
> to call in question:
> They contested his right to speak.
>
>
>
While Denounce has the feeling of ‘attacking’: *to condemn or censure openly or publicly*
Using these in your sample:
>
> They **contest** the ethos of their particular eras and in turn, inflict personal and political change.
>
>
>
>
> In these sources, they investigate the intricacies of human interaction, and how the distribution of power can be altered through **denouncing** the zeitgeists of the same country at two distinct points, one filled with racism and the latter with chaos.
>
>
> |
7,669,555 | Assume we have the following arrays:
```
a = [1, 2, 3, 4, 5]
```
and
```
b = [2, 3]
```
How can I subtract b from a? So that we have `c = a - b` which should be equal to `[1, 4, 5]`. jQuery solution would also be fine. | 2011/10/06 | [
"https://Stackoverflow.com/questions/7669555",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/407315/"
] | This is a modified version of the answer posted by @icktoofay.
In ES6 we can make use of:
* [`Array.prototype.contains()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes)
* [`Array.prototype.filter()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
* [`Arrow functions`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)
This will simplify our code to:
```
var c = a.filter(x => !b.includes(x));
```
**Demo:**
```js
var a = [1, 2, 3, 4, 5];
var b = [2, 3];
var c = a.filter(x => !b.includes(x));
console.log(c);
``` | Might be an outdated query but i thought this might be useful to someone.
```js
let first = [1,2,3,4,5,6,7,9];
let second = [2,4,6,8];
const difference = first.filter(item=>!second.includes(item));
console.log(difference);//[ 1, 3, 6,7]
/*
the above will not work for objects with properties
This might do the trick
*/
const firstObj = [{a:1,b:2},{a:3,b:4},{a:5,b:6},{a:7,b:8}]//not ideal. I know
const secondObj = [{a:3,b:4},{a:7,b:8}]
const objDiff = firstObj.filter(obj=>
!secondObj.find(sec=>//take note of the "!"
sec.a===obj.a
&&//or use || if you want to check for either or
sec.b===obj.b
)//this is formatted so that it is easily readable
);
console.log(objDiff)/*
[
{
"a": 1,
"b": 2
},
{
"a": 5,
"b": 6
}
]
*/
``` |
144,484 | Given the standard North American phone number format: (Area Code) Exchange - Subscriber, the set of possible numbers is about 6 billion. However, efficiently breaking down the nodes into the sections listed above would yield less than 12000 distinct nodes that can be arranged in groupings to get all the possible numbers.
This seems like a problem already solved.
Would it done via a graph or tree? | 2012/04/14 | [
"https://softwareengineering.stackexchange.com/questions/144484",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/42446/"
] | If you were doing this for ultimate memory efficency you could do better.
Start with the area code - I don't know how many are actually used but assuming you need to store all 3 digit values.
Presumably exchange codes are filled in order, so you would expect the lower ones to be used in more areas than the higher ones. So you could use a run-length coding to flag the sequences that are in use.
Finally actual phone numbers will be used or not at random so I would use a bit field to flag which of the 9999 possible last numbers are on. At one bit/number you need only 1K to store each set. | Graph isn't suitable for this, the implementation requires more memory than tree and it doesn't provide any additional features in this case.
Prefix trees? These are very efficient for search but memory representation isn't optimized for size. They're in fact very memory inefficient. They can also be used to compress data and write it to disk but memory representation takes much more memory than the data itself.
If you arrange by groups so only 3 last digits would be stored in the tree-like struct it'd be 3x4 + 1 bytes for each number anyway (3x4 byte pointer + 1 byte for data). ~78 GB just for 3 last digits of each number (if i remember the implementation details correctly). Which will require 64 bit pointers instead of 32b... so ~140GB of ram.
So the problem (in my opinion) is that for tree for each suffix in each group you still need at least one 32 bit pointer (which will probably turn out to be 64 bits because you'd need to allocate > 4GB for the data).
In my opinion most efficient way will be an array or 12000 pointers to structure like
```
char[x] prefix;
DWORD* suffixes;
int n_count;
```
so prefix, eg. 43333 suffix eg. `19821982 => number is 4333319821982` (n\_count -> count of numbers)
You store the numbers without separators to save space, one suffix after the other (eg. number 1 is suffixes+0, number 2 is suffixes+1) and you can search efficiently too, if you have it sorted.
This way it'd take just 4(DWORD)\*6 billion suffixes = 24GB of memory + size of 12k pointers + prefixes which is irrelevant
So instead of (at least!) 6 billion 64 bit pointers you'd just have (at most!) 6b of 32 bit suffixes.
But probably the numbers are continuous, so you can try array of (start\_suffix, end\_suffix) instead of just storing all suffixes should take much less. |
3,166,289 | I tried to upload my iPhone application to the App store, but received the following error: **The binary you uploaded was invalid. The icon file must be in .png format.**
The icon file IS in .png format, size 57x57, so assumed it is a bug and tried to upload with Application Uploader, when I got another error:
**Application failed codesign verification. The signature was invalid, or it was not signed with an Apple submission certificate.**
I followed every single step, and it is not working... it is driving me crazy! Please advise what should I do! | 2010/07/02 | [
"https://Stackoverflow.com/questions/3166289",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/351354/"
] | Many people were confusing (like me) modifying the code signing property of XCode.
You must ensure that your code signing identity property start with
**iPhone Distribution : Developer Name**
instead of
**iPhone Developer : Developer Name**
PS : If you have no option start with iPhone distribution, you didn't get production certificate yet. | Since you haven't mentioned anything regarding the fact that you did sign the code, I'm going to assume you didn't.
You'll need to get your application code signed in order for it to be accepted, so that the phone knows it's from a trusted developer, and not just a virus someone has uploaded.
Do you have a code signing certificate? |
3,322,627 | I have a long text that would not fit within the div it occupies. The div class is as follows:
```
.mydiv {
overflow:hidden;
padding:3px 3px 3px 5px;
white-space:nowrap;
}
```
Of course I can only see portion of text. The problem is that it shows first N characters and I want to show last N chars. How do I achieve it with CSS? `Text-align` doesn't help here. | 2010/07/23 | [
"https://Stackoverflow.com/questions/3322627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/135946/"
] | If you're able to wrap your text in another element, you can make it work as shown in [this fiddle](http://jsfiddle.net/9XbZ9/). I've floated a nested `<span>` to the right. | You can do it with just CSS:
<http://jsbin.com/ususu>
```
<div style="width: 150px; border: 1px solid red; overflow: hidden; position: relative; height: 2em;">
<div style="position: absolute; right: 0px; padding: .5em;white-space:nowrap;">
aaaaaaaaaaaabbbbbbbbbcccccccccccccccccddddddddddddddddddddeeeeeeeeeeeeeeeeeeeeffffffffffffffffffffgggggggggggggggggggghhhhhhhhhhhhhhhhiiiiiiiiiiiii
</div>
</div>
```
(tested in Firefox. YMMV) |
11,752,097 | I need to disable options with value "- Sold Out -" in a list of dynamic drop down menus. How can I do this easily with jQuery? Below is the HTML
```
<select id="field_0_1" class="text_select" name="field_0_1" onChange="">
<option value="">- Preferred Time -</option>
<option value="- Sold Out -">- Sold Out -</option>
<option value="2:30 - 4:00pm">2:30 - 4:00pm</option>
</select>
<select id="field_0_2" class="text_select" name="field_0_2" onChange="">
<option value="">- Preferred Time -</option>
<option value="- Sold Out -">- Sold Out -</option>
<option value="2:30 - 4:00pm">2:30 - 4:00pm</option>
</select>
<select id="field_0_3" class="text_select" name="field_0_3" onChange="">
<option value="">- Preferred Time -</option>
<option value="- Sold Out -">- Sold Out -</option>
<option value="2:30 - 4:00pm">2:30 - 4:00pm</option>
</select>
``` | 2012/08/01 | [
"https://Stackoverflow.com/questions/11752097",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1567428/"
] | ```
$("select option[value*='Sold Out']").prop('disabled',true);
```
**[Demo](http://jsfiddle.net/BYkVW/2/)**
### According to edit
```
$('#previous_select').on('change', function() {
// after creating the option
// try following
$("select option[value*='Sold Out']").prop('disabled',true);
});
``` | ```
$("#ddlList option[value='jquery']").attr("disabled","disabled");
``` |
29,306,958 | I have two columns in Bootstrap 3, one with a couple of images in it, the other with one big image. I want one column - the one with multiple images - to be partially overlapped the other, so one image overlaps the three other images. If I try this the big image gets moved either down or up. Is the a way to overlap these columns? it is impossible to put both images in the same column, due to the rest of the page.
Code:
```
<div class="col-md-6 col-md-offset-3">
<div class="col-md-4 col-md-pull-2">
<!-- three images -->
</div>
<div class="col-md-6">
<!-- bit image -->
</div>
<div class="col-md-6">
<!-- other bit image -->
</div>
</div>
```
Can anyone help me? | 2015/03/27 | [
"https://Stackoverflow.com/questions/29306958",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2969329/"
] | Please check if in the source code of the page where it's not working you have an element with `id="design-centre"` (probably an anchor `<a>`, often also used in conjunction with the `name` attribute). There probably will be none, but the homepage will have it. It's meant to be used as a kind of in-page navigation. Clicking a link that has a hash (`#`) at the end triggers the browser to look for an element with a corresponding `id`, and scroll the viewport so it's right on top. | As this is a dropdown. I don't think you need to add href to the anchor tag.
You can just keep a # inside the href.
This is the updated code,
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet"/>
<ul style="position:relative">
<li>
<a href="#" class="dropdown-toggle scroll"
data-toggle="dropdown" data-hover="dropdown">
Design Centre <i class="fa fa-angle-down"></i>
</a>
<ul class="menulist dropdown-menu">
<li><a href="/preview/#design-centre">Overview</a></li>
<li><a href="/preview/design-centre.php?action=video-testimonials">Video Testimonials</a></li>
<li><a href="/preview/design-centre.php?action=meet-the-team">Meet The Team</a></li>
<li><a href="/preview/design-centre.php?action=faq">FAQ</a></li>
<li><a href="/preview/design-centre.php?action=contact-us">Contact Us</a></li>
</ul>
</li></ul>
``` |
70,703,813 | I have a table with daily data by hour. I want to get a table with only one row per day. That row should have the max value for the column AforoTotal.
This is a part of the table, containing the records of three days.
| FechaHora | Fecha | Hora | AforoTotal |
| --- | --- | --- | --- |
| 2022-01-13T16:00:00Z | 2022-01-13 | 16:00:00 | 4532 |
| 2022-01-13T15:00:00Z | 2022-01-13 | 15:00:00 | 4419 |
| 2022-01-13T14:00:00Z | 2022-01-13 | 14:00:00 | 4181 |
| 2022-01-13T13:00:00Z | 2022-01-13 | 13:00:00 | 3914 |
| 2022-01-13T12:00:00Z | 2022-01-13 | 12:00:00 | 3694 |
| 2022-01-13T11:00:00Z | 2022-01-13 | 11:00:00 | 3268 |
| 2022-01-13T10:00:00Z | 2022-01-13 | 10:00:00 | 2869 |
| 2022-01-13T09:00:00Z | 2022-01-13 | 09:00:00 | 2065 |
| 2022-01-13T08:00:00Z | 2022-01-13 | 08:00:00 | 1308 |
| 2022-01-13T07:00:00Z | 2022-01-13 | 07:00:00 | 730 |
| 2022-01-13T06:00:00Z | 2022-01-13 | 06:00:00 | 251 |
| 2022-01-13T05:00:00Z | 2022-01-13 | 05:00:00 | 95 |
| 2022-01-13T04:00:00Z | 2022-01-13 | 04:00:00 | 44 |
| 2022-01-13T03:00:00Z | 2022-01-13 | 03:00:00 | 35 |
| 2022-01-13T02:00:00Z | 2022-01-13 | 02:00:00 | 28 |
| 2022-01-13T01:00:00Z | 2022-01-13 | 01:00:00 | 6 |
| 2022-01-13T00:00:00Z | 2022-01-13 | 00:00:00 | -18 |
| 2022-01-12T23:00:00Z | 2022-01-12 | 23:00:00 | 1800 |
| 2022-01-12T22:00:00Z | 2022-01-12 | 22:00:00 | 2042 |
| 2022-01-12T21:00:00Z | 2022-01-12 | 21:00:00 | 2358 |
| 2022-01-12T20:00:00Z | 2022-01-12 | 20:00:00 | 2827 |
| 2022-01-12T19:00:00Z | 2022-01-12 | 19:00:00 | 3681 |
| 2022-01-12T18:00:00Z | 2022-01-12 | 18:00:00 | 4306 |
| 2022-01-12T17:00:00Z | 2022-01-12 | 17:00:00 | 4377 |
| 2022-01-12T16:00:00Z | 2022-01-12 | 16:00:00 | 4428 |
| 2022-01-12T15:00:00Z | 2022-01-12 | 15:00:00 | 4424 |
| 2022-01-12T14:00:00Z | 2022-01-12 | 14:00:00 | 4010 |
| 2022-01-12T13:00:00Z | 2022-01-12 | 13:00:00 | 3826 |
| 2022-01-12T12:00:00Z | 2022-01-12 | 12:00:00 | 3582 |
| 2022-01-12T11:00:00Z | 2022-01-12 | 11:00:00 | 3323 |
| 2022-01-12T10:00:00Z | 2022-01-12 | 10:00:00 | 2805 |
| 2022-01-12T09:00:00Z | 2022-01-12 | 09:00:00 | 2159 |
| 2022-01-12T08:00:00Z | 2022-01-12 | 08:00:00 | 1378 |
| 2022-01-12T07:00:00Z | 2022-01-12 | 07:00:00 | 790 |
| 2022-01-12T06:00:00Z | 2022-01-12 | 06:00:00 | 317 |
| 2022-01-12T05:00:00Z | 2022-01-12 | 05:00:00 | 160 |
| 2022-01-12T04:00:00Z | 2022-01-12 | 04:00:00 | 106 |
| 2022-01-12T03:00:00Z | 2022-01-12 | 03:00:00 | 95 |
| 2022-01-12T02:00:00Z | 2022-01-12 | 02:00:00 | 86 |
| 2022-01-12T01:00:00Z | 2022-01-12 | 01:00:00 | 39 |
| 2022-01-12T00:00:00Z | 2022-01-12 | 00:00:00 | 0 |
| 2022-01-11T23:00:00Z | 2022-01-11 | 23:00:00 | 2032 |
| 2022-01-11T22:00:00Z | 2022-01-11 | 22:00:00 | 2109 |
| 2022-01-11T21:00:00Z | 2022-01-11 | 21:00:00 | 2362 |
| 2022-01-11T20:00:00Z | 2022-01-11 | 20:00:00 | 2866 |
| 2022-01-11T19:00:00Z | 2022-01-11 | 19:00:00 | 3948 |
| 2022-01-11T18:00:00Z | 2022-01-11 | 18:00:00 | 4532 |
| 2022-01-11T17:00:00Z | 2022-01-11 | 17:00:00 | 4590 |
| 2022-01-11T16:00:00Z | 2022-01-11 | 16:00:00 | 4821 |
| 2022-01-11T15:00:00Z | 2022-01-11 | 15:00:00 | 4770 |
| 2022-01-11T14:00:00Z | 2022-01-11 | 14:00:00 | 4405 |
| 2022-01-11T13:00:00Z | 2022-01-11 | 13:00:00 | 4040 |
| 2022-01-11T12:00:00Z | 2022-01-11 | 12:00:00 | 3847 |
| 2022-01-11T11:00:00Z | 2022-01-11 | 11:00:00 | 3414 |
| 2022-01-11T10:00:00Z | 2022-01-11 | 10:00:00 | 2940 |
| 2022-01-11T09:00:00Z | 2022-01-11 | 09:00:00 | 2105 |
| 2022-01-11T08:00:00Z | 2022-01-11 | 08:00:00 | 1353 |
| 2022-01-11T07:00:00Z | 2022-01-11 | 07:00:00 | 739 |
| 2022-01-11T06:00:00Z | 2022-01-11 | 06:00:00 | 248 |
| 2022-01-11T05:00:00Z | 2022-01-11 | 05:00:00 | 91 |
| 2022-01-11T04:00:00Z | 2022-01-11 | 04:00:00 | 63 |
| 2022-01-11T03:00:00Z | 2022-01-11 | 03:00:00 | 46 |
| 2022-01-11T02:00:00Z | 2022-01-11 | 02:00:00 | 42 |
| 2022-01-11T01:00:00Z | 2022-01-11 | 01:00:00 | 18 |
| 2022-01-11T00:00:00Z | 2022-01-11 | 00:00:00 | 5 |
My expected result is:
| FechaHora | Fecha | Hora | AforoTotal |
| --- | --- | --- | --- |
| 2022-01-13T16:00:00Z | 2022-01-13 | 16:00:00 | 4532 |
| 2022-01-12T16:00:00Z | 2022-01-12 | 16:00:00 | 4428 |
| 2022-01-11T17:00:00Z | 2022-01-11 | 17:00:00 | 4590 | | 2022/01/13 | [
"https://Stackoverflow.com/questions/70703813",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16167671/"
] | Another way which is little bit costly:
It will be working when (Fetcha and max(AforoTotal)) combination is unique.
In given example, I find it is unique.
```
SELECT * FROM your_table
WHERE Fecha||AforoTotal
IN
(SELECT Fecha||MAX( AforoTotal ) FROM your_table GROUP BY Fecha);
[Output]
https://i.stack.imgur.com/IFzWA.jpg
``` | thanks for your approach. This can be saved as a view in BigQuery and I can use it in DataStudio. I have not tested what happens when the combination is not unique, I will see how it behaves. |
245,428 | How to know the pid of active (focused) window?
I want to write a script in which it is necessary to know whether the user is actively using a program [browsing internet with somthing say firefox] or doing something else [writing text with something say gedit]
In my case i want to download big files but don't want to hurt browsering speed. so when i browse the active window is of firefox and i want to stop downloading. When i read pdf active window is of pdf reader and i want to resume download. That's it. | 2013/01/20 | [
"https://askubuntu.com/questions/245428",
"https://askubuntu.com",
"https://askubuntu.com/users/123897/"
] | bash
```bsh
xdotool getwindowpid `xdotool getactivewindow`
```
fish
```
xdotool getwindowpid (xdotool getactivewindow)
``` | You can install wmctrl then use it to list all windows, `wmctrl -l`. |
74,924 | I created this script to take informations "at-the-moment" of [this site](http://www.programme-tv.net/programme/toutes-les-chaines/en-ce-moment.html#Grandes%20cha%C3%AEnes):
```
Pictures of name channel
Name of channel
Pictures channel
Times
Title
Type
```
My script (Work):
```
<?php
$url="http://www.programme-tv.net/programme/toutes-les-chaines/en-ce-moment.html#Grandes%20cha%C3%AEnes";
$code_page = file_get_contents($url);
preg_match_all('/<div class="channelItem">(.*?)<img src="(.*?)" alt="Le programme de (.*?)" width="70" height="30">/is', $code_page, $chaines);
preg_match_all('/<div class="show (.*?) at-the-moment current (.*?)">(.*?)<div class="show-infos">(.*?)<\/div>/is', $code_page, $channels);
$i=0;
foreach ($channels as $channel) {
if($i==3){
for ($j=0; $j < 38; $j++) {
preg_match_all('/<span class="(.*?)"><img src="http:\/\/static.programme-tv.net\/var\/epgs\/169\/80x\/(.*?)" alt="(.*?)" width="80" \/><\/span>/', $channel[$j], $image[$j]);
}
}
if($i==4){
for ($j=0; $j < 38; $j++) {
preg_match_all('/<p class="time">(.*?)<\/p>/', $channel[$j], $time[$j]);
preg_match_all('/<p class="title">(.*?)<\/p>/', $channel[$j], $title[$j]);
preg_match_all('/<p class="type">(.*?)<\/p>/', $channel[$j], $type[$j]);
}
}
$i++;
}
for ($i=0; $i < 38; $i++) {
$test = strpos($chaines[2][$i],' </div>');
if($test != true){
echo 'Chaines images: <img src="'.$chaines[2][$i].'"/><br />';
echo 'Chaines: '.$chaines[3][$i].'<br />';
echo 'image : <img src="http://static.programme-tv.net/var/epgs/169/80x/'.$image[$i][2][0].'" /><br />';
echo 'Temps : '.trim($time[$i][1][0]).'<br />';
echo 'Titre : '.substr($title[$i][1][0], strpos($title[$i][1][0], '>') + 1, strrpos($title[$i][1][0], '<')).'<br />';
echo 'Type : '.$type[$i][1][0].'<br />';
echo '<hr>';
}
}
?>
```
I would like to improve and find a better regular expression pattern because I use 6 regular expression pattern. | 2014/12/26 | [
"https://codereview.stackexchange.com/questions/74924",
"https://codereview.stackexchange.com",
"https://codereview.stackexchange.com/users/61885/"
] | To be honest I don't think your current way of handling is 'clean'.
But I would suggest you to use a HTML DOM parser. I took the liberty to google it for you and <http://simplehtmldom.sourceforge.net/> seems quite what you need.
It's a PHP HTML parser, which allows you to write
```
// Find all element which class=foo
$ret = $html->find('.at-the-moment');
```
instead of
```
preg_match_all('/<div class="show (.*?) at-the-moment current (.*?)">(.*?)<div class="show-infos">(.*?)<\/div>/is', $code_page, $channels);
```
Also your other regexes can be switched (read the documentation)
To be honest, I never used this library before, but I've worked with beautifulsoup which is a Python equivalent, which would do the trick for you perfectly.
(source: <http://www.givegoodweb.com/post/210/html-parser-for-php>)
Wishing you the best! | ### Don't parse HTML with regular expressions
First of all, [don't parse HTML with regular expressions](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454).
Second of all, [don't parse HTML with regular expressions](https://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/1732454#1732454).
### Indentation
Pay attention to correct indentation, for example in this code:
>
>
> ```
> foreach ($channels as $channel) {
> if($i==3){
> // ...
> }
>
> if($i==4){
>
> ```
>
>
The indent level if this last `if` statement is unexpected.
It gives the impression that it's outside of the `foreach` loop,
but no it's still inside. Be careful,
this kind of thing can seriously hurt readability.
### Using an alternative pattern separator instead of `///`
You could simplify many of your patterns by using a different separator instead of `/`, for example `|`:
```
preg_match_all('|<span class="(.*?)"><img src="http://static.programme-tv.net/var/epgs/169/80x/(.*?)" alt="(.*?)" width="80" /></span>|', $channel[$j], $image[$j]);
```
This way you don't need to escape so many embedded `/`, which is a lot easier on the eyes too.
### Readability
I recommend to borrow from the formatting conventions of other languages and put spaces around operators and parentheses. Instead of this:
>
>
> ```
> if($i==4){
>
> ```
>
>
Write like this:
```
if ($i == 4) {
```
### Conditions on boolean expressions
When working with boolean values, you don't need the `==` or `!=` operators,
you can use the boolean values directly. Instead of this:
>
>
> ```
> if($test != true){
>
> ```
>
>
You can write simply:
```
if (!$test) {
``` |
186,185 | The Apple Watch Activity allows for setting an overall "Move" goal, but I don't see how to change the green "Exercise" goal from the default 30 minutes. Is there a way to accomplish this? | 2015/05/07 | [
"https://apple.stackexchange.com/questions/186185",
"https://apple.stackexchange.com",
"https://apple.stackexchange.com/users/4395/"
] | You aren't limited to one time around the ring in the Activity app. You get a double arrow for 1 hour of exercise, for example. You also receive awards for doubling or tripling the exercise ring.
You can use the Workout app to set whatever exercise goal you like. And you get a custom ring to fill in that app, based on target calories, distance, or time. | watchOS 7 enables changing the green Exercise Goal.
>
> Apple Watch > Activity app > Scroll to Bottom > Change Goals
>
>
>
[](https://i.stack.imgur.com/K2zNR.png)
* <https://kirkville.com/change-activity-goals-on-the-apple-watch-in-watchos-7/>
* <https://daringfireball.net/linked/2020/09/24/mcelhearn-watchos-7-goals> |
941,237 | I have just installed 16.04 on my [HP-149tx](https://support.hp.com/in-en/product/hp-15-ac100-notebook-pc-series/8499326/model/8960419/drivers) alongside Windows. I am unable to access the Wifi from Ubuntu. The signal is too weak even if I hold the laptop close to the router.I can confirm this is a driver issue since I have flawless access to my Wifi from Windows.
What I did to try and rectify this issue is try to download and install the wifi drivers as per instructions specified over [here](https://askubuntu.com/a/635629/628460). The problem I get when installing the driver is as follows-:
```
(Reading database ... 174937 files and directories currently installed.)
Preparing to unpack rtlwifi-new-dkms_0.10_all.deb ...
------------------------------
Deleting module version: 0.10
completely from the DKMS tree.
------------------------------
Done.
Unpacking rtlwifi-new-dkms (0.10) over (0.10) ...
Setting up rtlwifi-new-dkms (0.10) ...
Loading new rtlwifi-new-0.10 DKMS files...
First Installation: checking all kernels...
Building only for 4.8.0-36-generic
Building for architecture x86_64
Building initial module for 4.8.0-36-generic
Error! Bad return status for module build on kernel: 4.8.0-36-generic (x86_64)
Consult /var/lib/dkms/rtlwifi-new/0.10/build/make.log for more information.
```
Also the contents of make.log is as follows-:
```
DKMS make.log for rtlwifi-new-0.10 for kernel 4.8.0-36-generic (x86_64)
Sun Jul 30 17:10:27 IST 2017
make: Entering directory '/usr/src/linux-headers-4.8.0-36-generic'
LD /var/lib/dkms/rtlwifi-new/0.10/build/built-in.o
CC [M] /var/lib/dkms/rtlwifi-new/0.10/build/base.o
In file included from /var/lib/dkms/rtlwifi-new/0.10/build/base.c:30:0:
/var/lib/dkms/rtlwifi-new/0.10/build/wifi.h:1327:40: error: ‘IEEE80211_NUM_BANDS’ undeclared here (not in a function)
struct ieee80211_supported_band bands[IEEE80211_NUM_BANDS];
^
/var/lib/dkms/rtlwifi-new/0.10/build/base.c:138:10: error: ‘IEEE80211_BAND_2GHZ’ undeclared here (not in a function)
.band = IEEE80211_BAND_2GHZ,
^
/var/lib/dkms/rtlwifi-new/0.10/build/base.c:150:10: error: ‘IEEE80211_BAND_5GHZ’ undeclared here (not in a function)
.band = IEEE80211_BAND_5GHZ,
^
scripts/Makefile.build:289: recipe for target '/var/lib/dkms/rtlwifi-new/0.10/build/base.o' failed
make[1]: *** [/var/lib/dkms/rtlwifi-new/0.10/build/base.o] Error 1
Makefile:1491: recipe for target '_module_/var/lib/dkms/rtlwifi-new/0.10/build' failed
make: *** [_module_/var/lib/dkms/rtlwifi-new/0.10/build] Error 2
make: Leaving directory '/usr/src/linux-headers-4.8.0-36-generic'
```
I can confirm that my wifi lan card is a Realtek RTL8723BE device since that is what my Windows OS recognizes it as and I have installed the Windows equivalent driver for it and it working fine there.
The output from modinfo rtl8723be is as follows-:
```
alex@alex-HP-Notebook:~/Desktop/rtlwifi_new-master$ modinfo rtl8723be
filename: /lib/modules/4.8.0-36-generic/kernel/drivers/net/wireless/realtek/rtlwifi/rtl8723be/rtl8723be.ko
firmware: rtlwifi/rtl8723befw.bin
description: Realtek 8723BE 802.11n PCI wireless
license: GPL
author: Realtek WlanFAE <wlanfae@realtek.com>
author: PageHe <page_he@realsil.com.cn>
srcversion: 1520FD8B69687790125304A
alias: pci:v000010ECd0000B723sv*sd*bc*sc*i*
depends: rtlwifi,rtl8723-common,rtl_pci,btcoexist,mac80211
intree: Y
vermagic: 4.8.0-36-generic SMP mod_unload modversions
parm: swenc:Set to 1 for software crypto (default 0)
(bool)
parm: ips:Set to 0 to not use link power save (default 1)
(bool)
parm: swlps:Set to 1 to use SW control power save (default 0)
(bool)
parm: fwlps:Set to 1 to use FW control power save (default 1)
(bool)
parm: msi:Set to 1 to use MSI interrupts mode (default 0)
(bool)
parm: debug:Set debug level (0-5) (default 0) (int)
parm: disable_watchdog:Set to 1 to disable the watchdog (default 0)
(bool)
parm: ant_sel:Set to 1 or 2 to force antenna number (default 0)
```
Also my router is configured with the following parameters-:
```
Wireless Band: 2.4 GHz
802.11 Mode: Mixed 802.11n, 802.11g, 802.11b
Auto Channel Scan enabled
Wireless Channel : 2.437 GHz - CH 6
Channel Width: Auto 20/40 MHz
``` | 2017/07/30 | [
"https://askubuntu.com/questions/941237",
"https://askubuntu.com",
"https://askubuntu.com/users/628460/"
] | Quite often, the weak signal is a symptom of the antenna wire being connected to connection #1 on the card when the default driver is expecting to see the signal at connection #2. Of course, you could open the laptop and switch the wire or you could instruct the driver to explicitly select the working antenna connection. First, try connection #1:
```
sudo -i
echo "options rtl8723be ant_sel=1" > /etc/modprobe.d/rtl8723be.conf
exit
```
Reboot and test. If this is ineffective, try #2:
```
sudo -i
echo "options rtl8723be ant_sel=2" > /etc/modprobe.d/rtl8723be.conf
exit
``` | Have you checked your wifi signal strength? I suggest you to use wifi scanner <https://www.netspotapp.com/wireless-network-wifi-scanner.html> to monitor your network and identify problem areas first. I think the problem can be in the level of background noise at your house. |
4,710,491 | Is it mandatory to write `$(document).ready(function () {... })` every time ?
Can't we do it without this line? | 2011/01/17 | [
"https://Stackoverflow.com/questions/4710491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/412982/"
] | The reason for placing your code inside this function is that it will get called once the DOM has loaded - meaning that all the elements are accessible. Calling jQuery selectors without this function means that the elements have not necessarily been loaded into the DOM and might not be accessible (and you'll see weird results or nothing at all from your code).
So in essense, yes, it is necessary. | If you don't use that line, and just include the javascript in your body, it will execute as soon as it's loaded. If it's trying to act on DOM elements that have not yet loaded, unpredictable results will occur.... better to be safe than sorry. |
24,846 | There is a tree that bears fruit e.g. grapes or mangoes. The tree has its roots in the neighbour's house and a large part of the fruit is also in the neighbour's house.
But, some part of that tree has its branches all over a tree that is in my house. Those branches have fruit.
Can that fruit be eaten?
* I am looking for a reference from Quran or Hadith.
* The concept of stealing does not apply here because the neighbour is aware. My question is purely from Islamic point of view. | 2015/06/15 | [
"https://islam.stackexchange.com/questions/24846",
"https://islam.stackexchange.com",
"https://islam.stackexchange.com/users/2418/"
] | I think the best option would be to talk to the neighbor and ask for their permission. It is just good etiquette. In fact I can narrate my story. Our mango tree goes into our neighbor house and they always return our mangoes when they fall. It is just very nice of them. Once they had workers and found a lot of mangoes, they rang us the bell just to ask us if they can eat the mangoes. I said surely yes. So it definitely is a good etiquette and good for neighborhood.
As for what is right and what is wrong? I think it is ok to eat a mango or two from their tree that grow in your house. It is not stealing. If there are too many mangoes it is probably better to ask for permission.
To complete my story, out neighbor did ask to cut down the tree that grow into their house which we did so after all it was really our fault that our tree grow into their house and created all the mess for them. So it is probably not a big deal, it is just a matter of etiquette. Either was is fine, better is to ask for permission. | No , techinically it belongs to the person who maintains the tree , he being an owner and you are not the owner of the tree. The verses of stealing would be applicable here. |
56,856,011 | I'm trying to convert a serialized string into an array
This is the string i'm getting on php (form sent using serialized AJAX POST)
```
"ref_1=000CBA0000&name_1=Produto%20A&quantity_1=1&ref_2=000CBA0000&name_2=Produto%20A&quantity_2=1&ref_3=000CBA0000&name_3=Produto%20A&quantity_3=1"
```
every product that comes in the string have it's own ref,name,quantity, so currently my string comes with the information of 3 products, it may change every request.
I'm trying to convert the serialized string to an array with this format
```
[
[1]
ref => <copy the value from ref_1>
name => <copy the value from name_1>
quantity => <copy the value from quantity_1>
[2]
ref => <copy the value from ref_2>
name => <copy the value from name_2>
quantity => <copy the value from quantity_2>
[3]
ref => <copy the value from ref_3>
name => <copy the value from name_3>
quantity => <copy the value from quantity_3>
]
```
So later i can do a **foreach** product and fetch them individually.
i tried exploding the string with:
```
$array = explode("&",$string);
var_dump($array);
```
but that gives me a different result:
```
array(9) { [0]=> string(16) "ref_1=000CBA0000" [1]=> string(21) "name_1=Produto%20A" [2]=> string(12) "quantity_1=1" [3]=> string(16) "ref_2=000CBA0000" [4]=> string(21) "name_2=Produto%20A" [5]=> string(12) "quantity_2=1" [6]=> string(16) "ref_3=000CBA0000" [7]=> string(21) "name_3=Produto%20A" [8]=> string(12) "quantity_3=1" }
``` | 2019/07/02 | [
"https://Stackoverflow.com/questions/56856011",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1205650/"
] | **Before creation:**
You can set environment variable while creating the cluster.
Click on **Advanced Options** => Enter **Environment Variables**.
[](https://i.stack.imgur.com/y1XuV.jpg)
**After creation:**
Select your **cluster** => click on **Edit** => **Advance Options** => Edit or Enter new **Environment Variables** => **Confirm and Restart**.
[](https://i.stack.imgur.com/7tWoW.jpg)
**OR**
You can achieve the desired results by appending my environment variable declarations to the file /databricks/spark/conf/spark-env.sh. You may change the init file as follows:
```
%scala
dbutils.fs.put("dbfs:/databricks/init/set_spark_params.sh","""
|#!/bin/bash
|
|cat << 'EOF' > /databricks/driver/conf/00-custom-spark-driver-defaults.conf
|[driver] {
| "spark.sql.sources.partitionOverwriteMode" = "DYNAMIC"
|}
|EOF
""".stripMargin, true)
```
For more details, refer “[Databricks – Spark Configuration](https://docs.databricks.com/user-guide/clusters/spark-config.html)”.
Hope this helps. | Use databricks cluster policy [configuration](https://docs.databricks.com/administration-guide/clusters/policies.html#cluster-policy-attribute-paths).
The configuration will auto-add the environment variables during policy selection.
```
spark_env_vars.MY_ENV_VAR: {
"value":"2.11.2",
"type": "fixed"
}
``` |
22,087,076 | Does any one know how to do a simple image upload and display it on the page.
This is what I'm looking for.
* User(me) will choose a image
* The page will display the image without refreshing the page or going to another file.
* multiple `<img src>` will do because I need to display different image size.
This was my code. (Some of it are edited I got it from [here](http://jsfiddle.net/KyleMit/d3H9f/) )
```
<style>
/* Image Designing Propoerties */
.thumb {
height: 75px;
border: 1px solid #000;
margin: 10px 5px 0 0;
}
</style>
<script type="text/javascript">
/* The uploader form */
$(function () {
$(":file").change(function () {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
}
});
});
function imageIsLoaded(e) {
$('#myImg').attr('src', e.target.result);
$('#yourImage').attr('src', e.target.result);
};
</script>
<input type='file' />
</br><img id="myImg" src="#" alt="your image" height=200 width=100>
``` | 2014/02/28 | [
"https://Stackoverflow.com/questions/22087076",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3335903/"
] | ```
<img id="output_image" height=50px width=50px\
<input type="file" accept="image/*" onchange="preview_image(event)">
<script type"text/javascript">
function preview_image(event) {
var reader = new FileReader();
reader.onload = function(){
var output = document.getElementById('output_image');
output.src = reader.result;
}
reader.readAsDataURL(event.target.files[0]);
}
</script>
``` | ```
<li class="list-group-item active"><h5>Feaured Image</h5></li>
<li class="list-group-item">
<div class="input-group mb-3">
<div class="custom-file ">
<input type="file" class="custom-file-input" name="thumbnail" id="thumbnail">
<label class="custom-file-label" for="thumbnail">Choose file</label>
</div>
</div>
<div class="img-thumbnail text-center">
<img src="@if(isset($product)) {{asset('storage/'.$product->thumbnail)}} @else {{asset('images/no-thumbnail.jpeg')}} @endif" id="imgthumbnail" class="img-fluid" alt="">
</div>
</li>
<script>
$(function(){
$('#thumbnail').on('change', function() {
var file = $(this).get(0).files;
var reader = new FileReader();
reader.readAsDataURL(file[0]);
reader.addEventListener("load", function(e) {
var image = e.target.result;
$("#imgthumbnail").attr('src', image);
});
});
}
</script>
``` |
9,316,758 | It may sound stupid, but how can I remove a definite child from the stage?
e.g.
```
function giveMeResult(e:MouseEvent):void
{
if(stage.contains(result))
{removeChild(result);}
addChild(result); // this part works fine, but it adds one over another
}
```
it adds one result on the top of the previous one.
I want the function "giveMeResult: to remove "result" if is on the stage and add a new one.
UPDATE:*\**
result is a TextField, and result.txt ="" changes from time to time ...
```
trace (result.parent); /// gives [object Stage]
trace (result.stage); /// gives[object Stage]
trace (result.parent != null && result.parent == result.stage); // gives true
```
when
```
result.parent.removeChild(result);
```
is written without if statement - gives error *TypeError: Error #1009: Cannot access a property or method of a null object reference.*
when written inside:
```
if (result.parent !=null && result.parent == result.stage)
{
result.parent.removeChild(result);
}
```
nothing happens and new child is added on the top of the previous one.
Thanks to all!!!
The result is simple :)
All I had to do is just change result.txt without even removing it from the stage :) | 2012/02/16 | [
"https://Stackoverflow.com/questions/9316758",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1212216/"
] | All I had to do is just change result.txt without even removing it from the stage | Have you tried?
```
MovieClip(root).removeChild(result)
```
[EDIT]
```
function giveMeResult(e:MouseEvent):void{
if(result.parent != null && result.parent == result.stage){
stage.removeChild(result);
}
stage.addChild(result);
}
``` |
3,823,607 | I have the following gradient:
```
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<gradient
android:startColor="#ECECEC"
android:centerColor="#F6F6F4"
android:endColor="#F8F8F6"
android:angle="90"
android:dither="true"
/>
</shape>
```
I want this to be transparent because in my ListView I am setting this as my ListSelector:
```
<ListView android:layout_width="fill_parent"
android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/ARListView"
android:background="@drawable/transparent_background"
android:cacheColorHint="#00000000" android:drawSelectorOnTop="true"
android:listSelector="@drawable/stocks_selected_gradient">
</ListView>
``` | 2010/09/29 | [
"https://Stackoverflow.com/questions/3823607",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/19875/"
] | Just use an 8-digit color value, e.g. #FFF8F8F6, where the first two characters are the alpha value. FF being fully opaque, and 00 being fully transparent. | android:background="#00000000" android:cacheColorHint="#00000000"
this will make is transparent however, this is to make it a full transparency... |
552,818 | **"I am using flash as3, php and mysql"**
What is the difference between:
```
$username = $_POST['username'];
$password = md5( $_POST['password']);
```
and
```
$username = mysql_real_escape_string( $_POST['username']);
$password = mysql_real_escape_string(md5( $_POST['password']));
```
I am sending and retrieving variables from flash AS3 to php and back to AS3 again. The former one (without mysql\_real\_escape\_string) works fine. But the later one gets an error in flash. The error message is: "Parameter text must be non-null."
I tried "echo" (display) both result, the results are the same. Very strange.. Anyone have any idea? | 2009/02/16 | [
"https://Stackoverflow.com/questions/552818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/65379/"
] | Remember that mysql\_real\_escape\_string() needs an open database connection to work properly; if you're calling it before using mysql\_connect, it won't have the desired effect. | You just need the `mysql_real_escape_string` if you want to use a string in a query that is then executed by the `mysql_query` function. And furthermore you just need this function if you cannot ensure that this string doesn’t contain certain characters that can violate the integrity of the query you intended. |
751,744 | What are your thoughts on code that looks like this:
```
public void doSomething()
{
try
{
// actual code goes here
}
catch (Exception ex)
{
throw;
}
}
```
The problem I see is the actual error is not handled, just throwing the exception in a different place. I find it more difficult to debug because i don't get a line number where the actual problem is.
So my question is why would this be good?
---- EDIT ----
From the answers it looks like most people are saying it's pointless to do this with no custom or specific exceptions being caught. That's what i wanted comments on, when no specific exception is being caught. I can see the point of actually doing something with a caught exception, just not the way this code is. | 2009/04/15 | [
"https://Stackoverflow.com/questions/751744",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2847/"
] | Sometimes this is appropriate - when you're going to handle the exception higher up in the call stack. However, you'd need to do something in that catch block other than just re-throw for it to make sense, e.g. log the error:
```
public void doSomething()
{
try
{
// actual code goes here
}
catch (Exception ex)
{
LogException (ex); // Log error...
throw;
}
}
``` | I've seen instances where generic exceptions are caught like this and then re-packed in a custom Exception Object.
The difference between that and what you're saying is that those custom Exception objects hold MORE information about the actual exception that happened, not less. |
87,786 | One member of our household has some specific food allergies. Her food is often prepared differently, but not usually in a way where it is visually different from the rest of the food. Let’s say we’re cooking chicken thighs on a baking sheet for the whole family. My suggestion was to insert a toothpick. What’s the best way to mark her food? | 2018/02/16 | [
"https://cooking.stackexchange.com/questions/87786",
"https://cooking.stackexchange.com",
"https://cooking.stackexchange.com/users/65185/"
] | I have spent decades cooking for people who can't have gluten, and I and several other people can't have shrimp. The simplest thing to do is to make everyone's food meet the needs of the allergic person. So for example don't bread anyone's chicken, or make a single gluten-free gravy.
That's the simplest, but it may not meet your other needs. In that case, I avoid anything that can fall off or be missed. In the case of chicken pieces on a baking sheet, I would use one large sheet and one smaller pan, and put the special portion on the smaller pan. Now you can flip and turn the pieces freely, and you don't need to worry about the juices mingling or whatever. I do this when cooking regular and gluten-free pasta, for example; I use very different-sized pots. When I run a separate butter dish to avoid crumb contamination, it's not two identical white butter plates, one of which is labelled; it's a white plate for the might-have-gluten-crumbs butter and a small clear bowl for the keep-it-crumb-free butter. These visual cues are much larger than a toothpick and can't be missed or fall out or end up on the underside or whatever. | Whatever works for you is best. If the allergy is serious, you'd definitely want to not just mark, which means either:
* just don't use whatever they're allergic to
* use easily-distinguishable separate dishes (if there's one piece on one and 10 on the other, that works)
Some useful things when you do want separate dishes, beyond just smaller baking pans, some of which you might already have:
* oven-safe bowls (could be for the table, or mixing bowls)
* oven-safe pots
* oven-safe glass containers
* muffin tins
* mini cake or bread loaf pans
If it's something less sensitive, where crumbs or a bit of sauce or something won't cause issues, then some options, depending on what exactly it is:
* for attaching, with sufficiently solid food: a skewer (same idea as a toothpick but bigger so it's harder to lose it) or food-safe twine
* for visual dividers: aluminum foil, parchment paper
* to be fancy but convenient, as long as it's not getting moved around much: add a piece of something that's already in the meal, e.g. a slice of tomato on top
* to be really convenient, with solid food: just cut some marks into it |
13,896,528 | I explain what I am trying to do in comments above the parts in the method:
```
public int addPatron(String name) throws PatronException {
int i = 0;
//1. Iterate through a hashmap, and confirm the new name I am trying to add to the record doesn't already exist in the hashmap
for (Map.Entry<Integer, Patron> entry : patrons.entrySet()) {
Patron nameTest = entry.getValue();
//2. If the name I am trying to add already exists, we want to throw an exception saying as much.
if (nameTest.getName() == name) {
throw new PatronException ("This patron already exists");
//3. If the name is unique, we want to get the largest key value (customer number) already in the hash, an increment by one.
} else if (nameTest.getName() != name) {
Map.Entry<Integer,Patron> maxEntry = null;
for(Map.Entry<Integer, Patron> entryCheck : patrons.entrySet()) {
if (maxEntry == null || entryCheck.getKey() > maxEntry.getKey()) {
maxEntry = entryCheck;
i = maxEntry.getKey();
i++;
}
}
} else {
throw new PatronException("Something's not working!");
}
//4. If everything is ok up to this point, we want to us the name and the new customer id number, and use those to create a new Patron object, which then gets added to a hashmap for this class which contains all the patrons.
Patron newPatron = new Patron(name, i);
patrons.put(i, newPatron);
}
return i;
}
```
When I try and run a simple unit test that will fail if I successfully add the same name for addPatron twice in a row, the test fails.
```
try {
testLibrary.addPatron("Dude");
testLibrary.addPatron("Dude");
fail("This shouldn't have worked");
```
The test fails, telling me the addPatron method is able to use the same name twice.
@Jon Skeet:
My Patron class looks like this:
```
public class Patron {
//attributes
private String name = null;
private int cardNumber = 0;
//operations
public Patron (String name, int cardNumber){
this.name = name;
this.cardNumber = cardNumber;
}
public String getName(){
return name;
}
public int getCardNumber(){
return cardNumber;
}
```
} | 2012/12/15 | [
"https://Stackoverflow.com/questions/13896528",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1005450/"
] | As others have said, the use of `==` for comparing strings is almost certainly inappropriate. However, it shouldn't actually have caused a problem in your test case, as you're using the same constant string twice, so `==` should have worked. Of course, you should still fix the code to use `equals`.
It's also not clear what the `Patron` constructor or `getName` methods do - either of those could cause a problem (e.g. if they create a *new* copy of the string - that would cause your test to fail, but would also be unnecessary usually).
What's slightly more worrying to me is this comment:
```
// 3. If the name is unique, we want to get the largest key value (customer number)
// already in the hash, an increment by one.
```
This comment is *within* the main loop. So by that point we don't know that the name is unique - we only know that it doesn't match the name *of the patron in this iteration*.
Even more worrying - and I've only just noticed this - you perform the add *within the iteration block* too. It seems to me that you should have something more like this:
```
public int addPatron(String name) throws PatronException {
int maxKey = -1;
for (Map.Entry<Integer, Patron> entry : patrons.entrySet()) {
if (entry.getValue().getName().equals(name)) {
// TODO: Consider using IllegalArgumentException
throw new PatronException("This patron already exists");
}
maxKey = Math.max(maxKey, entry.getKey());
}
int newKey = maxKey + 1;
Patron newPatron = new Patron(name, newKey);
patrons.put(newKey, newPatron);
return newKey;
}
```
Additionally, it sounds like *really* you want a map from name to patron, possibly as well as the id to patron map. | You need to use equals to compare String objects in java, not ==. So replace:
```
if (nameTest.getName() == name) {
```
with:
```
if (nameTest.getName().equals(name)) {
``` |
361,856 | I need some help with jQuery script again :-) Just trying to play with jQuery..I use script below for coloring options of select element. It works in pure html, but in my asp.net 2.0 (Master + Content pages) does not. Script is placed in Head section.
```
function pageLoad(){
var allOddSelectOption = "select option:odd";
var evenStyle = "background-color:'#f4f4f4';color:'#555'";
$(allOddSelectOption).attr('style',evenStyle);
}
```
I tried also use `$(document).ready(function(){` but it didn't work too.
Any ideas, tips most welcome? | 2008/12/12 | [
"https://Stackoverflow.com/questions/361856",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/24507/"
] | Check [css(properties)](http://docs.jquery.com/CSS/css#properties), you can apply styles very easy.
```
$(document).ready(function(){
$("select option:odd").css({'background-color' : 'yellow', 'font-weight' : 'bolder'});
});
```
EDIT: For ASP .NET 2.0 `$(document).ready()` will work, since you can call it [multiple times](http://www.learningjquery.com/2006/09/multiple-document-ready) you will have no problem even if it's not in the head section.
---
For ASP .NET 3.5
You can add in your MasterPage a head placeholder like this:
```
<asp:ContentPlaceHolder id="head" runat="server">
</asp:ContentPlaceHolder>
```
and then in your child pages you can put html into it by a Content tag:
```
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
<script language="JavaScript>
//Scripts here!
</script>
</asp:Content>
``` | ASP.Net decorates your element IDs when you are using master pages. It will put a lot of stuff up front, but leave your original ID at the end. Because of that, you can use a selector like this on ASP.Net server control renderings.
```
$("[id$=originalIdFromAspxPage]").attr...
```
The `$=` part means this will match any elements with an ID that ends with the ID you give it.
It's not quite as efficient as a direct ID selector, but it works like a charm on ASP.Net pages. |
51,983,291 | I need advice.
I have CRM on laravel. We are doing booking now. There will be one common database. How to organize correctly?
1. One application with different namespaces and domain routes.
2. Two application
How do they design such systems?
Thanks! | 2018/08/23 | [
"https://Stackoverflow.com/questions/51983291",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4403617/"
] | I know this thread is fairly old, but maybe the answer can help some people stumbling upon the thread anyway.
We had the same problem (using NavigationView instead of BottomNavigationView) and for some reason Skytile's solution didn't work for us.
As Skytile pointed out, it is not possible (at least on API levels < 26) to set a custom tint list on individual items. However, it is possible to set the tint mode:
```
val itemsWithoutTint: List<Int> = listOf(12345)
for (i in 0 until getMenu().size()) {
val item = getMenu().getItem(i)
if (item.itemId in itemsWithoutTint) {
MenuItemCompat.setIconTintMode(item, PorterDuff.Mode.DST)
}
}
```
By setting the TintMode to DST (<https://developer.android.com/reference/android/graphics/PorterDuff.Mode>), the source (in this case the tint color) is ignored and the destination (the icon to be tinted) is left untouched. | Add color resource folder in resources and put bottom\_color\_state in that folder and replace your bottom\_color\_state code as following
```
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:color="@color/white" />
<item android:state_checked="false" android:color="@color/colorPrimaryDark"/>
</selector>
``` |
8,187,355 | Over using gdb, any one can see content of any registers ?
```
ex:
x/x $ebp + 0x4
print $eax
```
I wonder, Can I do same thing by just with c++ ? If yes, how? | 2011/11/18 | [
"https://Stackoverflow.com/questions/8187355",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | C++ does not specify any particular machine architecture; therefore, it would not be able to do anything standard related to (machine specific) registers. You'll have to check your compiler's documentation to see if doing these kinds of things are supported. | I believe the only way you can do this is to use assembly language to access the registers - but that's non-portable.
There's a good thread on the subject here:
<http://bytes.com/topic/c/answers/626071-how-access-processor-registers>
and I asked a question a while back about usage of assembly in C which would show you the basics (in the solutions) here:
[How does C code call assembly code (e.g. optimized strlen)?](https://stackoverflow.com/questions/7300160/how-does-c-code-call-assembly-code-e-g-optimized-strlen) |
19,900,081 | I have a single page web application which contains dfp ads. I have two dfp adunits that Iam firing and they are placed in between the content which is a list of articles for a particular category.
When I click on another category,it just loads articles for different category(doesnt change the url in address bar) and triggers the same ads. So this is like triggering the ads on the same page.
The ads dont show up the second time and this is because you cant use the same adunits on the same page.
Since I cannot use the refresh function provided by dfp since my DOM is reconstructed everytime, is there any way I can do this?. | 2013/11/11 | [
"https://Stackoverflow.com/questions/19900081",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1218430/"
] | If you are using jQuery take a look at the [plugin](https://github.com/coop182/jquery.dfp.js) I made which wraps DFP and allows you to use it quite easily within single page apps.
This is a demo using turbolinks which will be similar to your single page app:
<http://coop182.github.io/jquery.dfp.js/dfptests/demo1.html>
Any more questions just let me know.
Edit: here is another Single page example - <http://coop182.github.io/jquery.dfp.js/dfptests/spa.html> | Do it the hard way:
```
function myGoogleTagLoaderFn(callback) {
// reset googletag lib
window.googletag = null;
// we're using requirejs, so we have to do this as well
window.requirejs.undef('http://www.googletagservices.com/tag/js/gpt.js');
myRequireOr$getScriptFn('http://www.googletagservices.com/tag/js/gpt.js', function success() { callback(); });
}
```
Don't worry about loading the library on every page load, this is the same as in a non-singlepage site, and the lib sends reasonable cache headers. The downside of course is that the script gets re-evaluated everytime. The upside is you can use singleRequest mode this way. |
2,016,415 | This is my markup:
```
<div id="nav">
<ul>
<li><a href="#">Page 1</a></li>
<li><a href="#">Page 2</a></li>
<li>
<a href="#">Articles</a>
<ul class="inside-ul">
<li><a href="#">Article 1</a></li>
<li><a href="#">Article 2</a></li>
<li><a href="#">Article 3</a></li>
</ul>
</li>
<li><a href="#">Page 3</a></li>
</ul>
</div>
```
I apply styling to the parent `<ul>` like this:
```
#nav ul {
something;
}
#nav ul li {
something;
}
#nav ul li a {
something;
}
```
And I apply styling to the child `<ul>` like this:
```
.inside-ul {
something;
}
.inside-ul li {
something;
}
.inside-ul li a {
something;
}
```
But the problem is, the child `<ul>` (.inside-ul) doesn't change at all, it's like it inherits everything from its parent. I have tried using `!important` in my CSS file but it still remains the same.
Here is an image of what's happening:
<http://i47.tinypic.com/w1brkw.jpg>
I hope I've explained myself clearly, thanks. | 2010/01/06 | [
"https://Stackoverflow.com/questions/2016415",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/230701/"
] | Change
```
#nav ul {
something;
}
```
to
```
#nav > ul {
something;
}
```
That way the CSS is only applied to the child UL of #nav and not the sub UL. | It is a [CSS specificity](http://htmldog.com/guides/cssadvanced/specificity/) issue.
Id's have a value of 100 while classes have a value of 10 and each element name has a value of 1.
So `#nav ul` = 101
while `.inside_ul` = 10
If two selectors apply to the same element, the one with higher specificity wins.
So the #nav ul styles will take precedence. You will need to use
```
#nav ul.inside_ul
```
which has a specificity of 111. |
16,469,728 | I'm trying to have a div in which the top is barely visible (Image #1), but on mouseover it slides up to where it will have some copy in it (Image #2). Then on mouseout / leave the div returns back to #1 position.
Any help is greatly appreciated
[Link to IMG of what I'm trying accomplish](http://i.stack.imgur.com/MJ12v.jpg) | 2013/05/09 | [
"https://Stackoverflow.com/questions/16469728",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2282821/"
] | Everyone has likely since moved on, but I'd like to share my solution to this problem. (Sorry about the long variables names...)
The idea is simple: always keep the fireDate in the future.
-every time didFinishLaunchingWithOptions or didReceiveLocalNotification is invoked, simply cancel your current notification and reschedule a new one with a fireDate one interval unit in the future
-When your app launches iterate through all scheduled notifications, if the fireDate is not in the future you know that it was ignored
In my case, the notifications have a weekly repeat interval. I first reschedule any acknowledged notifications in didFinishLaunchingWithOptions:
```
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
UILocalNotification* localNotif = [launchOptions objectForKey:UIApplicationLaunchOptionsLocalNotificationKey];
if (localNotif != nil)
{
[NotificationsHelper rescheduleNotification:localNotif];
}
}
```
And also in didReceiveLocalNotification:
```
- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *) notification
{
[NotificationsHelper rescheduleNotification:notification];
}
```
At App Launch I check all notifications for any with a fireDate in the past:
```
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[self checkLocalNotifications:application];
}
```
Code for my "checkLocalNotifications" function:
```
- (void) checkLocalNotifications:(UIApplication *) application
{
UIApplication* app = [UIApplication sharedApplication];
NSArray* eventArray = [app scheduledLocalNotifications];
for (int i = 0; i < [eventArray count]; i++)
{
UILocalNotification* notification = [eventArray objectAtIndex:i];
if ([NotificationsHelper wasWeeklyRepeatingNotificationIgnored:notification])
{
[NotificationsHelper rescheduleNotification:notification];
NSLog(@"NotificationWasIgnored: %@ %@",notification.alertAction, notification.alertBody );
}
}
}
```
Code for my "wasWeeklyRepeatingNotificationIgnored" function:
```
+ (BOOL) wasWeeklyRepeatingNotificationIgnored:(UILocalNotification*) the_notification
{
BOOL result;
NSDate* now = [NSDate date];
// FireDate is earlier than now
if ([the_notification.fireDate compare:now] == NSOrderedAscending)
{
result = TRUE;
}
else
{
result = FALSE;
}
return result;
}
```
Code for my "rescheduleNotification" function:
```
+ (void) rescheduleNotification:(UILocalNotification*) the_notification
{
UILocalNotification* new_notification = [[UILocalNotification alloc] init];
NSMutableDictionary* userinfo = [[NSMutableDictionary alloc] init];
[new_notification setUserInfo:userinfo];
[new_notification setRepeatInterval:the_notification.repeatInterval];
[new_notification setSoundName:UILocalNotificationDefaultSoundName];
[new_notification setTimeZone:[NSTimeZone defaultTimeZone]];
[new_notification setAlertAction:the_notification.alertAction];
[new_notification setAlertBody:the_notification.alertBody];
[new_notification setRepeatCalendar:[NSCalendar currentCalendar]];
[new_notification setApplicationIconBadgeNumber:the_notification.applicationIconBadgeNumber];
NSCalendar* gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents* weekdayComponents = [gregorian components:NSWeekdayCalendarUnit
fromDate:the_notification.fireDate];
NSInteger weekday = [weekdayComponents weekday];
NSDate* next_week = [self addDay:weekday toHourMinute:the_notification.fireDate];
[new_notification setFireDate:next_week];
[[UIApplication sharedApplication] scheduleLocalNotification:new_notification];
[[UIApplication sharedApplication] cancelLocalNotification:the_notification];
}
``` | **If your UILocalNotifications increment the application icon badge number** (i.e. the number in the red circle on the top right of the app's icon), then there is a *ridiculously simple* way to check for unacknowledged UILocalNotifications: just check what the current `applicationIconBadgeNumber` is:
```
- (void)applicationWillEnterForeground:(UIApplication *)application
{
int unacknowledgedNotifs = application.applicationIconBadgeNumber;
NSLog(@"I got %d unacknowledged notifications", unacknowledgedNotifs);
//do something about it...
//You might want to reset the count afterwards:
[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
}
``` |
17,549,111 | I would like to monitor the following system information in my ASP.NET solution:
* current cpu usage (percent)
* available memory\* (free/total)
* available disk space (free/total)
\*note that I mean overall memory available to the whole system
I tried with windows perfmon (run --> perfmon.msc ) but it seems not to be what I'm searching for.
I need something that can tell me the resources load for every function or method called into my application.
Any suggestions are much appreciated.
EDIT:
Maybe it could be useful to know how to monitor, with perfmon, the % Process Time cosumed by a single process (for istance w3wp)
EDIT EDIT:
I found it! Add new counter --> Process --> % Processor Time on w3wp! THANKS | 2013/07/09 | [
"https://Stackoverflow.com/questions/17549111",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2541720/"
] | Use:
```
DELETE FROM users WHERE personID=$personID
```
Make sure you read up about [SQL Injection](http://en.wikipedia.org/wiki/SQL_injection) | You don't need the \* in the delete query
try
```
DELETE FROM users WHERE personID=$personID
``` |
11,280,102 | I was planning on learning a way to create my own programming language and I wanted to know what language to write a compiler with. C? C++? | 2012/07/01 | [
"https://Stackoverflow.com/questions/11280102",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1442564/"
] | Windows Vista and newer come with the .NET Framework installed by default. That in turn already provides a compiler for the .NET languages (most notably C# and VB.NET). It's the only provided language you could possibly write an efficient compiler in. Other languages are VBScript and JScript (via windows Scripting Host) and batch files, so nothing you'd really want to implement more complicated stuff in.
Depending on the complexity of the language you want to create, a C++ implementation may provide better performance, though. No offense, but you don't quite make the impression that you really know how to implement a compiler for a new language. Greg Hewgill's link should give you some starting points there. The thing is, creating a new (formal) language is anything but a trivial task. Yes, the tools to do it are free, and so is the knowledge. But you should really already have a solid understanding of the programming language you want to write the compiler or interpreter in before even attempting to do it. | I suggest you use C#; DLR is great for this purpose. |
17,591,768 | I am working on an application which will have an option for users to upload images. Once uploaded, the application will show other images from the web which look exactly similar, whether or not of the same size.
For this, I will create a temporary URL for the image so that I could provide Google custom search API the URL of the image. I would expect in response, URL's of images that are exactly the same or similar to it, perhaps in JSON format.
I did find a similar question posted in January. Till then Google did not support anything like this, apparently:
[Google Javascript Custom Search API: Search images by image url](https://stackoverflow.com/questions/14298398/google-javascript-custom-search-api-search-images-by-image-url)
One can also simply do:
<http://images.google.com/searchbyimage?site=search&image_url=>{Image URL}
Since that is not part of an official API, it may not be right to use this method.
Can someone help me? | 2013/07/11 | [
"https://Stackoverflow.com/questions/17591768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1001641/"
] | Well, the answer quite simply is TinEye Commercial API <https://api.tineye.com/welcome>. I was looking in the wrong place I guess, I did not have any luck with Google Custom Search API. | Would you need a simple result?
If you are, you can use Vision API of Google.
This is very simple.
<https://cloud.google.com/vision/>
You can try on the top.
First, access the URL.
Second, upload your image file on the "Try API"
Third, click "JSON" tab menu on the result.
You can be seen JSON about similar images. |
38,514,198 | I have lists of NLTK-tags as below. I would like to select only those tagged as 'NNP' and, more specifically, first and last names (e.g. Event Chair Iris Dankner, Even Producer Barbara Schorr).
```
O5 = [[(u'Room', 'NN'), (u'Designers', 'NNS'), (u',', ','), (u'BCRF', 'NNP'), (u'and', 'CC'), (u'Holiday', 'NNP'), (u'House', 'NNP'), (u'staff', 'NN'), (u'cheer', 'NN'), (u'themselves', 'PRP'), (u'for', 'IN'), (u'a', 'DT'), (u'job', 'NN'), (u'well', 'RB'), (u'done', 'VBN')], [(u'Holiday', 'NNP'), (u'House', 'NNP'), (u'Founder', 'NNP'), (u'and', 'CC'), (u'Event', 'NNP'), (u'Chair', 'NNP'), (u'Iris', 'NNP'), (u'Dankner', 'NNP'), (u'with', 'IN'), (u'Event', 'NNP'), (u'Producer', 'NNP'), (u'Barbara', 'NNP'), (u'Schorr', 'NNP')], [(u'Architect', 'NNP'), (u'Joan', 'NNP'), (u'Dineen', 'NNP'), (u'with', 'IN'), (u'Alyson', 'NNP'), (u'Liss', 'NNP')]]
```
Here I tried
```
O5 = [O5[i][0] for O5[i][1] == "NNP"]
```
And
```
O5 = [O5[i][0] for O5[i][1] = "NNP"]
```
Both produce `SyntaxError: invalid syntax`. Could anyone give me some suggestions here? Thank you!! | 2016/07/21 | [
"https://Stackoverflow.com/questions/38514198",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6057372/"
] | >
> **Note:** The post is about WebBrowser control, however, for all the new
> .NET projects the main solution is using
> [**WebView2**](https://learn.microsoft.com/en-us/microsoft-edge/webview2/?WT.mc_id=DT-MVP-5003235).
> To learn more, take a look at this post:
>
>
> * [Getting started with WebView2](https://stackoverflow.com/a/59960888/3110834).
>
>
>
WebBrowser Control
------------------
The [`WebBrowser`](https://learn.microsoft.com/en-us/dotnet/framework/winforms/controls/webbrowser-control-windows-forms?WT.mc_id=DT-MVP-5003235) control uses the same Internet Explorer version which is installed on your OS but it doesn't use the latest document mode by default and shows content in compatibility mode.
*Symptom -* As a symptom, the site works properly in Internet Explorer or other browsers, but `WebBrowser` control doesn't show the site well and for some sites it shows script errors.
*Solution -* You can tell the `WebBrowser` control to use the latest document mode without compatibility mode in `WebBrowser` control. You can follow instructions [here](https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/general-info/ee330730(v=vs.85)?WT.mc_id=DT-MVP-5003235#browser-emulation) to disable the setting using registry.
[Reference: [Browser Emulation](https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/general-info/ee330730(v=vs.85)?WT.mc_id=DT-MVP-5003235#browser-emulation)]
**Apply Browser Emulation setting using code**
If you want to apply the settings using code, run the following code once:
```
using (var key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(
@"Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION",
true))
{
var app = System.IO.Path.GetFileName(Application.ExecutablePath);
key.SetValue(app, 11001, Microsoft.Win32.RegistryValueKind.DWord);
key.Close();
}
```
In above code, I've used `11001` which means IE11 Edge mode.
>
> Internet Explorer 11. Webpages are displayed in IE11 edge mode,
> regardless of the declared !DOCTYPE directive. Failing to declare a
> !DOCTYPE directive causes the page to load in Quirks.
>
>
>
**Apply the Browser Emulation setting manually**
Open Registry editor and browse `HKEY_CURRENT_USER`, go to the following key:
```
Software\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION
```
Add the following values:
```
"YourApplicationFileName.exe"=dword:00002af9
"YourApplicationFileName.vshost.exe"=dword:00002af9
```
(In older versions of Visual Studio you needed to add *vshost.exe* value as well, when you run your program in Visual Studio.)
To create entries right click on an empty area of the right pane, then in the window which appears after selecting `dword` value, choose hexadecimal and enter `2af9`:
[](https://i.stack.imgur.com/nfjuq.png)
In above steps, I've used `11001` which means IE11 Edge mode.
Use WebViewCompatible Control for Windows Forms
-----------------------------------------------
You can also use the new [WebViewCompatible control for Windows Forms](https://learn.microsoft.com/en-us/windows/communitytoolkit/controls/wpf-winforms/webviewcompatible?WT.mc_id=DT-MVP-5003235). You can see simple steps to use here: [Replace WebBrowser control by new WebView Compatible control for Windows Forms](https://stackoverflow.com/a/59271260/3110834).
`WebViewCompatible` uses one of two rendering engines to support a broader set of Windows clients:
* On Windows 10 devices, the newer Microsoft Edge rendering engine is used to embed a view that renders richly formatted HTML content from a remote web server, dynamically generated code, or content files.
* On devices running older versions of Windows, the System.Windows.Controls.WebBrowser is used, which provides Internet Explorer engine-based rendering.
* **Note:** [`WebView2`](https://stackoverflow.com/a/59960888/3110834) is a replacement for `WebView` and `WebViewCompatible`.
Set X-UA-Compatibile meta tag
-----------------------------
In case that you have access to the html content of the page and you can change the content (for example it's a local html file, or the site belong to yourself) then you can set [`X-UA-Compatibile`](https://learn.microsoft.com/en-us/openspecs/ie_standards/ms-iedoco/380e2488-f5eb-4457-a07a-0cb1b6e4b4b5?WT.mc_id=DT-MVP-5003235) meta tag in the `head` like: `<meta http-equiv="X-UA-Compatible" content="IE=Edge" />`.
Use other Browser Controls
--------------------------
You can rely on other browser controls like [`CefSharp`](https://github.com/cefsharp/CefSharp). | The below procedures will add the correct key and remove it again.
Call the CreateBrowserKey upon loading the form that your web browser is in.
Then when closing the form, call the RemoveBrowserKey
```
Private Sub CreateBrowserKey(Optional ByVal IgnoreIDocDirective As Boolean = False)
' Dim basekey As String = Microsoft.Win32.Registry.CurrentUser.ToString
Dim value As Int32
' Dim thisAppsName As String = My.Application.Info.AssemblyName & ".exe"
' Value reference: http://msdn.microsoft.com/en-us/library/ee330730%28v=VS.85%29.aspx
' IDOC Reference: http://msdn.microsoft.com/en-us/library/ms535242%28v=vs.85%29.aspx
Select Case (New WebBrowser).Version.Major
Case 8
If IgnoreIDocDirective Then
value = 8888
Else
value = 8000
End If
Case 9
If IgnoreIDocDirective Then
value = 9999
Else
value = 9000
End If
Case 10
If IgnoreIDocDirective Then
value = 10001
Else
value = 10000
End If
Case 11
If IgnoreIDocDirective Then
value = 11001
Else
value = 11000
End If
Case Else
Exit Sub
End Select
Microsoft.Win32.Registry.SetValue(Microsoft.Win32.Registry.CurrentUser.ToString & BrowserKeyPath, _
Process.GetCurrentProcess.ProcessName & ".exe", _
value, _
Microsoft.Win32.RegistryValueKind.DWord)
End Sub
Private Sub RemoveBrowserKey()
Dim key As Microsoft.Win32.RegistryKey
key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(BrowserKeyPath.Substring(1), True)
key.DeleteValue(Process.GetCurrentProcess.ProcessName & ".exe", False)
End Sub
``` |
1,186,450 | My professor of calculus said that he will not adopt books like "stewart" or "thomas" because they are too easy for a physics undergrad course.
He said that Apostol is a great book for our case, but some people told me that this book focus a lot in the historical concept and was not good to them.
I know that my professor likes extreme rigour in math, so do i.
In the words of Apostol itself (preface):
Some people insist that the only way to really understand calculus is to start off with a thorough treatment of the real-number system and develop the subject step by step in a logical and rigorous fashion
What books follow this principle of learning calculus?
Thank you. | 2015/03/12 | [
"https://math.stackexchange.com/questions/1186450",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/104187/"
] | Spivak's *Calculus* and *Calculus on Manifolds* (for multivariable calculus) are pretty standard rigorous calculus texts. Rudin's *Principle's of Mathematical Analysis* is standard for a first analysis course, but may be too abstract for a physics course. If you don't like Apostol but still want the mathematical rigor, these are good alternatives.
There's also Strang's free calculus text [here.](http://ocw.mit.edu/resources/res-18-001-calculus-online-textbook-spring-2005/textbook/)
For more calculations, Hubbard's Vector Calculus book works as well.
Edit: Yes, it does depend on where you are from, since American students (such as myself) wouldn't study Spivak in our first year (to be fair, I actually never studied Spivak's *Calculus*, just his *Calculus on Manifolds* for a freshman advanced math course but this was far from the norm and only for math majors, not physics majors) and it is considered to be one of the best rigorous calculus textbooks as far as I'm aware. Seeing as the OP's professor mentions Apostol (although not mentioning *which* Apostol book he means, either his two Calculus books or his more advanced *Mathematical Analysis*), I think Spivak's Calculus books are a good alternative to Apostol's Calculus books, although they do not contain any differential equations theory or as extensive a treatment of linear algebra as Apostol (*Calculus on Manifolds* includes a bit of linear algebra in as far as it allows him to discuss total derivatives and multilinear forms).
All this said, I'd honestly need a bit more information on the course in order to give a proper alternative. There are far too many advanced "rigorous" vector calculus textbooks to choose from for such a general recommendation, so I gave what are considered by most people to be fairly standard references.
There are other books of course:
* Fitzpatrick's *Advanced Calculus*: Again, little in the way of
linear algebra or differential equations, but I think he explains
integration much better than Spivak and a bit more drawn out explanations, which I think is nice if you're new to the material.
* Boas's *Mathematical Methods in
the Physical Sciences*: This book probably has more material than you
need (PDEs, integral transforms, basic complex variables). However,
I'd say probably the first 400 pages is a great alternative to
Apostol, and as the title suggests it's good for a physics course.
* Stroyan's *Foundations of Infinitesimal Calculus*: Haven't read this one to be honest, but seems pretty good based on the table of contents, although it does seem a bit short.
* Protter's *Basic Elements of Real Analysis*: A nice springer undergraduate text which is an abstract version of Stewart's Calculus, but not quite as rigorous as others on this list. For more rigor but using a similar style, he also has a book called *A First Course in Real Analysis*, which I also like.
These are my best "general recommendations". Honestly, we do need me information to give good recommendations (does your class have a website/what is the class on/etc.).
Hope this helps. | Arihant Publishers Calculus by Amit M Aggarwal is the best as per your requirements.
This is from where i learnt <https://www.youtube.com/results?search_query=profrobbob+calculus+2..im> sure it will help! |
6,290,292 | I have an S3 bucket, and am using a GitHub [S3 class](http://undesigned.org.za/2007/10/22/amazon-s3-php-class), and I am successful in uploading a file, yet I haven't understood how can I update my database with the file path and name, once I have uploaded it.
Any help on the issue will be greatly appreciated.
**Edit:** code from GitHub which handles the upload
```
<?php
/**
* $Id$
*
* S3 form upload example
*/
if (!class_exists('S3')) require_once 'S3.php';
// AWS access info
if (!defined('awsAccessKey')) define('awsAccessKey', 'AccessKey');
if (!defined('awsSecretKey')) define('awsSecretKey', 'SecretKey');
// Check for CURL
if (!extension_loaded('curl') && !@dl(PHP_SHLIB_SUFFIX == 'so' ? 'curl.so' : 'php_curl.dll'))
exit("\nERROR: CURL extension not loaded\n\n");
// Pointless without your keys!
if (awsAccessKey == 'change-this' || awsSecretKey == 'change-this')
exit("\nERROR: AWS access information required\n\nPlease edit the following lines in this file:\n\n".
"define('awsAccessKey', 'change-me');\ndefine('awsSecretKey', 'change-me');\n\n");
S3::setAuth(awsAccessKey, awsSecretKey);
$bucket = 'media-socialbeautyapp-com';
$path = ''; // Can be empty ''
$lifetime = 3600; // Period for which the parameters are valid
$maxFileSize = (1024 * 1024 * 50); // 50 MB
$metaHeaders = array('uid' => 123);
$requestHeaders = array(
'Content-Type' => 'application/octet-stream',
'Content-Disposition' => 'attachment; filename=${filename}'
);
$params = S3::getHttpUploadPostParams(
$bucket,
$path,
S3::ACL_PUBLIC_READ,
$lifetime,
$maxFileSize,
201, // Or a URL to redirect to on success
$metaHeaders,
$requestHeaders,
false // False since we're not using flash
);
$uploadURL = 'https://' . $bucket . '.s3.amazonaws.com/';
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>S3 Form Upload</title>
</head>
<body>
<form method="post" action="<?php echo $uploadURL; ?>" enctype="multipart/form-data">
<?php
foreach ($params as $p => $v)
echo " <input type=\"hidden\" name=\"{$p}\" value=\"{$v}\" />\n";
?>
<input type="file" name="file" /> <input type="submit" value="Upload" />
</form>
<img src="https://media-socialbeautyapp-com.s3.amazonaws.com/Untitled-1.jpg" />
</body>
</html>
```
this code is from GitHub and it's ok yo upload files, but I don't know how to make it also update a database server I have. | 2011/06/09 | [
"https://Stackoverflow.com/questions/6290292",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/646891/"
] | Add another hidden input field with name="success\_action\_redirect". The value is the callback URL on your server. You can attach parameters to the callback URL, S3 will call it on success. Don't forget to generate a token and passing that along to make sure it is your callback coming back. | It looks like your code is uploading directly to S3, so you really don't have a way to know what was uploaded.
Consider [uploading the file to your local server **first**](http://php.net/manual/en/features.file-upload.php), write to the DB and then upload to S3.
Read up on [`inputFile()`](http://undesigned.org.za/2007/10/22/amazon-s3-php-class/documentation#inputFile) method - that looks like something you can use to upload files on your local disk to S3. |
96,646 | One of Ezio's assassinations requires me to kill a merchant hiding on a boat without being detected by any of his guards.
He's being guarded by an archer on the dock (no problem), two patrolling guards on the back of the boat (no problem), two stationary guards near the wheel (kind of a problem), and two heavy guards right in front of him (huge problem).
**What strategy, tool, or combination do I need to use to off this guy?** | 2012/12/20 | [
"https://gaming.stackexchange.com/questions/96646",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/5398/"
] | Taken from [this post](http://www.gamespot.com/assassins-creed-ii/answers/sequence-13-port-authority-mission-help-169445/):
>
> 1) Dive into the water, either from the rooftop directly (move along
> the roof to the right of the mission start-point) or work your way
> down to ground level
>
>
> 2) Swim to the other side of the boat- DO NOT get too close to the
> boat until you are round the other side
>
>
> 3) Climb up the hull to the right-hand side section of rigging just
> until you are able to grab the top railing
>
>
> 4) Shimmy across until you are towards the back of the boat, just
> behind the 2 guards that are over-looking your target
>
>
> 5) Wait until all patrolling guards are away from you (you can try and
> ledge assassinate some, one of my friends said this worked however it
> did not work for me)
>
>
> 6) Climb up and immediately drop onto the deck
>
>
> 7) IMMEDIATELY drop a smoke bomb- you should have time to do this just
> before you are spotted
>
>
> 8) Run past all guards, jump onto the rail above your target, and air
> assassinate him... DONE!
>
>
>
Alternatively, as user [bobbyrk puts it](http://www.gamefaqs.com/boards/956858-assassins-creed-ii/53562862):
>
> The way I did it, was first to swim around the front side of the boat,
> away from the dock. Climb up the side of the boat, and when the first
> guard gets to the back left corner of the boat, pull him over the
> edge.
>
>
> You don't have enough time to slide over and pull the second rear
> guard overboard, so don't bother trying. The guard on the dock will
> return, you have to be about three meters from the rear of the boat
> for him to not see you when he reaches his stopping point at the end
> of the dock. When he turns and walks away, monkey over to the back of
> the boat, take out the second rear guard, then jump to the dock, and
> use the gun to take out the dock guard. That'll draw the attention of
> the brutes and the guards at the front of the boat if you time it
> right.
>
>
> Get back in the water, and climb over to the left front side of the
> boat, near the forward stopping point of the patrolling guard on that
> side. When he gets there, pull him overboard. Repeat that process for
> the other patrolling guard. Don't bother with the two guards in the
> front end of the boat.
>
>
> Circle to the back end of the boat, climb up and walk slowly up behind
> the two guards in front of the wheel. Walk between them so you stab
> both at once, and you'll be free to take the target out.
>
>
> | My way was simple enough. Just do a double air assassination on the two guards at the top of the stairs, then once the sock guard is standing at the side of the boat use a pistol to gun him down the quickly dive into the water from the top of the staircase, this strategy is genius because both brutes and most guards will check it out and the funny thing is, one brute will fall into the water trust me it works I did it five times.
Now that their busy climbonto the rear of the boat( sometimes this may not be necessary because sometimes the rear guards will go to the staircase) then once the two rear guards are taken out shimmy to take out the patrolling left guard because the right is gone.
Once that's done just do a double kill on the two rear stationary guards then do an air assassination for the target. P.s I forgot to mention that you should climb onto the docks at the rear of the ships and it's best to have full ammo so you can shoot the guards that left the ship, do this after step one. |
720 | I was out on a ride yesterday and several times when I was changing up and down between big chain ring and little chain ring (I only have the 2 rings up front) it required 2 gear changes. The gears actually settled on an imaginary middle cog! How can I fix this? | 2010/09/06 | [
"https://bicycles.stackexchange.com/questions/720",
"https://bicycles.stackexchange.com",
"https://bicycles.stackexchange.com/users/188/"
] | I think Shimano integrated shifters ("brifters") for the front derailleur on a triple normally have 5 indexed positions: 1-3-5 are the main positions that match the chainrings and 2-4 are intermediate spots to avoid chain rub for some chainring+sprocket combinations. If you give the front shift lever a short pull it will click once and the front derailleur moves one position. Give it a full pull and it should click twice, moving two positions.
Normally going up to a bigger ring requires a 2-click upshift; sometimes you need to give it a one-click downshift afterwards to eliminate chain rub if you're in a larger rear cog. Going down a ring may only take a 1-click downshift, depending on what position the derailleur is in. All of this is based on my experience with a triple, but should work the same for a double.
If shifting problems are more noticable going up to a bigger ring (needs more clicks than before) then this is probably due to cable stretch. If you have a barrel adjuster on the front derailleur cable, try turning it counterclockwise (looking at it from the side where the cable housing enters it) to tension the cable a bit.
If the problem is when dropping down to a smaller ring, then either the cables are sticking somewhere (worn cables/housing) or the front derailleur is sticking (needs lubrication or has a worn spring). | This is probably down to the gear cables.
If the cables are new they may have stretched a little and you'll need to take the slack out by adjusting the tension, you usually do this with a barrel adjuster either at the shifter or inline in the shifter cable.
If the cables have been on the bike for some time then the problem is probably sticky cables, water and dirt get inside the cable outers and stop the shifter pulling enough cable through. from your description this seems the most likely option. You can try cleaning the cables but in my experience new cable inner and outers is the way to go. |
54,088,814 | I want to connect to a database using a parameter provided by the URL like this:
```
www.mywebsite.com/DATABASE_1/
```
This will redirect to the login page using that "DATABASE\_1" as the database to connect to.
I am new to Symfony and working with controllers, I've been a SQL developer all my life and I'm trying my hand at some new stuff. I already have a login form with authentication working perfectly using the Symfony docs with the database configured at .env file (<https://symfony.com/doc/4.0/security.html>). | 2019/01/08 | [
"https://Stackoverflow.com/questions/54088814",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10883212/"
] | You should not to connect to database from your controller and handle database connection directly. The way it works is declaring configuration for Doctrine in config/packages/doctrine.yaml. Doctrine connects to database by itself. To work with database in controllers, for example, you need to get Doctrine instance firstable. Like this:
`$post = $this->getDoctrine()
->getRepository(Post::class)
->findOneBy(['slug' => $postSlug]);`
And then you can easily fetch something from database via your `Repository`.
Check this link:
<https://symfony.com/doc/current/doctrine.html> | I'm not sure about this, but I guess you could make different `VirtualHost` tha point to your URLS and add different `ENV` parameters thats contains your doctrine connection string.
[On this link](https://symfony.com/doc/2.0/cookbook/configuration/external_parameters.html), there are example to set Env param in VirtualHost |
22,098,754 | In a small HBase cluster, all the slave nodes got restarted. When I started HBase services, one of the tables (test) became **inconsistent**.
In HDFS some blocks were missing(hbase blocks). So it was in safe mode. I gave `safemode -leave` command.
Then HBase table (test) became inconsistent.
***I performed below mentioned actions:***
1. I executed "**hbase hbck**" several times. 2 inconsistencies found for table "test".
`ERROR: Region { meta=>test,1m\x00\x03\x1B\x15,1393439284371.4c213a47bba83c47075f21fec7c6d862., hdfs => hdfs://master:9000/hbase/test/4c213a47bba83c47075f21fec7c6d862, deployed => } not deployed on any region server.`
2. **hbase hbck -fixMeta -fixAssignments** HBaseFsckRepair: Region still in transition, waiting for it to become assigned:
`{NAME => 'test,1m\x00\x03\x1B\x15,1393439284371.4c213a47bba83c47075f21fec7c6d862.', STARTKEY => '1m\x00\x03\x1B\x15', ENDKEY => '', ENCODED => 4c213a47bba83c47075f21fec7c6d862,}`
3. **hbase hbck -repair** HBaseFsckRepair: Region still in transition, waiting for it to become assigned:
`{NAME => 'test,1m\x00\x03\x1B\x15,1393439284371.4c213a47bba83c47075f21fec7c6d862.', STARTKEY => '1m\x00\x03\x1B\x15', ENDKEY => '', ENCODED => 4c213a47bba83c47075f21fec7c6d862,}`
4. I checked **datanode logs** in parallel.
Logs:
`org.apache.hadoop.hdfs.server.datanode.DataNode: opReadBlock BP-1015188871-192.168.1.11-1391187113543:blk_7616957984716737802_27846 received exception java.io.EOFException
WARN org.apache.hadoop.hdfs.server.datanode.DataNode: DatanodeRegistration(192.168.1.12, storageID=DS-831971799-192.168.1.12-50010-1391193910800, infoPort=50075, ipcPort=50020, storageInfo=lv=-40;cid=CID-7f99a9de-258c-493c-9db0-46b9e84b4c12;nsid=1286773982;c=0):Got exception while serving BP-1015188871-192.168.1.11-1391187113543:blk_7616957984716737802_27846 to /192.168.1.12:36127`
5. Checked **Namenode logs**
```
ERROR org.apache.hadoop.security.UserGroupInformation: PriviledgedActionException as:ubuntu (auth:SIMPLE) cause:java.io.FileNotFoundException: File does not exist: /hbase/test/4c213a47bba83c47075f21fec7c6d862/C 2014-02-28 14:13:15,738
INFO org.apache.hadoop.ipc.Server: IPC Server handler 6 on 9000, call org.apache.hadoop.hdfs.protocol.ClientProtocol.getBlockLocations from
10.10.242.31:42149: error: java.io.FileNotFoundException: File does not exist: /hbase/test/4c213a47bba83c47075f21fec7c6d862/C java.io.FileNotFoundException: File does not exist: /hbase/test/4c213a47bba83c47075f21fec7c6d862/C at org.apache.hadoop.hdfs.server.namenode.FSNamesystem.getBlockLocationsUpdateTimes(FSNamesystem.java:1301)
```
But, I am able to browse and download the file from HDFS. How can recover the data?
How can I make the "test" table consistent? | 2014/02/28 | [
"https://Stackoverflow.com/questions/22098754",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1862493/"
] | In HBase 2.0 (and possibly in previous versions), "not deployed on any region server" is typically solved by getting the region assigned.
1. Authenticate if you're on a secured cluster. You are on a secured cluster, aren't you? ;)
```
kinit [keytab] [principal]
```
2. Run HBase check to see which regions specifically are unassigned
```
hbase hbck -details
```
3. If you see an error like this:
```
ERROR: Region {
meta => my.tablename,,1500001112222.abcdef123456789abcdef12345678912.,
hdfs => hdfs://cluster/apps/hbase/data/data/default/my.tablename/abcdef123456789abcdef12345678912,
deployed => ,
replicaId => 0
} not deployed on any region server.
```
(the key being "not deployed on any region server"), then you should assign the region. This, it turns out, is pretty simple. Proceed to step 4.
4. Open an hbase shell
```
hbase shell
```
5. Assign the region by passing the encoded regionname to the assign method. As noted in the help documentation, this should not be called without the previous due diligence **as this command will do a force reassign**. The docs say, and I caution: **for experts only**.
```
hbase(main):001:0> assign 'abcdef123456789abcdef12345678912'
```
6. Double-check your work by running hbase check for your table that had the unassigned regions.
```
hbase hbck my.tablename
```
If you did everything correctly and if there's no underlying HDFS issue, you should see this message near the bottom of the hbck output:
```
0 inconsistencies detected.
Status: OK
``` | In `Hbase 2.0.2` version there is no repair option to recover inconsistencies.
1. Run hbase hbck command.
2. If the error mesaage look like mentioned below:
```
ERROR: Region { meta => EMP_NMAE,\x02\x00\x00\x00\x00,1571419090798.054b393c37a80563ae1aa60f29e3e4df., hdfs => hdfs://node1:8020/apps/hbase/data/data/LEVEL_RESULT/054b393c37a80563ae1aa60f29e3e4df, deployed => , replicaId => 0 } not deployed on any region server.
ERROR: Region { meta => TABLE_3,\x02174\x0011100383\x00496\x001,1571324271429.6959c7157693956825be65676ced605c., hdfs => hdfs://node1:8020/apps/hbase/data/data/TABLE_NAME/6959c7157693956825be65676ced605c, deployed => , replicaId => 0 } not deployed on any region server.
```
3. copy this error inconsistancy to an file and pull the alphanumeric value by using the below command.
If our inconsistancy count is less we can take value manually if the number is more it would be hectic to retrive the entire value. so use the below command to narrow down to alphanemeric alone which can be copied and put in hbase shell at a stretch.
```sh
cat inconsistant.out|awk -F'.' '{print $2}'
```
4. Open hbase hbase shell and assign these consistancy manually. LIKE BELOW:
```
assign '054b393c37a80563ae1aa60f29e3e4df'
assign '6959c7157693956825be65676ced605c'
assign '7058dfe0da0699865a5b63be9d3799ab'
assign 'd25529539bae49eb078c7d0ca6ce84e4'
assign 'e4ad94f58e310a771a0f5a1eade884cc'
```
once the assigning is completed run the hbase hbck command again |
22,542,454 | I'm trying to create a procedure that will insert me an new entry IF the ID is not already used. I just can't figure out what I'm not doing right there:
```
CREATE OR REPLACE PROCEDURE add_user
IS
BEGIN
IF NOT EXISTS SELECT * FROM tab WHERE tab.id = '111'
THEN
INSERT INTO tab(id, name, job, city, phone)
VALUES(111, 'Frank', 'Programmer', 'Chicago', '111111111');
END IF;
END;
``` | 2014/03/20 | [
"https://Stackoverflow.com/questions/22542454",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2908704/"
] | Do not try to enforce referential integrity in code as it is very, very likely that it will be very, very wrong. Not *obviously* wrong - no, this is the kind of "wrong" that only shows up when you have 200 users banging on the database and then something goes very very far south in a very big hurry and all of a sudden nobody can use the system or do their jobs and your phone is ringing and your boss is breathing steam and cinders down the back of your neck and you're sweating and there's perspiration running down your contacts and you can't see and you can't think and and and... You know, **that** kind of wrong. :-)
Instead, use the referential integrity features of the database that are designed to *prevent* this kind of wrong. A good place to start is with the rules about Normalization. You remember, you learned about them back in school, and everybody said how stooopid they were, and **WHY** do we have to learn this junk because everybody *knows* that **nobody** does this stuff because it, like, doesn't matter, does it, hah, hah, hah (aren't we smart)? Yeah, that stuff - the stuff that after a few days on a few projects like the paragraph above you suddenly Get Religion About, because it's what's going to save you (the *smarter* you, the *older-but-wiser* you) and your dumb ass from having days like the paragraph above.
So, first thing - ensure your table has a primary key. Given the field names above I'm going to suggest it should be the `ID` column. To create this constraint you issue the following command at the SQL\*Plus command line:
```
ALTER TABLE TAB ADD CONSTRAINT TAB_PK PRIMARY KEY(ID);
```
Now, rewrite your procedure as
```
CREATE OR REPLACE PROCEDURE add_user IS
BEGIN
INSERT INTO TAB
(id, name, job, city, phone)
VALUES
(111, 'Frank', 'Programmer', 'Chicago', '111111111');
EXCEPTION
WHEN DUP_VAL_ON_INDEX THEN
EXIT; -- fine - the user already exists
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error in ADD_USER : ' || SQLCODE || ' : ' || SQLERRM);
RAISE;
END;
```
So, rather than try to pre-check to see if the coast is clear we just barge right in and insert the damn user! For we are programmers! We are strong!! We care nothing for the potential risks!!! We drink caffeinated soft drinks WITH HIGH-FRUCTOSE CORN SYRUP!!!! Errors cannot frighten us!!!
**ARE WE NOT MEN?!?!?**
Well, actually, if we're *responsible* (rather than "reprehensible" :-) programmers, we actually care a whole helluva lot about potential errors, if only because we know they're gonna land on OUR desks, most likely when we'd rather be surfing the web, or learning a new programming language, or chatting to/drooling over the girl in the next aisle who works in marketing and who is seriously out of our league - my point being, errors concern us. Avoiding them, handling them properly - these things are what set professional developers apart from dweeb wannabees and management strikers. Which gets us to the line of code right after the `INSERT` statement:
**EXCEPTION**
That's right - we know things can go wrong with that `INSERT` statement - but because we *ARE* men, and we *ARE* responsible programmers, we're gonna Do The Right Thing, which in this case means "Handle The Exception We Can Forsee". And what do we do?
```
WHEN DUP_VAL_ON_INDEX THEN
```
GREAT! We KNOW we can get a DUP\_VAL\_ON\_INDEX exception, because that's what's gonna get thrown when we try to insert a user that already exists. And then we'll Do The Right Thing:
```
EXIT; -- fine - the user already exists.
```
which in this case is to ignore the error completely. No, really! We're trying to insert a new user. The user we're trying to insert is already there. What's not to love? Now, it may well be that in that mystical, mythical place called The Real World it's just possible that it might be considered gauche to simply ignore this fact, and there might be a requirement to do something like log the fact that someone tried to add an already-extant user - but here in PretendLand we're just going to say, fine - the user already exists so we're happy.
BUT WAIT - there's **more**! Not ONLY are we going to handle (and, yeah, ok, ignore) the DUP\_VAL\_ON\_INDEX exception, **BUT** we will also handle EVERY OTHER POSSIBLE ERROR CONDITION KNOWN TO MAN-OR-DATABASE KIND!!!
```
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE(TO_CHAR(SYSDATE, 'DD-MON-YYYY HH24:MI:SS') ||
' Error in ADD_USER : ' || SQLCODE || ' : ' || SQLERRM);
RAISE;
```
Which means we'll spit out a somewhat useful error message telling use WHEN, WHERE, and WHAT went wrong, and then re-raise the exception (whatever it might be) so that whomsoever called us gets it dumped gracelessly into THEIR lap so THEY can handle it. (Serves 'em right for calling us, the lazy so-and-so's...).
So, now you know.
Go thou and do good works.
And...share and enjoy. | You forgot to add `(` and `)` in IF statement:
```
CREATE OR REPLACE PROCEDURE add_user
IS
BEGIN
IF NOT EXISTS (SELECT * FROM tab WHERE tab.id = '111') THEN
INSERT INTO tab(id, name, job, city, phone)
VALUES(111, 'Frank', 'Programmer', 'Chicago', '111111111');
END IF;
END;
``` |
147,747 | As a photon has no mass and must always have velocity *c*, if I were to shine a laser straight up (so Earth's gravity would be pulling straight back on it), what would the effect be on the photon? It wouldn't slow it down nor divert it, correct? My understanding is that it would reduce the frequency of the photon (as it's kinetic energy must be reduced, just as a classical object would lose kinetic energy). If it's the case that only gravitational redshift would occur given this trajectory (and please correct me if I am wrong there), I have two similar questions:
Would not light leaving a galaxy therefore be affected by a gravitational redshift? Is that included when physicists perform calculations regarding the expansion of galaxies away from us (and how accurate could these calculations be, given general estimates of mass distributions, etc., particularly given dark matter's gravitational effects)? If not, could it be that what we now *think* is a separation of these galaxies is somewhat, primarily, or even completely just light being affected by gravity?
Also, would not light then be able to escape a black hole provided it entered in precisely perpendicular to the event horizon and the black hole was not moving at all orthogonally to the photon's trajectory? (Or, perhaps more plausibly, if a photon is emitted from inside the black hole with a relative velocity of *c* towards the event horizon.) And then just come out the other side severely redshifted (to a frequency of almost 0 Hz)? I'm familar with the GR equations for gravitational redshift, but it also does not work inside the Schwarzschild radius (as the denominator becomes a square root of a negative number).
Apologies if this is just confused ramblings of someone who knows just enough to be dangerous. | 2014/11/20 | [
"https://physics.stackexchange.com/questions/147747",
"https://physics.stackexchange.com",
"https://physics.stackexchange.com/users/64831/"
] | For the first question: Sure, light emitted by a galaxy is affected by the gravitational redshift, but the effect is small and independent of the distance of the galaxy from us. (See also the question "[Why is “gravitational” red-shift neglected in galaxy and galaxy cluster scales?](https://physics.stackexchange.com/questions/216213/why-is-gravitational-red-shift-neglected-in-galaxy-and-galaxy-cluster-scales)".)
For the second question: Once inside the black hole, you can't emit the photon towards the horizon, because every valid direction either a photon or a massive particle could travel is towards the center of the black hole. In a sense, trying to avoid the singularity once inside the horizon is like trying to avoid tomorrow when outside. | The question presupposes that photons would be emitted from the hard core of the black hole - that is, that they would fly into the air and then fall back in.
The black hole is not black on the inside when looking out. On the contrary, on the inside of the black hole, the sky would be bright.
Any laser pointed into the sky would transfer less energy to the sky than it received from it, therefore the net transfer of energy between the sky and the laser (from a laser of ordinary power) would still be into the laser, not out of it.
Incidentally, this does seem to suggest that we could communicate into black holes if there was appropriate equipment on both sides - by measuring the variance in the amount of energy going into a certain point (since a laser pointed out from inside the black hole would attenuate the absorbtion of energy from outside), though the measurement would have to take place over extraordinary amounts of Earth-time relative to time in the black hole.
The effective refractive index of the internal sky of the black hole would also require a laser there of extraordinary fine focus and alignment. |
15,063,724 | I need help to convert following ql query to Linq to Sql query.
```
select Name, Address
from Entity
group by Name, Address
having count(distinct LinkedTo) = 1
```
Idea is to find all unique Name, Address pairs who only have 1 distinct LinkedTo value. Remember that there are other columns in the table as well. | 2013/02/25 | [
"https://Stackoverflow.com/questions/15063724",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1509736/"
] | I would try something like this:
```
Entity.GroupBy(e => new { e.Name, e.Address})
.Where(g => g.Select(e => e.LinkedTo).Distinct().Count() == 1)
.Select(g => g.Key);
```
You should put a breakpoint after that line and check the SQL that is generated to find what is really going to the database. | You could use:
```
from ent in Entities
group ent by new { ent.Name, ent.Address } into grouped
where grouped.Select(g => g.LinkedTo).Distinct().Count() == 1
select new { grouped.Key.Name, grouped.Key.Address }
```
The generated SQL does not use a `having` clause. I'm not sure LINQ can generate that. |
27,787,923 | I have a very specific problem in which I must do something like (in HQL):
```
insert into EntityA(field1, field2, field3, field4, field5)
select
:paramForField1,
:paramForField2,
:paramForField3,
:paramForField4,
:paramForField5
from
EntityB
where
...
```
The parameters are being passed using `Query.setParameter(String, Object)` ([JavaDoc](https://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/Query.html#setParameter(java.lang.String,%20java.lang.Object) "JavaDoc")) and they are String, String, String, Date and an Enum.
Although the parameter number is right (five parameters for five fields), Hibernate keeps raising the following exception:
```
...
Caused by: org.hibernate.QueryException: number of select types did not match those for insert [insert into ...]
at org.hibernate.hql.ast.tree.IntoClause.validateTypes(IntoClause.java:116)
at org.hibernate.hql.ast.tree.InsertStatement.validate(InsertStatement.java:57)
at org.hibernate.hql.ast.HqlSqlWalker.postProcessInsert(HqlSqlWalker.java:701)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.insertStatement(HqlSqlBaseWalker.java:513)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:255)
at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:254)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:185)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:136)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:101)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:80)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:94)
at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:156)
at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:135)
at org.hibernate.impl.SessionImpl.createQuery(SessionImpl.java:1651)
...
```
I'm using Hibernate 3.3.2 GA.
Thanks in advance. | 2015/01/05 | [
"https://Stackoverflow.com/questions/27787923",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/304556/"
] | Starting with hibernate 4.3 this is possible. Versions before hibernate 4.3 did not support parameters in the select clause. | Try this instead:
```
Class<?> entityAClass = EntityA.class;
Field field1 = entityAClass.getDeclaredField("paramForField1");
field1.setAccessible(true);
String paramForField1 = field1.getName();
Field field2 = entityAClass.getDeclaredField("paramForField2");
field2.setAccessible(true);
String paramForField2 = field2.getName();
Field field3 = entityAClass.getDeclaredField("paramForField3");
field3.setAccessible(true);
String paramForField3 = field3.getName();
String hqlInsert = String.format(
"insert into EntityA(%1$s, %2$s, %3$s)" +
"select c.%1$s, c.%2$s, c.%3$s from EntityB b" +
"where ...",
paramForField1, paramForField2, paramForField3);
int createdEntities = s.createQuery( hqlInsert )
.executeUpdate();
```
Hibernate doesn't support parametrized INSERTs or SELECTs. You can use parameters in the WHERE clause only.
Any SQL string formatting is susceptible to [SQL injection](http://en.wikipedia.org/wiki/SQL_injection), that's why you need to use the Java Reflection idiom I suggested. If you don't supply a valid EntityA field name, then the field won't be resolved and an exception will be thrown.
This way you can build a dynamic query and also make sure you don't expose your code to SQL injection. |
71,508,566 | >
> Your app contains content that doesn’t comply with the Device and
> Network Abuse policy. We found your app is using a non-compliant
> version of Huawei Mobile Services SDK which contains code to download
> or install applications from unknown sources outside of Google Play.
>
>
>
**I am using Huawei Mobile Services SDK for Auto Eraser.**
>
> List of used dependency
>
>
>
```
implementation 'com.huawei.hms:ml-computer-vision-segmentation:3.0.0.301'
implementation 'com.huawei.hms:ml-computer-vision-image-segmentation-body-model:2.0.2.300'
buildscript {
repositories {
mavenCentral()
jcenter()
google()
maven {url 'http://developer.huawei.com/repo/'}
}
dependencies {
classpath 'com.android.tools.build:gradle:4.2.2'
//Auto eraser
classpath 'com.huawei.agconnect:agcp:1.3.1.300'
}
}
```
>
> Added below meta data in manifest.xml
>
>
>
```
<meta-data
android:name="com.huawei.hms.ml.DEPENDENCY"
android:value="imgseg" />
``` | 2022/03/17 | [
"https://Stackoverflow.com/questions/71508566",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6676310/"
] | **Update:**
*Note*:
If you have confirmed that the latest SDK version is used, before submitting a release to Google, please check the apks in all Testing track on Google Play Console(including Open testing, Closed testing, Internal testing). Ensure that the APKs on all tracks(including paused track) have updated to the latest HMS Core SDK.
---
HMS Core SDKs have undergone some version updates recently. To further improve user experience, update the HMS Core SDK integrated into your app to the latest version.
| **HMS Core SDK** | **Version** | **Link** |
| --- | --- | --- |
| Keyring | com.huawei.hms:keyring-credential:6.4.0.302 | [Link](https://developer.huawei.com/consumer/en/doc/development/Security-Guides/version-change-history-0000001179180527) |
| Location Kit | com.huawei.hms:location:6.4.0.300 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/version-change-history-0000001050986155) |
| Nearby Service | com.huawei.hms:nearby:6.4.0.300 | [Link](https://developer.huawei.com/consumer/en/doc/development/system-Guides/version-change-history-0000001050040574) |
| Contact Shield | com.huawei.hms:contactshield:6.4.0.300 | [Link](https://developer.huawei.com/consumer/en/doc/development/system-Guides/version-change-history-0000001058738898) |
| Video Kit | com.huawei.hms:videokit-player:1.0.12.300 | [Link](https://developer.huawei.com/consumer/en/doc/development/Media-Guides/version-change-history-0000001050199403) |
| Wireless kit | com.huawei.hms:wireless:6.4.0.202 | [Link](https://developer.huawei.com/consumer/en/doc/development/system-Guides/version-change-history-0000001050989943) |
| FIDO | com.huawei.hms:fido-fido2:6.3.0.304com.huawei.hms:fido-bioauthn:6.3.0.304com.huawei.hms:fido-bioauthn-androidx:6.3.0.304 | [Link](https://developer.huawei.com/consumer/en/doc/development/Security-Guides/version-change-history-0000001050750051) |
| Panorama Kit | com.huawei.hms:panorama:5.0.2.308 | [Link](https://developer.huawei.com/consumer/en/doc/development/Media-Guides/version-change-history-0000001050137382) |
| Push Kit | com.huawei.hms:push:6.5.0.300 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/android-app-version-0000001074227861) |
| Account Kit | com.huawei.hms:hwid:6.4.0.301 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/version-change-history-0000001050048874) |
| Identity Kit | com.huawei.hms:identity:6.4.0.301 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/version-change-history-0000001050040475) |
| Safety Detect | com.huawei.hms:safetydetect:6.4.0.301 | [Link](https://developer.huawei.com/consumer/en/doc/development/Security-Guides/version-change-history-0000001050156329) |
| Health Kit | com.huawei.hms:health:6.5.0.300 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/version-change-history-0000001057072287) |
| In-App Purchases | com.huawei.hms:iap:6.4.0.301 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/version-change-history-0000001050065947) |
| ML Kit | com.huawei.hms:ml-computer-vision-ocr:3.6.0.300com.huawei.hms:ml-computer-vision-cloud:3.5.0.301com.huawei.hms:ml-computer-card-icr-cn:3.5.0.300com.huawei.hms:ml-computer-card-icr-vn:3.5.0.300com.huawei.hms:ml-computer-card-bcr:3.5.0.300com.huawei.hms:ml-computer-vision-formrecognition:3.5.0.302com.huawei.hms:ml-computer-translate:3.6.0.312com.huawei.hms:ml-computer-language-detection:3.6.0.312com.huawei.hms:ml-computer-voice-asr:3.5.0.301com.huawei.hms:ml-computer-voice-tts:3.6.0.300com.huawei.hms:ml-computer-voice-aft:3.5.0.300com.huawei.hms:ml-computer-voice-realtimetranscription:3.5.0.303com.huawei.hms:ml-speech-semantics-sounddect-sdk:3.5.0.302com.huawei.hms:ml-computer-vision-classification:3.5.0.302com.huawei.hms:ml-computer-vision-object:3.5.0.307com.huawei.hms:ml-computer-vision-segmentation:3.5.0.303com.huawei.hms:ml-computer-vision-imagesuperresolution:3.5.0.301com.huawei.hms:ml-computer-vision-documentskew:3.5.0.301com.huawei.hms:ml-computer-vision-textimagesuperresolution:3.5.0.300com.huawei.hms:ml-computer-vision-scenedetection:3.6.0.300com.huawei.hms:ml-computer-vision-face:3.5.0.302com.huawei.hms:ml-computer-vision-skeleton:3.5.0.300com.huawei.hms:ml-computer-vision-livenessdetection:3.6.0.300com.huawei.hms:ml-computer-vision-interactive-livenessdetection:3.6.0.301com.huawei.hms:ml-computer-vision-handkeypoint:3.5.0.301com.huawei.hms:ml-computer-vision-faceverify:3.6.0.301com.huawei.hms:ml-nlp-textembedding:3.5.0.300com.huawei.hms:ml-computer-ner:3.5.0.301com.huawei.hms:ml-computer-model-executor:3.5.0.301 | [Link](https://developer.huawei.com/consumer/en/doc/development/hiai-Guides/version-changehistory-0000001050040023) |
| Analytics Kit | com.huawei.hms:hianalytics:6.5.0.300 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/version-change-history-0000001050705116) |
| Dynamic Tag Manager | com.huawei.hms:dtm-api:6.5.0.300 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/version-change-history-android-0000001050043913) |
| Site Kit | com.huawei.hms:site:6.4.0.304 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/android-sdk-version-change-history-0000001050156624) |
| HEM Kit | com.huawei.hms:hemsdk:1.0.4.303 | [Link](https://developer.huawei.com/consumer/en/doc/development/system-Guides/hem-version-change-history-0000001058818904) |
| Map Kit | com.huawei.hms:maps:6.5.0.301 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/android-sdk-version-change-history-0000001050156688) |
| Wallet Kit | com.huawei.hms:wallet:4.0.5.300 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/version-change-history-0000001050042326) |
| Awareness Kit | com.huawei.hms:awareness:3.1.0.302 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/version-change-history-0000001050033093) |
| Crash | com.huawei.agconnect:agconnect-crash:1.7.0.300 | [Link](https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-crash-sdkchangenotes-0000001054941952) |
| APM | com.huawei.agconnect:agconnect-apms:1.5.2.310 | [Link](https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/agc-apm-android-releasenotes-0000001052887266) |
| Ads Kit | com.huawei.hms:ads-prime:3.4.55.300 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMSCore-Guides/publisher-service-version-change-history-0000001050066909) |
| Paid Apps | com.huawei.hms:drm:2.5.8.301 | [Link](https://developer.huawei.com/consumer/en/doc/development/AppGallery-connect-Guides/appgallerykit-paidapps-sdkchangenotes-0000001073783146) |
| Base | com.huawei.hms:base:6.4.0.303 | |
Required versions for cross-platform app development:
| Platform | Plugin Name | Version | Link |
| --- | --- | --- | --- |
| React Native | react-native-hms-analytics | 6.3.2-301 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050159909) |
| | react-native-hms-iap | 6.4.0-301 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050726208) |
| | react-native-hms-location | 6.4.0-300 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050140226) |
| | react-native-hms-map | 6.3.1-304 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050141050) |
| | react-native-hms-push | 6.3.0-304 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050155836) |
| | react-native-hms-site | 6.4.0-300 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050178629) |
| | react-native-hms-nearby | 6.2.0-301 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001054140445) |
| | react-native-hms-account | 6.4.0-301 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050766267) |
| | react-native-hms-ads | 13.4.54-300 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050438945) |
| | react-native-hms-adsprime | 13.4.54-300 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050438945) |
| | react-native-hms-availability | 6.4.0-303 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001137756139) |
| Cordova(Ionic-CordovaIonic-Capacitor) | cordova-plugin-hms-analyticsionic-native-hms-analytics | 6.3.2-301 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050134727) |
| | cordova-plugin-hms-locationionic-native-hms-location | 6.4.0-300 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050142197) |
| | cordova-plugin-hms-nearbyionic-native-hms-nearby | 6.2.0-301 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001062262624) |
| | cordova-plugin-hms-accountionic-native-hms-account | 6.4.0-301 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001051086314) |
| | cordova-plugin-hms-pushionic-native-hms-push | 6.3.0-304 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050135703) |
| | cordova-plugin-hms-siteionic-native-hms-site | 6.4.0-300 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050175533) |
| | cordova-plugin-hms-iapionic-native-hms-iap | 6.4.0-301 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001126433215) |
| | cordova-plugin-hms-availabilityionic-native-hms-availability | 6.4.0-303 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001085863384) |
| | cordova-plugin-hms-adsionic-native-hms-ads | 13.4.54-300 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050312764) |
| | cordova-plugin-hms-adsprimeionic-native-hms-adsprime | 13.4.54-300 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050312764) |
| | cordova-plugin-hms-mapionic-native-hms-map | 6.0.1-305 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050204329) |
| | cordova-plugin-hms-mlionic-native-hms-ml | 2.0.5-303 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001051085722) |
| Flutter | huawei\_safetydetect | 6.4.0+301 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001061666870) |
| | huawei\_iap | 6.2.0+301 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050730646) |
| | huawei\_health | 6.3.0+302 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001074429198) |
| | huawei\_fido | 6.3.0+304 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001077561088) |
| | huawei\_push | 6.3.0+304 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050417995) |
| | huawei\_account | 6.4.0+301 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050726410) |
| | huawei\_ads | 13.4.55+300 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050196419) |
| | huawei\_analytics | 6.5.0+300 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050171091) |
| | huawei\_map | 6.5.0+301 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050190751) |
| | huawei\_hmsavailability | 6.4.0+303 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001128012871) |
| | huawei\_location | 6.0.0+303 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050433501) |
| | huawei\_adsprime | 13.4.55+300 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050196419) |
| | huawei\_ml | 3.2.0+301 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001051432486) |
| | huawei\_site | 6.0.1+304 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050179102) |
| Xamarin | Huawei.Hms.Hianalytics | 6.4.1.302 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050141587) |
| | Huawei.Hms.Location | 6.4.0.300 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050140266) |
| | Huawei.Hms.Nearby | 6.2.0.301 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001062117591) |
| | Huawei.Hms.Push | 6.3.0.304 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050136488) |
| | Huawei.Hms.Site | 6.4.0.300 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050135803) |
| | Huawei.Hms.Fido | 6.3.0.304 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001096426801) |
| | Huawei.Hms.Iap | 6.4.0.301 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050767521) |
| | Huawei.Hms.Hwid | 6.4.0.301 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001051005767) |
| | Huawei.Hms.Ads-prime | 3.4.54.302 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050176478) |
| | Huawei.Hms.Ads | 3.4.54.302 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050176478) |
| | Huawei.Hms.Maps | 6.5.0.301 | [Link](https://developer.huawei.com/consumer/en/doc/development/HMS-Plugin-Guides/version-change-history-0000001050141070) |
If you have any further questions or encounter any issues integrating any of these kits, please feel free to contact us.
| **Region** | **Email** |
| --- | --- |
| Europe | developereu@huawei.com |
| Asia Pacific | developerapac@huawei.com |
| Latin America | developerla@huawei.com |
| Middle East & Africa | developermea@huawei.com |
| Russia | developer\_ru@huawei.com | | I solved it by doing similar to what @Daniel has suggested to avoid such worries in the future:
1. Create different product flavors in your app level Gradle file:
```
android {
...
flavorDimensions 'buildFlavor'
productFlavors {
dev {
dimension 'buildFlavor'
}
production {
dimension 'buildFlavor'
}
huawei {
dimension 'buildFlavor'
}
}
}
```
2. Restrict the Huawei related dependencies so they're only available for Huawei product flavor:
```
huaweiImplementation "com.huawei.hms:iap:3.0.3.300"
huaweiImplementation "com.huawei.hms:game:3.0.3.300"
huaweiImplementation "com.huawei.hms:hwid:5.0.1.301"
huaweiImplementation "com.huawei.hms:push:5.0.0.300"
huaweiImplementation "com.huawei.hms:hianalytics:5.0.3.300"
huaweiImplementation "com.huawei.hms:location:5.0.0.301"
```
3. Since `dev` and `production` flavors are not going to have Huawei dependencies now, you may get build errors for the Huawei related classes that you use in your app.
For that I create dummy classes with the same packages tree as Huawei, for instance:
app > src > dev > java > com > huawei > hms > analytics > HiAnalytics.kt
```
class HiAnalytics {
companion object {
@JvmStatic
fun getInstance(context: Context): HiAnalyticsInstance {
return HiAnalyticsInstance()
}
}
}
```
4. This solves the `Cannot resolve symbol` error when trying to import Huawei classes in your main, dev, or production flavors and you can import those classes anywhere:
```
import com.huawei.hms.analytics.HiAnalytics
```
Now if you change the build variant to `dev`, you should have access to the dummy classes in your app. If you change it to `huawei`, you should be able to access the classes from Huawei dependencies. |
1,146,387 | I'm using Subtitle Edit to make subtitles for a video, it is supposed to let the user choose between several video engines, one of them is VLC. I can only choose DirectShow since the other options are [disabled](https://i.stack.imgur.com/D2Lz0.png). I have installed the latest version of both programs and the LAV splitters, nothing seems to be working. I'd appreciate some help.
OS: Win 7
VLC: 2.2.4
SubEdit:3.2 | 2016/11/16 | [
"https://superuser.com/questions/1146387",
"https://superuser.com",
"https://superuser.com/users/530423/"
] | Is your computer 32-bit or 64-bit? You must install the VLC version equivalent to your computer. If it still doesn't work, reinstall VLC. I had to reinstall VLC 64-bit version twice to make it work.
<http://www.nikse.dk/SubtitleEdit/Help#codecs> | I could not select Media Classic Player when reinstalled SE because I upgraded to Windows 8.1. I tried many different things but did not work. Finally, I then realized it might because the codecs (K-Lite) were installed in the D drive. I uninstalled and reinstalled them in C and the problem was solved! |
53,184,161 | I am writing a program in Java that needs to take a numeric phone number from the user, for example: 555-GET-FOOD and then print all the numbers, 555-438-3663.
I ran into some issues because my program just print one number, not all of it. Also, How do I make it that the user can enter dashes as part of their input, for example: 555-GET-FOOD.
This is what I've done so far:
```
import java.util.*;
public class NumberTranslator {
public static void main(String[] args) {
// Create Scanner for user input
Scanner input = new Scanner(System.in);
// Ask the user to enter the phone number
System.out.println("Please enter the Phone number in this format: (555-XXX-XXXX) ");
// Save the phone number into a string
String phoneNumber = input.nextLine();
//phoneNumber = phoneNumber.substring(0, 3) + "-" + phoneNumber.substring(3,6)+"-"+phoneNumber.substring(6,10)+"-";
phoneNumber = phoneNumber.toUpperCase();
long phoneNumberTranslated = fullPhoneNumber(phoneNumber);
System.out.println(phoneNumberTranslated);
}
public static long fullPhoneNumber(String phoneNumber) {
long number = 0;
int strLength = phoneNumber.length();
for(int i = 0; i < strLength; i++) {
char letter = phoneNumber.charAt(i);
if(Character.isLetter(letter)) {
switch(letter) {
case 'A' : case 'B' : case 'C' : number = 2; break;
case 'D' : case 'E' : case 'F' : number = 3; break;
case 'G' : case 'H' : case 'I' : number = 4; break;
case 'J' : case 'K' : case 'L' : number = 5; break;
case 'M' : case 'N' : case 'O' : number = 6; break;
case 'P' : case 'Q' : case 'R' : case 'S' : number = 7; break;
case 'T' : case 'U' : case 'V' : number = 8; break;
case 'W' : case 'X' : case 'Y' : case 'Z' : number = 9; break;
}
}
else if(Character.isDigit(letter)) {
Character.getNumericValue(letter);
}
else {
System.out.println("Invalid character!");
}
}
return number;
}
}
```
The Output I get is as follow:
Please enter the Phone number in this format: (555-XXX-XXXX)
555getfood
3 | 2018/11/07 | [
"https://Stackoverflow.com/questions/53184161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] | I suggest that you simply create a map for these
```
Map<Character, String> numbers = new HashMap <Character, String> ();
numbers.put('A', "1" );
numbers.put('B', "1" );
numbers.put('C', "1" );
numbers.put('D', "2" );
numbers.put('E', "2" );
numbers.put('F', "2" );
// etc
for (char c: phoneNumber.toCharArray()) {
String val = numbers.get (c);
if (val == null) val = String.valueOf(c); // if no mapping use as it is
System.out.print (val);
}
``` | The issue you have is that you aren't adding to the number - you're overwriting it each time. It would probably be easier to have number be a String and append the corresponding digit to the result string during each iteration of the loop.
Also, in the "else if", you're not doing anything with the expression - you have to store that value in some variable or it doesn't get saved anywhere.
Finally, to let the user input dashes, just add another "else if" where you check if the character is '-', and if it is, you append a dash to the result string. |
2,513,058 | I have an image folder stored at ~/Content/Images/
I am loading these images via
```
<img src="/Content/Images/Image.png" />
```
Recently, the images aren't loading and I am getting the following errors in my error log. What's weird is that some images load fine, while others do not load.
Anyone have any idea what is wrong with my routes? Am I missing an ignore route for the /Content/ folder?
I am also getting the same error for favicon.ico and a bunch of other image files...
```
<Fatal> -- 3/25/2010 2:32:38 AM -- System.Web.HttpException: The controller for path '/Content/Images/box_bottom.png' could not be found or it does not implement IController.
at System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(Type controllerType)
at System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName)
at System.Web.Mvc.MvcHandler.ProcessRequest(HttpContextBase httpContext)
at System.Web.Mvc.MvcHandler.ProcessRequest(HttpContext httpContext)
at System.Web.Mvc.MvcHandler.System.Web.IHttpHandler.ProcessRequest(HttpContext httpContext)
at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
```
My current routes look like this:
```
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
routes.MapRoute(
"ControllerDefault", // Route name
"{controller}/project/{projectid}/{action}/{searchid}", // URL with parameters
new { controller = "Listen", action = "Index", searchid = "" } // Parameter defaults
);
```
Thanks! | 2010/03/25 | [
"https://Stackoverflow.com/questions/2513058",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23695/"
] | I would insert another ignored route immediately under the first one.
```
routes.IgnoreRoute("Content/Images/{*pathInfo}");
``` | ```
<img src="<%= Url.Content("~/Content/Images/Image.png")%>" alt="does this work?" />
``` |
53,252,030 | I am struggling with this complex query. I am trying to insert the order position of some products.
For example,
I have currently table 1 with a position of NULL, I want to group each Product ID and assign each size a menu position based on ProductID group and using this FIND\_IN\_SET:
`FIND_IN_SET(size,"UNI,XS,S,M,L,XL,XXL,3XL,4XL,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60") asc;`
In other words, I want it to look like Table2.
Table1
```
ID | ProductID | Size | Menu_position
1 | 100 | S | NULL
2 | 100 | M | NULL
3 | 100 | L | NULL
4 | 101 | 40 | NULL
5 | 101 | 41 | NULL
6 | 101 | 42 | NULL
7 | 102 | XS | NULL
8 | 102 | L | NULL
```
Table2
```
ID | ProductID | Size | Menu_position
1 | 100 | S | 1
2 | 100 | M | 2
3 | 100 | L | 3
4 | 101 | 40 | 1
5 | 101 | 41 | 2
6 | 101 | 42 | 3
7 | 102 | XS | 1
8 | 102 | L | 2
```
What I collected so far:
**Number of products Group:**`select count(distinct ProductID) from Table1`
**Sort size based on specific order:** `SELECT * FROM Table1 ORDER BY FIND_IN_SET(size,"UNI,XS,S,M,L,XL,XXL,3XL,4XL,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60") asc;` | 2018/11/11 | [
"https://Stackoverflow.com/questions/53252030",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10487045/"
] | You can use variables in pre-MySQL 8.0:
```
SELECT t1.*,
(@rn := if(@p = productid, @rn + 1,
if(@p := productid, 1, 1)
)
) as menu_position
FROM (SELECT t1.*
FROM Table1 t1
ORDER BY ProductId,
FIND_IN_SET(size, 'UNI,XS,S,M,L,XL,XXL,3XL,4XL,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60') asc
) AS alias CROSS JOIN
(SELECT @p := -1, @rn := 0) params;
```
In MySQL 8+, this is much simpler:
```
select t1.*,
row_number() over (partition by productid order by FIND_IN_SET(size, 'UNI,XS,S,M,L,XL,XXL,3XL,4XL,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60')) as menu_position
from table1 t1
``` | Create a two-column table containing all the the `Size` values in one column and the integer order of those sizes in the second column--call that table `menu_pos`. Join this to your `Table` on size, to produce a table or view (call this `product_pos`) containing columns `product_id`, `size`, and `menu_pos`. Then modify the `menu_pos` values to ensure that they are strictly sequential using a window function, such as:
```
select
product_id,
size,
rank() over (partition by product_id order by menu_pos) as new_menu_pos
from
product_pos;
```
Window functions require MySQL 8. |
88,766 | I think the title explains it all.
In more detail, I'm using the data set from [this Kaggle](https://www.kaggle.com/camnugent/sandp500?select=merge.sh) page.
The data set doesn't come with a daily change in percent, so I copied the dataset and made a new column for the daily percentage change, which I calculate by $$\Delta daily = \frac{Opening Price-Closing Price}{Opening Price}.$$
I went to do a basic sanity check, and make sure that nothing is going wrong with my column for daily percentage change.
I first picked a few dates and companies and calculated the $\Delta daily$ by hand, then compared it to the value my code gives; everything matched up there. However, I then tried to look at the mean $\Delta daily$ for a few stocks that have been wildly successful over the last few years (Facebook, netflix, amazon, etc). When I take the average $\Delta daily$, a lot of these companies are coming up with an average daily percentage change that is very near zero, or even slightly negative. Worth noting, I tried taking the average growth over several different time intervals; I'd even restrict myself to stretches of time where a stock had very few dips, but still the average $\Delta daily$ for the restricted time windows. For example AMZN was selling at roughly 300\$/share in january of 2015 and roughly 700\$/share in january of 2016, but when I look at $\Delta daily$ for this period of time, I get $-.0003913$. More than double the growth over the year, but an average daily change of $-.4$%? That seems way off.
I began wondering if there was something wrong with the dataset, but then I chose a few of the tech giants and plotted their growth against time over the last few years, and the graph is a near perfect resemblance of the growth chart that I see elsewhere, so the data seems to be fine.
I'm wondering if anyone has any thoughts on what's going on here. Is my intuition just wrong? Is it possible to have an average daily return that's near zero or negative, but still very strong growth in the long run? Is there something about the way I'm building my `percent.delta` vector that's incorrect?
There's really not much code to share, but here's what I have, in case it's useful. Sorry if it's a little sloppy; I was just messing around with some stuff and so didn't make it as tidy as I would for a more formal project.
Thanks in advance for any thoughts.
```
allstocks<-read.csv(file='all_stocks_5yr.csv')
allstocks2<-read.csv(file='all_stocks_5yr.csv') #copy data to alter
percent_delta <-as.vector(numeric(619040)) #no. observations; vector that will contain daily %change
for (i in 1:619040){
percent_delta[i]<-(allstocks2$open[i]-allstocks2$close[i])/allstocks2$open[i]
} #fill vector with daily %change
allstocks2$percent.delta<-percent_delta
#just a check that trends in R match trends seen elsewhere. Can use smth other than NFLX
plot(subset(allstocks2, Name=="NFLX")$date, subset(allstocks2, Name=="NFLX")$close)
#avg percent.delta for, e.g., AMZN between, e.g., jan2015-jan2016
mean(subset(subset(allstocks2,Name=="AMZN"),as.Date(date)>=as.Date("2015-01-23")
& as.Date(date)<=as.Date("2016-01-04"))$percent.delta)
#avg percent_delta for, e.g., AMZN between, e.g., jan2015-jan2016
``` | 2021/01/31 | [
"https://datascience.stackexchange.com/questions/88766",
"https://datascience.stackexchange.com",
"https://datascience.stackexchange.com/users/111169/"
] | This simply has to do with the fact that returns are compounding, i.e. the daily percentage changes are cumulative. If a stock gets has a daily percentage change of 1% for a single year (trading for 252 days), and therefore also an average change of 1% the total return over this year will not be equal to 1%. The actual return is equal to $(1 + 0.01) ^{252} - 1 \approx 11.274$, meaning around **1127.4%**, which is much larger than the average daily change of 1%. To get the correct total return over a specific period you have to multiply the percentage change for each period, which in your case is daily. | Had my subtraction backwards.e
Should have been $\frac{close-open}{open}$, not $\frac{open-close}{open}$
Whoops |
238,750 | I recently read somewhere a single word that described a person who enjoyed an argument - in the sense of a lively debate. It may have been a word implying a positive or neutral context but I don't think it was negative or derogatory.
A complex word (uncommon in colloquial use), medium length (7-8 letters), possibly ending in -ic. *One or more of these points may be a false memory.*
Any ideas? | 2015/04/11 | [
"https://english.stackexchange.com/questions/238750",
"https://english.stackexchange.com",
"https://english.stackexchange.com/users/116780/"
] | ***contentious, quarrelsome, cantankerous, O.E. contekors, [grizzle guts](https://books.google.ca/books?id=4J5Fo7OSfXgC&pg=PT593&dq=quarrelsome%20slang&hl=en&sa=X&ei=nGopVY12t4CxBPq4gLgH&redir_esc=y#v=onepage&q=quarrelsome%20slang&f=false), obstructive, argol-bargolous, quarrelsome; argy-bargy (—1887) [is mostly Scottish], scolding; ill- natured, disputatious, [boiler (sl)](https://books.google.ca/books?id=5GpLcC4a5fAC&pg=PA149&dq=quarrelsome%20slang&hl=en&sa=X&ei=2GspVZL7BMmIsQSau4DgBg&redir_esc=y#v=onepage&q=quarrelsome%20slang&f=false)*** | Some good answers here but just wanted to add **devil's advocate** - <https://en.wikipedia.org/wiki/Devil%27s_advocate> |
24,690,160 | **What is the difference between the `div` tag and the new HTML5 `aside` tag?**
W3Schools has a very similar description for the two -
* [**Aside**](http://www.w3schools.com/tags/tag_aside.asp)
* [**Div**](http://www.w3schools.com/tags/tag_div.asp)
I have also seen many sites use the `aside` tag where a `div` tag would be perfectly fine.
Although, when I put them both into practise, they behave the same way, like so:
```
<aside>
<h4>This is a heading</h4>
<p>This is a very short paragraph.</p>
</aside>
<div>
<h4>This is a heading</h4>
<p>This is a very short paragraph.</p>
</div>
```
**[WORKING EXAMPLE](http://jsfiddle.net/X37Y4/)**
So my question is, what is the main difference between the two? When should one be used over the other? | 2014/07/11 | [
"https://Stackoverflow.com/questions/24690160",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1799136/"
] | ### Short answer:
>
> **`<div>`** tag defines a general division or section in HTML.
>
>
> **`<aside>`** tag has the same representations as a div, but contains content that is only related to the main page content.
>
>
>
### Difference
>
> Both have the same behavior but have a different meaning logically.
>
>
> | The only practical difference (for now at least) is that old browsers do not recognize `aside` at all. They will treat it as undefined, not as a block element like `div`. Old versions of IE do not even let you style an `aside` element, though there are JavaScript-based ways to fix this.
The theoretical difference is explained in HTML5 drafts such as the current [HTML5 LC](http://www.w3.org/TR/html5/). Note that w3schools.com is not an authority of any kind; see <http://w3fools.com>. |
9,671,780 | Basically I want to be able, in Javascript (JQuery optionally), to search into a JSON with nested elements for a particular element and edit it.
Ex. search for "components" with id 110 and change the name to "video card".
Notice the following JSON is just an example. I am wondering if javascript libraries or good tricks exist to do such a thing, I don't think traversing the whole json or writing my own methods is the best solution.
```
{
"computers": [
{
"id": 10,
"components": [
{
"id": 56,
"name": "processor"
},
{
"id": 24,
"name": "ram"
}
]
},
{
"id": 11,
"components": [
{
"id": 110,
"name": "graphic card"
},
{
"id": 322,
"name": "motherboard"
}
]
}
]
}
``` | 2012/03/12 | [
"https://Stackoverflow.com/questions/9671780",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/689763/"
] | You could try [linq.js](http://linqjs.codeplex.com/). | You can use this javascript lib, DefiantJS (<http://defiantjs.com>), with which you can filter matches using XPath on JSON structures. To put it in JS code:
```
var data = {
"computers": [
{
"id": 10,
"components": [
{ "id": 56, "name": "processor" },
{ "id": 24, "name": "ram" }
]
},
{
"id": 11,
"components": [
{ "id": 110, "name": "graphic card" },
{ "id": 322, "name": "motherboard" }
]
}
]
},
res = JSON.search( data, '//components[id=110]' );
res[0].name = 'video card';
```
Here is a working fiddle;
<http://jsfiddle.net/g8fZw/>
DefiantJS extends the global object JSON with the method "search" and returns an array with matches (empty array if no matches were found). You can try out the lib and XPath queries using the XPath Evaluator here:
<http://www.defiantjs.com/#xpath_evaluator> |
19,229,386 | I have installed `openssl` on a Microsoft Windows machine and I was trying to do this conversion:
From:
* `.pfx`
To:
* `.crt`
* `.pem`
* `.key`
But I keep getting this error trying to use certificate:
```
Mac verify error: invalid password?
``` | 2013/10/07 | [
"https://Stackoverflow.com/questions/19229386",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2855359/"
] | In my case it was special characters in password which confuse argument parser. So call without `-password ...` argument and typing password on request did the trick. | For xelat's solution, it's no longer working if you create `.pfx` with OpenSSL 3 because AES-256-CBC is a new default cipher despite most of devices are not supporting it. To solve this, use this command instead:
```sh
openssl pkcs12 -in path.p12 -out myoutput.pem -nocerts -nodes -password pass:<mypassword> -certpbe PBE-SHA1-3DES -keypbe PBE-SHA1-3DES -nomac
``` |
24,805,521 | What is the best practice to switch between `UIViewControllers` for iOS in `Objective-C`? Now I have a menu `UIViewController` and a game's main screen `UIViewController`. In the menu there's a "New game" `UIButton` which should switch to the game's main controller. I do it like this:
```
- (IBAction)newGameButtonClicked:(id)sender {
ViewController *gameViewController =
[self.storyboard instantiateViewControllerWithIdentifier:@"GameViewController"];
[self presentViewController:gameViewController animated:NO completion:^{
// ...
}];
}
```
When player dies, other view controller should be showed and I do it in the similar way like this:
```
MenuViewController *menuViewController =
[self.storyboard instantiateViewControllerWithIdentifier:@"MenuViewController"];
[self presentViewController:menuViewController animated:NO completion:^{
// ...
}];
```
Is it right or there is a better way to achieve this behavior?
Thanks in advance. | 2014/07/17 | [
"https://Stackoverflow.com/questions/24805521",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1608835/"
] | If you want to init an `UIViewController` from the `UIStoryboard` you can do it like in your example. I would just use a `UINavigationController` as parent `UIViewController` and push them to the `UINavigationController`.
```
NSString *strVC = [NSString stringWithFormat:@"%@", [MenuViewController class]];
MenuViewController *menuViewController =
[self.storyboard instantiateViewControllerWithIdentifier:strVC];
[self.navigationController pushViewController:menuViewController
animated:YES];
```
When using `segues` like @mehinger explained, use `[segue destinationViewController]`. But this is just needed if you want to set any variables to the `UIViewController` before pushing it. | Segues are the way to do when switching between view controllers:
```
- (IBAction)newGameButtonClicked:(id)sender {
[self performSegueWithIdentifier:@"goToGameViewController"];
}
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if(segue.identifier isEqualToString:@"goToGameViewController") {
GameViewController *gameViewController = [GameViewController new];
//do any other preparation you would like
}
}
```
In your storyboard you can then drag a segue from one view controller to the other and indicate its identifier as "goToGameViewController". |
36,867,049 | for some reason, logstash (version 1.5) can't process logs with this exception:
*{:timestamp=>"2016-04-26T09:20:12.141000-0400", :message=>"Failed parsing date from field", :field=>"time", :value=>"2016-04-26T09:20:03.520-04:00", :exception=>java.lang.IllegalArgumentException: Invalid format: "2016-04-26T09:20:03.520-04:00" is malformed at "T09:20:03.520-04:00", :level=>:warn}*
My Time field in json is:
```
"time":"25-04-2016 04:21:06.786"
```
my logstash configuration is:
```
filter {
if [type] == "json" {
json {
source => "message"
}
date {
match => [ "time", "dd-MM-yyyy HH:mm:ss", "dd-MM-yyyy HH:mm:ss:SSS", "dd-MM-yyyy HH:mm:ss.SSS", "yyyy-MM-dd HH:mm:ss,SSS" ]
}
}
}
```
On Elasticsearch side I see this exception:
*failed to parse date field [25-04-2016 04:48:14.305], tried both date format [dateOptionalTime], and timestamp number with locale []
java.lang.IllegalArgumentException: Invalid format: "25-04-2016 04:48:14.305" is malformed at "16 04:48:14.305"*
How do I fix this? | 2016/04/26 | [
"https://Stackoverflow.com/questions/36867049",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3323914/"
] | I had the same problem; Logstash will happily do its job, but then Elasticsearch would complain with this same error. You can see that '@timestamp' is produced with the correct variable. The key is understanding this sort of error is the bit where it says something like the following:
```
[2020-07-22 12:27:40,814][DEBUG][action.bulk ] [logs-p03] [logstash-2020.07.22][0] failed to execute bulk item (index) index {[logstash-2020.07.22][logs] ... org.elasticsearch.index.mapper.MapperParsingException: failed to parse [shibidp_timestamp]
...
Caused by: org.elasticsearch.index.mapper.MapperParsingException: failed to parse date field [20200722T002739Z], tried both date format [dateOptionalTime], and timestamp number with locale []
...
Caused by: java.lang.IllegalArgumentException: Invalid format: "20200722T002739Z" is malformed at "2739Z"
```
This indicates that the mapping is screwy... let's see:
```
GET http://127.0.0.1:9200/logstash-2020.07.22/_mapping
...
"shibidp_severity" : {
"type" : "string",
"index" : "not_analyzed",
"fields" : {
"raw" : {
"type" : "string",
"index" : "not_analyzed",
"ignore_above" : 256
}
}
},
"shibidp_timestamp" : {
"type" : "date",
"format" : "dateOptionalTime"
},
...
```
I included shibidp\_severity just to show how most (string things) get mapped. The template doesn't include anything that would match shibidp\_timestamp, or any of the other fields that get mapped as type "date" with format: "dateOptionalTime"
Fields that get mapped to this (looking at GET <http://127.0.0.1:9200/logstash-2020.07.22/_mapping>)
* @timestamp
* date
* shibidp\_timestamp
This behaviour would appear to be related to dynamic date detection
<https://www.elastic.co/guide/en/elasticsearch/reference/current/dynamic-field-mapping.html>
<https://www.elastic.co/guide/en/elasticsearch/reference/1.7/mapping-dynamic-mapping.html>
In my case, this dynamic mapping caused a bit of a race condition (the first 'shibidp\_timestamp' value encountered informs the mapping for that day's index. Let's see the difference:
```
$ (d="2020.07.18"; curl -s http://127.0.0.1:9200/logstash-$d/_mapping | jq -c '.["logstash-'$d'"].mappings.logs.properties.shibidp_timestamp')
{"fields":{"raw":{"ignore_above":256,"index":"not_analyzed","type":"string"}},"index":"not_analyzed","type":"string"}
$ (d="2020.07.19"; curl -s http://127.0.0.1:9200/logstash-$d/_mapping | jq -c '.["logstash-'$d'"].mappings.logs.properties.shibidp_timestamp')
{"format":"dateOptionalTime","type":"date"}
```
This shows the mapping for shibidp\_timestamp in two different daily indices. The former is what we get when encounter something that looks like a string; the latter is something we get when it looks like a timestamp (but fails to then parse as a timestamp)
There are a few things you could do to address this:
* use logstash to remove shibidp\_timestamp from the incoming JSON that logstash is sending (this might be useful if you've already used the logstash 'date' plugin to convert that to the @timestamp field). This would be effective immediately.
* alter the mapping (template) such that shibidp\_timestamp gets explicitly mapped to a string, and wait for tomorrow's index to begin (or delete today's index)
* include 'basic\_date\_time\_no\_millis' (to match 20200722T002739Z) to the '*default*'.'dynamic\_date\_formats' list (also applied at index creation) <https://www.elastic.co/guide/en/elasticsearch/reference/1.6/mapping-dynamic-mapping.html> | Your `@timestamp` has offset (timzeone value) and you need to add that to your configuration. Please see this link: <https://www.elastic.co/guide/en/logstash/current/plugins-filters-date.html>
* `Z` time zone offset or identity
+ `Z`: Timezone offset structured as HHmm (hour and minutes offset from Zulu/UTC). Example: -0700.
+ `ZZ`: Timezone offset structured as HH:mm (colon in between hour and minute offsets). Example: -07:00.
+ `ZZZ`: Timezone identity. Example: America/Los\_Angeles. Note: Valid IDs are listed on the [Joda.org available time zones page](http://joda-time.sourceforge.net/timezones.html).
So your pattern should looks pretty much like that:
`YYYY-MM-dd HH:mm:ss.SSSZ` |
26,491,140 | i have url like this :
```
http://192.168.6.1/Images/Work3ererg.png
http://192.168.6.1/Images/WorwefewfewfefewfwekThumb.png
http://192.168.6.1/Images/ewfefewfewfewf23243.png
http://192.168.6.1/Images/freferfer455ggg.png
http://192.168.6.1/Images/regrgrger54654654.png
```
i would like to know `http://192.168.6.1` from those url...how can i achieve this using jquery or javascript?
what am i trying to do it :
```
i got this string from my JavaScript : http://192.168.6.1/Images/Work3ererg.png
```
using this javscript string :
i want to put `**https://192.168.6.1/**` instead of `**http://localhost:37774**` including **http**
```
$("#" + id).css("background", "rgba(0, 0, 0, 0) url(http://localhost:37774/Images/PBexVerticalLine1.png) no-repeat scroll 0% 0% / auto padding-box border-box")
```
Thanks | 2014/10/21 | [
"https://Stackoverflow.com/questions/26491140",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2447764/"
] | ```
var url = 'http://192.168.6.1/Images/Work3ererg.png';
var host = url.substr(0,url.indexOf('/',7));
```
`url.indexOf('/',7)`means search `/` after `http://`
Then use `substr` to get string from start to the first `/` after `http://` | you can use **RegularExpression** (pure JavaScript) to do this job
for example you can use
```
var ip = ''; // will contain the ip address
var ips = [] // ips is an array that will contain all the ip address
var url = 'http://192.168.6.1/Images/Work3ererg.png';
url.replace(/http:\/\/(.+?)\//,function(all,first){
// first will be something like 192.168.6.1
// while all will be something like http://192.168.6.1
ip = first;
});
// url can be a a list of ip address in this case we should add the
// g flag(which means global, not just the first match but all the matches )
url ='http://192.168.6.1/Images/Work3ererg.png';
url +='http://192.168.6.2/Images/Work3ererg.png';
url.replace(/http:\/\/(.+?)\//g,function(all,first){
ips.push(first);
});
``` |
3,992,242 | Basically in my website I have a sidebar with a stack of boxes; each box can be collapsed or expanded by the user. I need to save the status of each box for the currently logged in user.
I don't want to use cookies because if an user changes browser or computer, all the boxes will go to the default status.
Should I save this information on the database making a query every time the user collapses/expands a box? How would you handle this? Thanks.
**Edit:** What if an user clicks on the toggle button repeatedly, like ten times in two seconds, just because he enjoys the boxes' animation? He will make ten queries in two seconds. So maybe the question should be: *when* should I save this data? | 2010/10/21 | [
"https://Stackoverflow.com/questions/3992242",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/459271/"
] | Your desired features are contradictory.
1. Length at compile time
2. Defined in header file
3. Single copy across compilation units
To get (1) and (2), you need to declare the variable as `static` or put it in an unnamed namespace. However, this will cause a definition in each compilation unit, which goes against (3).
To get (2) and (3), you need to declare the variable as `extern`, but then you won't get (1).
Now, if your linker is smart, it might optimize away the multiple copies, but I'm not sure if the standard allows it...
I recommend the `const char FOO[] = "foo";` syntax declared in an unnamed namespace or as `static` if it need to be found in a specific namespace. If the string is very large, then I go for an `extern`. | This is how I see it. I wouldn't use any of those as it is. First, I'm inclined by #2, but, take into account that you have to declare the variable as extern in the .h, and select some .cpp to actually store the string:
```
// .h
extern const char*const STR;
// .cpp
const char*const STR = "abc";
```
The only drawback, not having the length at run-time, doesn't seem to me a real reason to move to other option. If you have several strings, you can always have a set of integer constants (or `#define`s) to specify each string's length, such as `STR_LEN`. If you have a lot of them, you won't write them at hand anyway, and you can then generate automatically the `..._LEN` constants at the same time. |
19,156,231 | I have the following function in my `Website model`
```
public function update_website_status($id = null,$status ){
$this->saveField('is_approved',$status,array('website_id' => $id));
}
```
Now if i wish to call this function from a `controller` how would i set the `$id` and the `$status`?
I know this is rather basic but i simply couldn't find an example in the Cake Cookbook (Documentation).
Also is the way i am "searching" aka. making sure its the right `website`\_id the correct way of doing it? | 2013/10/03 | [
"https://Stackoverflow.com/questions/19156231",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2745998/"
] | I know that the RedGate tools can peek inside a backup file, but it's a commercial product, not sure if there are any other free tools that can. | I'm not sure you can interpret what is inside sql server backup files with out restoring onto a development server.
but as long as you restore onto a dev server you shouldn't have any major concerns. |
44,995,570 | [Here](https://jsfiddle.net/uz6y3L2y/2/) is my code:
```
$(document).ready(function(){
$('a').bind('mouseenter', function() {
var self = $(this);
this.iid = setTimeout(function() {
var tag_name = self.text(),
top = self.position().top + self.outerHeight(true),
left = self.position().left;
$('body').append("<div class='tag_info'>Some explanations about "+tag_name+"</div>");
$(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);
}, 525);
}).bind('mouseleave', function(){
if(this.iid){
clearTimeout(this.iid)
remove($('.tag_info'));
}
});
});
```
As you see in the fiddle I've provided, when your mouse leaves the tag, that black box still exists. Why? And how can I remove it? | 2017/07/09 | [
"https://Stackoverflow.com/questions/44995570",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5259594/"
] | ```js
$(document).ready(function(){
$('a').bind('mouseenter', function() {
var self = $(this);
this.iid = setTimeout(function() {
var tag_name = self.text(),
top = self.position().top + self.outerHeight(true),
left = self.position().left;
$('body').append("<div class='tag_info'>Some explanations about "+tag_name+"</div>");
$(".tag_info").css({top: top + "px", left: left + "px"}).fadeIn(200);
}, 525);
}).bind('mouseleave', function(){
$('.tag_info').remove();
});
});
```
```css
body{
padding: 20px;
}
a {
color: #3e6d8e !important;
background-color: #E1ECF4;
padding: 2px 5px;
}
.tag_info{
position: absolute;
width: 130px;
height: 100px;
display:none;
background-color: black;
color: white;
padding: 10px;
}
```
```html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a>tag1</a>
<a>tag2</a>
```
```
check the code `https://jsfiddle.net/uz6y3L2y/3/` may help you.
``` | in jQuery selector define in first.
```
$('.tag_info').remove();
``` |
8,610 | So, I've read Sketching User Experience by Bill Buxton and several blogs discussion how to start the ideation process in a good way with sketching. I've also read about different pens, such as Copic and Sharpie, and seen showcases of UI sketches. But, nowhere have I found any resources about actually becoming better at the sketching craft specifically for UI/UX. Are there any? | 2011/06/28 | [
"https://ux.stackexchange.com/questions/8610",
"https://ux.stackexchange.com",
"https://ux.stackexchange.com/users/4596/"
] | Here's a blog post that has some ideas:
<http://www.uxbooth.com/blog/tools-for-sketching-user-experiences/>
There's a Flickr group, though I don't know if it's being moderated anymore:
<http://www.flickr.com/groups/uxsketches/pool/>
And Jakob Linowski has a lot of great posts on hand sketching:
<http://wireframes.linowski.ca/>
Personally, I'm a fan of simple tools:
* pencil for quick sketching
* thicj and thick black markers for clean-up
* a few primary colors for noting interaction (red, yellow, etc) | I think there's only one way to get better: Practice, practice and practice. |
22,248,110 | I have a list, that I wanted to convert to a dictionary.
```
L = [
is_text,
is_archive,
is_hidden,
is_system_file,
is_xhtml,
is_audio,
is_video,
is_unrecognised
]
```
Is there any way to do this, can I convert to dictionary like this by program:
```
{
"is_text": is_text,
"is_archive": is_archive,
"is_hidden" : is_hidden
"is_system_file": is_system_file
"is_xhtml": is_xhtml,
"is_audio": is_audio,
"is_video": is_video,
"is_unrecognised": is_unrecognised
}
```
Variables are boolean here.
So that I can easily pass this dictionary to my function
```
def updateFileAttributes(self, file_attributes):
m = models.FileAttributes(**file_attributes)
m.save()
``` | 2014/03/07 | [
"https://Stackoverflow.com/questions/22248110",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1182058/"
] | I have made few assumptions here to derive this result.
The variables in the List are the only available bool variables in the scope.
```
{ x:eval(x) for x in dir() if type(eval(x)) is bool }
```
or if you have enforced an naming convention for your variables
```
{ x:eval(x) for x in dir() if x.startswith('is_') }
``` | Below code works.
For Variables to String
```
>>> a = 10
>>> b =20
>>> c = 30
>>> lst = [a,b,c]
>>> lst
[10, 20, 30]
>>> {str(item):item for item in lst}
{'10': 10, '30': 30, '20': 20}
```
For string only.
```
>>> lst = ['a','b','c']
>>> lst
['a', 'b', 'c']
>>> {item:item for item in lst}
{'a': 'a', 'c': 'c', 'b': 'b'}
``` |
169,566 | How can I create a column in SharePoint 2013 which represent the current date. For example today is 02/09/2016 tomorrow should be 02/10/2016, 02/10/2016... and so on each day the date must be changed.
I was wondering if someone could tell me, thanks. | 2016/02/09 | [
"https://sharepoint.stackexchange.com/questions/169566",
"https://sharepoint.stackexchange.com",
"https://sharepoint.stackexchange.com/users/43990/"
] | Create One **Calculated** type column and set data return formula type to **Number** and apply this formula:
```
="<img src='/_layouts/images/blank.gif' onload=""{"&" var day=new Date();"&" this.parentNode.innerHTML= day ;"&"}"">"
```
You will current date and time.
UPDATE
======
For only Date try below formula:
```
="<img src='/_layouts/images/blank.gif' onload=""{"&" var day=new Date();"&" var n = day.format('dd/MM/yyyy');"&" this.parentNode.innerHTML= n ;"&"}"">"
```
--- | You create the column as you'd like, and set the default value to Todays Date.
[](https://i.stack.imgur.com/IyOwr.png) |
7,828,452 | I'm working on a WPF app, using .NET 4. I'm also trying to wrap my head about WPF Commands, and not always rely upon events, as I've done for upteen years. I'm trying to figure out which command to use. I've come across a Search command, that that appears to be a part of the NavigationCommands, which doesn't make sense to me to use. I've also found the Find command, but that's associated with Control-F, which makes me think its for finding a search in a document, like a Word document, so again, that doesn't look right to me.
Here's what I want to accomplish. I will have some textboxes on the windows, for things like first name, last name, SSN and DOB. I want to make it possible for the user to enter any or all of those, and then click on a button. It then performs a search against our database for all records matching the parameters the user gave. It will then put the returned results in a list box on the same window.
What WPF commmand do I use for that? | 2011/10/19 | [
"https://Stackoverflow.com/questions/7828452",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/197791/"
] | >
> Could this RegEx have been structured in such a way as to bypass the first array entry and just produce the desired result?
>
>
>
Absolutely. Use [assertions](http://us.php.net/manual/en/regexp.reference.assertions.php). This regex:
```
preg_match_all('/(?<=\^)[^^]*?(?=~)/', $str, $newStr);
```
Results in:
```
Array
(
[0] => Array
(
[0] => Jony
[1] => Smith
[2] => example-free@wpdevelop.com
)
)
``` | Whenever you have problems to imagine the function of preg\_match\_all you should use an evaluator like [preg\_match\_all tester @ regextester.net](http://regextester.net/preg_match_all.php)
This shows you the result in realtime and you can configure things like the result order, meta instructions, offset capturing and many more. |
5,150,476 | I have a registration form on which I use client side validation (Required, StringLength etc. specified on my view model). The form is currently pretty much how the scaffolder creates it:
```
@using (Html.BeginForm("Index", "Registration"))
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Registration details</legend>
@Html.ValidationSummary(false, "Please correct these errors:")
@Html.ValidationMessageFor(model => model.Username)
<div class="editor-label">
@Html.LabelFor(model => model.Username)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Username)
</div>
<p>
<input type="submit" value="Register" />
</p>
</fieldset>
}
```
The only difference is that I moved the ValidationMessageFor to the top right beneath the ValidationSummary.
What I would like to do is display the client side validation errors in the validation summary. Currently they are just displayed on top of the form but not using the validation summary. How can I display client side validation errors using the validation summary? Is this even possible?
**Update**
Darin I have used your code in a new project and this is what it looks like for me when the client side validation kicks in:
[Client side validation http://tinypic.com/images/404.gif](http://tinypic.com/images/404.gif)
I expected this to be shown IN the validation summary with the validation summary styles applied. I also submitted the form which then look like this:
[](https://i.stack.imgur.com/dGbMd.jpg)
Thanks,
b3n | 2011/03/01 | [
"https://Stackoverflow.com/questions/5150476",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/395377/"
] | This article seems to explain how add client side validation summary into the validation summary:
<http://geekswithblogs.net/stun/archive/2011/01/28/aspnet-mvc-3-client-side-validation-summary-with-jquery-validation-unobtrusive-javascript.aspx>
However I did not test it by myself and it does not seem to have any difference with your code. If it does not work a good point to look might be jquery.validate.unobtrusive.js file on a function that actually places validation errors:
```
function onErrors(form, validator) { // 'this' is the form element
var container = $(this).find("[data-valmsg-summary=true]"),
list = container.find("ul");
if (list && list.length && validator.errorList.length) {
list.empty();
container.addClass("validation-summary-errors")
.removeClass("validation-summary-valid");
$.each(validator.errorList, function () {
$("<li />").html(this.message).appendTo(list);
});
}
}
``` | i have solved this problem after 2 day of intense research, and finaly, i found the answer by myself and my experimentations !
To display the Client-side Validator message in the validator Summary there is 3 easy step :
1- put `<add key="ClientValidationEnabled" value="false" />` in the `<appSettings>` section of your web.config
2- add your validation the "false" attribut in your view : `@Html.ValidationSummary(false)`
3- Remove all `ValidationMessageFor(x => x.Property)` in your view.
when you,ll click in your submit button, the client-side Validation message will be displayed in your validation summary.
Enjoy! |
3,056 | I was reading this [CompTIA Security+ SYO-201 book](http://rads.stackoverflow.com/amzn/click/0789747138), and the author David Prowse claims that:
>
> Whichever VM you select, the VM cannot cross the software boundaries set in
> place. For example, a virus might infect a computer when executed and spread to
> other files in the OS. However, a virus executed in a VM will spread through the
> VM but not affect the underlying actual OS.
>
>
>
So if I'm running VMWare player and execute some malware on my virtual machine's OS, I don't have to worry about my host system being compromised, at *all*?
What if the virtual machine shares the network with the host machine, and shared folders are enabled?
Isn't it still possible for a worm to copy itself to the host machine that way? Isn't the user still vulnerable to AutoRun if the OS is Windows and they insert a USB storage device?
How secure are virtual machines, really? How much do they protect the host machine from malware and attacks? | 2011/04/12 | [
"https://security.stackexchange.com/questions/3056",
"https://security.stackexchange.com",
"https://security.stackexchange.com/users/2053/"
] | I think that author assertion is **not completely** true. Actually, there are two types of **hypervisor** in virtualization area. *Hypervisor* is a piece of computer software, firmware or hardware that **creates** and **runs** *virtual machine*s. Those types are:
* **Type-1 hypervisors**
* **Type-2 hypervisors**
Type-1 hypervisor runs **directly** on the host's hardware to control the hardware and to manage guest operating systems. For this reason, they are sometimes called **bare metal** hypervisors ***whereas*** Type-2 hypervisor runs on a **conventional operating system** just as other computer programs do. *VMWare* or *VirtualBox* are example of Type-2 hypervisor because they are run as programs in host *OS*s.
For Type-2 hypervisors, there is [**RoboLinux**](http://www.robolinux.org) project which has an unique feature called **Stealth VM**. *Stealth VM software installer* that allows you to build a Windows 7 clone running in a **secure Linux partition**. The system is protected from malware, anything you download will be contained w**ithin the virtual machine** and it is intended for people who must have a specific Windows program with the convenience of being able to restore the operating system as new in just two clicks.
There is **[Qubes OS](https://www.qubes-os.org/)** which is developed on **Linux** and **[Xen](http://www.xenproject.org/)** as an example for Type-1 hypervisors. Qubes OS takes an approach called **security by isolation**, which in this context means keeping the things you do on your computer securely isolated in **different VMs** so that one VM getting compromised won’t affect the others. Unlike Type-2 hypervisors, it has a secure **inter-VM file transfer system** to handle sharing folders' risk. In theory, that organization is more secure than Type-2 virtualization according to developers.
In short, the author should indicate **which** hypervisor or virtual system.
**References**:
* <https://en.wikipedia.org/wiki/Hypervisor>
* <https://www.qubes-os.org/>
* <http://www.robolinux.org>
* <http://www.xenproject.org/>
* <http://www.hacker10.com/computer-security/vpn-ready-linux-distribution-robolinux/> | 1. Physical isolation will always be more robust than using logical isolation. In physically-isolated systems (servers, etc.), a security issue in one physically-isolated system will not become an issue in another through shared hypervisor or HW. Of course, the network is another vector that needs to be addressed.
2. For all intents and purposes, VMs/Hypervisors (see notes later) could provide adequate isolation between the VM. That is also an underlying premise in using Cloud Service Providers (CSPs) where multi-tenant systems share the same HW, using not only virtualized servers, but also virtual networks and storage. There are certain hypervisor-based systems have been approved for providing isolation between systems of different classification levels on the same platform (<https://en.wikipedia.org/wiki/NetTop>).
3. The distinction between Type 1 (bare metal) and Type 2 hypervisors is an important one. Type 2 hypervisors will not be any more secure than the underlying Host OS. They also don't typically have the same control over the HW as Type 1 hypervisors do.
4. Hypervisor security capabilities and assurance in their correct operation:
Different hypervisors make different claims in terms of VM isolation and control over VM to physical HW resources. For instance, ESXi claims "VM domain isolation" and it has been independently evaluated for this and other security requirements through the Common Criteria (CC) process. If you use a hypervisor that has not been independently validated, you're taking the vendor's word that its does what they claim it does and does it correctly.
5. All complex SW can be misconfigured, exposing vulnerabilities. It is important to configure hypervisor using CIS Benchmarks, Vendor Guidance or DISA STIGs to remove known configuration vulnerabilities.
6. All SW may have security bugs (implementation vulnerabilities), so it is also important to have a vulnerability management program to quickly identify and patch such.
In summary:
1. Use Type 1 hypervisors that are CC-certified.
2. Securely configure per security configuration guidance.
3. Have a security vulnerability management program in place.
4. Have a comprehensive security architecture in place (Network and Host IDS), AV, security monitoring, boundary controls, etc.
5. For any centralized virtualization infr. management, such as WMware vCenter, ensure that the manager platform, the manager and the manager to the managed hypervisor instance interfaces are secured. For instance: the vCenter is deployed on a secure, hardened server, with strong admin. authentication and access control. The platform is protected at the host (AV/HIDS), network level (FWs, NIDS/NIPS) and security monitoring is in place (e.g., SIEM). Interfaces use proper data-in-transit (DIT) encryption, mutual authentication and proper Key Management (KM).
6. Do recognize that virtual isolation does introduce an additional risk relative to physical isolation. But should be manageable if the above areas are addressed. |
46,894 | Is there nowadays any case for brevity over clarity with method names?
Tonight I came across the Python method `repr()` which seems like a bad name for a method to me. It's not an English word. It apparently is an abbreviation of 'representation' and even if you can deduce that, it still doesn't tell you what the method does.
A good method name is subjective to a certain degree, but I had assumed that modern best practices agreed that names should be at least full words and descriptive enough to reveal enough about the method that you would easily find one when looking for it. Method names made from words help let your code read like English.
`repr()` seems to have no advantages as a name other than being short and IDE auto-complete makes this a non-issue. An additional reason given in an answer is that python names are brief so that you can do many things on one line. Surely the better way is to just extract the many things to their own function, and repeat until lines are not too long.
Are these just a hangover from the unix way of doing things? Commands with names like `ls`, `rm`, `ps` and `du` (if you could call those names) were hard to find and hard to remember. I know that the everyday usage of commands such as these is different than methods in code so the matter of whether those are bad names is a different matter. | 2011/02/11 | [
"https://softwareengineering.stackexchange.com/questions/46894",
"https://softwareengineering.stackexchange.com",
"https://softwareengineering.stackexchange.com/users/13825/"
] | I heard a great quote on this once, something along the lines of:
>
> Code is written to be read by humans,
> not computers
>
>
>
If computers were all we cared about we would still be writing assembler, or 1s and 0s for that matter. We have to consider the people who will be using our code, as an API for example, or the person who comes after us and maintains our code. So, unless the language we are using prohibits it, meaningful, real word method and variable names should be considered best practice. | Short method names mattered in the time of 128k or less of memory where literally every byte counted. Today, there absolutely no reason to use cryptic abbreviated names for methods when longer more descriptive names do not have any practical costs. |
295,690 | I've got a section of code on a b2evo PHP site that does the following:
```
$content = preg_replace_callback(
'/[\x80-\xff]/',
create_function( '$j', 'return "&#".ord($j[0]).";";' ),
$content);
```
What does this section of code do? My guess is that it strips out ascii characters between 128 and 256, but I can't be sure.
Also, as it stands, every time this bit of code is called from within a page, PHP allocates and then does not free upto 2K of memory. If the function is called 1000+ times on a page (this can happen), then the page uses an extra 2MB of memory.
This is causing problems with my web application. Why am I losing memory, and how do I rewrite this so I don't get a memory leak? | 2008/11/17 | [
"https://Stackoverflow.com/questions/295690",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1726/"
] | Not really stripping, it replaces high-Ascii characters by their entities.
See [preg\_replace\_callback](http://fr.php.net/manual/en/function.preg-replace-callback.php "PHP: preg_replace_callback - Manual").
create\_function is used to make an anonymous function, but you can use a plain function instead:
```
$content = 'Çà ! Nœm dé fîçhïèr tôrdù, @ pöür têstër... ? ~ Œ[€]';
$content = preg_replace_callback('/[\x80-\xff]/', 'CB_CharToEntity', $content);
echo $econtent . '<br>';
echo htmlspecialchars($content) . '<br>';
echo htmlentities($content) . '<br>';
echo htmlentities($content, ENT_NOQUOTES, 'cp1252') . '<br>';
function CB_CharToEntity($matches)
{
return '&#' . ord($matches[0]) . ';';
}
```
[EDIT] Found a cleaner, probably faster way to do the job! ^\_^ Just use htmlentities with options fitting your needs. | It's `create_function` that's leaking your memory - just use a normal function instead and you'll be fine.
The function itself is replacing the characters with numeric HTML entities (`&#xxx;`) |
52,740,523 | I'm missing something basic here (newish to JQuery).
I have the id of an element ex an array and wish to get it's parent.
but the parent object looks like a whole function declaration of some type, when I display it.
What am I missing please.
Thx
```
$.each(arr, function (){
var thisElId = arr[i][0];
alert(thisElId); //correct
var EnclSpanParentText = $('#' + thisElId).parents(".accordion-heading").text;
alert("SpanParent " + EnclSpanParentText);
if (EnclSpanParentText == "Read")
```
[](https://i.stack.imgur.com/30cpk.png) | 2018/10/10 | [
"https://Stackoverflow.com/questions/52740523",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1156020/"
] | Two things:
1. You're using *`parents`*, which gives you the full ancestry of the element, not just its parent. It's not clear to me whether you meant to do that. If you're looking for its closest parent matching the given selector, use `closest(...)` or `parents(...).first()`
2. You're not \*calling `text`, you're just referring to it. To *call* it (since it's a function), you add `()` to the end.
So either
```
var EnclSpanParentText = $('#' + thisElId).parents(".accordion-heading").text();
// --------------------------------------------------------------------------^^
alert("SpanParent " + EnclSpanParentText);
```
or
```
var EnclSpanParentText = $('#' + thisElId).closest(".accordion-heading").text();
// ----------------------------------------^^^^^^^---------------------------^^
alert("SpanParent " + EnclSpanParentText);
```
or similar. | first of all text() is a function not a property
second you can use this .. as per my understanding.
```
$.each(arr, function (i,o)
{
var thisElId = $(this);
alert(thisElId); //correct
var EnclSpanParentText =thisElId.parent().text() ;
alert("SpanParent " + EnclSpanParentText);
if (EnclSpanParentText == "Read")
``` |
1,816,573 | If mysql record with condition exists-update it,else create new record | 2009/11/29 | [
"https://Stackoverflow.com/questions/1816573",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/182671/"
] | You can use the `REPLACE INTO` for that with the syntax of `INSERT INTO`. This way MySQL will invoke an `UPDATE` whenever there's a fictive constraint violation.
Be aware that this construct is MySQL-specific, so your query ain't going to work whenever you switch from DB. | Are you looking for [`INSERT ... ON DUPLICATE KEY UPDATE`](http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html)? |
1,207,902 | I saw the [the news that emacs 23.1 was released](http://lwn.net/Articles/344436/).
**For a programmer,** What are the big reasons to upgrade? I'm currently on 22.2.
None of the features listed really seem like must-haves for me. The most immediately interesting bit is that nXML is now integrated. I already have it though.
But I have to admit I don't know what is really behind "smarter minibuffer completion" or "per buffer text scaling".
Anyone have any tips or examples of what these things are? | 2009/07/30 | [
"https://Stackoverflow.com/questions/1207902",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/48082/"
] | M-x butterfly
 | While I was using the pre-releases, the most noticeable feature has been the improved font support. and some small things about smarter window splitting. |
52,456,719 | I have a very simple Jenkins build which is needed for several repositories. All these repositories have the same organisation, the same branches, etc. There is no difference except the repository name.
Each single repository should be able to trigger the build for only this specific repository. I imagine something like combining a [parameterized build](https://wiki.jenkins.io/display/JENKINS/Parameterized+Build) with a WebHook URL containing a query parameter for the repository name maybe.
Any ideas or pointers about that? | 2018/09/22 | [
"https://Stackoverflow.com/questions/52456719",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6104854/"
] | After having done a bit more research I think I will try the "GitHub Organization" job type. It scans all repositories for a given GitHub organization or owner and automatically manages corresponding jobs. | Somewhere I read about an organization where they put most standard pipelines into comprehensive shared libraries. [This article](https://jenkins.io/blog/2017/06/27/speaker-blog-SAS-jenkins-world/ "This article") is quite a good read about that.
My own company uses "Seedjobs" to create multiple pipelines with only one job. Read [this article](https://docs.mesosphere.com/services/jenkins/3.5.4-2.150.1/script-template-job-dsl/) for an overview on that idea. |
6,446,363 | I'm loading a TreeView from a list, and the user has a button to delete an item and it deletes it from the list no problem, but there is also a button to update the TreeView with the list after items have been deleted, I have no problem adding the new items to the TreeView but is there a way to clear all the items in the TreeView before I add new items, so I don't have duplicates in the TreeView? I have tried looking on other spots on the internet for the answer but cant find it, I've tried simple things like:
```
treeView1.Items.Clear();
```
but it doesn't work.
Sorry, I mentioned it on a comment, below that I'm pretty sure this line does in fact clear it, I am just not using it in the right place, thanks all for your answers. | 2011/06/22 | [
"https://Stackoverflow.com/questions/6446363",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/776647/"
] | First of all, Items and Clear should be capitalized in your example. Maybe that's the only problem.
Second, if you are populating the tree by setting its ItemsSource, then you are not allowed to add and remove items from its Items collection by hand. Instead, you should make the source an ObservableCollection instead of a List. Then the treeview will automatically update itself to reflect changes in the source collection | did you try
```
treeView1.DataBind();
``` |
67,548,332 | I have two tables in Excel, one with categories and listings, and another with points based on the category and listing threshold. It goes as follows:
Categories table:
| ID | CATEGORY | LISTINGS | Points |
| --- | --- | --- | --- |
| 001 | A | 56 | |
| 002 | C | 120 | |
| 003 | A | 4 | |
| 004 | B | 98 | |
Points table:
| Category | tier1 | tier2 | tier3 |
| --- | --- | --- | --- |
| A | Tier 1 | Tier 2 | Tier 3 |
| Range | 1-30 | 31-90 | 91- |
| Points | 10 | 20 | 30 |
| | | | |
| B | Tier 1 | Tier 2 | Tier 3 |
| Range | 1-25 | 26-100 | 101- |
| Points | 10 | 20 | 30 |
| | | | |
| C | Tier 1 | Tier 2 | Tier 3 |
| Range | 1-40 | 41-80 | 81- |
| Points | 10 | 20 | 30 |
I started with an INDEX MATCH formula pointing at the points:
```
=INDEX(Points!A1:D11, MATCH(Categories!B2, Points!A1:A11, 0)+2)
```
--> the +2 is to get the points directly
I also though of evaluating the thresholds with this formula:
```
=IF(Categories!C2 >= NUMBERVALUE(LEFT(Points!D3, FIND("-",Points!D3)-1)),Points!D4, IF(Categories!C2 >=NUMBERVALUE(LEFT(Points!C3, FIND("-",Points!C3)-1)),Points!C4, Points!B4))
```
I thought that the else if the if would make it faster.
Could someone help me populate the Points column in the Categories table? VBA code is also acceptable. The tables are in different sheets. | 2021/05/15 | [
"https://Stackoverflow.com/questions/67548332",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15196667/"
] | A slightly verbose formula which takes the data as originally formatted (using Excel 365 Let):
```
=LET(ranges,INDEX(Points!B$2:D$12,MATCH(B2,Points!A$1:A$12,0),0),
leftRanges,VALUE(LEFT(ranges,FIND("-",ranges)-1)),
points,INDEX(Points!B$2:D$12,MATCH(B2,Points!A$1:A$12,0)+1,0),
INDEX(points,MATCH(C2,leftRanges)))
```
[](https://i.stack.imgur.com/v52b4.png) | Please, try the next code. It uses arrays and should be very fast, working only in memory. Please use your sheets when setting `shC` and `shP` as your real sheets. I only use the active sheet and the next one for testing reason:
```
Sub GetPoints()
Dim shC As Worksheet, shP As Worksheet, lastRC As Long, lastRP As Long, arrBC, arrP, arrPP, arrFin
Dim i As Long, j As Long, p As Long, k As Long
Set shC = ActiveSheet 'use here your Categories sheet
Set shP = shC.Next 'use here your Points sheet
lastRC = shC.Range("A" & shC.rows.count).End(xlUp).row
lastRP = shP.Range("A" & shP.rows.count).End(xlUp).row
arrBC = shC.Range("B2:C" & lastRC).Value 'put the range B:C in an array
arrP = shP.Range("A2:D" & lastRP).Value 'put all the range in an array
ReDim arrFin(1 To UBound(arrBC), 1 To 1) 'redim the array to keep processed values
For i = 1 To UBound(arrBC) 'iterate between Categ array elements:
For j = 1 To UBound(arrP) 'iterate between Points array elements:
If arrP(j, 1) = arrBC(i, 1) Then 'if Category is found:
For p = 2 To 4 'iterate between the next array row elements
arrPP = Split(arrP(j + 1, p), "-") 'split the element by "-" to determine the interval
If arrPP(1) <> "" Then 'for the tier3 case:
If arrBC(i, 2) >= CLng(arrPP(0)) And arrBC(i, 2) <= CLng(arrPP(1)) Then
k = k + 1
arrFin(k, 1) = arrP(j + 2, p): j = j + 2: Exit For 'place the value in the final array and exit iteration
End If
Else 'for the tier1 and tier2 cases:
If arrBC(i, 2) >= CLng(arrPP(0)) Then
k = k + 1
arrFin(k, 1) = arrP(j + 2, p): j = j + 2: Exit For 'place the value in the final array and exit iteration
End If
End If
Next p
End If
Next j
Next i
'drop the final array result at once:
shC.Range("D2").Resize(UBound(arrFin), 1).Value = arrFin
End Sub
``` |
565,013 | I'm working on a coilgun and I need to discharge a capacitor bank through a coil to create a strong magnetic field. My coil has a resistance of 266 milliohms and when fully charged, the capacitors are at 200V with a capacitance of 4700uF total. This will result in a peak current of 750A (ignoring wire resistance and ESR of the capacitors).
Up until now I have just touched the wires together to close the circuit but I need to time the switching in a controlled way. My problem is that I have no clue what component to use to switch ~700A 200V. Of course the 700A peak is only for a very short amount of time and the whole pulse should last around a millisecond.
I have tried using 5x irfp260n MOSFETS in parallel, each MOSFET should be able to handle 200A peak so it would total 1000A when connected in parallel. Unfortunately one of the MOSFETS always dies after a couple shots (I did take care of the reverse voltage generated by the coil). I also am aware that connecting MOSFETS in parallel is generally not a good practice.
I have looked into thyristors but the inability to switch them off through the gate makes them useless for me. "Gate turn-off thyristors" looked interesting but I could only find really expensive ones (in order of hunderds of euros). IGBTs are known for being able to handle more current but I failed to find any that were rated for this kind of current.
Does anyone know a solution to switch 700A 200VDC for 1 millisecond? | 2021/05/13 | [
"https://electronics.stackexchange.com/questions/565013",
"https://electronics.stackexchange.com",
"https://electronics.stackexchange.com/users/268421/"
] | You are working with 200V power source, and irfp260n has absolute maximum drain-source voltage 200V. So this mosfet is not suitable for the task, you have to have some margin. And you are not even considering transients and ringing, which is inevitable. Use mosfets with much higher voltage rating. Like 500V. And consider ringing, because you are talking about coil. | Very fast turn-on is essential here so you need a very powerful gate drive. You don't care so much about ringing etc. So go ahead and pump 10A into each of the gates.
If this is still too slow to protect your FETs, maybe check out some GaN parts which have much lower gate charge.
Another step you can take to slightly delay the current surge until after full turn on is to add a tiny series inductance with the caps. Around 100nH |
17,154 | On juniper switches is something like root user. Are there any things that must be done from that user?
For what root user can be usefull? Or isn't usefull, and can be safetly disabled? | 2015/03/09 | [
"https://networkengineering.stackexchange.com/questions/17154",
"https://networkengineering.stackexchange.com",
"https://networkengineering.stackexchange.com/users/14268/"
] | Ryan is correct, you can do absolutely anything from root. JUNOS is built on FreeBSD and inherits that behavior. But to be honest, it's rarely used directly.
The biggest **practical** example I can think of offhand would be to collect core files from devices without another type of authentication, whether its due to a configuration issue or maybe you have redundant routing engines or a virtual chassis setup. Non-master members don't authenticate with the network, so should you need to get into a member device to collect files, you could use root access in the shell to get those files.
When you first start up any Juniper device, you CANNOT commit your first configuration without root-authentication set, so you are forced to have a root password set. I guess you could think of it as a failsafe, should everything break.
However, you can disable your users from starting a shell with root privileges with login classes.
<https://www.juniper.net/techpubs/software/junos-es/junos-es93/junos-es-admin-guide/login-classes.html>
There are a couple of ways to do it, but one example would be:
*set system login class **class\_name** deny-commands "(^start shell$)"*
Another:
*set system login class **class\_name** permissions **permission\_bits\_to\_set***
If you EXCLUDE *"maintenance"* as a permission bit, they will not be able to become the superuser (root). | The `root` user for any \*nix platform is capable of performing any functions on the system they want - and I mean **anything**. I'd suggest you [look into a wiki article](http://en.wikipedia.org/wiki/Superuser) on this as it is a little beyond the scope of this SE.
It is good practice to disable root access to your juniper devices. Most environments disable it in a few different ways.
* blank out the root password
* disable ssh root-login
* disable root-login tampering on user-accounts |
2,550,188 | This question has been asked in an examination of the Indian Statistical Institute, Kolkata for second year Master of Statistics students in the subject Martingale Theory.
>
> Q. Mr.Trump decides to post a random message on the Facebook and
> starts typing a random sequence $\{U\_k\}\_{k\geq1}$ of letters such that
> they are chosen independently and uniformly from the $26$ English
> alphabets. Find out the expected time of the first appearance of the
> word "COVFEFE". We may assume that Trump has his caps lock on so
> that only upper case letters are typed. Assume further that the letters
> are typed at the rate of one letter per second.
>
>
>
I have no idea as to how to proceed. I will be grateful for any help. | 2017/12/04 | [
"https://math.stackexchange.com/questions/2550188",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/118296/"
] | I'm a little late to the party, but here's my solution:
Let's say we have a word $w$ in an alphabet of size $b$, and we have an infinite stream of random letters. let's say we have a gremlin that runs along the stream up until the first occurrence of the word, and then starts from scratch at the next letter. for example, if $w=aba$ then given the stream $aababaababb$ the gremlin will find $a{\bf aba}baababb$ first, then start over from the next letter and find the next occurence of $w$, $a{\bf aba}ba{\bf aba}bb$. note the gremlin missed a copy of $w$ because it overlapped a copy that it did find.
we can think of the stream as a sequence of "gremlin runs", which are the runs from the point the gremlin starts at to the end of the next occurrence of $w$. for example, in the example the runs are $a{\bf aba}$, $ba{\bf aba}$, with a trailing $bb$ (one can assume there are no trails in the infinite stream case). all the runs are completely independent and have the exact same distribution. if we denote by $L$ the expected length of a gremlin run (which is the quantity we are trying to find), and denote by $\mu$ the density of the occurrences of $w$ that the gremlin finds, we get $L=\frac{1}{\mu}$. (the density is the ratio between how many occurrences the gremlin found to how many letters he read, when taken to infinity.)
whenever our gremlin found the word, it is possible that it missed another instance of $w$ sharing $k$ of the same letters, exactly when the first and last $k$ letters of the word are the same. (for example, for $aba$ the first $a$ is the same as the last $a$ so it's true for $k=1$, so it's possible the gremlin would find ${\bf aba}ba$ and miss the second copy). in that case, there are $|w|-k$ more letters to chose, so the chance of having a missed copy of $w$ sharing $k$ letters is exactly $b^{|w|-k}$.
denote $c\_k=1$ if the first and last $k$ letters of $w$ are the same for $1\le k<|w|$ and $c\_k=0$ otherwise. also denote $\rho=\sum\_{k=1}^{|w|-1}c\_k b^{k-|w|}$. so, the density of missed occurrences of $w$ is exactly $\rho\mu$, and the density of occurrences of $w$ is $(1+\rho)\mu$. that's just plainly $b^{-|w|}$, so $\mu=\frac{b^{-|w|}}{1+\rho}$.
therefore, $L=\frac{1}{\mu}=(1+\rho)b^{|w|}=\sum\_{k=1}^{|w|-1}c\_k b^{k}+b^{|w|}$. if you will, the first and last $|w|$ letters of $w$ are just the word itself, so $c\_{|w|}=1$, and $L=\sum\_{k=1}^{|w|}c\_k b^{k}$.
this would explain why the "covfefe" example gave such a nice answer - $26^7$.
formal sidenote: the strong law of large numbers formally justifies that the densities exist with probability 1 and that everything that was claimed holds with probability 1. | My answer is based on the answer of Mike Spivey [on a related question](https://math.stackexchange.com/questions/73758/probability-of-n-successes-in-a-row-at-the-k-th-bernoulli-trial-geometric), which uses [the probability generating function](https://en.wikipedia.org/wiki/Probability-generating_function) $G(z)$ of a discrete random variable $X$:
$$G(z) = \sum\_{k=0}^{\infty} p(k)z^k $$
where $p$ is the probability mass function of $X$. The probability generating function has the nice property that $E[X] = \lim\_{z \to 1-}G'(z)$ (limit from below).
I will adapt Mike's answer for completeness here. Any thoughts would be appreciated, I'm curious to know if my reasoning was correct or if there is a clever way of solving this problem!
We need a specific sequence of seven characters to form the word "COVFEFE". First a "C", then "O", followed by "V" and so on. We can label the event of typing a correct next character to form the word "COVFEFE" with $S$ and the typing of an incorrect character with $F$. The word "COVFEFE" appearing in a long sequence of characters would then be described by the event $A\cdot SSSSSSS = AS^7$, i.e. a sequence $A$ of any character combination without seven $S$ in a row followed by seven $S$ in a row. Many characters will likely appear before we finally get to $AS^7$. Mr. Trump could type out "COVFEFXCOVFEFE" (the event $S^6FS^7$) or "AAACOVFEFE" ($F^3S^7$), for instance. Undoubtedly, all these character sequences will spark a lively debate on social media if mr. Trump is actually tweeting out nuclear launch codes and impending doom is imminent.
We can look at the situation in the following way. Mr. Trump will play a game of typing random characters, one after another, and the game will end when he types seven $S$ in a row. We need to find the expected number of tries before this happens.
Let $X$ be the probality mass function of the number of characters typed before "COVFEFE" appears. To find the expected number of tries, we need to find the probability generating function of $X$. To find the generating function, look at the infinite sum of possible ways to get seven successes in a row on the last seven tries:
$$S^{7} + FS^{7} + FFS^{7} + SFS^{7} + SSFS^{7} + FSFS^{7} + SFFS^{7} + ...$$
Now, if we were to set $S = pz$ and $F = (1-p)z$, with $p$ the probability of typing the correct next character (and assuming independence), note that we have actually found the probability generating function $G(z)$!
We can rewrite the above expression using a summation and even further simplify using the power sum rule:
$$\sum\_{k=0}^{\infty} (F + SF + S^2F + S^3F + S^4F + S^5F + S^6F)^k S^7 = \frac{S^7}{1 - (F + SF + S^2F + S^3 + S^4F + S^5F + S^6F)}$$
If we now substitute $S = pz$ and $F = (1-p)z$, we find:
$$G(z) = \frac{p^7z^7}{1-(1-p)z + (pz)(1-p)z + (pz)^2(1-p)z + (pz)^3(1-p)z + (pz)^3(1-p)z+ (pz)^4(1-p)z + (pz)^5(1-p)z + (pz)^6(1-p)z}$$
At this point we need to find $\lim\_{z \to 1-} G'(z)$, which is horrible. I used Wolfram Alpha to do this. The result:
$$E[X] = \frac{1+p+p^2+p^3+p^4+p^5+p^6}{p^7}$$
The probability of typing a correct character is $p = \frac{1}{26}$. Calculating the expected number of characters typed before "COVFEFE" appears, we find $E[X] = 8353082582$. In the case of one character per second, this is the final answer.
Just for fun, I did a little test seeing how many characters I could write out per minute, and it came down to about 300. Mr. Trump says he has pretty big hands, so I'm sure he'll manage 400 CPM. This gives $\frac{8353082582}{400 \cdot 60 \cdot 24 \cdot 365.25}$ which is about 39 years and 8 months, not accounting for sleeping, golf and other responsibilities. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.