That's how I've added mine in profiles json table,
{
"guid": "{00000000-0000-0000-ba54-000000000002}",
"name": "Git",
"commandline": "C:/Program Files/Git/bin/bash.exe --login",
"icon": "%PROGRAMFILES%/Git/mingw64/share/git/git-for-windows.ico",
"startingDirectory": "%USERPROFILE%",
"hidden": false
}
In my case, Device date-time was set to a future date. Changing the date setting to "automatic" fixed the issue.
I am now able to successfully build. Not sure exactly which step "fixed" things, but this was the sequence:
While I am not sure exactly which parts were necessary, I think the previous certificates were the problem. I hate Xcode :(
Thanks for help.
This link helped.
Spring Boot auto-configuration tries to configure beans automatically based on the dependencies added to the classpath. And because we have a JPA dependency (spring-data-starter-jpa) on our classpath, it tries to configure it.
The problem: Spring boot doesn't have the all the info needed to configure the JPA data source i.e. the JDBC connection properties. Solutions:
The above link excludes the DataSourceAutoConfiguration.class
with
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
But this didn't work for me. I instead, had to exclude 2 AutoConfig classes:
@SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, XADataSourceAutoConfiguration.class})
My problem was the same as that in the original question, only that I was running via Eclipse and not cmd. Tried all the solutions listed, but didn't work. The final working solution for me, however, was while running via cmd (or can be run similarly via Eclipse). Used a modified command appended with spring config from cmd:
start java -Xms512m -Xmx1024m <and the usual parameters as needed, like PrintGC etc> -Dspring.config.location=<propertiesfiles> -jar <jar>
I guess my issue was the spring configurations not being loaded correctly.
@Bhabadyuti Bal give us a good answer, in gradle you can use :
compile 'org.springframework.boot:spring-boot-starter-data-jpa'
compile 'com.h2database:h2'
in test time :
testCompile 'org.reactivecommons.utils:object-mapper:0.1.0'
testCompile 'com.h2database:h2'
In development, activating a Spring Boot profile when a specific Maven profile is activate is straight. You should use the profiles
property of the spring-boot-maven-plugin in the Maven profile such as :
<project>
<...>
<profiles>
<profile>
<id>development</id>
<activation>
<activeByDefault>true</activeByDefault>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<profiles>
<profile>development</profile>
</profiles>
</configuration>
</plugin>
</plugins>
</build>
</profile>
<profiles>
</...>
</project>
You can run the following command to use both the Spring Boot and the Maven development
profile :
mvn spring-boot:run -Pdevelopment
If you want to be able to map any Spring Boot profiles to a Maven profile with the same profile name, you could define a single Maven profile and enabling that as the presence of a Maven property is detected. This property would be the single thing that you need to specify as you run the mvn
command.
The profile would look like :
<profile>
<id>spring-profile-active</id>
<activation>
<property>
<name>my.active.spring.profiles</name>
</property>
</activation>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<profiles>
<profile>${my.active.spring.profiles}</profile>
</profiles>
</configuration>
</plugin>
</plugins>
</build>
</profile>
And you can run the following command to use both the Spring Boot and the Maven development
profile :
mvn spring-boot:run -Dmy.active.spring.profiles=development
or :
mvn spring-boot:run -Dmy.active.spring.profiles=integration
or :
mvn spring-boot:run -Dmy.active.spring.profiles=production
And so for...
This kind of configuration makes sense as in the generic Maven profile you rely on the my.active.spring.profiles
property that is passed to perform some tasks or value some things.
For example I use this way to configure a generic Maven profile that packages the application and build a docker image specific to the environment selected.
If your using maven,
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<profiles>
<profile>dev</profile>
</profiles>
</configuration>
</plugin>
</plugins>
</build>
this set dev as active profile
./mvnw spring-boot:run
will have dev as active profile.
Spring Boot seems had changed the way of reading the VM options as it evolves. Here's some way to try when you launch an application in Intellij and want to active some profile:
Open "Edit configuration" in "Run", and in "VM options", add: -Dspring.profiles.active=local
It actually works with one project of mine with Spring Boot v2.0.3.RELEASE
and Spring v5.0.7.RELEASE
, but not with another project with Spring Boot v2.1.1.RELEASE
and Spring v5.1.3.RELEASE
.
Also, when running with Maven or JAR, people mentioned this:
mvn spring-boot:run -Drun.profiles=dev
or
java -jar -Dspring.profiles.active=dev XXX.jar
(See here: how to use Spring Boot profiles)
It is mentioned somewhere, that Spring changes the way of launching the process of applications if you specify some JVM options; it forks another process and will not pass the arg it received so this does not work. The only way to pass args to it, is:
mvn spring-boot:run -Dspring-boot.run.jvmArguments="..."
Again, this is for Maven. https://docs.spring.io/spring-boot/docs/current/maven-plugin/examples/run-debug.html
What works for me for the second project, was setting the environment variable, as mentioned in some answer above: "Edit configuration" - "Environment variable", and:
SPRING_PROFILES_ACTIVE=local
In my case I have different application.properties depending on the environment, something like:
application.properties (base file)
application-dev.properties
application-qa.properties
application-prod.properties
and application.properties contains a property spring.profiles.active to pick the proper file.
For my integration tests, I created a new application-test.properties
file inside test/resources
and with the @TestPropertySource({ "/application-test.properties" })
annotation this is the file who is in charge of picking the application.properties I want depending on my needs for those tests
Try this:
@PropertySource("classpath:${spring.profiles.active:production}_file.properties")
Add to VM options: -Dspring.profiles.active=dev
Or you can add it to the build.gradle file to make it work: bootRun.systemProperties = System.properties.
It's not a big issue i faced. Just clean the project and restart your xcode!! Hope it will be working for you! It's working for me. :)
Or First of all clean the project by holding Shift(?)+Command(?)+K or Select Product > Clean
Then
Go to XCode Menu> Preference
Select Account > Team > View Details
Select any Provisioning profile from Provisioning Profiles list
Right click > Select Show in Finder. Then you will see all lists of provisioning profiles
Select all provisionaling list from the folder and move it to trash
Download All provisioning profiles by clicking Download All below Provisioning Profile lists.
Now, Run again and it should Work!
Way out for me was to add
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
annotation to class running Spring boot (marked with `@SpringBootApplication).
Finally, it looks like:
@SpringBootApplication
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class Application{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
use this URL : "https://twitter.com/(userName)/profile_image?size=original"
If you are using TWitter SDK you can get the user name when logged in, with TWTRAPIClient
, using TWTRAuthSession
.
This is the code snipe for iOS:
if let twitterId = session.userID{
let twitterClient = TWTRAPIClient(userID: twitterId)
twitterClient.loadUser(withID: twitterId) {(user, error) in
if let userName = user?.screenName{
let url = "https://twitter.com/\(userName)/profile_image?size=original")
}
}
}
Solutions described here work, but I want to add that you need to have correct target selected on the top left corner of Build Settings in Xcode. Lost some time figuring this out...
Try to remove and add ios again
ionic cordova platform remove ios
ionic cordova platform add ios
Worked in my case
In my case I had created a SB app from the SB Initializer and had included a fair number of deps in it to other things. I went in and commented out the refs to them in the build.gradle file and so was left with:
implementation 'org.springframework.boot:spring-boot-starter-hateoas'
compileOnly 'org.projectlombok:lombok'
developmentOnly 'org.springframework.boot:spring-boot-devtools'
runtimeOnly 'org.hsqldb:hsqldb'
runtimeOnly 'org.postgresql:postgresql'
annotationProcessor 'org.springframework.boot:spring-boot-configuration-processor'
annotationProcessor 'org.projectlombok:lombok'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
testImplementation 'org.springframework.restdocs:spring-restdocs-mockmvc'
as deps. Then my bare-bones SB app was able to build and get running successfully. As I go to try to do things that may need those commented-out libs I will add them back and see what breaks.
There's another way by setting the OS variable, SPRING_PROFILES_ACTIVE.
for eg :
SPRING_PROFILES_ACTIVE=dev gradle clean bootRun
Reference : How to set active Spring profiles
Both commands are correct :
mvn clean install -Pdev1
mvn clean install -P dev1
The problem is most likely not profile activation, but the profile not accomplishing what you expect it to.
It is normal that the command :
mvn help:active-profiles
does not display the profile, because is does not contain -Pdev1
. You could add it to make the profile appear, but it would be pointless because you would be testing maven itself.
What you should do is check the profile behavior by doing the following :
activeByDefault
to true
in the profile configuration,mvn help:active-profiles
(to make sure it is effectively
activated even without -Pdev1
),mvn install
.It should give the same results as before, and therefore confirm that the problem is the profile not doing what you expect.
You might want to add the following to your pom and try compiling
<repositories>
<repository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<url>http://repo.spring.io/libs-snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
</pluginRepositories>
I faced the same Maven connection timeout issue and resolved by disabling/whitelisting the anti-virus & firewall setting.
The issue got resolved immediately:
org.apache.maven.wagon.providers.http.httpclient.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:239)
<a href="#"><i class="fab fa-facebook-square"></i></a>
<a href="#"><i class="fab fa-twitter-square"></i></a>
<a href="#"><i class="fas fa-basketball-ball"></i></a>
<a href="#"><i class="fab fa-google-plus-square"></i></a>
All you have to do is wrap your font-awesome icon link in your HTML
with an anchor tag.
Following this format:
<a href="Link here"> <font-awesome icon code> </a>
It's simple, go to this folder:
~/Library/MobileDevice/Provisioning\ Profiles/
Open finder on your mac, and click on Go -> Go to Folder ... Just paste this into the search bar and hit Open. It will show the list of provisioning profiles present in Xcode. Delete all provisioning profiles.
Close SQL Server Management Studio. Type Services.msc in the run command to open the services window.
Search for SQL Server Service and right click it and select properties.
In the Log On Tab, select system account/or select your domain ID and Account and password.
Once it finds your login name press OK.
Now type your login’s passwords in both the fields.
Restart the services so that the new changes are applied as shown in figure below.
Now start SQL Server Management Studio and try to run the query if still not working try a system restart.
... or execute the following query:
USE [master]
GO
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
GO
EXEC master.dbo.sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
GO
Hi I face the same problem today. After reading "Spentak"'s answer i tried to make code signing of my target to set to iOSDeveloper, and still did not work. But after i changing "Provisioning Profile" to "Automatic", the project got built and ran without any code signing errors.
1- run python manage.py makemigrations <appname>
2- run python manage.py sqlmigrate <appname> <migrationname>
- you will find migrationname in migration folder under appname (without '.py' extension of course)
3- copy all text of result # all sql commands that generated
4- go to your db ide and paste as new query and run it
now all changes are applied on your db
It worked for = I just removed "archetypes" folder from below location
C:\Users\Lenovo.m2\repository\org\apache\maven
But you may change following for experiment - download latest binary zip of Maven, add to you C:\ drive and change following....
Change Proxy
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username></username>
<password></password>
<host>10.23.73.253</host>
<port>8080</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
We have had this issue quite recently and found out it was to do with the version of Maven we were using. We were using 3.1.0 and could not upload to nexus, we kept getting 401's, we reverted back to 3.0.3 and the issue went away.
Easiest way to confirm is to work through the maven versions and run "mvn deploy" on your project.
Further details can be found here: https://issues.apache.org/jira/browse/WAGON-421
if you do not have any database in your application simply disable the auto-config of datasource by adding below annotation.
@SpringBootApplication(exclude={DataSourceAutoConfiguration.class})
Update with Spring Boot 2.2.2.Release.
Full example here, https://www.surasint.com/spring-boot-override-property-example/
Assume that, in your jar file, you have the application.properties which have these two line:
server.servlet.context-path=/test
server.port=8081
Then, in production, you want to override the server.port=8888 but you don't want to override the other properties.
First you create another file, ex override.properties and have online this line:
server.port=8888
Then you can start the jar like this
java -jar spring-boot-1.0-SNAPSHOT.jar --spring.config.location=classpath:application.properties,/opt/somewhere/override.properties
I didn't touch the "save to a folder" option. I just copied the two files/directories you mentioned in your question to the new machine, then ran defaults read com.googlecode.iterm2
.
I was looking for something and I found this post. I post this code that managed many-to-many relationships in case someone needs it.
var UserInRole = db.UsersInRoles.Include(u => u.UserProfile).Include(u => u.Roles)
.Select (m => new
{
UserName = u.UserProfile.UserName,
RoleName = u.Roles.RoleName
});
In the Oracle RDBMS, it is possible to use a multi-row subquery in the select clause as long as the (sub-)output is encapsulated as a collection. In particular, a multi-row select clause subquery can output each of its rows as an xmlelement that is encapsulated in an xmlforest.
First of all you missed ScriptService attribute to add in webservice.
[ScriptService]
After then try following method to call webservice via JSON.
var webAddr = "http://Domain/VBRService.asmx/callJson"; var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr); httpWebRequest.ContentType = "application/json; charset=utf-8"; httpWebRequest.Method = "POST"; using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream())) { string json = "{\"x\":\"true\"}"; streamWriter.Write(json); streamWriter.Flush(); } var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse(); using (var streamReader = new StreamReader(httpResponse.GetResponseStream())) { var result = streamReader.ReadToEnd(); return result; }
Try this online tool http://www.easy-udid.com. I tested it on various iOS devices (iOS 6 and 7) and it works fine. Handful tool to quickly add customer's UDID in developer's profile
Sometimes, especially after generating a new certificate or starting to use a new code signing identity, there seems to be no other way to fix this, other than doing some cleaning the .pbxproj file. This is probably a bug that will be fixed, so if you are reading this long after this post, maybe you should try some other solution.
There is an excellent post about this in the pixeldock blog: http://www.pixeldock.com/blog/code-sign-error-provisioning-profile-cant-be-found/
In short, mostly quoting from that article, you need to:
Good luck!
These settings have now moved to Preferences > Accounts
:
Nice answers abowe, but don't forget one IMPORTANT thing - they provide different results!
var idList = new int[1, 2, 2, 2, 2]; // same user is selected 4 times
var userProfiles = _dataContext.UserProfile.Where(e => idList.Contains(e)).ToList();
This will return 2 rows from DB (and this could be correct, if you just want a distinct sorted list of users)
BUT in many cases, you could want an unsorted list of results. You always have to think about it like about a SQL query. Please see the example with eshop shopping cart to illustrate what's going on:
var priceListIDs = new int[1, 2, 2, 2, 2]; // user has bought 4 times item ID 2
var shoppingCart = _dataContext.ShoppingCart
.Join(priceListIDs, sc => sc.PriceListID, pli => pli, (sc, pli) => sc)
.ToList();
This will return 5 results from DB. Using 'contains' would be wrong in this case.
Still had trouble after trying all of the answers above (I use Visual Studio 2013). Nothing was copied to the publish folder.
The catch was that if I run MSBuild with an individual project instead of a solution, I have to put an additional parameter that specifies Visual Studio version:
/p:VisualStudioVersion=12.0
12.0
is for VS2013, replace with the version you use. Once I added this parameter, it just worked.
The complete command line looks like this:
MSBuild C:\PathToMyProject\MyProject.csproj /p:DeployOnBuild=true /p:PublishProfile=MyPublishProfile /p:VisualStudioVersion=12.0
I've found it here:
http://www.asp.net/mvc/overview/deployment/visual-studio-web-deployment/command-line-deployment
They state:
If you specify an individual project instead of a solution, you have to add a parameter that specifies the Visual Studio version.
Change the active scheme Device from Simulator to Generic iOS Device
Include moment.js and using the below code you can format your date
var formatDate= 1399919400000;
var responseDate = moment(formatDate).format('DD/MM/YYYY');
My output is "13/05/2014"
If your file idea/workspace.xml
is added to .gitignore (or its parent folder) just add
it manually to git version control. Also you can add it using TortoiseGit. After the next push you will see, that your problem is solved.
For Eclipse, setting -Dspring.profiles.active
variable in the VM arguments would do the trick.
Go to
Right Click Project --> Run as --> Run Configurations --> Arguments
And add your -Dspring.profiles.active=dev
in the VM arguments
I strongly recommend to use a Maven Repository Manager such as Nexus. It will help you to get stable and reproducible builds with Maven. As the Repository Manager is usually in your LAN, you don't have to configure the proxy settings, but you need to define some other configurations:
http://www.sonatype.com/books/nexus-book/reference/maven-sect-single-group.html
Seaching for answer I couldn't find any to be easy and flexible at the same time, then I found the Spring Security Reference and I realized there are near to perfect solutions. AOP solutions often are the greatest ones for testing, and Spring provides it with @WithMockUser
, @WithUserDetails
and @WithSecurityContext
, in this artifact:
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<version>4.2.2.RELEASE</version>
<scope>test</scope>
</dependency>
In most cases, @WithUserDetails
gathers the flexibility and power I need.
Basically you just need to create a custom UserDetailsService
with all the possible users profiles you want to test. E.g
@TestConfiguration
public class SpringSecurityWebAuxTestConfig {
@Bean
@Primary
public UserDetailsService userDetailsService() {
User basicUser = new UserImpl("Basic User", "[email protected]", "password");
UserActive basicActiveUser = new UserActive(basicUser, Arrays.asList(
new SimpleGrantedAuthority("ROLE_USER"),
new SimpleGrantedAuthority("PERM_FOO_READ")
));
User managerUser = new UserImpl("Manager User", "[email protected]", "password");
UserActive managerActiveUser = new UserActive(managerUser, Arrays.asList(
new SimpleGrantedAuthority("ROLE_MANAGER"),
new SimpleGrantedAuthority("PERM_FOO_READ"),
new SimpleGrantedAuthority("PERM_FOO_WRITE"),
new SimpleGrantedAuthority("PERM_FOO_MANAGE")
));
return new InMemoryUserDetailsManager(Arrays.asList(
basicActiveUser, managerActiveUser
));
}
}
Now we have our users ready, so imagine we want to test the access control to this controller function:
@RestController
@RequestMapping("/foo")
public class FooController {
@Secured("ROLE_MANAGER")
@GetMapping("/salute")
public String saluteYourManager(@AuthenticationPrincipal User activeUser)
{
return String.format("Hi %s. Foo salutes you!", activeUser.getUsername());
}
}
Here we have a get mapped function to the route /foo/salute and we are testing a role based security with the @Secured
annotation, although you can test @PreAuthorize
and @PostAuthorize
as well.
Let's create two tests, one to check if a valid user can see this salute response and the other to check if it's actually forbidden.
@RunWith(SpringRunner.class)
@SpringBootTest(
webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
classes = SpringSecurityWebAuxTestConfig.class
)
@AutoConfigureMockMvc
public class WebApplicationSecurityTest {
@Autowired
private MockMvc mockMvc;
@Test
@WithUserDetails("[email protected]")
public void givenManagerUser_whenGetFooSalute_thenOk() throws Exception
{
mockMvc.perform(MockMvcRequestBuilders.get("/foo/salute")
.accept(MediaType.ALL))
.andExpect(status().isOk())
.andExpect(content().string(containsString("[email protected]")));
}
@Test
@WithUserDetails("[email protected]")
public void givenBasicUser_whenGetFooSalute_thenForbidden() throws Exception
{
mockMvc.perform(MockMvcRequestBuilders.get("/foo/salute")
.accept(MediaType.ALL))
.andExpect(status().isForbidden());
}
}
As you see we imported SpringSecurityWebAuxTestConfig
to provide our users for testing. Each one used on its corresponding test case just by using a straightforward annotation, reducing code and complexity.
As you see @WithUserDetails
has all the flexibility you need for most of your applications. It allows you to use custom users with any GrantedAuthority, like roles or permissions. But if you are just working with roles, testing can be even easier and you could avoid constructing a custom UserDetailsService
. In such cases, specify a simple combination of user, password and roles with @WithMockUser.
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
@WithSecurityContext(
factory = WithMockUserSecurityContextFactory.class
)
public @interface WithMockUser {
String value() default "user";
String username() default "";
String[] roles() default {"USER"};
String password() default "password";
}
The annotation defines default values for a very basic user. As in our case the route we are testing just requires that the authenticated user be a manager, we can quit using SpringSecurityWebAuxTestConfig
and do this.
@Test
@WithMockUser(roles = "MANAGER")
public void givenManagerUser_whenGetFooSalute_thenOk() throws Exception
{
mockMvc.perform(MockMvcRequestBuilders.get("/foo/salute")
.accept(MediaType.ALL))
.andExpect(status().isOk())
.andExpect(content().string(containsString("user")));
}
Notice that now instead of the user [email protected] we are getting the default provided by @WithMockUser
: user; yet it won't matter because what we really care about is his role: ROLE_MANAGER
.
As you see with annotations like @WithUserDetails
and @WithMockUser
we can switch between different authenticated users scenarios without building classes alienated from our architecture just for making simple tests. Its also recommended you to see how @WithSecurityContext works for even more flexibility.
In my case I had code like this:
function.call(context, arg);
I got error message under IE
TypeError: Object doesn't support property or method 'error'
In the body of 'function' I had "console.error" and it turns that console object is undefined when your console is closed. I have fixed this by checking if console and console.error are defined
From accepted answer:
You go to your "device manager", find your "network adapters", then should find the virtual wifi adapter, then right click it and enable it
Maybe your device is hidden - first you should unhide it from the device manger, then re-enable the adapter from the device manger tools.
Can I recommend doing it this way, define your test like this:
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
TestPreperationExecutionListener.class
})
@Transactional
@ActiveProfiles(profiles = "localtest")
@ContextConfiguration
public class TestContext {
@Test
public void testContext(){
}
@Configuration
@PropertySource("classpath:/myprops.properties")
@ImportResource({"classpath:context.xml" })
public static class MyContextConfiguration{
}
}
with the following content in myprops.properties file:
spring.profiles.active=localtest
With this your second properties file should get resolved:
META-INF/spring/config_${spring.profiles.active}.properties
I tried following instructions given in most of the comments on this thread, including the chosen answer but the error persisted. I did some research and found this page that gave a solution that helped me out (okay, with some guessing though of my part).
So what I did is that I replaced the version number in the maven surefire plugin as follows:
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.0.0-M1</version>
I hope this helps!
Catch all. When solutions mentioned here don't work(happend in my case), simply delete all contents from '.m2' folder/directory, and do mvn clean install
.
The 'u' in front of the string values means the string is a Unicode string. Unicode is a way to represent more characters than normal ASCII can manage. The fact that you're seeing the u
means you're on Python 2 - strings are Unicode by default on Python 3, but on Python 2, the u
in front distinguishes Unicode strings. The rest of this answer will focus on Python 2.
You can create a Unicode string multiple ways:
>>> u'foo'
u'foo'
>>> unicode('foo') # Python 2 only
u'foo'
But the real reason is to represent something like this (translation here):
>>> val = u'???????????? ? ?????????????'
>>> val
u'\u041e\u0437\u043d\u0430\u043a\u043e\u043c\u044c\u0442\u0435\u0441\u044c \u0441 \u0434\u043e\u043a\u0443\u043c\u0435\u043d\u0442\u0430\u0446\u0438\u0435\u0439'
>>> print val
???????????? ? ?????????????
For the most part, Unicode and non-Unicode strings are interoperable on Python 2.
There are other symbols you will see, such as the "raw" symbol r
for telling a string not to interpret backslashes. This is extremely useful for writing regular expressions.
>>> 'foo\"'
'foo"'
>>> r'foo\"'
'foo\\"'
Unicode and non-Unicode strings can be equal on Python 2:
>>> bird1 = unicode('unladen swallow')
>>> bird2 = 'unladen swallow'
>>> bird1 == bird2
True
but not on Python 3:
>>> x = u'asdf' # Python 3
>>> y = b'asdf' # b indicates bytestring
>>> x == y
False
Its better to perform this over Master branch
Edit .gitignore file. Add the below line in it.
.idea
Remove .idea folder from remote repo. using below command.
git rm -r --cached .idea
For more info. reference: Removing Files from a Git Repository Without Actually Deleting Them
Stage .gitignore file. Using below command
git add .gitignore
Commit
git commit -m 'Removed .idea folder'
Push to remote
git push origin master
I think Nosql is "more suitable" in these scenarios at least (more supplementary is welcome)
Easy to scale horizontally by just adding more nodes.
Query on large data set
Imagine tons of tweets posted on twitter every day. In RDMS, there could be tables with millions (or billions?) of rows, and you don't want to do query on those tables directly, not even mentioning, most of time, table joins are also needed for complex queries.
Disk I/O bottleneck
If a website needs to send results to different users based on users' real-time info, we are probably talking about tens or hundreds of thousands of SQL read/write requests per second. Then disk i/o will be a serious bottleneck.
This is something that I have used successfully to convert Context
to Activity
when operating within the UI in fragments or custom views. It will unpack ContextWrapper recursively or return null if it fails.
public Activity getActivity(Context context)
{
if (context == null)
{
return null;
}
else if (context instanceof ContextWrapper)
{
if (context instanceof Activity)
{
return (Activity) context;
}
else
{
return getActivity(((ContextWrapper) context).getBaseContext());
}
}
return null;
}
To tweak a bit in order to handle the case where the variable is not set you could use a default value:
@Value("${spring.profiles.active:unknown}")
private String activeProfile;
This way if spring.profiles.active
is set, it will take it else it will take the default value unknown
.
So no exception will be triggered. And no need to force add something like @ActiveProfiles("test")
in your test to make it pass.
Get device token in Swift 3
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
let deviceTokenString = deviceToken.reduce("", {$0 + String(format: "%02X", $1)})
print("Device token: \(deviceTokenString)")
}
If you don't want to create another migration-file for a small, recent change - from Rails Console:
ActiveRecord::Migration.change_column :profiles, :show_attribute, :boolean, :default => true
Then exit and re-enter rails console, so DB-Changes will be in-effect. Then, if you do this ...
Profile.new()
You should see the "show_attribute" default-value as true.
For existing records, if you want to preserve existing "false" settings and only update "nil" values to your new default:
Profile.all.each{|profile| profile.update_attributes(:show_attribute => (profile.show_attribute == nil ? true : false)) }
Update the migration that created this table, so any future builds of the DB will get it right from the onset. Also run the same process on any deployed-instances of the DB.
If using the "new db migration" method, you can do the update of existing nil-values in that migration.
<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">
<proxies>
<proxy>
<active>true</active>
<protocol>http</protocol>
<host>proxy.somewhere.com</host>
<port>8080</port>
<username>proxyuser</username>
<password>somepassword</password>
<nonProxyHosts>www.google.com|*.somewhere.com</nonProxyHosts>
</proxy>
</proxies>
</settings>
Window > Preferences > Maven > User Settings
Just keep the following in mind.
In IIS if you have a folder for example called Pages with multiple websites in it. Website will inherit settings from the web.config file from the parent directory. So even if the folder page (in this example Pages) isn't a website but contains a web.config file, all websites listed inside of it will inherit the setting.
Try the following code
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
WebDriver DRIVER = new FirefoxDriver();
DRIVER.get("http://www.google.com");
I added -adaptive-resize 60%
to the suggested command, but with -quality 60%
.
convert -strip -interlace Plane -gaussian-blur 0.05 -quality 60% -adaptive-resize 60% img_original.jpg img_resize.jpg
These were my results
I'm not sure if that conversion destroys my image too much, but I honestly didn't think my conversion looked like crap. It was a wide angle panorama and I didn't care for meticulous obstruction.
I am using Google API for .Net, but no doubt you can find the same way to obtain this information using other version of API. As user872858 mentioned, scope userinfo.profile has been deprecated (google article) .
To obtain user profile info I use following code (re-written part from google's example):
IAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = Secrets,
Scopes = new[] { PlusService.Scope.PlusLogin,"https://www.googleapis.com/auth/plus.profile.emails.read" }
});
TokenResponse _token = flow.ExchangeCodeForTokenAsync("", code, "postmessage",
CancellationToken.None).Result;
// Create an authorization state from the returned token.
context.Session["authState"] = _token;
// Get tokeninfo for the access token if you want to verify.
Oauth2Service service = new Oauth2Service(
new Google.Apis.Services.BaseClientService.Initializer());
Oauth2Service.TokeninfoRequest request = service.Tokeninfo();
request.AccessToken = _token.AccessToken;
Tokeninfo info = request.Execute();
if (info.VerifiedEmail.HasValue && info.VerifiedEmail.Value)
{
flow = new GoogleAuthorizationCodeFlow(
new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = Secrets,
Scopes = new[] { PlusService.Scope.PlusLogin }
});
UserCredential credential = new UserCredential(flow,
"me", _token);
_token = credential.Token;
_ps = new PlusService(
new Google.Apis.Services.BaseClientService.Initializer()
{
ApplicationName = "Your app name",
HttpClientInitializer = credential
});
Person userProfile = _ps.People.Get("me").Execute();
}
Than, you can access almost anything using userProfile.
UPDATE: To get this code working you have to use appropriate scopes on google sign in button. For example my button:
<button class="g-signin"
data-scope="https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.profile.emails.read"
data-clientid="646361778467-nb2uipj05c4adlk0vo66k96bv8inqles.apps.googleusercontent.com"
data-accesstype="offline"
data-redirecturi="postmessage"
data-theme="dark"
data-callback="onSignInCallback"
data-cookiepolicy="single_host_origin"
data-width="iconOnly">
</button>
You will have to go to your developer site, go to your certificates, and generate a new one for your current MAC and add it to your keychain.
And then you will need to add the Provisioning Profile again. It should work now. Basically you need to perform the same steps you did when you first got your Dev Certificate.
Review the pom.xml
file inside of target/checkout/
. Chances are, the pom.xml
in your trunk or master branch does not have the distributionManagement
tag.
None of these answers were correct in my case.. the order seems dependent on the alphabetical ordering of the <id> tag, which is an arbitrary string. Hence this forced repo search order:
<repository>
<id>1_maven.apache.org</id>
<releases> <enabled>true</enabled> </releases>
<snapshots> <enabled>true</enabled> </snapshots>
<url>https://repo.maven.apache.org/maven2</url>
<layout>default</layout>
</repository>
<repository>
<id>2_maven.oracle.com</id>
<releases> <enabled>true</enabled> </releases>
<snapshots> <enabled>false</enabled> </snapshots>
<url>https://maven.oracle.com</url>
<layout>default</layout>
</repository>
After inserting any row you can get last inserted id by below line of query.
INSERT INTO aspnet_GameProfiles(UserId,GameId) VALUES(@UserId, @GameId); SELECT @@IDENTITY
This is the way that I did it for a uni project, works fine, prob not safe tho
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
$title = $_POST['title'];
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$pass = $_POST['password'];
$cpass = $_POST['cpassword'];
$check = 1;
if (){
}
else{
$check = 1;
}
if ($check == 1){
require_once('website_data_collecting/db.php');
$sel_user = "SELECT * FROM users WHERE user_email='$email'";
$run_user = mysqli_query($con, $sel_user);
$check_user = mysqli_num_rows($run_user);
if ($check_user > 0){
echo '<div style="margin: 0 0 10px 20px;">Email already exists!</br>
<a href="recover.php">Recover Password</a></div>';
}
else{
$users_tb = "INSERT INTO users ".
"(user_name, user_email, user_password) ".
"VALUES('$name','$email','$pass')";
$users_info_tb = "INSERT INTO users_info".
"(user_title, user_surname)".
"VALUES('$title', '$surname')";
mysql_select_db('dropbox');
$run_users_tb = mysql_query( $users_tb, $conn );
$run_users_info_tb = mysql_query( $users_info_tb, $conn );
if(!$run_users_tb || !$run_users_info_tb){
die('Could not enter data: ' . mysql_error());
}
else{
echo "Entered data successfully\n";
}
mysql_close($conn);
}
}
My situation and what I did to fix it:
I have a javascript file included on an HTML page as follows:
Page Name: test.html
<!DOCTYPE html>
<html>
<head>
<script src="scripts/common.js"></script>
<title>Test debugging JS in Chrome</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div>
<script type="text/javascript">
document.write("something");
</script>
</div>
</body>
</html>
Now entering the Javascript Debugger in Chrome, I click the Scripts Tab, and drop down the list as shown above. I can clearly see scripts/common.js however I could NOT see the current html page test.html in the drop down, therefore I could not debug the embedded javascript:
<script type="text/javascript">
document.write("something");
</script>
That was perplexing. However, when I removed the obsolete type="text/javascript" from the embedded script:
<script>
document.write("something");
</script>
..and refreshed / reloaded the page, voila, it appeared in the drop down list, and all was well again.
I hope this is helpful to anyone who is having issues debugging embedded javascript on an html page.
Under
Provisioning -> Distribution -> Distribution Provisioning Profiles
I downloaded the desired certificate again and installed it. Now I don't see an empty file in Xcode. The build also works now (no code sign error).
What I also did: I downloaded the WWDR and installed it, but I don't know if that was the reason (because I think it's always the same)
I had this error because I registered the wrong class in this line of code:
JAXBContext context = JAXBContext.newInstance(MyRootXmlClass.class);
ManyToManyField isn`t a good choice.You can use some snippets to implement MultipleChoiceField.You can be inspired by MultiSelectField with comma separated values (Field + FormField) But it has some bug in it.And you can install django-multiselectfield.This is more prefect.
<script>
$(document).ready(function () {
var msg = '@ViewBag.ErrorMessage'
if (msg.length > 0)
OnFailure('Register', msg);
});
function OnSuccess(header,Message) {
$("#Message_Header").text(header);
$("#Message_Text").text(Message);
$('#MessageDialog').modal('show');
}
function OnFailure(header,error)
{
$("#Message_Header").text(header);
$("#Message_Text").text(error);
$('#MessageDialog').modal('show');
}
</script>
The API docs on link_to show some examples of adding querystrings to both named and oldstyle routes. Is this what you want?
link_to
can also produce links with anchors or query strings:
link_to "Comment wall", profile_path(@profile, :anchor => "wall")
#=> <a href="/profiles/1#wall">Comment wall</a>
link_to "Ruby on Rails search", :controller => "searches", :query => "ruby on rails"
#=> <a href="/searches?query=ruby+on+rails">Ruby on Rails search</a>
link_to "Nonsense search", searches_path(:foo => "bar", :baz => "quux")
#=> <a href="/searches?foo=bar&baz=quux">Nonsense search</a>
Maybe too late, but I'd cast 0/1 as bit to make the datatype eventually becomes True/False when consumed by .NET framework:
SELECT EntityId,
EntityName,
CASE
WHEN EntityProfileIs IS NULL
THEN CAST(0 as bit)
ELSE CAST(1 as bit) END AS HasProfile
FROM Entities
LEFT JOIN EntityProfiles ON EntityProfiles.EntityId = Entities.EntityId`
for your example:
{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}
you will have to do something of this effect:
JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");
this returns the array object.
Then iterating will be as follows:
int size = the_json_array.length();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
//Blah blah blah...
arrays.add(another_json_object);
}
//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);
//The end...
You will have to determine if the data is an array (simply checking that charAt(0)
starts with [
character).
Hope this helps.
Place this dependency, and dont forget to select : Include dependencies with "provided" scope
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
My problem was one of my elements had the xmlns attribute:
<?xml version="1.0" encoding="utf-8"?>
<RETS ReplyCode="0">
<RETS-RESPONSE xmlns="blahblah">
...
</RETS-RESPONSE>
</RETS>
No matter what I tried the xmlns attribute seemed to be breaking the serializer, so I removed any trace of xmlns="..." from the xml file:
<?xml version="1.0" encoding="utf-8"?>
<RETS ReplyCode="0">
<RETS-RESPONSE>
...
</RETS-RESPONSE>
</RETS>
and voila! Everything worked.
I now parse the xml file to remove this attribute before deserializing. Not sure why this works, maybe my case is different since the element containing the xmlns attribute is not the root element.
That exception means that you are trying to unpack a tuple, but the tuple has too many values with respect to the number of target variables. For example: this work, and prints 1, then 2, then 3
def returnATupleWithThreeValues():
return (1,2,3)
a,b,c = returnATupleWithThreeValues()
print a
print b
print c
But this raises your error
def returnATupleWithThreeValues():
return (1,2,3)
a,b = returnATupleWithThreeValues()
print a
print b
raises
Traceback (most recent call last):
File "c.py", line 3, in ?
a,b = returnATupleWithThreeValues()
ValueError: too many values to unpack
Now, the reason why this happens in your case, I don't know, but maybe this answer will point you in the right direction.
I have seen comments in INI files, so yes. Please refer to this Wikipedia article. I could not find an official specification, but that is the correct syntax for comments, as many game INI files had this as I remember.
Edit
The API returns the Value and the Comment (forgot to mention this in my reply), just construct and example INI file and call the API on this (with comments) and you can see how this is returned.
Had this issue occur when everything seemed to be setup correctly, build setting were pointing to correct provisioning profile, code signing was properly setup, etc.
Issue occurred because I had just created a new scheme and hadn't regenerated my CocoaPods for the new configurations. As you can see from the image, the new ad-hoc configuration is pointing to the Pods.production
configuration, instead of a Pods.ad-hoc
configuration (and test respectively)
To fix:
None
-- cocoapods wouldn't generate the configs unless I did thispod install
That's it!
Simple steps to get this done:
Now all the dots are connected and it should work. This works for both dev and distribution.
Well, I can think of a CSS hack that will resolve this issue.
You could add the following line in your CSS file:
* html .blog_list div.postbody img { width:75px; height: SpecifyHeightHere; }
The above code will only be seen by IE6. The aspect ratio won't be perfect, but you could make it look somewhat normal. If you really wanted to make it perfect, you would need to write some javascript that would read the original picture width, and set the ratio accordingly to specify a height.
Iterable is a generic interface. A problem you might be having (you haven't actually said what problem you're having, if any) is that if you use a generic interface/class without specifying the type argument(s) you can erase the types of unrelated generic types within the class. An example of this is in Non-generic reference to generic class results in non-generic return types.
So I would at least change it to:
public class ProfileCollection implements Iterable<Profile> {
private ArrayList<Profile> m_Profiles;
public Iterator<Profile> iterator() {
Iterator<Profile> iprof = m_Profiles.iterator();
return iprof;
}
...
public Profile GetActiveProfile() {
return (Profile)m_Profiles.get(m_ActiveProfile);
}
}
and this should work:
for (Profile profile : m_PC) {
// do stuff
}
Without the type argument on Iterable, the iterator may be reduced to being type Object so only this will work:
for (Object profile : m_PC) {
// do stuff
}
This is a pretty obscure corner case of Java generics.
If not, please provide some more info about what's going on.
Here is the answer for those of you looking like I did all over the web trying to find out how to do this task. Uploading a photo to a server with the file name stored in a mysql database and other form data you want in your Database. Please let me know if it helped.
Firstly the form you need:
<form method="post" action="addMember.php" enctype="multipart/form-data">
<p>
Please Enter the Band Members Name.
</p>
<p>
Band Member or Affiliates Name:
</p>
<input type="text" name="nameMember"/>
<p>
Please Enter the Band Members Position. Example:Drums.
</p>
<p>
Band Position:
</p>
<input type="text" name="bandMember"/>
<p>
Please Upload a Photo of the Member in gif or jpeg format. The file name should be named after the Members name. If the same file name is uploaded twice it will be overwritten! Maxium size of File is 35kb.
</p>
<p>
Photo:
</p>
<input type="hidden" name="size" value="350000">
<input type="file" name="photo">
<p>
Please Enter any other information about the band member here.
</p>
<p>
Other Member Information:
</p>
<textarea rows="10" cols="35" name="aboutMember">
</textarea>
<p>
Please Enter any other Bands the Member has been in.
</p>
<p>
Other Bands:
</p>
<input type="text" name="otherBands" size=30 />
<br/>
<br/>
<input TYPE="submit" name="upload" title="Add data to the Database" value="Add Member"/>
</form>
Then this code processes you data from the form:
<?php
// This is the directory where images will be saved
$target = "your directory";
$target = $target . basename( $_FILES['photo']['name']);
// This gets all the other information from the form
$name=$_POST['nameMember'];
$bandMember=$_POST['bandMember'];
$pic=($_FILES['photo']['name']);
$about=$_POST['aboutMember'];
$bands=$_POST['otherBands'];
// Connects to your Database
mysqli_connect("yourhost", "username", "password") or die(mysqli_error()) ;
mysqli_select_db("dbName") or die(mysqli_error()) ;
// Writes the information to the database
mysqli_query("INSERT INTO tableName (nameMember,bandMember,photo,aboutMember,otherBands)
VALUES ('$name', '$bandMember', '$pic', '$about', '$bands')") ;
// Writes the photo to the server
if(move_uploaded_file($_FILES['photo']['tmp_name'], $target))
{
// Tells you if its all ok
echo "The file ". basename( $_FILES['uploadedfile']['name']). " has been uploaded, and your information has been added to the directory";
}
else {
// Gives and error if its not
echo "Sorry, there was a problem uploading your file.";
}
?>
Code edited from www.about.com
I just tried it on another website, in firefox. After trying to save the webpage, it gave me a save-file-as dropdown menu with an option called webpage, svg only.
Try using another temporary pair:
pair<string,double> temp;
vector<pair<string,double>> revenue;
// Inside the loop
temp.first = "string";
temp.second = map[i].second;
revenue.push_back(temp);
First make a backup of your /var/lib/mysql/ directory just to be safe.
sudo mkdir /home/<your username>/mysql/
cd /var/lib/mysql/
sudo cp * /home/<your username>/mysql/ -R
Next purge MySQL (this will remove php5-mysql and phpmyadmin as well as a number of other libraries so be prepared to re-install some items after this.
sudo apt-get purge mysql-server-5.1 mysql-common
Remove the folder /etc/mysql/ and it's contents
sudo rm /etc/mysql/ -R
Next check that your old database files are still in /var/lib/mysql/ if they are not then copy them back in to the folder then chown root:root
(only run these if the files are no longer there)
sudo mkdir /var/lib/mysql/
sudo chown root:root /var/lib/mysql/ -R
cd ~/mysql/
sudo cp * /var/lib/mysql/ -R
Next install mysql server
sudo apt-get install mysql-server
Finally re-install any missing packages like phpmyadmin and php5-mysql.
minimumFontSize
has been deprecated with iOS 6. You can use minimumScaleFactor
.
yourLabel.adjustsFontSizeToFitWidth=YES;
yourLabel.minimumScaleFactor=0.5;
This will take care of your font size according width of label and text.
You can store and read string information in a cookie.
If it is a session id coming from the server, the server can generate this cookie. And when another request is sent to the server the cookie will come too. Without having to do anything in the browser.
However if it is javascript that creates the session Id. You can create a cookie with javascript, with a function like:
function writeCookie(name,value,days) {
var date, expires;
if (days) {
date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
expires = "; expires=" + date.toGMTString();
}else{
expires = "";
}
document.cookie = name + "=" + value + expires + "; path=/";
}
Then in each page you need this session Id you can read the cookie, with a function like:
function readCookie(name) {
var i, c, ca, nameEQ = name + "=";
ca = document.cookie.split(';');
for(i=0;i < ca.length;i++) {
c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1,c.length);
}
if (c.indexOf(nameEQ) == 0) {
return c.substring(nameEQ.length,c.length);
}
}
return '';
}
The read function work from any page or tab of the same domain that has written it, either if the cookie was created from the page in javascript or from the server.
To store the id:
var sId = 's234543245';
writeCookie('sessionId', sId, 3);
To read the id:
var sId = readCookie('sessionId')
I know that this is super-duper old, but on the off chance that someone comes looking for this, as of Visual Basic 14, Vb supports interpolation. Sooooo cool!
Example:
SQLQueryString = $"
Insert into Employee values(
{txtEmployeeNo},
{txtContractsStartDate},
{txtSeatNo},
{txtFloor},
{txtLeaves}
)"
It works. Documentation Here
Edit: After writing this, I realized that the OP was talking about VBA. This will not work in VBA!!! However, I will leave this up here, because as someone new to VB, I stumbled upon this question looking for a solution to just this problem in VB.net. If this helps someone else, great.
You need to add query.addEntity(SwitcherServiceSource.class) before calling the .list() on query.
MSDN seems to indicate that the Cxxx casts for specific types can improve performance in VB .NET because they are converted to inline code. For some reason, it also suggests DirectCast as opposed to CType in certain cases (the documentations states it's when there's an inheritance relationship; I believe this means the sanity of the cast is checked at compile time and optimizations can be applied whereas CType always uses the VB runtime.)
When I'm writing VB .NET code, what I use depends on what I'm doing. If it's prototype code I'm going to throw away, I use whatever I happen to type. If it's code I'm serious about, I try to use a Cxxx cast. If one doesn't exist, I use DirectCast if I have a reasonable belief that there's an inheritance relationship. If it's a situation where I have no idea if the cast should succeed (user input -> integers, for example), then I use TryCast so as to do something more friendly than toss an exception at the user.
One thing I can't shake is I tend to use ToString instead of CStr but supposedly Cstr is faster.
It's an inlined image (png), encoded in base64. It can make a page faster: the browser doesn't have to query the server for the image data separately, saving a round trip.
(It can also make it slower if abused: these resources are not cached, so the bytes are included in each page load.)
I was the same problem and as Pengyy suggest, that is the fix. Thanks a lot.
My problem on the Browser Console:
PortafolioComponent.html:3 ERROR Error: Error trying to diff '[object Object]'. Only arrays and iterables are allowed(…)
In my case my code fix was:
//productos.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
@Injectable()
export class ProductosService {
productos:any[] = [];
cargando:boolean = true;
constructor( private http:Http) {
this.cargar_productos();
}
public cargar_productos(){
this.cargando = true;
this.http.get('https://webpage-88888a1.firebaseio.com/productos.json')
.subscribe( res => {
console.log(res.json());
this.cargando = false;
this.productos = res.json().productos; // Before this.productos = res.json();
});
}
}
Just copy war file to standalone/deployments/ folder, it should deploy it automatically. It'll also create your_app_name.deployed file, when your application is deployed. Also be sure that you start server with bin/standalone.sh script.
Here is answer for your question.
db.getCollection('users').aggregate([
{$match : {admin : 1}},
{$lookup: {from: "posts",localField: "_id",foreignField: "owner_id",as: "posts"}},
{$project : {
posts : { $filter : {input : "$posts" , as : "post", cond : { $eq : ['$$post.via' , 'facebook'] } } },
admin : 1
}}
])
Or either you can go with mongodb group option.
db.getCollection('users').aggregate([
{$match : {admin : 1}},
{$lookup: {from: "posts",localField: "_id",foreignField: "owner_id",as: "posts"}},
{$unwind : "$posts"},
{$match : {"posts.via":"facebook"}},
{ $group : {
_id : "$_id",
posts : {$push : "$posts"}
}}
])
I'm was trying to do the same thing and it was bugging the crap out of me. In firefox, it appears that if you try to do some things when the escape key is pressed, it continues processing the escape key which then cancels whatever you were trying to do. Alert works fine. But in my case, I wanted to go back in the history which did not work. Finally figured out that I had to force the propagation of the event to stop as shown below...
if (keyCode == 27)
{
history.back();
if (window.event)
{
// IE works fine anyways so this isn't really needed
e.cancelBubble = true;
e.returnValue = false;
}
else if (e.stopPropagation)
{
// In firefox, this is what keeps the escape key from canceling the history.back()
e.stopPropagation();
e.preventDefault();
}
return (false);
}
As others said, it's a time change in 1927 in Shanghai.
It was 23:54:07
in Shanghai, in the local standard time, but then after 5 minutes and 52 seconds, it turned to the next day at 00:00:00
, and then local standard time changed back to 23:54:08
. So, that's why the difference between the two times is 343 seconds, not 1 second, as you would have expected.
The time can also mess up in other places like the US. The US has Daylight Saving Time. When the Daylight Saving Time starts the time goes forward 1 hour. But after a while, the Daylight Saving Time ends, and it goes backward 1 hour back to the standard time zone. So sometimes when comparing times in the US the difference is about 3600
seconds not 1 second.
But there is something different about these two-time changes. The latter changes continuously and the former was just a change. It didn't change back or change again by the same amount.
It's better to use UTC unless if needed to use non-UTC time like in display.
You can use the --prefer-source
flag for composer to checkout external packages with the VCS information (if any available). You can simply revert to the original state. Also if you issue the composer update
command composer will detect any changes you made locally and ask if you want to discard them.
Your .gitignore file is related to your root project (ZF2 skeleton) and it prevents the vendor dir (where your third party libs are) from committing to your own VCS. The ignore file is unrelated to the git repo's of your vendors.
I use this:
1) The parent activity call the secondary activity with the method "startActivityForResult"
2) In the secondary activity when is closing:
int exitCode = 1; // Select the number you want
setResult(exitCode);
finish();
3) And in the parent activity override the method "onActivityResult":
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
int exitCode = 1;
if(resultCode == exitCode) {
super.setResult(exitCode); // use this if you have more than 2 activities
finish();
}
}
This works fine for me.
JSON notation has only a handful of native datatypes (objects, arrays, strings, numbers, booleans, and null), so anything serialized in JSON needs to be expressed as one of these types.
As shown in the json module docs, this conversion can be done automatically by a JSONEncoder and JSONDecoder, but then you would be giving up some other structure you might need (if you convert sets to a list, then you lose the ability to recover regular lists; if you convert sets to a dictionary using dict.fromkeys(s)
then you lose the ability to recover dictionaries).
A more sophisticated solution is to build-out a custom type that can coexist with other native JSON types. This lets you store nested structures that include lists, sets, dicts, decimals, datetime objects, etc.:
from json import dumps, loads, JSONEncoder, JSONDecoder
import pickle
class PythonObjectEncoder(JSONEncoder):
def default(self, obj):
if isinstance(obj, (list, dict, str, unicode, int, float, bool, type(None))):
return JSONEncoder.default(self, obj)
return {'_python_object': pickle.dumps(obj)}
def as_python_object(dct):
if '_python_object' in dct:
return pickle.loads(str(dct['_python_object']))
return dct
Here is a sample session showing that it can handle lists, dicts, and sets:
>>> data = [1,2,3, set(['knights', 'who', 'say', 'ni']), {'key':'value'}, Decimal('3.14')]
>>> j = dumps(data, cls=PythonObjectEncoder)
>>> loads(j, object_hook=as_python_object)
[1, 2, 3, set(['knights', 'say', 'who', 'ni']), {u'key': u'value'}, Decimal('3.14')]
Alternatively, it may be useful to use a more general purpose serialization technique such as YAML, Twisted Jelly, or Python's pickle module. These each support a much greater range of datatypes.
Learn python the hard way ex 34
try this
animals = ['bear' , 'python' , 'peacock', 'kangaroo' , 'whale' , 'platypus']
# print "The first (1st) animal is at 0 and is a bear."
for i in range(len(animals)):
print "The %d animal is at %d and is a %s" % (i+1 ,i, animals[i])
# "The animal at 0 is the 1st animal and is a bear."
for i in range(len(animals)):
print "The animal at %d is the %d and is a %s " % (i, i+1, animals[i])
Updating the 'phones' function in Justen's answer using AngularJS 1.1.5 syntax.
Original:
phones: function($q, Phone) {
var deferred = $q.defer();
Phone.query(function(phones) {
deferred.resolve(phones);
});
return deferred.promise;
}
Updated:
phones: function(Phone) {
return Phone.query().$promise;
}
Much shorter thanks to the Angular team and contributors. :)
This is also the answer of Maximilian Hoffmann. Apparently that commit made it into 1.1.5.
To amend kris' answer, starting with Git 2.20 (Q4 2018), the proper command for git mergetool
will be
git config --global merge.guitool kdiff3
That is because "git mergetool
" learned to take the "--[no-]gui
" option, just like
"git difftool
" does.
See commit c217b93, commit 57ba181, commit 063f2bd (24 Oct 2018) by Denton Liu (Denton-L
).
(Merged by Junio C Hamano -- gitster
-- in commit 87c15d1, 30 Oct 2018)
mergetool
: accept-g/--[no-]gui
as argumentsIn line with how
difftool
accepts a-g/--[no-]gui
option, makemergetool
accept the same option in order to use themerge.guitool
variable to find the default mergetool instead ofmerge.tool
.
Get rid from your <Button>
wrap div using display:block
and float:left
in both <Button>
and <h1>
and specifying their width
with a position:relative
to your Section
. This approach has the advantage of not needing another div
only to position your <Button>
html
<section>
<h1>some long long long long header, a whole line, 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6</h1>
<button>button</button>
</section>
? css
section {
position: relative;
width: 50%;
border: 1px solid;
float:left;
}
h1 {
display: block;
width:70%;
float:left;
}
button
{
position:relative;
top:0;
left:0;
float:left;
}
?
No need to use second ajax function, you can get it back on success inside a function, another issue here is you don't know when the first ajax call finished, then, even if you use SESSION you may not get it within second AJAX call.
SO, I recommend using one AJAX call and get the value with success.
example: in first ajax call
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data){
console.log(data);
alert(data);
//or if the data is JSON
var jdata = jQuery.parseJSON(data);
}
});
What @deceze said is correct, it seems that your JSON is malformed, try this:
{
"Coords": [{
"Accuracy": "30",
"Latitude": "53.2778273",
"Longitude": "-9.0121648",
"Timestamp": "Fri Jun 28 2013 11:43:57 GMT+0100 (IST)"
}, {
"Accuracy": "30",
"Latitude": "53.2778273",
"Longitude": "-9.0121648",
"Timestamp": "Fri Jun 28 2013 11:43:57 GMT+0100 (IST)"
}, {
"Accuracy": "30",
"Latitude": "53.2778273",
"Longitude": "-9.0121648",
"Timestamp": "Fri Jun 28 2013 11:43:57 GMT+0100 (IST)"
}, {
"Accuracy": "30",
"Latitude": "53.2778339",
"Longitude": "-9.0121466",
"Timestamp": "Fri Jun 28 2013 11:45:54 GMT+0100 (IST)"
}, {
"Accuracy": "30",
"Latitude": "53.2778159",
"Longitude": "-9.0121201",
"Timestamp": "Fri Jun 28 2013 11:45:58 GMT+0100 (IST)"
}]
}
Use json_decode
to convert String into Object (stdClass
) or array: http://php.net/manual/en/function.json-decode.php
[edited]
I did not understand what do you mean by "an official JSON object", but suppose you want to add content to json via PHP and then converts it right back to JSON?
assuming you have the following variable:
$data = '{"Coords":[{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27770755361785","Longitude":"-9.011979642121824","Timestamp":"Fri Jul 05 2013 12:02:09 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"}]}';
You should convert it to Object (stdClass):
$manage = json_decode($data);
But working with stdClass
is more complicated than PHP-Array, then try this (use second param with true
):
$manage = json_decode($data, true);
This way you can use array functions: http://php.net/manual/en/function.array.php
adding an item:
$manage = json_decode($data, true);
echo 'Before: <br>';
print_r($manage);
$manage['Coords'][] = Array(
'Accuracy' => '90'
'Latitude' => '53.277720488429026'
'Longitude' => '-9.012038778269686'
'Timestamp' => 'Fri Jul 05 2013 11:59:34 GMT+0100 (IST)'
);
echo '<br>After: <br>';
print_r($manage);
remove first item:
$manage = json_decode($data, true);
echo 'Before: <br>';
print_r($manage);
array_shift($manage['Coords']);
echo '<br>After: <br>';
print_r($manage);
any chance you want to save to json to a database or a file:
$data = '{"Coords":[{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.277720488429026","Longitude":"-9.012038778269686","Timestamp":"Fri Jul 05 2013 11:59:34 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27770755361785","Longitude":"-9.011979642121824","Timestamp":"Fri Jul 05 2013 12:02:09 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"},{"Accuracy":"65","Latitude":"53.27769091555766","Longitude":"-9.012051410095722","Timestamp":"Fri Jul 05 2013 12:02:17 GMT+0100 (IST)"}]}';
$manage = json_decode($data, true);
$manage['Coords'][] = Array(
'Accuracy' => '90'
'Latitude' => '53.277720488429026'
'Longitude' => '-9.012038778269686'
'Timestamp' => 'Fri Jul 05 2013 11:59:34 GMT+0100 (IST)'
);
if (($id = fopen('datafile.txt', 'wb'))) {
fwrite($id, json_encode($manage));
fclose($id);
}
I hope I have understood your question.
Good luck.
If you already have your line of text in a variable $LINE, then you should be able to say
for L in $LINE; do
echo $L;
done
i have used it in this way and its working fine
quantity=prompt("Please enter the quantity","1");
quantity=parseInt(quantity);
if (!isNaN( quantity ))
{
totalAmount=itemPrice*quantity;
}
return totalAmount;
imho there are two cases for branches that were forgot to close
Case 1: branch was not merged into default
in this case I update to the branch and do another commit with --close-branch, unfortunatly this elects the branch to become the new tip and hence before pushing it to other clones I make sure that the real tip receives some more changes and others don't get confused about that strange tip.
hg up myBranch
hg commit --close-branch
Case 2: branch was merged into default
This case is not that much different from case 1 and it can be solved by reproducing the steps for case 1 and two additional ones.
in this case I update to the branch changeset, do another commit with --close-branch and merge the new changeset that became the tip into default. the last operation creates a new tip that is in the default branch - HOORAY!
hg up myBranch
hg commit --close-branch
hg up default
hg merge myBranch
Hope this helps future readers.
If you have multiple versions as well as multiple architectures (32 bit, 64 bit) you will need to add a -32 or -64 at the end of your version.
For windows, go to cmd and type py --list and it will produce the versions you have installed. The list will look like the following:
Installed Pythons found by py Launcher for Windows
-3.7-64 *
-3.7-32
-3.6-32
The full command as an example will be:
py -3.6-32 -m pip install (package)
If you want to get more indepth, to install a specific version of a package on a specific version of python, use ==(version) after the package. As an example,
py -3.6-32 -m pip install opencv-python==4.1.0.25
You might want to try the very new and simple CSS3 feature:
img {
object-fit: contain;
}
It preserves the picture ratio (as when you use the background-picture trick), and in my case worked nicely for the same issue.
Be careful though, it is not supported by IE (see support details here).
I had a similar problem. GET requests worked and their (empty) request bodies got written to the the log file. POST requests failed with a 404. Experimenting a bit, I found that all POST requests were failing. I found a forum posting asking about POST requests and the solution there worked for me. That solution? Add a proxy_header
line right before the proxy_pass
line, exactly like the one in the example below.
server {
listen 192.168.0.1:45080;
server_name foo.example.org;
access_log /path/to/log/nginx/post_bodies.log post_bodies;
location / {
### add the following proxy_header line to get POSTs to work
proxy_set_header Host $http_host;
proxy_pass http://10.1.2.3;
}
}
(This is with nginx 1.2.1 for what it is worth.)
Are you using JTextArea
's append(String)
method to add additional text?
JTextArea txtArea = new JTextArea("Hello, World\n", 20, 20);
txtArea.append("Goodbye Cruel World\n");
Firstly, I believe that trying to do several things at once is a bad practice in general and I suggest you think over what you are trying to achieve.
It serves as a good theoretical question though and from what I gather the CopyOnWriteArraySet
implementation of java.util.Set
interface satisfies your rather special requirements.
http://download.oracle.com/javase/1,5.0/docs/api/java/util/concurrent/CopyOnWriteArraySet.html
you can set a width for yor element which will show only the button and will hide the "no file chosen".
This can be accomplished by Unmarshaling into a map[string]json.RawMessage
.
var objmap map[string]json.RawMessage
err := json.Unmarshal(data, &objmap)
To further parse sendMsg
, you could then do something like:
var s sendMsg
err = json.Unmarshal(objmap["sendMsg"], &s)
For say
, you can do the same thing and unmarshal into a string:
var str string
err = json.Unmarshal(objmap["say"], &str)
EDIT: Keep in mind you will also need to export the variables in your sendMsg struct to unmarshal correctly. So your struct definition would be:
type sendMsg struct {
User string
Msg string
}
You have to install it explixitly using the python package manager as
I think I got there in the end.
The task is like this:
- name: Populate genders
set_fact:
genders: "{{ genders|default({}) | combine( {item.item.name: item.stdout} ) }}"
with_items: "{{ people.results }}"
It loops through each of the dicts (item
) in the people.results
array, each time creating a new dict like {Bob: "male"}
, and combine()
s that new dict in the genders
array, which ends up like:
{
"Bob": "male",
"Thelma": "female"
}
It assumes the keys (the name
in this case) will be unique.
I then realised I actually wanted a list of dictionaries, as it seems much easier to loop through using with_items
:
- name: Populate genders
set_fact:
genders: "{{ genders|default([]) + [ {'name': item.item.name, 'gender': item.stdout} ] }}"
with_items: "{{ people.results }}"
This keeps combining the existing list with a list containing a single dict. We end up with a genders
array like this:
[
{'name': 'Bob', 'gender': 'male'},
{'name': 'Thelma', 'gender': 'female'}
]
To answer the questions directly:
Will
collect()
behave the same way if called on a dataframe?
Yes, spark.DataFrame.collect
is functionally the same as spark.RDD.collect
. They serve the same purpose on these different objects.
What about the
select()
method?
There is no such thing as spark.RDD.select
, so it cannot be the same as spark.DataFrame.select
.
Does it also work the same way as
collect()
if called on a dataframe?
The only thing that is similar between select
and collect
is that they are both functions on a DataFrame. They have absolutely zero overlap in functionality.
Here's my own description: collect
is the opposite of sc.parallelize
. select
is the same as the SELECT
in any SQL statement.
If you are still having trouble understanding what collect
actually does (for either RDD or DataFrame), then you need to look up some articles about what spark is doing behind the scenes. e.g.:
str
in Python is represented in Unicode
.UTF-8
is an encoding standard to encode Unicode
string to bytes
. There are many encoding standards out there (e.g. UTF-16
, ASCII
, SHIFT-JIS
, etc.).When the client sends data to your server and they are using UTF-8
, they are sending a bunch of bytes
not str
.
You received a str
because the "library" or "framework" that you are using, has implicitly converted some random bytes
to str
.
Under the hood, there is just a bunch of bytes
. You just need ask the "library" to give you the request content in bytes
and you will handle the decoding yourself (if library can't give you then it is trying to do black magic then you shouldn't use it).
UTF-8
encoded bytes
to str
: bs.decode('utf-8')
str
to UTF-8
bytes
: s.encode('utf-8')
I want to suggest shortest answer (one more functional style):
Catch<FormatException, OverflowException>(() =>
{
WebId = new Guid(queryString["web"]);
},
exception =>
{
WebId = Guid.Empty;
});
For this you need to create several "Catch" method overloads, similar to System.Action:
[DebuggerNonUserCode]
public static void Catch<TException1, TException2>(Action tryBlock,
Action<Exception> catchBlock)
{
CatchMany(tryBlock, catchBlock, typeof(TException1), typeof(TException2));
}
[DebuggerNonUserCode]
public static void Catch<TException1, TException2, TException3>(Action tryBlock,
Action<Exception> catchBlock)
{
CatchMany(tryBlock, catchBlock, typeof(TException1), typeof(TException2), typeof(TException3));
}
and so on as many as you wish. But you need to do it once and you can use it in all your projects (or, if you created a nuget package we could use it too).
And CatchMany implementation:
[DebuggerNonUserCode]
public static void CatchMany(Action tryBlock, Action<Exception> catchBlock,
params Type[] exceptionTypes)
{
try
{
tryBlock();
}
catch (Exception exception)
{
if (exceptionTypes.Contains(exception.GetType())) catchBlock(exception);
else throw;
}
}
p.s. I haven't put null checks for code simplicity, consider to add parameter validations.
p.s.2 If you want to return a value from the catch, it's necessary to do same Catch methods, but with returns and Func instead of Action in parameters.
I was facing this issue in eclipse . What I did was, killed the running java process from the task manager.
It worked for me.
There is no way you can delete a pull request yourself -- you and the repo owner (and all users with push access to it) can close it, but it will remain in the log. This is part of the philosophy of not denying/hiding what happened during development.
However, if there are critical reasons for deleting it (this is mainly violation of Github Terms of Service), Github support staff will delete it for you.
Whether or not they are willing to delete your PR for you is something you can easily ask them, just drop them an email at [email protected]
UPDATE: Currently Github requires support requests to be created here: https://support.github.com/contact
You probably are going to want to use the following declaration:
height: 100%;
This will set the div's height to 100% of its containers height, which will make it fill the parent div.
In the S3 management console, click on the checkmark for the bucket, and click on the empty button from the top right.
If I understand your question correctly you want records from the settings database if they don't have a join accross to the character_settings table or if that joined record has character_id = 1.
You should therefore do
SELECT `settings`.*, `character_settings`.`value`
FROM (`settings`)
LEFT OUTER JOIN `character_settings`
ON `character_settings`.`setting_id` = `settings`.`id`
WHERE `character_settings`.`character_id` = '1' OR
`character_settings`.character_id is NULL
T-SQL
declare @thirtydaysago datetime
declare @now datetime
set @now = getdate()
set @thirtydaysago = dateadd(day,-30,@now)
select @now, @thirtydaysago
or more simply
select dateadd(day, -30, getdate())
MYSQL
SELECT DATE_ADD(NOW(), INTERVAL -30 DAY)
In the documentaion http://contactform7.com/text-fields/#textarea
[textarea* message id:contact-message 10x2 placeholder "Your Message"]
The above will generate a textarea with cols="10" and rows="2"
<textarea name="message" cols="10" rows="2" class="wpcf7-form-control wpcf7-textarea wpcf7-validates-as-required" id="contact-message" aria-required="true" aria-invalid="false" placeholder="Your Message"></textarea>
Tapestry 5 can be setup very quickly using maven archetypes. See the Tapestry 5 tutorial: http://tapestry.apache.org/tapestry5/tutorial1/
An "id" Specifies a unique id for an element & a class Specifies one or more classnames for an element . So its better to use "Class" instead of "id".
Here's a less involved trick to deal with media queries. Cross browser support is a bit limiting as it doesn't support mobile IE.
if (window.matchMedia('(max-width: 694px)').matches)
{
//do desired changes
}
See Mozilla documentation for more details.
If your string is already split into an array, you'll not need the split part.
function findLongestWord(str) {
str = str.split(' ');
var longest = 0;
for(var i = 0; i < str.length; i++) {
if(str[i].length >= longest) {
longest = str[i].length;
}
}
return longest;
}
findLongestWord("The quick brown fox jumped over the lazy dog");
Copy and paste your code line bro , it will work trust me :) i am thinking ,you get a ssl error. If you use override onReceivedSslError method and remove super it's super method. Just write handler.proceed() ,error will solve.
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
activity.setTitle("Loading...");
activity.setProgress(progress * 100);
if (progress == 100)
activity.setTitle(getResources().getString(R.string.app_name));
}
});
webView.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.d("Failure Url :" , failingUrl);
}
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
Log.d("Ssl Error:",handler.toString() + "error:" + error);
handler.proceed();
}
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setDomStorageEnabled(true);
webView.loadUrl(Constant.VIRTUALPOS_URL + "token=" + Preference.getInstance(getContext()).getToken() + "&dealer=" + Preference.getInstance(getContext()).getDealerCode());
Do not use @@fetch_status - this will return status from the last cursor in the current connection. Use the example below:
declare @sqCur cursor;
declare @data varchar(1000);
declare @i int = 0, @lastNum int, @rowNum int;
set @sqCur = cursor local static read_only for
select
row_number() over (order by(select null)) as RowNum
,Data -- you fields
from YourIntTable
open @cur
begin try
fetch last from @cur into @lastNum, @data
fetch absolute 1 from @cur into @rowNum, @data --start from the beginning and get first value
while @i < @lastNum
begin
set @i += 1
--Do your job here
print @data
fetch next from @cur into @rowNum, @data
end
end try
begin catch
close @cur --|
deallocate @cur --|-remove this 3 lines if you do not throw
;throw --|
end catch
close @cur
deallocate @cur
I tried this too, and works very well:
<%= link_to home_index_path do %>
<div class='logo-container'>
<div class='logo'>
<%= image_tag('bar.ico') %>
</div>
<div class='brand' style='font-size: large;'>
.BAR
</div>
</div>
<% end %>
If you need to organize data in columns of 1 / 2 / 4 depending of the viewport size then push and pull may be no option at all. No matter how you order your items in the first place, one of the sizes may give you a wrong order.
A solution in this case is to use nested rows and cols without any push or pull classes.
In XS you want...
A
B
C
D
E
F
G
H
In SM you want...
A E
B F
C G
D H
In MD and above you want...
A C E G
B D F H
Use nested two-column child elements in a surrounding two-column parent element:
Here is a working snippet:
<script src="https://code.jquery.com/jquery-1.12.4.min.js" type="text/javascript" ></script>_x000D_
<link href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"> _x000D_
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
_x000D_
<div class="row">_x000D_
<div class="col-sm-6">_x000D_
<div class="row">_x000D_
<div class="col-md-6"><p>A</p><p>B</p></div>_x000D_
<div class="col-md-6"><p>C</p><p>D</p></div>_x000D_
</div>_x000D_
</div>_x000D_
<div class="col-sm-6">_x000D_
<div class="row">_x000D_
<div class="col-md-6"><p>E</p><p>F</p></div>_x000D_
<div class="col-md-6"><p>G</p><p>H</p></div>_x000D_
</div>_x000D_
</div>_x000D_
</div>
_x000D_
Another beauty of this solution is, that the items appear in the code in their natural order (A, B, C, ... H) and don't have to be shuffled, which is nice for CMS generation.
You are right, it's confusing that SQL Server allows you to create duplicate indexes on the same field(s). But the fact that you can create another doesn't indicate that the PK index doesn't also already exist.
The additional index does no good, but the only harm (very small) is the additional file size and row-creation overhead.
var str = 'sample string';
[].map.call(str, function(x) {
return x;
}).reverse().join('');
OR
var str = 'sample string';
console.log(str.split('').reverse().join(''));
// Output: 'gnirts elpmas'
You can set Navigation rootviewcontroller as a main view controller. This idea can use for auto login as per application requirement.
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
UIViewController viewController = (HomeController*)[mainStoryboard instantiateViewControllerWithIdentifier: @"HomeController"];
UINavigationController navController = [[UINavigationController alloc] initWithRootViewController:viewController];
self.window.rootViewController = navController;
if (NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_6_1) {
// do stuff for iOS 7 and newer
navController.navigationBar.barTintColor = [UIColor colorWithRed:88/255.0 green:164/255.0 blue:73/255.0 alpha:1.0];
navController.navigationItem.leftBarButtonItem.tintColor = [UIColor colorWithRed:88/255.0 green:164/255.0 blue:73/255.0 alpha:1.0];
navController.navigationBar.tintColor = [UIColor whiteColor];
navController.navigationItem.titleView.tintColor = [UIColor whiteColor];
NSDictionary *titleAttributes =@{
NSFontAttributeName :[UIFont fontWithName:@"Helvetica-Bold" size:14.0],
NSForegroundColorAttributeName : [UIColor whiteColor]
};
navController.navigationBar.titleTextAttributes = titleAttributes;
[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];
}
else {
// do stuff for older versions than iOS 7
navController.navigationBar.tintColor = [UIColor colorWithRed:88/255.0 green:164/255.0 blue:73/255.0 alpha:1.0];
navController.navigationItem.titleView.tintColor = [UIColor whiteColor];
}
[self.window makeKeyAndVisible];
For StoryboardSegue Users
UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle: nil];
// Go to Login Screen of story board with Identifier name : LoginViewController_Identifier
LoginViewController *loginViewController = (LoginViewController*)[mainStoryboard instantiateViewControllerWithIdentifier:@“LoginViewController_Identifier”];
navigationController = [[UINavigationController alloc] initWithRootViewController:testViewController];
self.window.rootViewController = navigationController;
[self.window makeKeyAndVisible];
// Go To Main screen if you are already Logged In Just check your saving credential here
if([SavedpreferenceForLogin] > 0){
[loginViewController performSegueWithIdentifier:@"mainview_action" sender:nil];
}
Thanks
Try the --force
option. svn help checkout
gives the details.
I would suggest editing the /etc/default/jenkins
vi /etc/default/jenkins
And changing the $JENKINS_HOME variable (around line 23) to
JENKINS_HOME=/home/jenkins
Then restart the Jenkins with usual
/etc/init.d/jenkins start
Cheers!
I have this setup in my Ubuntu .vimrc. I don't see any swap files in my project files.
set undofile
set undolevels=1000 " How many undos
set undoreload=10000 " number of lines to save for undo
set backup " enable backups
set swapfile " enable swaps
set undodir=$HOME/.vim/tmp/undo " undo files
set backupdir=$HOME/.vim/tmp/backup " backups
set directory=$HOME/.vim/tmp/swap " swap files
" Make those folders automatically if they don't already exist.
if !isdirectory(expand(&undodir))
call mkdir(expand(&undodir), "p")
endif
if !isdirectory(expand(&backupdir))
call mkdir(expand(&backupdir), "p")
endif
if !isdirectory(expand(&directory))
call mkdir(expand(&directory), "p")
endif
I created a sample project on github to load a UIView from a .xib file inside another .xib file. Or you can do it programmatically.
This is good for little widgets you want to reuse on different UIViewController objects.
Note that the bb.array() doesn't honor the byte-buffers position, and might be even worse if the bytebuffer you are working on is a slice of some other buffer.
I.e.
byte[] test = "Hello World".getBytes("Latin1");
ByteBuffer b1 = ByteBuffer.wrap(test);
byte[] hello = new byte[6];
b1.get(hello); // "Hello "
ByteBuffer b2 = b1.slice(); // position = 0, string = "World"
byte[] tooLong = b2.array(); // Will NOT be "World", but will be "Hello World".
byte[] world = new byte[5];
b2.get(world); // world = "World"
Which might not be what you intend to do.
If you really do not want to copy the byte-array, a work-around could be to use the byte-buffer's arrayOffset() + remaining(), but this only works if the application supports index+length of the byte-buffers it needs.
A couple of issues
>
in -exec
without something like bash -c '... > ...'
. Though the >
will overwrite the file, so you want to redirect the entire find
anyway rather than each -exec
. +30
is older
than 30 days, -30
would be modified in last 30 days.-exec
really isn't needed, you could list everything with various -printf
options. Something like below should work
find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt
Example with -printf
find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt
This will list files in format "permissions owner group time date filename". -printf
is generally preferable to -exec
in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec
. Depending on the version of find
, you may also be able to use -ls
, which has a similar format to above.
If you want a fairly advanced tool to do some serious poking around, look at the Memory Analyzer project at Eclipse, contributed to them by SAP.
Some of what you can do is mind-blowingly good for finding memory leaks etc -- including running a form of limited SQL (OQL) against the in-memory objects, i.e.
SELECT toString(firstName) FROM com.yourcompany.somepackage.User
Totally brilliant.
Checkout TickTick.
It's a true Bash JSON parser.
#!/bin/bash
. /path/to/ticktick.sh
# File
DATA=`cat data.json`
# cURL
#DATA=`curl http://foobar3000.com/echo/request.json`
tickParse "$DATA"
echo ``pathname``
echo ``headers["user-agent"]``
In my case the error was probably due to an incorrect merge between .gitmodules on two branches with different submodules configurations. After taking suggestions from this forum, I solved the problem editing manually the .gitmodules file, adding the missing submodule entry is pretty easy. After that, the command git submodule update --init --recursive worked with no issues.
id
overviewAn Android id
is an integer commonly used to identify views; this id
can be assigned via XML (when possible) and via code (programmatically.) The id
is most useful for getting references for XML-defined View
s generated by an Inflater
(such as by using setContentView
.)
id
via XML
android:id="@+id/
somename"
to your view.android:id
will be assigned a unique int
for use in code.android:id
's int
value in code using "R.id.
somename" (effectively a constant.)int
can change from build to build so never copy an id from gen/
package.name/R.java
, just use "R.id.
somename".id
assigned to a Preference
in XML is not used when the Preference
generates its View
.)id
via code (programmatically)id
s using someView.setId(
int);
int
must be positive, but is otherwise arbitrary- it can be whatever you want (keep reading if this is frightful.)id
sXML
-assigned id
s will be unique.id
s do not have to be uniqueid
s can (theoretically) conflict with XML
-assigned id
s.id
s won't matter if queried correctly (keep reading).id
s don't matterfindViewById(int)
will iterate depth-first recursively through the view hierarchy from the View you specify and return the first View
it finds with a matching id
.id
s assigned before an XML-defined id
in the hierarchy, findViewById(R.id.somename)
will always return the XML-defined View so id
'd.ID
sViewGroup
with id
.LinearLayout
with android:id="@+id/placeholder"
.ViewGroup
with View
s.id
s that are convenient to each view.Query these child views using placeholder.findViewById(convenientInt);
API 17 introduced View.generateViewId()
which allows you to generate a unique ID.
If you choose to keep references to your views around, be sure to instantiate them with getApplicationContext()
and be sure to set each reference to null in onDestroy
. Apparently leaking the Activity
(hanging onto it after is is destroyed) is wasteful.. :)
android:id
for use in codeAPI 17 introduced View.generateViewId()
which generates a unique ID. (Thanks to take-chances-make-changes for pointing this out.)*
If your ViewGroup
cannot be defined via XML (or you don't want it to be) you can reserve the id via XML to ensure it remains unique:
Here, values/ids.xml defines a custom id
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="reservedNamedId" type="id"/>
</resources>
Then once the ViewGroup or View has been created, you can attach the custom id
myViewGroup.setId(R.id.reservedNamedId);
id
exampleFor clarity by way of obfuscating example, lets examine what happens when there is an id
conflict behind the scenes.
layout/mylayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/placeholder"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
To simulate a conflict, lets say our latest build assigned R.id.placeholder
(@+id/placeholder
) an int
value of 12
..
Next, MyActivity.java defines some adds views programmatically (via code):
int placeholderId = R.id.placeholder; // placeholderId==12
// returns *placeholder* which has id==12:
ViewGroup placeholder = (ViewGroup)this.findViewById(placeholderId);
for (int i=0; i<20; i++){
TextView tv = new TextView(this.getApplicationContext());
// One new TextView will also be assigned an id==12:
tv.setId(i);
placeholder.addView(tv);
}
So placeholder
and one of our new TextView
s both have an id
of 12! But this isn't really a problem if we query placeholder's child views:
// Will return a generated TextView:
placeholder.findViewById(12);
// Whereas this will return the ViewGroup *placeholder*;
// as long as its R.id remains 12:
Activity.this.findViewById(12);
*Not so bad
You want a .jardesc
file. They do not kick off automatically, but it's within 2 clicks.
Export > Java > JAR file
Next
.jardesc
fileNow, all you have to do is right click on your .jardesc
file and choose Create JAR
and it will export it in the same spot.
Your feature branch is done and ready to commit to master, develop or other target branch with only one commit
Replace master with your target branch : develop and so on
You can convert yourInt
to bytes by using a ByteBuffer
like this:
return ByteBuffer.allocate(4).putInt(yourInt).array();
Beware that you might have to think about the byte order when doing so.
In case you need short unique IDs as your filename, try shortuuid
, shortuuid uses lowercase and uppercase letters and digits, and removing similar-looking characters such as l, 1, I, O and 0.
>>> import shortuuid
>>> shortuuid.uuid()
'Tw8VgM47kSS5iX2m8NExNa'
>>> len(ui)
22
compared to
>>> import uuid
>>> unique_filename = str(uuid.uuid4())
>>> len(unique_filename)
36
>>> unique_filename
'2d303ad1-79a1-4c1a-81f3-beea761b5fdf'
Try this code it works:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim CustomeDate As String = ("#" & DOE.Value.Date.ToString("d/MM/yyyy") & "#")
MsgBox(CustomeDate.ToString)
con.Open()
dadap = New System.Data.OleDb.OleDbDataAdapter("SELECT * FROM QRY_Tran where FORMAT(qry_tran.doe,'d/mm/yyyy') = " & CustomeDate & "", con)
ds = New System.Data.DataSet
dadap.Fill(ds)
Dgview.DataSource = ds.Tables(0)
con.Close()
Note : if u use dd
for date representation it will return nothing while selecting 1 to 9 so use d
for selection
'Date time format
'MMM Three-letter month.
'ddd Three-letter day of the week.
'd Day of the month.
'HH Two-digit hours on 24-hour scale.
'mm Two-digit minutes.
'yyyy Four-digit year.
The documentation contains a full list of the date formats.
ABCpdf.NET (http://www.websupergoo.com/abcpdf-5.htm)
We use and recommend.
Very good component, it not only convert a webpage to PDF like an image but really convert text, image, formatting, etc...
It's not free but it's cheap.
If you want to find the button only by its class name and using jQLite only, you can do like below:
var myListButton = $document.find('button').filter(function() {
return angular.element(this).hasClass('multi-files');
});
Hope this helps. :)
The DragListView lib does this really neat with very nice support for custom animations such as elevation animations. It is also still maintained and updated on a regular basis.
Here is how you use it:
1: Add the lib to gradle first
dependencies {
compile 'com.github.woxthebox:draglistview:1.2.1'
}
2: Add list from xml
<com.woxthebox.draglistview.DragListView
android:id="@+id/draglistview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
3: Set the drag listener
mDragListView.setDragListListener(new DragListView.DragListListener() {
@Override
public void onItemDragStarted(int position) {
}
@Override
public void onItemDragEnded(int fromPosition, int toPosition) {
}
});
4: Create an adapter overridden from DragItemAdapter
public class ItemAdapter extends DragItemAdapter<Pair<Long, String>, ItemAdapter.ViewHolder>
public ItemAdapter(ArrayList<Pair<Long, String>> list, int layoutId, int grabHandleId, boolean dragOnLongPress) {
super(dragOnLongPress);
mLayoutId = layoutId;
mGrabHandleId = grabHandleId;
setHasStableIds(true);
setItemList(list);
}
5: Implement a viewholder that extends from DragItemAdapter.ViewHolder
public class ViewHolder extends DragItemAdapter.ViewHolder {
public TextView mText;
public ViewHolder(final View itemView) {
super(itemView, mGrabHandleId);
mText = (TextView) itemView.findViewById(R.id.text);
}
@Override
public void onItemClicked(View view) {
}
@Override
public boolean onItemLongClicked(View view) {
return true;
}
}
For more detailed info go to https://github.com/woxblom/DragListView
I just removed all the private libraries in JavaBuildPath and added the jars again.. It worked
If you have a text as
var sampleText ="ä_öü_ßÄ_ TESTED Ö_Ü!@#$%^&())(&&++===.XYZ"
To replace all special character (!@#$%^&())(&&++= ==.) without replacing the characters(including umlaut)
Use below regex
sampleText = sampleText.replace(/[`~!@#$%^&*()|+-=?;:'",.<>{}[]\/\s]/gi,'');
OUTPUT : sampleText = "ä_öü_ßÄ____TESTED_Ö_Ü_____________________XYZ"
This would replace all with an underscore which is provided as second argument to the replace function.You can add whatever you want as per your requirement
Strings are iterable (just like a list).
I'm interpreting that you really want something like:
fd = open(filename,'rU')
chars = []
for line in fd:
for c in line:
chars.append(c)
or
fd = open(filename, 'rU')
chars = []
for line in fd:
chars.extend(line)
or
chars = []
with open(filename, 'rU') as fd:
map(chars.extend, fd)
chars would contain all of the characters in the file.
While working in a big project which has complex build system and where it is hard to get (or modify) the gcc/g++ command directly there is another way to see the result of macro expansion. Simply redefine the macro, and you will get output similiar to following:
file.h: note: this is the location of the previous definition
#define MACRO current_value
Earlier mentioned solution with PHP version check added:
$max_includes = version_compare(PHP_VERSION, '5', '<') ? 0 : 1;
if (count(get_included_files()) <= $max_includes)
{
exit('Direct access is not allowed.');
}
Using swing you could simply use a JLabel
public static void main(String[] args) throws MalformedURLException {
URL url = new URL("<URL to your Animated GIF>");
Icon icon = new ImageIcon(url);
JLabel label = new JLabel(icon);
JFrame f = new JFrame("Animation");
f.getContentPane().add(label);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setLocationRelativeTo(null);
f.setVisible(true);
}
You can use the for command:
FOR /F "eol=; tokens=2,3* delims=, " %i in (myfile.txt) do @echo %i %j %k
Type
for /?
at the command prompt. Also, you can parse ini files!
Here's a one liner for bash scripts to get a list of weekdays, this is python 3. Easily modified for whatever, the int at the end is the number of days in the past you want.
python -c "import sys,datetime; print('\n'.join([(datetime.datetime.today() - datetime.timedelta(days=x)).strftime(\"%Y/%m/%d\") for x in range(0,int(sys.argv[1])) if (datetime.datetime.today() - datetime.timedelta(days=x)).isoweekday()<6]))" 10
Here is a variant to provide a start (or rather, end) date
python -c "import sys,datetime; print('\n'.join([(datetime.datetime.strptime(sys.argv[1],\"%Y/%m/%d\") - datetime.timedelta(days=x)).strftime(\"%Y/%m/%d \") for x in range(0,int(sys.argv[2])) if (datetime.datetime.today() - datetime.timedelta(days=x)).isoweekday()<6]))" 2015/12/30 10
Here is a variant for arbitrary start and end dates. not that this isn't terribly efficient, but is good for putting in a for loop in a bash script:
python -c "import sys,datetime; print('\n'.join([(datetime.datetime.strptime(sys.argv[1],\"%Y/%m/%d\") + datetime.timedelta(days=x)).strftime(\"%Y/%m/%d\") for x in range(0,int((datetime.datetime.strptime(sys.argv[2], \"%Y/%m/%d\") - datetime.datetime.strptime(sys.argv[1], \"%Y/%m/%d\")).days)) if (datetime.datetime.strptime(sys.argv[1], \"%Y/%m/%d\") + datetime.timedelta(days=x)).isoweekday()<6]))" 2015/12/15 2015/12/30
There is a builtin mixin: transparentize($color, $amount);
background-color: transparentize(#F05353, .3);
The amount should be between 0 to 1;
Official Sass Documentation (Module: Sass::Script::Functions)
If you just want the first number to match you can do it like this:
[item for item in a if item[0] == 1]
If you are just searching for tuples with 1 in them:
[item for item in a if 1 in item]
The following resolved the problem for me:
Go to Control Panel -> Network and Internet -> change adapter settings
Right click on VirtualBox Host-Only Network and select properties
The following options must be ticked
If see another program select and uninstall it.
In VirtualBox go to File -> Preferences -> Network
Double click on VirtualBox Host-Only ethernet adapter
Edit like this:
IPV4 address: 192.168.56.1
mask: 255.255.255.0
DHCP: address 192.168.56.100
mask: 255.255.255.0
low bounds: 192.168.56.101
high bound: 192.168.56.254
Restart or log off your windows and start genymotion
If that didn't solve your problem in VirtualBox go to File -> Preferences -> Network and delete Host-Only ethernet adapter.
If you care about getting coordinates based on an ellipsoid rather than a sphere, take a look at Geographic_coordinate_conversion - it gives the formulae. GEodetic Datum has the WGS84 constants you need for the conversion.
The formulae there also take into account the altitude relative to the reference ellipsoid surface (useful if you are getting altitude data from a GPS device).
Just complementing: It's kind of obvious, but you can use static imports to give you a hand, like this:
import static javax.swing.JOptionPane.*;
public class SimpleDialog(){
public static void main(String argv[]) {
showMessageDialog(null, "Message", "Title", ERROR_MESSAGE);
}
}
I fear this might turn out to BE the long way round but could depend on how big your data set is – presumably more than four months for example.
Assuming your data is in ColumnA:C
and has column labels in Row 1, also that Month is formatted mmm
(this last for ease of sorting):
D2
=IF(AND(A2=A1,C2=C1),D1+1,1)
(One way to deal with what is the tricky issue of multiple entries for the same person for the same month).A1:D(last occupied row no.)
F1
.I’m hoping this would be adequate for your needs because pivot table should automatically update (provided range is appropriate) in response to additional data with refresh. If not (you hard taskmaster), continue but beware that the following steps would need to be repeated each time the source data changes.
L1
.L1
and shift down.L1
.ColumnL
, select Row Labels
and numeric values.L2:L(last selected cell)
Happy to explain further/try again (I've not really tested this) if does not suit.
EDIT (To avoid second block of steps above and facilitate updating for source data changes)
.0. Before first step 2. add a blank row at the very top and move A2:D2
up.
.2. Adjust cell references accordingly (in D3
=IF(AND(A3=A2,C3=C2),D2+1,1)
.
.3. Create pivot table from A:D
.6. Overwrite Row Labels
with Name
.
.7. PivotTable Tools, Design, Report Layout, Show in Tabular Form and sort rows and columns A>Z.
.8. Hide Row1
, ColumnG
and rows and columns that show (blank)
.
Steps .0. and .2. in the edit are not required if the pivot table is in a different sheet from the source data (recommended).
Step .3. in the edit is a change to simplify the consequences of expanding the source data set. However introduces (blank)
into pivot table that if to be hidden may need adjustment on refresh. So may be better to adjust source data range each time that changes instead: PivotTable Tools, Options, Change Data Source, Change Data Source, Select a table or range). In which case copy rather than move in .0.
Default.sublime-theme file works unless you have installed a theme. If you did, go to your theme's github repo and download the your_theme.sublime-theme file and put it in your 'User' folder.
In that file, find "class": "sidebar_label",
add "font.size":16
to that section.
The smallest piece of code would be:
public List<Integer> myWork(int[] array) {
return Arrays.asList(ArrayUtils.toObject(array));
}
where ArrayUtils comes from commons-lang :)
Create an array to store the objects:
ArrayList<MyObject> list = new ArrayList<MyObject>();
In a single step:
list.add(new MyObject (1, 2, 3)); //Create a new object and adding it to list.
or
MyObject myObject = new MyObject (1, 2, 3); //Create a new object.
list.add(myObject); // Adding it to the list.
It is all about the right tool for the job. Neither is better 100% of the time. Both systems were created by man and have flaws. Sorry, but we suck and making perfect stuff.
I like dynamic typing because it gets out of my way, but yes runtime errors can creep up that I didn't plan for. Where as static typing may fix the aforementioned errors, but drive a novice(in typed languages) programmer crazy trying to cast between a constant char and a string.
Both C# and Java don't have plain functions only member functions (aka methods). And the methods are not first-class citizens. First-class functions allow us to create beautiful and powerful code, as seen in F# or Clojure languages. (For instance, first-class functions can be passed as parameters and can return functions.) Java and C# ameliorate this somewhat with interfaces/delegates.
Func<int, int, int> randInt = (n1, n2) => new Random().Next(n1, n2);
So, Func
is a built-in delegate which brings some functional programming features and helps reduce code verbosity.
Random Samples and Permutations ina dataframe If it is in matrix form convert into data.frame use the sample function from the base package indexes = sample(1:nrow(df1), size=1*nrow(df1)) Random Samples and Permutations
A slave isn't a server, it's a client type application. Network clients (almost) never use a specific port. Instead, they ask the OS for a random free port. This works much better since you usually run clients on many machines where the current configuration isn't known in advance. This prevents thousands of "client wouldn't start because port is already in use" bug reports every day.
You need to tell the security department that the slave isn't a server but a client which connects to the server and you absolutely need to have a rule which says client:ANY -> server:FIXED. The client port number should be >= 1024 (ports 1 to 1023 need special permissions) but I'm not sure if you actually gain anything by adding a rule for this - if an attacker can open privileged ports, they basically already own the machine.
If they argue, then ask them why they don't require the same rule for all the web browsers which people use in your company.
There are a lot of answers already but just want to share with you what I came up with :) Can't say this solution counts on any edge case but anyway )
const getMostFrequentElement = ( arr ) => {
const counterSymbolKey = 'counter'
const mostFrequentSymbolKey = 'mostFrequentKey'
const result = arr.reduce( ( acc, cur ) => {
acc[ cur ] = acc[ cur ] ? acc[ cur ] + 1 : 1
if ( acc[ cur ] > acc[ Symbol.for( counterSymbolKey ) ] ) {
acc[ Symbol.for( mostFrequentSymbolKey ) ] = cur
acc[ Symbol.for( counterSymbolKey ) ] = acc[ cur ]
}
return acc
}, {
[ Symbol.for( mostFrequentSymbolKey ) ]: null,
[ Symbol.for( counterSymbolKey ) ]: 0
} )
return result[ Symbol.for( mostFrequentSymbolKey ) ]
}
Hope it will be helpful for someone )
I think you should call the super.draw()
method first before you do anything in surfaceView's draw method.
If you have the numpy
package:
In [16]: x = [1,2,3,4]
...: import numpy
...: numpy.average(x)
Out[16]: 2.5
Here's a very compact, but entirely correct version:
do while(isspace(*s)) s++; while(*d++ = *s++);
And here, just for my amusement, are code-golfed versions that aren't entirely correct, and get commenters upset.
If you can risk some undefined behavior, and never have empty strings, you can get rid of the body:
while(*(d+=!isspace(*s++)) = *s);
Heck, if by space you mean just space character:
while(*(d+=*s++!=' ')=*s);
Don't use that in production :)
-H/--header <header>
(HTTP) Extra header to use when getting a web page. You may specify
any number of extra headers. Note that if you should add a custom
header that has the same name as one of the internal ones curl would
use, your externally set header will be used instead of the internal
one. This allows you to make even trickier stuff than curl would
normally do. You should not replace internally set headers without
knowing perfectly well what you're doing. Remove an internal header
by giving a replacement without content on the right side of the
colon, as in: -H "Host:".
curl will make sure that each header you add/replace get sent with
the proper end of line marker, you should thus not add that as a
part of the header content: do not add newlines or carriage returns
they will only mess things up for you.
See also the -A/--user-agent and -e/--referer options.
This option can be used multiple times to add/replace/remove multi-
ple headers.
curl --header "X-MyHeader: 123" www.google.com
You can see the request that curl sent by adding the -v
option.
If you truly want to discard the commits you've made locally, i.e. never have them in the history again, you're not asking how to pull - pull means merge, and you don't need to merge. All you need do is this:
# fetch from the default remote, origin
git fetch
# reset your current branch (master) to origin's master
git reset --hard origin/master
I'd personally recommend creating a backup branch at your current HEAD first, so that if you realize this was a bad idea, you haven't lost track of it.
If on the other hand, you want to keep those commits and make it look as though you merged with origin, and cause the merge to keep the versions from origin only, you can use the ours
merge strategy:
# fetch from the default remote, origin
git fetch
# create a branch at your current master
git branch old-master
# reset to origin's master
git reset --hard origin/master
# merge your old master, keeping "our" (origin/master's) content
git merge -s ours old-master
The number 0
in {0:X}
refers to the position in the list or arguments. In this case 0
means use the first value, which is Blue
. Use {1:X}
for the second argument (Green
), and so on.
colorstring = String.Format("#{0:X}{1:X}{2:X}{3:X}", Blue, Green, Red, Space);
The syntax for the format parameter is described in the documentation:
Format Item Syntax
Each format item takes the following form and consists of the following components:
{ index[,alignment][:formatString]}
The matching braces ("{" and "}") are required.
Index Component
The mandatory index component, also called a parameter specifier, is a number starting from 0 that identifies a corresponding item in the list of objects. That is, the format item whose parameter specifier is 0 formats the first object in the list, the format item whose parameter specifier is 1 formats the second object in the list, and so on.
Multiple format items can refer to the same element in the list of objects by specifying the same parameter specifier. For example, you can format the same numeric value in hexadecimal, scientific, and number format by specifying a composite format string like this: "{0:X} {0:E} {0:N}".
Each format item can refer to any object in the list. For example, if there are three objects, you can format the second, first, and third object by specifying a composite format string like this: "{1} {0} {2}". An object that is not referenced by a format item is ignored. A runtime exception results if a parameter specifier designates an item outside the bounds of the list of objects.
Alignment Component
The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.
Format String Component
The optional formatString component is a format string that is appropriate for the type of object being formatted. Specify a standard or custom numeric format string if the corresponding object is a numeric value, a standard or custom date and time format string if the corresponding object is a DateTime object, or an enumeration format string if the corresponding object is an enumeration value. If formatString is not specified, the general ("G") format specifier for a numeric, date and time, or enumeration type is used. The colon is required if formatString is specified.
Note that in your case you only have the index and the format string. You have not specified (and do not need) an alignment component.
I think you can get away by just installing the OLEDB Drivers - http://www.microsoft.com/en-us/download/details.aspx?id=13255
I think this is what you want...
Sub SaveWorksheetsAsCsv()
Dim WS As Excel.Worksheet
Dim SaveToDirectory As String
Dim CurrentWorkbook As String
Dim CurrentFormat As Long
CurrentWorkbook = ThisWorkbook.FullName
CurrentFormat = ThisWorkbook.FileFormat
' Store current details for the workbook
SaveToDirectory = "H:\test\"
For Each WS In Application.ActiveWorkbook.Worksheets
WS.SaveAs SaveToDirectory & WS.Name, xlCSV
Next
Application.DisplayAlerts = False
ThisWorkbook.SaveAs Filename:=CurrentWorkbook, FileFormat:=CurrentFormat
Application.DisplayAlerts = True
' Temporarily turn alerts off to prevent the user being prompted
' about overwriting the original file.
End Sub
I am assuming you want to do something programatically.
You might consider, using getenv to pull the value out of the ORACLE_HOME environmental variable. Assuming you are talking C or C++ or Pro*C.
well you can always create your textviews etc dynamically and set your onclicklisteners like you would do with an adapter
Adding on, you can turn off the creation of vshost files for your Release build configuration and have it enabled for Debug.
Steps
Reference
Excerpt from MSDN How to: Disable the Hosting Process
Calls to certain APIs can be affected when the hosting process is enabled. In these cases, it is necessary to disable the hosting process to return the correct results.
To disable the hosting process
When the hosting process is disabled, several debugging features are unavailable or experience decreased performance. For more information, see Debugging and the Hosting Process.
In general, when the hosting process is disabled:
- The time needed to begin debugging .NET Framework applications increases.
- Design-time expression evaluation is unavailable.
- Partial trust debugging is unavailable.
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
$("#content").attr("src","http://vnexpress.net");
})
</script>
</head>
<body>
<iframe id="content"></div>
</body>
</html>
Add tabe row using JQuery:
if you want to add row after last of table's row child, you can try this
$('#myTable tr:last').after('<tr>...</tr><tr>...</tr>');
if you want to add row 1st of table's row child, you can try this
$('#myTable tr').after('<tr>...</tr><tr>...</tr>');
just go to the window bottom tray click on wamp icon ,click mysql->my.ini,then there is option ;sql-mode="" uncomment this make it like sql-mode="" and restart wamp worked for me
I used Ctrl+Shift+F. Next, put a \n
in the search box and enable regular expressions box. Then in the find results, in the end of the screen are the number of files searched and lines of code found.
You can use [^\n\s]\r\n
to skip blank and space-only lines (credits to Zach in the comments).
I've personally never seen .cc
in any project that I've worked on, but in all technicality the compiler won't care.
Who will care is the developers working on your source, so my rule of thumb is to go with what your team is comfortable with. If your "team" is the open source community, go with something very common, of which .cpp
seems to be the favourite.
I use setdefault()
when I want a default value in an OrderedDict
. There isn't a standard Python collection that does both, but there are ways to implement such a collection.
You need to do encode
on tmp[0]
, not on tmp
.
tmp
is not a string. It contains a (Unicode) string.
Try running type(tmp)
and print dir(tmp)
to see it for yourself.
Since you cannot set value=""
within your first option
, you'll need to create your own rule using the built-in addMethod()
method.
jQuery:
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
year: {
selectcheck: true
}
}
});
jQuery.validator.addMethod('selectcheck', function (value) {
return (value != '0');
}, "year required");
});
HTML:
<select name="year">
<option value="0">Year</option>
<option value="1">1955</option>
<option value="2">1956</option>
</select>
Working Demo: http://jsfiddle.net/tPRNd/
Original Answer: (Only if you can set value=""
within the first option
)
To properly validate a select
element with the jQuery Validate plugin simply requires that the first option
contains value=""
. So remove the 0
from value="0"
and it's fixed.
jQuery:
$(document).ready(function () {
$('#myform').validate({ // initialize the plugin
rules: {
year: {
required: true,
}
}
});
});
HTML:
<select name="year">
<option value="">Year</option>
<option value="1">1955</option>
<option value="2">1956</option>
</select>
For a different approach, I would suggest using the XeTeX or LuaTex system. They allow you to access system fonts (TrueType, OpenType, etc) and set font features. In a typical LaTeX document, you just need to include this in your headers:
\usepackage{fontspec}
\defaultfontfeatures{Mapping=tex-text,Scale=MatchLowercase}
\setmainfont{Times}
\setmonofont{Lucida Sans Typewriter}
It's the fontspec
package that allows for \setmainfont
and \setmonofont
. The ability to choose a multitude of font features is beyond my expertise, but I would suggest looking up some examples and seeing if this would suit your needs.
Just don't forget to replace your favorite latex compiler by the appropriate one (xelatex or lualatex).
This is one of the method to overcome this issue.
client.cpp
#ifndef SOCKET_CLIENT_CLASS
#define SOCKET_CLIENT_CLASS
#ifndef BOOST_ASIO_HPP
#include <boost/asio.hpp>
#endif
class SocketClient // Or whatever the name is... {
// ...
bool read(int, char*); // Or whatever the name is...
// ... };
#endif
client.h
bool SocketClient::read(int, char*)
{
// Implementation goes here...
}
main.cpp
#include <iostream>
#include <string>
#include <sstream>
#include <boost/asio.hpp>
#include <boost/thread/thread.hpp>
#include "client.h"
// ^^ Notice this!
main.h
int main()
You need to add a metadata exchange (mex) endpoint to your service:
<services>
<service name="MyService.MyService" behaviorConfiguration="metadataBehavior">
<endpoint
address="http://localhost/MyService.svc"
binding="customBinding" bindingConfiguration="jsonpBinding"
behaviorConfiguration="MyService.MyService"
contract="MyService.IMyService"/>
<endpoint
address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange"/>
</service>
</services>
Now, you should be able to get metadata for your service
Update: ok, so you're just launching this from Visual Studio - in that case, it will be hosted in Cassini, the built-in web server. That beast however only supports HTTP - you're not using that protocol in your binding...
Also, since you're hosting this in Cassini, the address of your service will be dictated by Cassini - you don't get to define anything.
So my suggestion would be:
So I would change the config to:
<behaviors>
<serviceBehaviors>
<behavior name="metadataBehavior">
<serviceMetadata httpGetEnabled="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<services>
<service name="MyService.MyService" behaviorConfiguration="metadataBehavior">
<endpoint
address="" <!-- don't put anything here - Cassini will determine address -->
binding="basicHttpBinding"
contract="MyService.IMyService"/>
<endpoint
address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange"/>
</service>
</services>
Once you have that, try to do a View in Browser
on your SVC file in your Visual Studio solution - if that doesn't work, you still have a major problem of some sort.
If it works - now you can press F5 in VS and your service should come up, and using the WCF Test Client app, you should be able to get your service metadata from a) the address that Cassini started your service on, or b) the mex address (Cassini's address + /mex
)
Use functools.partial, not lambdas! And ofc Perform is a useless function, you can pass around functions directly.
for func in [Action1, partial(Action2, p), partial(Action3, p, r)]:
func()
Complementary at @Radu answer, As in SQL, you can add the table name in the parameter if you have many table with the same attribute.
.order_by("TableName.name desc")
An example, available for POSIX compliant systems :
/*
* This program displays the names of all files in the current directory.
*/
#include <dirent.h>
#include <stdio.h>
int main(void) {
DIR *d;
struct dirent *dir;
d = opendir(".");
if (d) {
while ((dir = readdir(d)) != NULL) {
printf("%s\n", dir->d_name);
}
closedir(d);
}
return(0);
}
Beware that such an operation is platform dependant in C.
Source : http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1046380353&id=1044780608
To add to Daniel G's solution:
from datetime import date
class FakeDate(date):
"A manipulable date replacement"
def __new__(cls, *args, **kwargs):
return date.__new__(date, *args, **kwargs)
This creates a class which, when instantiated, will return a normal datetime.date object, but which is also able to be changed.
@mock.patch('datetime.date', FakeDate)
def test():
from datetime import date
FakeDate.today = classmethod(lambda cls: date(2010, 1, 1))
return date.today()
test() # datetime.date(2010, 1, 1)
You can simply read each line from the file and assign it to an array.
#!/bin/bash
i=0
while read line
do
arr[$i]="$line"
i=$((i+1))
done < file.txt
There is a lot of ways to achieve this. In regards to the way you are asking, with a hidden form element.
create this form element inside your form:
<input type="hidden" name="total" value="">
So your form like this:
<form id="sampleForm" name="sampleForm" method="post" action="phpscript.php">
<input type="hidden" name="total" id="total" value="">
<a href="#" onclick="setValue();">Click to submit</a>
</form>
Then your javascript something like this:
<script>
function setValue(){
document.sampleForm.total.value = 100;
document.forms["sampleForm"].submit();
}
</script>
Use an control flow library like after
after.map(array, function (value, done) {
// do something async
setTimeout(function () {
// do something with the value
done(null, value * 2)
}, 10)
}, function (err, mappedArray) {
// all done, continue here
console.log(mappedArray)
})
CXXFLAGS = -O3 -o prog -rdynamic -D_GNU_SOURCE -L./libmine
LIBS = libmine.a -lpthread
See jsocket. Haven't used it myself. Been more than 3 years since last update (as of 26/6/2014).
* Uses flash :(
From the documentation:
<script type='text/javascript'>
// Host we are connecting to
var host = 'localhost';
// Port we are connecting on
var port = 3000;
var socket = new jSocket();
// When the socket is added the to document
socket.onReady = function(){
socket.connect(host, port);
}
// Connection attempt finished
socket.onConnect = function(success, msg){
if(success){
// Send something to the socket
socket.write('Hello world');
}else{
alert('Connection to the server could not be estabilished: ' + msg);
}
}
socket.onData = function(data){
alert('Received from socket: '+data);
}
// Setup our socket in the div with the id="socket"
socket.setup('mySocket');
</script>
Just do
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("document.getElementById('id').value='1988-01-01'");
As of mid-December 2019, the CSS4 min/max-function is exactly what you want:
(tread with care, this is very new, older browsers (aka IE & msEdge) don't support it just yet)
(supported as of Chromium 79 & Firefox v75)
https://developer.mozilla.org/en-US/docs/Web/CSS/min
https://developer.mozilla.org/en-US/docs/Web/CSS/max
Example:
blockquote {
font-size: max(1em, 12px);
}
That way the font-size will be 1em (if 1em > 12px), but at least 12px.
Unfortunatly this awesome CSS3 feature isn't supported by any browsers yet, but I hope this will change soon!
Edit:
This used to be part of CSS3, but was then re-scheduled for CSS4.
As per December 11th 2019, support arrived in Chrome/Chromium 79 (including on Android, and in Android WebView), and as such also in Microsoft Chredge aka Anaheim including Opera 66 and Safari 11.1 (incl. iOS)
I have got kept a handy helper method to take care of this based on one answer posted above:
Imports:
import com.google.i18n.phonenumbers.NumberParseException
import com.google.i18n.phonenumbers.PhoneNumberUtil
Function:
fun parseCountryCode( phoneNumberStr: String?): String {
val phoneUtil = PhoneNumberUtil.getInstance()
return try {
// phone must begin with '+'
val numberProto = phoneUtil.parse(phoneNumberStr, "")
numberProto.countryCode.toString()
} catch (e: NumberParseException) {
""
}
}
I had the exact same problem.
The reason - bad IIS config file.
Try deleting the automatically-created IISExpress
folder, which is usually located at %userprofile%/Documents
, e.g. C:\Users\[you]\Documents\IISExpress
.
Don't worry, VS should create it again - correctly, this time - once you run your solution again.
EDIT: Command line for deleting the folder:
rmdir /s /q "%userprofile%\Documents\IISExpress"
namespace MySingleton {
interface IMySingleton {
doSomething(): void;
}
class MySingleton implements IMySingleton {
private usePrivate() { }
doSomething() {
this.usePrivate();
}
}
export var Instance: IMySingleton = new MySingleton();
}
This way we can apply an interface, unlike in Ryan Cavanaugh's accepted answer.
For basic data retrieval I would be going for Linq without hesitation.
Since moving to Linq I've found the following advantages:
Example URL: /rest/{keyword}
This URL is an example for path parameters. We can get this URL data by using @PathParam
.
Example URL: /rest?keyword=java&limit=10
This URL is an example for query parameters. We can get this URL data by using @Queryparam
.
You can catch it like any other exception:
try {
foo();
}
catch (const std::bad_alloc&) {
return -1;
}
Quite what you can usefully do from this point is up to you, but it's definitely feasible technically.
In general you cannot, and should not try, to respond to this error. bad_alloc
indicates that a resource cannot be allocated because not enough memory is available. In most scenarios your program cannot hope to cope with that, and terminating soon is the only meaningful behaviour.
Worse, modern operating systems often over-allocate: on such systems, malloc
and new
can return a valid pointer even if there is not enough free memory left – std::bad_alloc
will never be thrown, or is at least not a reliable sign of memory exhaustion. Instead, attempts to access the allocated memory will then result in a segmentation fault, which is not catchable (you can handle the segmentation fault signal, but you cannot resume the program afterwards).
The only thing you could do when catching std::bad_alloc
is to perhaps log the error, and try to ensure a safe program termination by freeing outstanding resources (but this is done automatically in the normal course of stack unwinding after the error gets thrown if the program uses RAII appropriately).
In certain cases, the program may attempt to free some memory and try again, or use secondary memory (= disk) instead of RAM but these opportunities only exist in very specific scenarios with strict conditions:
It’s exceedingly rare that applications have control over point 1 — userspace applications never do, it’s a system-wide setting that requires root permissions to change.1
OK, so let’s assume you’ve fixed point 1. What you can now do is for instance use a LRU cache for some of your data (probably some particularly large business objects that can be regenerated or reloaded on demand). Next, you need to put the actual logic that may fail into a function that supports retry — in other words, if it gets aborted, you can just relaunch it:
lru_cache<widget> widget_cache;
double perform_operation(int widget_id) {
std::optional<widget> maybe_widget = widget_cache.find_by_id(widget_id);
if (not maybe_widget) {
maybe_widget = widget_cache.store(widget_id, load_widget_from_disk(widget_id));
}
return maybe_widget->frobnicate();
}
…
for (int num_attempts = 0; num_attempts < MAX_NUM_ATTEMPTS; ++num_attempts) {
try {
return perform_operation(widget_id);
} catch (std::bad_alloc const&) {
if (widget_cache.empty()) throw; // memory error elsewhere.
widget_cache.remove_oldest();
}
}
// Handle too many failed attempts here.
But even here, using std::set_new_handler
instead of handling std::bad_alloc
provides the same benefit and would be much simpler.
1 If you’re creating an application that does control point 1, and you’re reading this answer, please shoot me an email, I’m genuinely curious about your circumstances.
new
in c++?The usual notion is that if new
operator cannot allocate dynamic memory of the requested size, then it should throw an exception of type std::bad_alloc
.
However, something more happens even before a bad_alloc
exception is thrown:
C++03 Section 3.7.4.1.3: says
An allocation function that fails to allocate storage can invoke the currently installed new_handler(18.4.2.2), if any. [Note: A program-supplied allocation function can obtain the address of the currently installed new_handler using the set_new_handler function (18.4.2.3).] If an allocation function declared with an empty exception-specification (15.4), throw(), fails to allocate storage, it shall return a null pointer. Any other allocation function that fails to allocate storage shall only indicate failure by throw-ing an exception of class std::bad_alloc (18.4.2.1) or a class derived from std::bad_alloc.
Consider the following code sample:
#include <iostream>
#include <cstdlib>
// function to call if operator new can't allocate enough memory or error arises
void outOfMemHandler()
{
std::cerr << "Unable to satisfy request for memory\n";
std::abort();
}
int main()
{
//set the new_handler
std::set_new_handler(outOfMemHandler);
//Request huge memory size, that will cause ::operator new to fail
int *pBigDataArray = new int[100000000L];
return 0;
}
In the above example, operator new
(most likely) will be unable to allocate space for 100,000,000 integers, and the function outOfMemHandler()
will be called, and the program will abort after issuing an error message.
As seen here the default behavior of new
operator when unable to fulfill a memory request, is to call the new-handler
function repeatedly until it can find enough memory or there is no more new handlers. In the above example, unless we call std::abort()
, outOfMemHandler()
would be called repeatedly. Therefore, the handler should either ensure that the next allocation succeeds, or register another handler, or register no handler, or not return (i.e. terminate the program). If there is no new handler and the allocation fails, the operator will throw an exception.
new_handler
and set_new_handler
?new_handler
is a typedef for a pointer to a function that takes and returns nothing, and set_new_handler
is a function that takes and returns a new_handler
.
Something like:
typedef void (*new_handler)();
new_handler set_new_handler(new_handler p) throw();
set_new_handler's parameter is a pointer to the function operator new
should call if it can't allocate the requested memory. Its return value is a pointer to the previously registered handler function, or null if there was no previous handler.
Given the behavior of new
a well designed user program should handle out of memory conditions by providing a proper new_handler
which does one of the following:
Make more memory available: This may allow the next memory allocation attempt inside operator new's loop to succeed. One way to implement this is to allocate a large block of memory at program start-up, then release it for use in the program the first time the new-handler is invoked.
Install a different new-handler: If the current new-handler can't make any more memory available, and of there is another new-handler that can, then the current new-handler can install the other new-handler in its place (by calling set_new_handler
). The next time operator new calls the new-handler function, it will get the one most recently installed.
(A variation on this theme is for a new-handler to modify its own behavior, so the next time it's invoked, it does something different. One way to achieve this is to have the new-handler modify static, namespace-specific, or global data that affects the new-handler's behavior.)
Uninstall the new-handler: This is done by passing a null pointer to set_new_handler
. With no new-handler installed, operator new
will throw an exception ((convertible to) std::bad_alloc
) when memory allocation is unsuccessful.
Throw an exception convertible to std::bad_alloc
. Such exceptions are not be caught by operator new
, but will propagate to the site originating the request for memory.
Not return: By calling abort
or exit
.
You have a syntax error in your script and, as noted by xXPhenom22Xx, you must instantiate the tooltip.
<script type="text/javascript">
$(document).ready(function() {
$('.btn-danger').tooltip();
}); //END $(document).ready()
</script>
Note that I used your class "btn-danger". You can create a different class, or use an id="someidthatimakeup"
.
You can't. If it was downloaded via the iTunes store it was built for a different processor and won't work in the simulator.
has_key has been deprecated in Python 3.0. Alternatively you can use 'in'
graph={'A':['B','C'],
'B':['C','D']}
print('A' in graph)
>> True
print('E' in graph)
>> False
Years after everyone's answer, I too want to present how I did it for my project
/// <summary>
/// /Reads an excel file and converts it into dataset with each sheet as each table of the dataset
/// </summary>
/// <param name="filename"></param>
/// <param name="headers">If set to true the first row will be considered as headers</param>
/// <returns></returns>
public DataSet Import(string filename, bool headers = true)
{
var _xl = new Excel.Application();
var wb = _xl.Workbooks.Open(filename);
var sheets = wb.Sheets;
DataSet dataSet = null;
if (sheets != null && sheets.Count != 0)
{
dataSet = new DataSet();
foreach (var item in sheets)
{
var sheet = (Excel.Worksheet)item;
DataTable dt = null;
if (sheet != null)
{
dt = new DataTable();
var ColumnCount = ((Excel.Range)sheet.UsedRange.Rows[1, Type.Missing]).Columns.Count;
var rowCount = ((Excel.Range)sheet.UsedRange.Columns[1, Type.Missing]).Rows.Count;
for (int j = 0; j < ColumnCount; j++)
{
var cell = (Excel.Range)sheet.Cells[1, j + 1];
var column = new DataColumn(headers ? cell.Value : string.Empty);
dt.Columns.Add(column);
}
for (int i = 0; i < rowCount; i++)
{
var r = dt.NewRow();
for (int j = 0; j < ColumnCount; j++)
{
var cell = (Excel.Range)sheet.Cells[i + 1 + (headers ? 1 : 0), j + 1];
r[j] = cell.Value;
}
dt.Rows.Add(r);
}
}
dataSet.Tables.Add(dt);
}
}
_xl.Quit();
return dataSet;
}
Man, I had the issue in one of my eclipse projects, amazingly the issue was the order of the jars in my .project file. believe it or not!
There is one use that has not already been mentioned in C++, and that is not to refer to the own object or disambiguate a member from a received variable.
You can use this
to convert a non-dependent name into an argument dependent name inside template classes that inherit from other templates.
template <typename T>
struct base {
void f() {}
};
template <typename T>
struct derived : public base<T>
{
void test() {
//f(); // [1] error
base<T>::f(); // quite verbose if there is more than one argument, but valid
this->f(); // f is now an argument dependent symbol
}
}
Templates are compiled with a two pass mechanism. During the first pass, only non-argument dependent names are resolved and checked, while dependent names are checked only for coherence, without actually substituting the template arguments.
At that step, without actually substituting the type, the compiler has almost no information of what base<T>
could be (note that specialization of the base template can turn it into completely different types, even undefined types), so it just assumes that it is a type. At this stage the non-dependent call f
that seems just natural to the programmer is a symbol that the compiler must find as a member of derived
or in enclosing namespaces --which does not happen in the example-- and it will complain.
The solution is turning the non-dependent name f
into a dependent name. This can be done in a couple of ways, by explicitly stating the type where it is implemented (base<T>::f
--adding the base<T>
makes the symbol dependent on T
and the compiler will just assume that it will exist and postpones the actual check for the second pass, after argument substitution.
The second way, much sorter if you inherit from templates that have more than one argument, or long names, is just adding a this->
before the symbol. As the template class you are implementing does depend on an argument (it inherits from base<T>
) this->
is argument dependent, and we get the same result: this->f
is checked in the second round, after template parameter substitution.
import java.util.concurrent.atomic.AtomicInteger;
public class PrintEvenOddTester {
public static void main(String ... args){
Printer print = new Printer(false);
Thread t1 = new Thread(new TaskEvenOdd(print, "Thread1", new AtomicInteger(1)));
Thread t2 = new Thread(new TaskEvenOdd(print,"Thread2" , new AtomicInteger(2)));
t1.start();
t2.start();
}
}
class TaskEvenOdd implements Runnable {
Printer print;
String name;
AtomicInteger number;
TaskEvenOdd(Printer print, String name, AtomicInteger number){
this.print = print;
this.name = name;
this.number = number;
}
@Override
public void run() {
System.out.println("Run method");
while(number.get()<10){
if(number.get()%2 == 0){
print.printEven(number.get(),name);
}
else {
print.printOdd(number.get(),name);
}
number.addAndGet(2);
}
}
}
class Printer {
boolean isEven;
public Printer() { }
public Printer(boolean isEven) {
this.isEven = isEven;
}
synchronized void printEven(int number, String name) {
while (!isEven) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(name+": Even:" + number);
isEven = false;
notifyAll();
}
synchronized void printOdd(int number, String name) {
while (isEven) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(name+": Odd:" + number);
isEven = true;
notifyAll();
}
}
I think you cannot speak of a "conversion" here. That will be a whole project. To "convert" it i think you have to write it again for the iphone.
Have a look at this question:
Is there a multiplatform framework for developing iPhone / Android applications?
As you can see from the answers there, there is no good way of developing applications for both platforms at the same time (except if you're developing games where flash makes it easy to be portable).
I'm surprised nobody has suggested using patches yet.
Say you'd like to test a merge from your_branch
into master
(I'm assuming you have master
checked out):
$ git diff master your_branch > your_branch.patch
$ git apply --check your_branch.patch
$ rm your_branch.patch
That should do the trick.
If you get errors like
error: patch failed: test.txt:1
error: test.txt: patch does not apply
that means that the patch wasn't successful and a merge would produce conflicts. No output means the patch is clean and you'd be able to easily merge the branch
Note that this will not actually change your working tree (aside from creating the patch file of course, but you can safely delete that afterwards). From the git-apply documentation:
--check
Instead of applying the patch, see if the patch is applicable to the
current working tree and/or the index file and detects errors. Turns
off "apply".
Note to anyone who is smarter/more experienced with git than me: please do let me know if I'm wrong here and this method does show different behaviour than a regular merge. It seems strange that in the 8+ years that this question has existed noone would suggest this seemingly obvious solution.
I faced this issue today, and I resolved it by doing the following steps:
1) manually inserting that troubling user providing value of mandatory fields into mysql.user
mysql> insert into user(Host, User, Password, ssl_type)
values ('localhost', 'jack', 'jack', 'ANY');
2)
mysql> select * from user where User = 'jack';
1 row in set (0.00 sec)
3) A.
mysql> drop user jack;
Query OK, 0 rows affected (0.00 sec)
B. mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
C. mysql> create user 'jack' identified by 'jack';
Query OK, 0 rows affected (0.00 sec)
D. mysql> select Host, User, Password, ssl_type from user where User = 'jack';
+-----------+-----------+-------------------------------------------+----------+
| Host | User | Password | ssl_type |
+-----------+-----------+-------------------------------------------+----------+
| localhost | jack | jack | ANY |
| % | jack | *45BB7035F11303D8F09B2877A00D2510DCE4D758 | |
+-----------+-----------+-------------------------------------------+----------+
2 rows in set (0.00 sec)
4) A.
mysql> delete from user
where User = 'nyse_user' and
Host = 'localhost' and
Password ='nyse';
Query OK, 1 row affected (0.00 sec)
B.
mysql> select Host, User, Password, ssl_type from user where User = 'jack';
+------+-----------+-------------------------------------------+----------+
| Host | User | Password | ssl_type |
+------+-----------+-------------------------------------------+----------+
| % | jack | *45BB7035F11303D8F09B2877A00D2510DCE4D758 | |
+------+-----------+-------------------------------------------+----------+
1 row in set (0.00 sec)
Hope this helps.
Your class doesn't have a __init__()
, so by the time it's instantiated, the attribute atoms
is not present. You'd have to do C.setdata('something')
so C.atoms
becomes available.
>>> C = Residues()
>>> C.atoms.append('thing')
Traceback (most recent call last):
File "<pyshell#84>", line 1, in <module>
B.atoms.append('thing')
AttributeError: Residues instance has no attribute 'atoms'
>>> C.setdata('something')
>>> C.atoms.append('thing') # now it works
>>>
Unlike in languages like Java, where you know at compile time what attributes/member variables an object will have, in Python you can dynamically add attributes at runtime. This also implies instances of the same class can have different attributes.
To ensure you'll always have (unless you mess with it down the line, then it's your own fault) an atoms
list you could add a constructor:
def __init__(self):
self.atoms = []
Don't bother checking if the file exists, just try to remove it.
rm -f /p/a/t/h
# or
rm /p/a/t/h 2> /dev/null
Note that the second command will fail (return a non-zero exit status) if the file did not exist, but the first will succeed owing to the -f
(short for --force
) option. Depending on the situation, this may be an important detail.
But more likely, if you are appending to the file it is because your script is using >>
to redirect something into the file. Just replace >>
with >
. It's hard to say since you've provided no code.
Note that you can do something like test -f /p/a/t/h && rm /p/a/t/h
, but doing so is completely pointless. It is quite possible that the test will return true but the /p/a/t/h will fail to exist before you try to remove it, or worse the test will fail and the /p/a/t/h will be created before you execute the next command which expects it to not exist. Attempting this is a classic race condition. Don't do it.
Maybe you coul'd use UTF8 bold chars.
For examples: https://yaytext.com/bold-italic/
It works on Chromium 80.0, I don't know on other browsers...
From the documentation for strtotime()
:
Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.
In your date string, you have 12-16-2013
. 16
isn't a valid month, and hence strtotime()
returns false
.
Since you can't use DateTime class, you could manually replace the -
with /
using str_replace()
to convert the date string into a format that strtotime()
understands:
$date = '2-16-2013';
echo date('Y-m-d', strtotime(str_replace('-','/', $date))); // => 2013-02-16
Assuming your example text is representative of all the text, one line would consume about 75 bytes on my machine:
In [3]: sys.getsizeof('usedfor zipper fasten_coat')
Out[3]: 75
Doing some rough math:
75 bytes * 8,000,000 lines / 1024 / 1024 = ~572 MB
So roughly 572 meg to store the strings alone for one of these files. Once you start adding in additional, similarly structured and sized files, you'll quickly approach your virtual address space limits, as mentioned in @ShadowRanger's answer.
If upgrading your python isn't feasible for you, or if it only kicks the can down the road (you have finite physical memory after all), you really have two options: write your results to temporary files in-between loading in and reading the input files, or write your results to a database. Since you need to further post-process the strings after aggregating them, writing to a database would be the superior approach.
Here is a quick and dirty trick:
>>> ms = Warning()
>>> ms.foo = 123
>>> ms.bar = 'akafrit'
How does it works? It just re-use the builtin class Warning
(derived from Exception
) and use it as it was you own defined class.
The good points are that you do not need to import or define anything first, that "Warning" is a short name, and that it also makes clear you are doing something dirty which should not be used elsewhere than a small script of yours.
By the way, I tried to find something even simpler like ms = object()
but could not (this last exemple is not working). If you have one, I am interested.
Let me try this with an example:
Regex Code: (?:animal)(?:=)(\w+)(,)\1\2
Search String:
Line 1 - animal=cat,dog,cat,tiger,dog
Line 2 - animal=cat,cat,dog,dog,tiger
Line 3 - animal=dog,dog,cat,cat,tiger
(?:animal)
--> Non-Captured Group 1
(?:=)
--> Non-Captured Group 2
(\w+)
--> Captured Group 1
(,)
--> Captured Group 2
\1
--> result of captured group 1 i.e In Line 1 is cat, In Line 2 is cat, In Line 3 is dog.
\2
--> result of captured group 2 i.e comma (,)
So in this code by giving \1
and \2
we recall or repeat the result of captured group 1 and 2 respectively later in the code.
As per the order of code (?:animal)
should be group 1 and (?:=)
should be group 2 and continues..
but by giving the ?:
we make the match-group non captured (which do not count off in matched group, so the grouping number starts from the first captured group and not the non captured), so that the repetition of the result of match-group (?:animal)
can't be called later in code.
Hope this explains the use of non capturing group.
JSON is better if you want to backup Data and restore it on a different machine or via FTP.
For example with serialize if you store data on a Windows server, download it via FTP and restore it on a Linux one it could not work any more due to the charachter re-encoding, because serialize stores the length of the strings and in the Unicode > UTF-8 transcoding some 1 byte charachter could became 2 bytes long making the algorithm crash.
if you want it without try and except then there is the solution
what you are trying to do is print 'hello' if 'harry' in a list then the solution is
'hello' if 'harry' in sam else ''
var myPer = 35;
$("#progressbar")
.progressbar({ value: myPer })
.children('.ui-progressbar-value')
.html(myPer.toPrecision(3) + '%')
.css("display", "block");
You can try this:
import subprocess
import sys
process = subprocess.Popen(
cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE
)
while True:
out = process.stdout.read(1)
if out == '' and process.poll() != None:
break
if out != '':
sys.stdout.write(out)
sys.stdout.flush()
If you use readline instead of read, there will be some cases where the input message is not printed. Try it with a command the requires an inline input and see for yourself.
Solution for those who are interested in sending params and headers in GET request
$http.get('https://www.your-website.com/api/users.json', {
params: {page: 1, limit: 100, sort: 'name', direction: 'desc'},
headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
}
)
.then(function(response) {
// Request completed successfully
}, function(x) {
// Request error
});
Complete service example will look like this
var mainApp = angular.module("mainApp", []);
mainApp.service('UserService', function($http, $q){
this.getUsers = function(page = 1, limit = 100, sort = 'id', direction = 'desc') {
var dfrd = $q.defer();
$http.get('https://www.your-website.com/api/users.json',
{
params:{page: page, limit: limit, sort: sort, direction: direction},
headers: {Authorization: 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
}
)
.then(function(response) {
if ( response.data.success == true ) {
} else {
}
}, function(x) {
dfrd.reject(true);
});
return dfrd.promise;
}
});
It can easily be done if u had declared a class that extends from Application
This class will be like a singleton, so when u need a context u can get it just like this:
I think this is the better answer and the cleaner
Here is my code from Utilities package:
public static String getAppNAme(){
return MyOwnApplication.getInstance().getString(R.string.app_name);
}
You can do it using mysqldump tool in command-line:
mysqldump your_database_name > script.sql
This creates a file with database create statements together with insert statements.
More info about options for mysql dump: https://dev.mysql.com/doc/refman/5.7/en/mysqldump-sql-format.html
Please try this code:-
$url = 'url_to_post';
$data = array("first_name" => "First name","last_name" => "last name","email"=>"[email protected]","addresses" => array ("address1" => "some address" ,"city" => "city","country" => "CA", "first_name" => "Mother","last_name" => "Lastnameson","phone" => "555-1212", "province" => "ON", "zip" => "123 ABC" ) );
$data_string = json_encode(array("customer" =>$data));
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type:application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
echo "$result";
I used interop to open Excel and to modify the column widths once the data was done. If you use interop to spit the data into a new Excel workbook (if this is what you want), it will be terribly slow. Instead, I generated a .CSV
, then opened the .CSV
in Excel. This has its own problems, but I've found this the quickest method.
First, convert the .CSV
:
// Convert array data into CSV format.
// Modified from http://csharphelper.com/blog/2018/04/write-a-csv-file-from-an-array-in-c/.
private string GetCSV(List<string> Headers, List<List<double>> Data)
{
// Get the bounds.
var rows = Data[0].Count;
var cols = Data.Count;
var row = 0;
// Convert the array into a CSV string.
StringBuilder sb = new StringBuilder();
// Add the first field in this row.
sb.Append(Headers[0]);
// Add the other fields in this row separated by commas.
for (int col = 1; col < cols; col++)
sb.Append("," + Headers[col]);
// Move to the next line.
sb.AppendLine();
for (row = 0; row < rows; row++)
{
// Add the first field in this row.
sb.Append(Data[0][row]);
// Add the other fields in this row separated by commas.
for (int col = 1; col < cols; col++)
sb.Append("," + Data[col][row]);
// Move to the next line.
sb.AppendLine();
}
// Return the CSV format string.
return sb.ToString();
}
Then, export it to Excel:
public void ExportToExcel()
{
// Initialize app and pop Excel on the screen.
var excelApp = new Excel.Application { Visible = true };
// I use unix time to give the files a unique name that's almost somewhat useful.
DateTime dateTime = DateTime.UtcNow;
long unixTime = ((DateTimeOffset)dateTime).ToUnixTimeSeconds();
var path = @"C:\Users\my\path\here + unixTime + ".csv";
var csv = GetCSV();
File.WriteAllText(path, csv);
// Create a new workbook and get its active sheet.
excelApp.Workbooks.Open(path);
var workSheet = (Excel.Worksheet)excelApp.ActiveSheet;
// iterate over each value and throw it in the chart
for (var column = 0; column < Data.Count; column++)
{
((Excel.Range)workSheet.Columns[column + 1]).AutoFit();
}
currentSheet = workSheet;
}
You'll have to install some stuff, too...
Right click on the solution from solution explorer and select "Manage NuGet Packages." - add Microsoft.Office.Interop.Excel
It might actually work right now if you created the project the way interop wants you to. If it still doesn't work, I had to create a new project in a different category. Under New > Project, select Visual C# > Windows Desktop > Console App. Otherwise, the interop tools won't work.
In case I forgot anything, here's my 'using' statements:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
[disclaimer: I'm one of the contributors]
We built a very simple free/opensource component that adds SAML support for ASP.NET apps https://github.com/jitbit/AspNetSaml
Basically it's just one short C# file you can throw into your project (or install via Nuget) and use it with your app
This will Sound crazy, when ever i build the project the error will be displayed and the avast antivirus will show it as malicious attempt and the project does not run.i just simply disable my antivirus and build my solution again the missing .EXE file has been Created and the project has been successfully executed.
Or you can try this
Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug
I landed up on this page when searching for a solution for “Could not open input file” error. Here's my 2 cents for this error.
I faced this same error while because I was using parameters in my php file path like this:
/usr/bin/php -q /home/**/public_html/cron/job.php?id=1234
But I found out that this is not the proper way to do it. The proper way of sending parameters is like this:
/usr/bin/php -q /home/**/public_html/cron/job.php id=1234
Just replace the "?"
with a space " "
.
I managed to get FTP access to the customer's server and so was able to track down the problem.
After the form is POSTed, I authenticate the user and then redirect to the main part of the app.
Util::redirect('/apps/content');
The error was occurring not on the posting of the form, but on the redirect immediately following it. For some reason, IIS was continuing to presume the POST method for the redirect, and then objecting to the POST to /apps/content
as it's a directory.
The error message never indicated that it was the following page that was generating the error - thanks Microsoft!
The solution was to add a trailing slash:
Util::redirect('/apps/content/');
IIS could then resolve the redirect to a default document as is no longer attempting to POST to a directory.
In case anyone is interested in a general one-liner, simply get the current ticks and use it to set the new ticks by sampling every other tick.
ax.set_xticks(ax.get_xticks()[::2])
can also use:
$("input.DateFrom").datepicker({
minDate: 'today'
});
It sounds like you are on the right track with your directory structure. When you compile the dependent code, specify the -classpath
argument of javac
. Use the parent directory of the com
directory, where com
, in turn, contains company/thing/YourClass.class
So, when you do this:
javac -classpath <parent> client.java
The <parent>
should be referring to the parent of com
. If you are in com
, it would be ../
.
Try to put android:gravity="center_vertical|right"
inside parent LinearLayout else as you are inside RelativeLayout you can put android:layout_centerInParent="true"
inside your scrollView
.
Another situation when you may need this is if you have stl collection of pointers and want to change them using stl algorithm. Example of for_each in c++98.
struct Storage {
typedef std::list<Object*> ObjectList;
ObjectList objects;
void change() {
typedef void (*ChangeFunctionType)(Object*&);
std::for_each<ObjectList::iterator, ChangeFunctionType>
(objects.begin(), objects.end(), &Storage::changeObject);
}
static void changeObject(Object*& item) {
delete item;
item = 0;
if (someCondition) item = new Object();
}
};
Otherwise, if you use changeObject(Object* item) signature you have copy of pointer, not original one.
Shorter code with ES6
objArray.sort((a, b) => a.DepartmentName.toLowerCase().localeCompare(b.DepartmentName.toLowerCase()))
If don't store it locally and use the link that they provide you might have an improved performance.The client might have the scripts already cached in some cases. As for the case of jQueryUI i would recommend not loading it until necessary. They are both minimized, but you can fire up the console and look at the network tab and see how long it takes for it to load, once it is initially downloaded it will be cached so you shouldn't worry afterwards.My conclusion would be yes use them both but use a CDN
The trick for me was to add double quotes around keys and values. If you use a PHP function like json_encode
will give you a JSON encoded string and an idea how to properly encode yours.
jQuery('#elm-id').data('datakey')
will return an object of the string, if the string is properly encoded as json.
As per jQuery documentation: (http://api.jquery.com/jquery.parsejson/)
Passing in a malformed JSON string results in a JavaScript exception being thrown. For example, the following are all invalid JSON strings:
"{test: 1}"
(test
does not have double quotes around it)."{'test': 1}"
('test'
is using single quotes instead of double quotes)."'test'"
('test'
is using single quotes instead of double quotes).".1"
(a number must start with a digit; "0.1"
would be valid)."undefined"
(undefined
cannot be represented in a JSON string; null
, however, can be)."NaN"
(NaN
cannot be represented in a JSON string; direct representation of Infinity is also nsrand(time(NULL));
int nRandonNumber = rand()%((nMax+1)-nMin) + nMin;
printf("%d\n",nRandonNumber);
switch($someString.ToLower())
{
"yes" { $_ = "y" }
"y" { "You entered Yes." }
default { "You entered No." }
}
You can arbitrarily branch, cascade, and merge cases in this fashion, as long as the target case is located below/after the case or cases where the $_ variable is respectively reassigned.
n.b. As cute as this behavior is, it seems to reveal that the PowerShell interpreter is not implementing switch/case as efficiently as one might hope or assume. For one, stepping with the ISE debugger suggests that instead of optimized lookup, hashing, or binary branching, each case is tested in turn, like so many if-else statements. (If so, consider putting your most common cases first.) Also, as shown in this answer, PowerShell continues testing cases after having satisfied one. And cruelly enough, there even happens to be a special optimized 'switch' opcode available in .NET CIL which, because of this behavior, PowerShell can't take advantage of.
Consider the case in which a service worker acts as an agnostic cache. Your only goal is serve the same resources that you would get from the network, but faster. Of course you can't ensure all the resources will be part of your origin (consider libraries served from CDNs, for instance). As the service worker has the potential of altering network responses, you need to guarantee you are not interested in the contents of the response, nor on its headers, nor even on the result. You're only interested on the response as a black box to possibly cache it and serve it faster.
This is what { mode: 'no-cors' }
was made for.
Global variables can be used in Node when used wisely.
Declaration of global variables in Node:
a = 10;
GLOBAL.a = 10;
global.a = 10;
All of the above commands the same actions with different syntaxes.
Use global variables when they are not about to be changed
Here an example of something that can happen when using global variables:
// app.js
a = 10; // no var or let or const means global
// users.js
app.get("/users", (req, res, next) => {
res.send(a); // 10;
});
// permissions.js
app.get("/permissions", (req, res, next) => {
a = 11; // notice that there is no previous declaration of a in the permissions.js, means we looking for the global instance of a.
res.send(a); // 11;
});
Explained:
Run users route first and receive 10;
Then run permissions route and receive 11;
Then run again the users route and receive 11 as well instead of 10;
Global variables can be overtaken!
Now think about using express and assignin res object as global.. And you end up with async error become corrupt and server is shuts down.
When to use global vars?
As I said - when var is not about to be changed.
Anyways it's more recommended that you will be using the process.env
object from the config file.
Some of the common ways to create a String array are
This will create an array of 5 strings with initial values to be empty string.
<String?>
(5)This will create an array of size 5 with initial values to be null. You can use String data to modify the array.
When you know the contents of array already then you can initialise the array directly.
There is an easy way for creating an multi dimensional array of strings as well.
var matrix = Array(5){Array(6) {""}}
This is how you can create a matrix with 5 rows and 6 columns with initial values of empty string.
Table or record locking is available in Access during data writes. You can control the Default record locking through Tools | Options | Advanced tab:
You can set this on a form's Record Locks or in your DAO/ADO code for specific needs.
Transactions shouldn't be a problem if you use them correctly.
Best practice: Separate your tables from All your other code. Give each user their own copy of the code file and then share the data file on a network server. Work on a 'test' copy of the code (and a link to a test data file) and then update user's individual code files separately. If you need to make data file changes (add tables, columns, etc), you will have to have all users get out of the application to make the changes.
See other answers for Oracle comparison.
You could also use INDEX MATCH
, which is more "powerful" than vlookup. This would give you exactly what you are looking for:
Here is my solution. By calling the function below you ensure that all dirs leading to the file path specified exist. Note that file_path
argument is not directory name here but rather a path to a file that you are going to create after calling mkpath()
.
Eg., mkpath("/home/me/dir/subdir/file.dat", 0755)
shall create /home/me/dir/subdir
if it does not exist. mkpath("/home/me/dir/subdir/", 0755)
does the same.
Works with relative paths as well.
Returns -1
and sets errno
in case of an error.
int mkpath(char* file_path, mode_t mode) {
assert(file_path && *file_path);
for (char* p = strchr(file_path + 1, '/'); p; p = strchr(p + 1, '/')) {
*p = '\0';
if (mkdir(file_path, mode) == -1) {
if (errno != EEXIST) {
*p = '/';
return -1;
}
}
*p = '/';
}
return 0;
}
Note that file_path
is modified during the action but gets restored afterwards. Therefore file_path
is not strictly const
.
All double quotes inside double quotes which suround the string must be changed doubled. As example I had one of json file strings : "delivery": "Standard", In Vba Editor I changed it into """delivery"": ""Standard""," and everythig works correctly. If you have to insert a lot of similar strings, my proposal first, insert them all between "" , then with VBA editor replace " inside into "". If you will do mistake, VBA editor shows this line in red and you will correct this error.
I'm one of the developers who helped create Sass.
The difference is UI. Underneath the textual exterior they are identical. This is why sass and scss files can import each other. Actually, Sass has four syntax parsers: scss, sass, CSS, and less. All of these convert a different syntax into an Abstract Syntax Tree which is further processed into CSS output or even onto one of the other formats via the sass-convert tool.
Use the syntax you like the best, both are fully supported and you can change between them later if you change your mind.
i reached this question while trying to find all procedures which use a certain table
Oracle SQL Developer offers this capability, as pointed out in this article : https://www.thatjeffsmith.com/archive/2012/09/search-and-browse-database-objects-with-oracle-sql-developer/
From the View menu, choose Find DB Object. Choose a DB connection. Enter the name of the table. At Object Types, keep only functions, procedures and packages. At Code section, check All source lines.
That what I use often for this case:
declare @colnames varchar(max)=''
select @colnames=@colnames+','+name from syscolumns where object_id(tablename)=id and name not in (column3,column4)
SET @colnames=RIGHT(@colnames,LEN(@colnames)-1)
@colnames
looks like column1,column2,column5
We could do it with jQuery:
$(window).resize(function(){
alert(window.innerWidth);
$scope.$apply(function(){
//do something to update current scope based on the new innerWidth and let angular update the view.
});
});
Be aware that when you bind an event handler inside scopes that could be recreated (like ng-repeat scopes, directive scopes,..), you should unbind your event handler when the scope is destroyed. If you don't do this, everytime when the scope is recreated (the controller is rerun), there will be 1 more handler added causing unexpected behavior and leaking.
In this case, you may need to identify your attached handler:
$(window).on("resize.doResize", function (){
alert(window.innerWidth);
$scope.$apply(function(){
//do something to update current scope based on the new innerWidth and let angular update the view.
});
});
$scope.$on("$destroy",function (){
$(window).off("resize.doResize"); //remove the handler added earlier
});
In this example, I'm using event namespace from jQuery. You could do it differently according to your requirements.
Improvement: If your event handler takes a bit long time to process, to avoid the problem that the user may keep resizing the window, causing the event handlers to be run many times, we could consider throttling the function. If you use underscore, you can try:
$(window).on("resize.doResize", _.throttle(function (){
alert(window.innerWidth);
$scope.$apply(function(){
//do something to update current scope based on the new innerWidth and let angular update the view.
});
},100));
or debouncing the function:
$(window).on("resize.doResize", _.debounce(function (){
alert(window.innerWidth);
$scope.$apply(function(){
//do something to update current scope based on the new innerWidth and let angular update the view.
});
},100));
Change setTimeout("changeImage()", 30000);
to setInterval("changeImage()", 30000);
and remove var timerid = setInterval(changeImage, 30000);
.
The Windows x64 installer shows the a path in the installer UI/wizard.
You can confirm which path it used later, by opening your mongod.cfg
file. My mongod.cfg
was located here C:\Program Files\MongoDB\Server\4.0\bin\mongod.cfg
(change for your version of MongoDB!
When I opened my mongd.cfg
I found this line, showing the default db path:
dbPath: C:\Program Files\MongoDB\Server\4.0\data
However, this caused an error when trying to run mongod
, which was still expecting to find C:\data\db
:
2019-05-05T09:32:36.084-0700 I STORAGE [initandlisten] exception in initAndListen: NonExistentPath: Data directory C:\data\db\ not found., terminating
You could pass mongod
a --dbpath=...
parameter. In my case:
mongod --dbpath="C:\Program Files\MongoDB\Server\4.0\data"
Try the --cd= option. Assuming your GIT Bash resides in C:\Program Files\Git it would be:
"C:\Program Files\Git\git-bash.exe" --cd="e:\SomeFolder"
If used inside registry key, folder parameter can be provided with %1:
"C:\Program Files\Git\git-bash.exe" --cd="%1"
Note that your initial query is probably not returning what you want:
SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age
FROM availables INNER JOIN rooms ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094 GROUP BY availables.bookdate
You are grouping by book date, but you are not using any grouping function on the second column of your query.
The query you are probably looking for is:
SELECT availables.bookdate AS Date, count(*) as subtotal, sum(DATEDIFF(now(),availables.updated_at) as Age)
FROM availables INNER JOIN rooms ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
GROUP BY availables.bookdate
Technically, there is no difference between a class and a case class -- even if the compiler does optimize some stuff when using case classes. However, a case class is used to do away with boiler plate for a specific pattern, which is implementing algebraic data types.
A very simple example of such types are trees. A binary tree, for instance, can be implemented like this:
sealed abstract class Tree
case class Node(left: Tree, right: Tree) extends Tree
case class Leaf[A](value: A) extends Tree
case object EmptyLeaf extends Tree
That enable us to do the following:
// DSL-like assignment:
val treeA = Node(EmptyLeaf, Leaf(5))
val treeB = Node(Node(Leaf(2), Leaf(3)), Leaf(5))
// On Scala 2.8, modification through cloning:
val treeC = treeA.copy(left = treeB.left)
// Pretty printing:
println("Tree A: "+treeA)
println("Tree B: "+treeB)
println("Tree C: "+treeC)
// Comparison:
println("Tree A == Tree B: %s" format (treeA == treeB).toString)
println("Tree B == Tree C: %s" format (treeB == treeC).toString)
// Pattern matching:
treeA match {
case Node(EmptyLeaf, right) => println("Can be reduced to "+right)
case Node(left, EmptyLeaf) => println("Can be reduced to "+left)
case _ => println(treeA+" cannot be reduced")
}
// Pattern matches can be safely done, because the compiler warns about
// non-exaustive matches:
def checkTree(t: Tree) = t match {
case Node(EmptyLeaf, Node(left, right)) =>
// case Node(EmptyLeaf, Leaf(el)) =>
case Node(Node(left, right), EmptyLeaf) =>
case Node(Leaf(el), EmptyLeaf) =>
case Node(Node(l1, r1), Node(l2, r2)) =>
case Node(Leaf(e1), Leaf(e2)) =>
case Node(Node(left, right), Leaf(el)) =>
case Node(Leaf(el), Node(left, right)) =>
// case Node(EmptyLeaf, EmptyLeaf) =>
case Leaf(el) =>
case EmptyLeaf =>
}
Note that trees construct and deconstruct (through pattern match) with the same syntax, which is also exactly how they are printed (minus spaces).
And they can also be used with hash maps or sets, since they have a valid, stable hashCode.
With:
global index_add_counter
You are not defining, just declaring so it's like saying there is a global index_add_counter
variable elsewhere, and not create a global called index_add_counter
. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global
keyword and initialize your variable:
index_add_counter = 0
Now you can import it with:
from app import index_add_counter
The construction:
global index_add_counter
is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:
index_add_counter = 0
def test():
global index_add_counter # means: in this scope, use the global name
print(index_add_counter)
To move and delete specific records by selecting using WHERE query,
BEGIN TRANSACTION;
Insert Into A SELECT * FROM B where URL="" AND email ="" AND Annual_Sales_Vol="" And OPENED_In="" AND emp_count="" And contact_person= "" limit 0,2000;
delete from B where Id In (select Id from B where URL="" AND email ="" AND Annual_Sales_Vol="" And OPENED_In="" AND emp_count="" And contact_person= "" limit 0,2000);
commit;
I'm going to attempt to explain this without making any mistakes, but I'm betting this will attract a clarification or two in the comments.
A data frame is a list. When you subset a data frame using the name of a column and [
, what you're getting is a sublist (or a sub data frame). If you want the actual atomic column, you could use [[
, or somewhat confusingly (to me) you could do aframe[,2]
which returns a vector, not a sublist.
So try running this sequence and maybe things will be clearer:
avector <- as.vector(aframe['a2'])
class(avector)
avector <- aframe[['a2']]
class(avector)
avector <- aframe[,2]
class(avector)
Try this:
Update TableB Set
Code = Coalesce(
(Select Max(Value)
From TableA
Where Id = b.Id), 123)
From TableB b
An application is CPU-bound when the arithmetic/logical/floating-point (A/L/FP) performance during the execution is mostly near the theoretical peak-performance of the processor (data provided by the manufacturer and determined by the characteristics of the processor: number of cores, frequency, registers, ALUs, FPUs, etc.).
The peek performance is very difficult to be achieved in real-world applications, for not saying impossible. Most of the applications access memory in different parts of the execution and the processor is not doing A/L/FP operations during several cycles. This is called Von Neumann Limitation due to the distance that exists between the memory and the processor.
If you want to be near the CPU peak-performance a strategy could be to try to reuse most of the data in the cache memory in order to avoid requiring data from the main memory. An algorithm that exploits this feature is the matrix-matrix multiplication (if both matrices can be stored in the cache memory). This happens because if the matrices are size n x n
then you need to do about 2 n^3
operations using only 2 n^2
FP numbers of data. On the other hand matrix addition, for example, is a less CPU-bound or a more memory-bound application than the matrix multiplication since it requires only n^2
FLOPs with the same data.
In the following figure the FLOPs obtained with a naive algorithms for the matrix addition and the matrix multiplication in an Intel i5-9300H, is shown:
Note that as expected the performance of the matrix multiplication in bigger than the matrix addition. These results can be reproduced by running test/gemm
and test/matadd
available in this repository.
I suggest also to see the video given by J. Dongarra about this effect.
There's a simple way to get rid of this restriction by using the datePicker component provided by jQuery.
Include jQuery and jQuery UI libraries (I'm still using an old one)
Use the following snip
$(function() {
$( "#id_of_the_component" ).datepicker({ dateFormat: 'yy-mm-dd'});
});
See jQuery UI DatePicker - Change Date Format if needed.
In case your JENKINS_HOME directory is too large to copy, and all you need is to set up same jobs, Jenkins Plugins and Jenkins configurations (and don't need old Job artifacts and reports), then you can use the ThinBackup Plugin:
Install ThinBackup on both the source and the target Jenkins servers
Configure the backup directory on both (in Manage Jenkins ? ThinBackup ? Settings)
On the source Jenkins, go to ThinBackup ? Backup Now
Copy from Jenkins source backup directory to the Jenkins target backup directory
On the target Jenkins, go to ThinBackup ? Restore, and then restart the Jenkins service.
If some plugins or jobs are missing, copy the backup content directly to the target JENKINS_HOME.
If you had user authentication on the source Jenkins, and now locked out on the target Jenkins, then edit Jenkins config.xml, set <useSecurity>
to false, and restart Jenkins.
http://php.net/session.gc-maxlifetime
session.gc_maxlifetime = 1440
(1440 seconds = 24 minutes)