I did exactly the same issue using the dependency below:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
I just change to version 46 and everything works.
There was an error in understanding of return Type Just add Header and it will solve your problem
@Headers("Content-Type: application/json")
For my case, I follow the steps from Firebase
and by mistake I pated it in a wrong file.
Then, I returned to the project from Project
to Android
. Once in the Android view
I pasted the file /projectname/app/YOUR-FILE-HERE
and now, you have to compile again.
Try this:
From this question.
In my case I was using jackson-databind-2.8.8.jar
that is not compatible with JDK 1.6
I need to use so Spring wasn't loading this converter. I downgraded the version and it works now.
If your data changes a lot, you can use
mAdapter.notifyItemRangeChanged(0, yourData.size());
or some single items in your data set changes, your can use
mAdapter.notifyItemChanged(pos);
For detailed methods usage, you can refer the doc, in a way, try not to directly use mAdapter.notifyDataSetChanged()
.
You can use map
:
List<String> names =
personList.stream()
.map(Person::getName)
.collect(Collectors.toList());
EDIT :
In order to combine the Lists of friend names, you need to use flatMap
:
List<String> friendNames =
personList.stream()
.flatMap(e->e.getFriends().stream())
.collect(Collectors.toList());
In my case I was getting this message due to a runtime error with Junit which wasn't at all visible from the output of the gradle test task execution. I've run into this for a couple reasons:
org.junit.platform:junit-platform-launcher
dependency with a version that didn't match the junit version I was usingMETA-INF/services
for a Junit test listener which I had commented outYou can try re-running with --debug
and search for FAILED
or org.gradle.api.internal.tasks.testing.TestSuiteExecutionException
. In my second case, the exception was:
2020-10-20T11:34:26.517-0700 [DEBUG] [TestEventLogger]
2020-10-20T11:34:26.517-0700 [DEBUG] [TestEventLogger] Gradle Test Executor 1 STARTED
2020-10-20T11:34:26.661-0700 [DEBUG] [TestEventLogger]
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger] Gradle Test Executor 1 FAILED
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger] org.gradle.api.internal.tasks.testing.TestSuiteExecutionException: Could not complete execution for Gradle Test Executor 1.
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger] at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:63)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger] at java.lang.reflect.Method.invoke(Method.java:498)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger] at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger] at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger] at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger] at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger] at com.sun.proxy.$Proxy2.stop(Unknown Source)
2020-10-20T11:34:26.662-0700 [DEBUG] [TestEventLogger] at org.gradle.api.internal.tasks.testing.worker.TestWorker.stop(TestWorker.java:132)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger] at java.lang.reflect.Method.invoke(Method.java:498)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger] at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger] at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger] at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger] at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger] at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:413)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger] at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger] at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger] at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger] at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger] at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger] at java.lang.Thread.run(Thread.java:748)
2020-10-20T11:34:26.663-0700 [DEBUG] [TestEventLogger]
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger] Caused by:
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger] java.util.ServiceConfigurationError: org.junit.platform.launcher.TestExecutionListener: Provider com.example.myproject.MyCommentedOutClass not found
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger] at java.util.ServiceLoader.fail(ServiceLoader.java:239)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger] at java.util.ServiceLoader.access$300(ServiceLoader.java:185)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger] at java.util.ServiceLoader$LazyIterator.nextService(ServiceLoader.java:372)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger] at java.util.ServiceLoader$LazyIterator.next(ServiceLoader.java:404)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger] at java.util.ServiceLoader$1.next(ServiceLoader.java:480)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger] at java.lang.Iterable.forEach(Iterable.java:74)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger] at org.junit.platform.launcher.core.LauncherFactory.create(LauncherFactory.java:94)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger] at org.junit.platform.launcher.core.LauncherFactory.create(LauncherFactory.java:67)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger] at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.processAllTestClasses(JUnitPlatformTestClassProcessor.java:97)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger] at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor$CollectAllTestClassesExecutor.access$000(JUnitPlatformTestClassProcessor.java:79)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger] at org.gradle.api.internal.tasks.testing.junitplatform.JUnitPlatformTestClassProcessor.stop(JUnitPlatformTestClassProcessor.java:75)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger] at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.stop(SuiteTestClassProcessor.java:61)
2020-10-20T11:34:26.664-0700 [DEBUG] [TestEventLogger] ... 25 more
Notice that these are DEBUG
logs. I didn't see anything helpful with just --info
Add a toolbar to your xml
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
app:popupTheme="@style/ThemeOverlay.AppCompat.Light">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Fragment title"/>
</android.support.v7.widget.Toolbar>
Then inside your onCreateView method in the Fragment:
Toolbar toolbar = view.findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.ic_back_button);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().onBackPressed();
}
});
this can be achieved using below...
List<String> unavailable = list1.stream()
.filter(e -> !list2.contains(e))
.collect(Collectors.toList());
There is no error when I use your code,
but I am calling the hasLetter
method like this:
hasLetter("a",words);
Check your firewall setting and set
<property>
<name>fs.default.name</name>
<value>hdfs://MachineName:9000</value>
</property>
replace localhost to machine name
In simple, using Comparator and Collection you can sort like below in reversal order using JAVA 8
import java.util.Comparator;;
import java.util.stream.Collectors;
Arrays.asList(files).stream()
.sorted(Comparator.comparing(File::getLastModified).reversed())
.collect(Collectors.toList());
In your example there is no big difference between str -> str
and Function.identity()
since internally it is simply t->t
.
But sometimes we can't use Function.identity
because we can't use a Function
. Take a look here:
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
this will compile fine
int[] arrayOK = list.stream().mapToInt(i -> i).toArray();
but if you try to compile
int[] arrayProblem = list.stream().mapToInt(Function.identity()).toArray();
you will get compilation error since mapToInt
expects ToIntFunction
, which is not related to Function
. Also ToIntFunction
doesn't have identity()
method.
If you only need to detect the presence of duplicates (instead of listing them, which is what the OP wanted), just convert them into both a List and Set, then compare the sizes:
List<Integer> list = ...;
Set<Integer> set = new HashSet<>(list);
if (list.size() != set.size()) {
// duplicates detected
}
I like this approach because it has less places for mistakes.
By changing runProguard to minifyEnabled, part of the issue gets fixed.
But the fix can cause "Library Projects cannot set application Id" (you can find the fix for this here Android Studio 1.0 and error "Library projects cannot set applicationId").
By removing application Id in the build.gradle file, you should be good to go.
I've preferred using the params filter for parameter-centric content-type.. I believe that should work in conjunction with the produces attribute.
@GetMapping(value="/person/{id}/",
params="format=json",
produces=MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Person> getPerson(@PathVariable Integer id){
Person person = personMapRepository.findPerson(id);
return ResponseEntity.ok(person);
}
@GetMapping(value="/person/{id}/",
params="format=xml",
produces=MediaType.APPLICATION_XML_VALUE)
public ResponseEntity<Person> getPersonXML(@PathVariable Integer id){
return GetPerson(id); // delegate
}
You're nesting mocking inside of mocking. You're calling getSomeList()
, which does some mocking, before you've finished the mocking for MyMainModel
. Mockito doesn't like it when you do this.
Replace
@Test
public myTest(){
MyMainModel mainModel = Mockito.mock(MyMainModel.class);
Mockito.when(mainModel.getList()).thenReturn(getSomeList()); --> Line 355
}
with
@Test
public myTest(){
MyMainModel mainModel = Mockito.mock(MyMainModel.class);
List<SomeModel> someModelList = getSomeList();
Mockito.when(mainModel.getList()).thenReturn(someModelList);
}
To understand why this causes a problem, you need to know a little about how Mockito works, and also be aware in what order expressions and statements are evaluated in Java.
Mockito can't read your source code, so in order to figure out what you are asking it to do, it relies a lot on static state. When you call a method on a mock object, Mockito records the details of the call in an internal list of invocations. The when
method reads the last of these invocations off the list and records this invocation in the OngoingStubbing
object it returns.
The line
Mockito.when(mainModel.getList()).thenReturn(someModelList);
causes the following interactions with Mockito:
mainModel.getList()
is called,when
is called,thenReturn
is called on the OngoingStubbing
object returned by the when
method.The thenReturn
method can then instruct the mock it received via the OngoingStubbing
method to handle any suitable call to the getList
method to return someModelList
.
In fact, as Mockito can't see your code, you can also write your mocking as follows:
mainModel.getList();
Mockito.when((List<SomeModel>)null).thenReturn(someModelList);
This style is somewhat less clear to read, especially since in this case the null
has to be casted, but it generates the same sequence of interactions with Mockito and will achieve the same result as the line above.
However, the line
Mockito.when(mainModel.getList()).thenReturn(getSomeList());
causes the following interactions with Mockito:
mainModel.getList()
is called,when
is called,mock
of SomeModel
is created (inside getSomeList()
),model.getName()
is called,At this point Mockito gets confused. It thought you were mocking mainModel.getList()
, but now you're telling it you want to mock the model.getName()
method. To Mockito, it looks like you're doing the following:
when(mainModel.getList());
// ...
when(model.getName()).thenReturn(...);
This looks silly to Mockito
as it can't be sure what you're doing with mainModel.getList()
.
Note that we did not get to the thenReturn
method call, as the JVM needs to evaluate the parameters to this method before it can call the method. In this case, this means calling the getSomeList()
method.
Generally it is a bad design decision to rely on static state, as Mockito does, because it can lead to cases where the Principle of Least Astonishment is violated. However, Mockito's design does make for clear and expressive mocking, even if it leads to astonishment sometimes.
Finally, recent versions of Mockito add an extra line to the error message above. This extra line indicates you may be in the same situation as this question:
3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed
If you're open to using a third-party library, you can use the Collectors2
class in Eclipse Collections to convert the List
to a Bag
using a Stream
. A Bag
is a data structure that is built for counting.
Bag<String> counted =
list.stream().collect(Collectors2.countBy(each -> each));
Assert.assertEquals(1, counted.occurrencesOf("World"));
Assert.assertEquals(2, counted.occurrencesOf("Hello"));
System.out.println(counted.toStringOfItemToCount());
Output:
{World=1, Hello=2}
In this particular case, you can simply collect
the List
directly into a Bag
.
Bag<String> counted =
list.stream().collect(Collectors2.toBag());
You can also create the Bag
without using a Stream
by adapting the List
with the Eclipse Collections protocols.
Bag<String> counted = Lists.adapt(list).countBy(each -> each);
or in this particular case:
Bag<String> counted = Lists.adapt(list).toBag();
You could also just create the Bag directly.
Bag<String> counted = Bags.mutable.with("Hello", "Hello", "World");
A Bag<String>
is like a Map<String, Integer>
in that it internally keeps track of keys and their counts. But, if you ask a Map
for a key it doesn't contain, it will return null
. If you ask a Bag
for a key it doesn't contain using occurrencesOf
, it will return 0.
Note: I am a committer for Eclipse Collections.
Faced same issue. In my case the reason was pretty stupid - github token I used for authorization was issued for the organization that doesn't own the repo I tried to publish into. So check repo title and ownership.
This is possible in Java 9.
Stream.generate(() -> null)
.takeWhile(x -> iterator.hasNext())
.map(n -> iterator.next())
.forEach(System.out::println);
I think you can try to load that csv into a RDD and then create a dataframe from that RDD, here is the document of creating dataframe from rdd:http://spark.apache.org/docs/latest/sql-programming-guide.html#interoperating-with-rdds
Java 8 way to do this:
List<Integer> list = Arrays.asList(1,2,3,4);
Comparator<Integer> comparator = Integer::compare;
list.stream().sorted(comparator.reversed()).forEach(System.out::println);
I believe rather than enabling eager fetch, it make sense to re-initialise your entity where its needed to avoid LazyInitializationException
exception
Hibernate.initialize(your entity);
Ideally you would put that in a directive, but you can also just put it in the controller. http://jsfiddle.net/tnq86/15/
angular.module('App', [])
.controller('AppCtrl', function ($scope) {
$scope.model = 0;
$scope.initSlider = function () {
$(function () {
// wait till load event fires so all resources are available
$scope.$slider = $('#slider').slider({
slide: $scope.onSlide
});
});
$scope.onSlide = function (e, ui) {
$scope.model = ui.value;
$scope.$digest();
};
};
$scope.initSlider();
});
The directive approach:
HTML
<div slider></div>
JS
angular.module('App', [])
.directive('slider', function (DataModel) {
return {
restrict: 'A',
scope: true,
controller: function ($scope, $element, $attrs) {
$scope.onSlide = function (e, ui) {
$scope.model = ui.value;
// or set it on the model
// DataModel.model = ui.value;
// add to angular digest cycle
$scope.$digest();
};
},
link: function (scope, el, attrs) {
var options = {
slide: scope.onSlide
};
// set up slider on load
angular.element(document).ready(function () {
scope.$slider = $(el).slider(options);
});
}
}
});
I would also recommend checking out Angular Bootstrap's source code: https://github.com/angular-ui/bootstrap/blob/master/src/tooltip/tooltip.js
You can also use a factory to create the directive. This gives you ultimate flexibility to integrate services around it and whatever dependencies you need.
Response you are getting is in object form i.e.
{
"dstOffset" : 3600,
"rawOffset" : 36000,
"status" : "OK",
"timeZoneId" : "Australia/Hobart",
"timeZoneName" : "Australian Eastern Daylight Time"
}
Replace below line of code :
List<Post> postsList = Arrays.asList(gson.fromJson(reader,Post.class))
with
Post post = gson.fromJson(reader, Post.class);
This is quite easy with jQuery using insertAfter()
or insertBefore()
:
<div class="left">content</div>
<div class="right">sidebar</div>
<script>
$('.right').insertBefore('left');
</script>
_x000D_
If you want to to set o condition for mobile devices you can make it like this:
<script>
var $iW = $(window).innerWidth();
if ($iW < 992){
$('.right').insertBefore('.left');
}else{
$('.right').insertAfter('.left');
}
</script>
_x000D_
example https://jsfiddle.net/w9n27k23/
Simple Steps
Did you consider using nginx (or other event based web server) instead of apache?
nginx shall allow higher number of connections and consume much less resources (as it is event based and does not create separate process per connection). Anyway, you will need some processes, doing real work (like WSGI servers or so) and if they stay on the same server as the front end web server, you only shift the performance problem to a bit different place.
Latest apache version shall allow similar solution (configure it in event based manner), but this is not my area of expertise.
I spent few hours on this.
Even if I had the right dependency the problem was fixed only after I deleted the com.fasterxml.jackson folder in the .m2 repository under C:\Users\username.m2 and updated the project
Right, many alternatives are listed. The easiest and cleanest would be just using the enhanced for
statement as below. The Expression
is of some type that is iterable.
for ( FormalParameter : Expression ) Statement
For example, to iterate through, List<String> ids, we can simply so,
for (String str : ids) {
// Do something
}
Many people have answered the mechanical details already, but it's worth noting: This is a poor design choice, by Java.
Java's asList
method is documented as "Returns a fixed-size list...". If you take its result and call (say) the .add
method, it throws an UnsupportedOperationException
. This is unintuitive behavior! If a method says it returns a List
, the standard expectation is that it returns an object which supports the methods of interface List
. A developer shouldn't have to memorize which of the umpteen util.List
methods create List
s that don't actually support all the List
methods.
If they had named the method asImmutableList
, it would make sense. Or if they just had the method return an actual List
(and copy the backing array), it would make sense. They decided to favor both runtime-performance and short names, at the expense of violating both the Principle of Least Surprise and the good-O.O. practice of avoiding UnsupportedOperationException
s.
(Also, the designers might have made a interface ImmutableList
, to avoid a plethora of UnsupportedOperationException
s.)
<project>
[...]
<build>
[...]
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>(whatever version is current)</version>
<configuration>
<!-- or whatever version you use -->
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
[...]
</build>
[...]
</project>
See the config page for the maven compiler plugin:
http://maven.apache.org/plugins/maven-compiler-plugin/examples/set-compiler-source-and-target.html
Oh, and: don't use Java 1.3.x, current versions are Java 1.7.x or 1.8.x
If you're using Maven and the latest Jackson code then you can remove all the Jackson-specific configuration from your spring configuration XML files (you'll still need an annotation-driven tag <mvc:annotation-driven/>) and simply add some Jackson dependencies to your pom.xml file. See below for an example of the dependencies. This worked for me and I'm using:
spring-security version 3.1.0.RELEASE.
...<dependencies>
...
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.2.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.2.3</version>
</dependency>
...
</dependencies>...
If you don't mind using 3rd party libraries, AOL's cyclops-react lib (disclosure I am a contributor) has extensions for all JDK Collection types, including List. The ListX interface extends java.util.List and adds a large number of useful operators, including filter.
You can simply write-
ListX<Long> sourceLongList = ListX.of(1L, 10L, 50L, 80L, 100L, 120L, 133L, 333L);
ListX<Long> targetLongList = sourceLongList.filter(l -> l > 100);
ListX also can be created from an existing List (via ListX.fromIterable)
if you read a bit further - "Of course, on the backend, there are threads and processes for DB access and process execution. However, these are not explicitly exposed to your code, so you can’t worry about them other than by knowing that I/O interactions e.g. with the database, or with other processes will be asynchronous from the perspective of each request since the results from those threads are returned via the event loop to your code."
about - "everything runs in parallel except your code" - your code is executed synchronously, whenever you invoke an asynchronous operation such as waiting for IO, the event loop handles everything and invokes the callback. it just not something you have to think about.
in your example: there are two requests A (comes first) and B. you execute request A, your code continue to run synchronously and execute request B. the event loop handles request A, when it finishes it invokes the callback of request A with the result, same goes to request B.
Use Bootstrap Affix:
/* Note: Try to remove the following lines to see the effect of CSS positioning */_x000D_
.affix {_x000D_
top: 0;_x000D_
width: 100%;_x000D_
}_x000D_
_x000D_
.affix + .container-fluid {_x000D_
padding-top: 70px;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<title>Bootstrap Example</title>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<div class="container-fluid" style="background-color:#F44336;color:#fff;height:200px;">_x000D_
<h1>Bootstrap Affix Example</h1>_x000D_
<h3>Fixed (sticky) navbar on scroll</h3>_x000D_
<p>Scroll this page to see how the navbar behaves with data-spy="affix".</p>_x000D_
<p>The navbar is attached to the top of the page after you have scrolled a specified amount of pixels.</p>_x000D_
</div>_x000D_
_x000D_
<nav class="navbar navbar-inverse" data-spy="affix" data-offset-top="197">_x000D_
<ul class="nav navbar-nav">_x000D_
<li class="active"><a href="#">Basic Topnav</a></li>_x000D_
<li><a href="#">Page 1</a></li>_x000D_
<li><a href="#">Page 2</a></li>_x000D_
<li><a href="#">Page 3</a></li>_x000D_
</ul>_x000D_
</nav>_x000D_
_x000D_
<div class="container-fluid" style="height:1000px">_x000D_
<h1>Some text to enable scrolling</h1>_x000D_
<h1>Some text to enable scrolling</h1>_x000D_
<h1>Some text to enable scrolling</h1>_x000D_
<h1>Some text to enable scrolling</h1>_x000D_
<h1>Some text to enable scrolling</h1>_x000D_
<h1>Some text to enable scrolling</h1>_x000D_
<h1>Some text to enable scrolling</h1>_x000D_
<h1>Some text to enable scrolling</h1>_x000D_
<h1>Some text to enable scrolling</h1>_x000D_
<h1>Some text to enable scrolling</h1>_x000D_
<h1>Some text to enable scrolling</h1>_x000D_
</div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
This usually means that something is trying to access the @property "givenName".
If you were doing something with Interface Builder(IB)
, the usual cause is that you either:
First of all, why is the map a HashMap<String, ArrayList<String>>
and not a HashMap<String, List<String>>
? Is there some reason why the value must be a specific implementation of interface List
(ArrayList
in this case)?
Arrays.asList
does not return a java.util.ArrayList
, so you can't assign the return value of Arrays.asList
to a variable of type ArrayList
.
Instead of:
allWords = Arrays.asList(strTemp.toLowerCase().split("\\s+"));
Try this:
allWords.addAll(Arrays.asList(strTemp.toLowerCase().split("\\s+")));
I've found a solution through configuring the Spring container, but it's still not exactly what I wanted.
I rolled back to Spring 3.0.5, removed and in it's place I changed my config file to:
<bean
class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<bean
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="objectMapper" ref="jacksonObjectMapper" />
</bean>
</list>
</property>
</bean>
<bean id="jacksonObjectMapper" class="org.codehaus.jackson.map.ObjectMapper" />
<bean id="jacksonSerializationConfig" class="org.codehaus.jackson.map.SerializationConfig"
factory-bean="jacksonObjectMapper" factory-method="getSerializationConfig" />
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="targetObject" ref="jacksonSerializationConfig" />
<property name="targetMethod" value="setSerializationInclusion" />
<property name="arguments">
<list>
<value type="org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion">NON_NULL</value>
</list>
</property>
</bean>
This is of course similar to responses given in other questions e.g.
configuring the jacksonObjectMapper not working in spring mvc 3
The important thing to note is that mvc:annotation-driven and AnnotationMethodHandlerAdapter cannot be used in the same context.
I'm still unable to get it working with Spring 3.1 and mvc:annotation-driven though. A solution that uses mvc:annotation-driven and all the benefits that accompany it would be far better I think. If anyone could show me how to do this, that would be great.
It's because Arrays.asList(array)
return List<int[]>
. array
argument is treated as one value you want to wrap (you get list of arrays of ints), not as vararg.
Note that it does work with object types (not primitives):
public boolean contains(final String[] array, final String key) {
return Arrays.asList(array).contains(key);
}
or even:
public <T> boolean contains(final T[] array, final T key) {
return Arrays.asList(array).contains(key);
}
But you cannot have List<int>
and autoboxing is not working here.
1.Check
build settings -> Search Path -> User Header Search Paths ->
2.Check import style(KEY POINT),
if your's podfile
have set
use_frameworks!
In yours File-Bridging-Header.h
,the formatter should like this
#import "MBProgressHUD.h"
else should be below
#import <MBProgressHUD.h>
3.That must be work! trust me
In this code you just need to call this in your button click.
private void list_paired_Devices() {
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
ArrayList<String> devices = new ArrayList<>();
for (BluetoothDevice bt : pairedDevices) {
devices.add(bt.getName() + "\n" + bt.getAddress());
}
ArrayAdapter arrayAdapter = new ArrayAdapter(bluetooth.this, android.R.layout.simple_list_item_1, devices);
emp.setAdapter(arrayAdapter);
}
Using lambda:
strList.stream().map(org.apache.commons.lang3.math.NumberUtils::toInt).collect(Collectors.toList());
Choosing to Project -> Clean should resolve this
Here you can find how to set path to JDK for Glassfish: http://www.devdaily.com/blog/post/java/fixing-glassfish-jdk-path-problem-solved
Check
glassfish\config\asenv.bat
where java path is configured
REM set AS_JAVA=C:\Program Files\Java\jdk1.6.0_04\jre/..
set AS_JAVA=C:\Program Files\Java\jdk1.5.0_16
"there is no problem with tomcat".
I have suffered 4-5 days to resolve the issue (same issue mentioned above). here i was using tomcat 8.5. Finally, the issue got resolved, the issue was with the "Corrupted jar files". You have to delete all your .m2 repository (for me C:\Users\Bandham.m2\repository). den run "mvn clean install" command from your project folder.
happy coding.
Give one UP if it is solved your problem.
just my 2 cents:
final int a[] = {1,2,3};
java.lang.Iterable<Integer> aIterable=new Iterable<Integer>() {
public Iterator<Integer> iterator() {
return new Iterator<Integer>() {
private int pos=0;
public boolean hasNext() {
return a.length>pos;
}
public Integer next() {
return a[pos++];
}
public void remove() {
throw new UnsupportedOperationException("Cannot remove an element of an array.");
}
};
}
};
here it's a simple:
File file = new File(path);
int size = (int) file.length();
byte[] bytes = new byte[size];
try {
BufferedInputStream buf = new BufferedInputStream(new FileInputStream(file));
buf.read(bytes, 0, bytes.length);
buf.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Add permission in manifest.xml:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
I also met this problem when I've made ListView for android app:
Map<String, Object> m;
for(int i=0; i < dates.length; i++){
m = new HashMap<String, Object>();
m.put(ATTR_DATES, dates[i]);
m.put(ATTR_SQUATS, squats[i]);
m.put(ATTR_BP, benchpress[i]);
m.put(ATTR_ROW, row[i]);
data.add(m);
}
The problem was that I've forgotten to use the [i]
index inside the loop
Use OnCommand event of imagebutton. Within it do
<asp:Button id="Button1" Text="Click" CommandName="Something" CommandArgument="your command arg" OnCommand="CommandBtn_Click" runat="server"/>
Code-behind:
void CommandBtn_Click(Object sender, CommandEventArgs e)
{
switch(e.CommandName)
{
case "Something":
// Do your code
break;
default:
break;
}
}
What I understand your question is that you want to fetch an element in an ArrayList
at a specific location.
Suppose your list contains Integers 1,2,3,4,5 and you want to fetch the value 3. Then the following lines of code will work.
ArrayList<Integer> list = new ArrayList<Integer>();
if(list.contains(3)){//check if the list contains the element
list.get(list.indexOf(3));//get the element by passing the index of the element
}
Either ways you could use list.get(list.lastIndexOf(3))
This is works. Kind of.
public static Object[] toArray(List<?> a) {
Object[] arr = new Object[a.size()];
for (int i = 0; i < a.size(); i++)
arr[i] = a.get(i);
return arr;
}
Then the main method.
public static void main(String[] args) {
List<String> list = new ArrayList<String>() {{
add("hello");
add("world");
}};
Object[] arr = toArray(list);
System.out.println(arr[0]);
}
Generally if the installation went smoothly, it will create the desktop icons/folders. Maybe check the installation summary log to see if there's any underlying errors.
It should be located C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log(date stamp)\
Nope, no difference. It's just syntactic sugar. Arrays.asList(..)
creates an additional list.
Instead of using relative paths, you could also use the predefined macros of VS to achieve this.
$(ProjectDir)
points to the directory of your .vcproj
file, $(SolutionDir)
is the directory of the .sln
file.
You get a list of available macros when opening a project, go to
Properties → Configuration Properties → C/C++ → General
and hit the three dots:
In the upcoming dialog, hit Macros to see the macros that are predefined by the Studio (consult MSDN for their meaning):
You can use the Macros by typing $(MACRO_NAME)
(note the $
and the round brackets).
div
's will naturally resize in accordance with their content.
If you set no height on your div, it will expand to contain its conent.
An exception to this rule is when the div contains floating elements. If this is the case you'll need to do a bit extra to ensure that the containing div (wrapper) clears the floats.
Here's some ways to do this:
#wrapper{
overflow:hidden;
}
Or
#wrapper:after
{
content:".";
display:block;
clear:both;
visibility:hidden;
}
Your value:
this.element = $(id);
is a jQuery object, not a pure Canvas element.
To turn it back so you can call getContext()
, call this.element.get(0)
, or better yet store the real element and not the jQuery object:
function canvasLayer(location, id) {
this.width = $(window).width();
this.height = $(window).height();
this.element = document.createElement('canvas');
$(this.element)
.attr('id', id)
.text('unsupported browser')
.attr('width', this.width) // for pixels
.attr('height', this.height)
.width(this.width) // for CSS scaling
.height(this.height)
.appendTo(location);
this.context = this.element.getContext("2d");
}
See running code at http://jsfiddle.net/alnitak/zbaMh/, ideally using the Chrome Javascript Console so you can see the resulting object in the debug output.
Form the Inheritance concept, If some perticular method is not available in the current class it will search for that method in super classes. If available it executes.
It executes
AbstractList<E>
classadd()
method which throwsUnsupportedOperationException
.
When you are converting from an Array to a Collection Obejct. i.e., array-based to collection-based API then it is going to provide you fixed-size collection object, because Array's behaviour is of Fixed size.
java.util.Arrays.asList( T... a )
Souce samples for conformation.
public class Arrays {
public static <T> List<T> asList(T... a) {
return new java.util.Arrays.ArrayList.ArrayList<>(a); // Arrays Inner Class ArrayList
}
//...
private static class ArrayList<E> extends AbstractList<E> implements RandomAccess, java.io.Serializable {
//...
}
}
public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E> {
public void add(int index, E element) {
throw new UnsupportedOperationException();
}
public E set(int index, E element) {
throw new UnsupportedOperationException();
}
public E remove(int index) {
throw new UnsupportedOperationException();
}
public Iterator<E> iterator() {
return new Itr();
}
private class Itr implements Iterator<E> {
//...
}
public ListIterator<E> listIterator() {
return listIterator(0);
}
private class ListItr extends Itr implements ListIterator<E> {
//...
}
}
Form the above Source you may observe that java.util.Arrays.ArrayList
class doesn't @Override add(index, element), set(index, element), remove(index)
. So, From inheritance it executes super AbstractList<E>
class add()
function which throws UnsupportedOperationException
.
As AbstractList<E>
is an abstract class it provides the implementation to iterator() and listIterator()
. So, that we can iterate over the list object.
List<String> list_of_Arrays = Arrays.asList(new String[] { "a", "b" ,"c"});
try {
list_of_Arrays.add("Yashwanth.M");
} catch(java.lang.UnsupportedOperationException e) {
System.out.println("List Interface executes AbstractList add() fucntion which throws UnsupportedOperationException.");
}
System.out.println("Arrays ? List : " + list_of_Arrays);
Iterator<String> iterator = list_of_Arrays.iterator();
while (iterator.hasNext()) System.out.println("Iteration : " + iterator.next() );
ListIterator<String> listIterator = list_of_Arrays.listIterator();
while (listIterator.hasNext()) System.out.println("Forward iteration : " + listIterator.next() );
while(listIterator.hasPrevious()) System.out.println("Backward iteration : " + listIterator.previous());
You can even create Fixed-Size array form Collections class Collections.unmodifiableList(list);
Sample Source:
public class Collections {
public static <T> List<T> unmodifiableList(List<? extends T> list) {
return (list instanceof RandomAccess ?
new UnmodifiableRandomAccessList<>(list) :
new UnmodifiableList<>(list));
}
}
A Collection
— sometimes called a container — is simply an object that groups multiple elements into a single unit. Collections are used to store, retrieve, manipulate, and communicate aggregate data.
@see also
Two options:
Firstly, you can escape it using a backslash -- \(
Alternatively, since it's a single character, you can put it in a character class, where it doesn't need to be escaped -- [(]
When using guava (See doc) there is Iterators.forEnumeration
. Given an Enumeration x
you can do the following:
to get a immutable Set:
ImmutableSet.copyOf(Iterators.forEnumeration(x));
to get a immutable List:
ImmutableList.copyOf(Iterators.forEnumeration(x));
to get a hashSet:
Sets.newHashSet(Iterators.forEnumeration(x));
Take a look at this forum http://htmlcoderhelper.com/why-is-using-a-wild-card-with-a-java-import-statement-bad/. Theres a discussion on how using wildcards can lead to conflicts if you add new classes to the packages and if there are two classes with the same name in different packages where only one of them will be imported.
List<Integer> i = new ArrayList<Integer>(Arrays.asList(0,1,2,3,4,5,6,7,8,9,10));
List<Integer> j = new ArrayList<Integer>();
You need to specify the type for array list or the compiler will give that warning because it cannot identify that you are using the list in a type safe way.
You can try something like this:
List<String> list = new ArrayList<String>(Arrays.asList(array));
public ArrayList(Collection c)
Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator. The ArrayList instance has an initial capacity of 110% the size of the specified collection.
Taken from here
This can be done using the shuffle method:
private List<Integer> getJumbledList() {
List<Integer> myArrayList2 = new ArrayList<Integer>();
myArrayList2.add(8);
myArrayList2.add(4);
myArrayList2.add(9);
Collections.shuffle(myArrayList2);
return myArrayList2;
I don't this the all the above answers are giving the exact solution for comparing two lists of Objects. Most of above approaches can be helpful in following limit of comparisons only - Size comparison - Reference comparison
But if we have same sized lists of objects and different data on the objects level then this comparison approaches won't help.
I think the following approach will work perfectly with overriding equals and hashcode method on the user-defined object.
I used Xstream lib for override equals and hashcode but we can override equals and hashcode by out won logics/comparison too.
Here is the example for your reference
import com.thoughtworks.xstream.XStream;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
class TestClass {
private String name;
private String id;
public void setName(String value) {
this.name = value;
}
public String getName() {
return this.name;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object o) {
XStream xstream = new XStream();
String oxml = xstream.toXML(o);
String myxml = xstream.toXML(this);
return myxml.equals(oxml);
}
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
XStream xstream = new XStream();
String myxml = xstream.toXML(this);
return myxml.hashCode();
}
}
public class XstreamCompareTest {
public static void main(String[] args) throws ParseException {
checkObjectEquals();
}
private static void checkObjectEquals() {
List<TestClass> testList1 = new ArrayList<TestClass>();
TestClass tObj1 = new TestClass();
tObj1.setId("test3");
tObj1.setName("testname3");
testList1.add(tObj1);
TestClass tObj2 = new TestClass();
tObj2.setId("test2");
tObj2.setName("testname2");
testList1.add(tObj2);
testList1.sort((TestClass t1, TestClass t2) -> t1.getId().compareTo(t2.getId()));
List<TestClass> testList2 = new ArrayList<TestClass>();
TestClass tObj3 = new TestClass();
tObj3.setId("test3");
tObj3.setName("testname3");
testList2.add(tObj3);
TestClass tObj4 = new TestClass();
tObj4.setId("test2");
tObj4.setName("testname2");
testList2.add(tObj4);
testList2.sort((TestClass t1, TestClass t2) -> t1.getId().compareTo(t2.getId()));
if (isNotMatch(testList1, testList2)) {
System.out.println("The list are not matched");
} else {
System.out.println("The list are matched");
}
}
private static boolean isNotMatch(List<TestClass> clist1, List<TestClass> clist2) {
return clist1.size() != clist2.size() || !clist1.equals(clist2);
}
}
The most important thing is that you can ignore the fields by Annotation (@XStreamOmitField) if you don't want to include any fields on the equal check of Objects. There are many Annotations like this to configure so have a look deep about the annotations of this lib.
I am sure this answer will save your time to identify the correct approach for comparing two lists of objects :). Please comment if you see any issues on this.
Use CollectionUtils
or ArrayUtils
from stanford-postagger-3.0.jar
import static edu.stanford.nlp.util.ArrayUtils.asSet;
or
import static edu.stanford.nlp.util.CollectionUtils.asSet;
...
String [] array = {"1", "q"};
Set<String> trackIds = asSet(array);
Your and
should be a &&
in the where
clause.
where epl.DepartAirportAfter > sd.UTCDepartureTime
and epl.ArriveAirportBy > sd.UTCArrivalTime
should be
where epl.DepartAirportAfter > sd.UTCDepartureTime
&& epl.ArriveAirportBy > sd.UTCArrivalTime
This one has burned me many times. Arrays.asList
creates an unmodifiable list.
From the Javadoc: Returns a fixed-size list backed by the specified array.
Create a new list with the same content:
newList.addAll(Arrays.asList(newArray));
This will create a little extra garbage, but you will be able to mutate it.
I cannot see any way of making this take a fixed amount of time or space, both will increase with the size of the list.
I would make use of an IdentityHashMap (given that there is not yet an IdentityHashSet) and store each Node into the map. Before a node is stored you would call containsKey on it. If the Node already exists you have a cycle.
ItentityHashMap uses == instead of .equals so that you are checking where the object is in memory rather than if it has the same contents.
I recently had to convert an array to a List. Later on the program filtered the list attempting to remove the data. When you use the Arrays.asList(array) function, you create a fixed size collection: you can neither add nor delete. This entry explains the problem better than I can: Why do I get an UnsupportedOperationException when trying to remove an element from a List?.
In the end, I had to do a "manual" conversion:
List<ListItem> items = new ArrayList<ListItem>();
for (ListItem item: itemsArray) {
items.add(item);
}
I suppose I could have added conversion from an array to a list using an List.addAll(items) operation.
If all you're really doing is removing the second character, regardless of what it is, you can do this:
s/.//2
but your command is building a mv
command and piping it to the shell for execution.
This is no more readable than your version:
find -type f | sed -n 'h;s/.//4;x;s/^/mv /;G;s/\n/ /g;p' | sh
The fourth character is removed because find
is prepending each filename with "./".
Considering that we have Set<String> stringSet
we can use following:
List<String> strList = new ArrayList<>(stringSet);
List<String> strList = Lists.newArrayList(stringSet);
List<String> strList = new ArrayList<>();
CollectionUtils.addAll(strList, stringSet);
List<String> strList = List.copyOf(stringSet);
List<String> strList = stringSet.stream().collect(Collectors.toUnmodifiableList());
import static java.util.stream.Collectors.*;
List<String> stringList1 = stringSet.stream().collect(toList());
As per the doc for the method toList()
There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned; if more control over the returned List is required, use toCollection(Supplier).
So if we need a specific implementation e.g. ArrayList
we can get it this way:
List<String> stringList2 = stringSet.stream().
collect(toCollection(ArrayList::new));
We can make use of Collections::unmodifiableList
method and wrap the list returned in previous examples. We can also write our own custom method as:
class ImmutableCollector {
public static <T> Collector<T, List<T>, List<T>> toImmutableList(Supplier<List<T>> supplier) {
return Collector.of( supplier, List::add, (left, right) -> {
left.addAll(right);
return left;
}, Collections::unmodifiableList);
}
}
And then use it as:
List<String> stringList3 = stringSet.stream()
.collect(ImmutableCollector.toImmutableList(ArrayList::new));
Another possibility is to make use of collectingAndThen
method which allows some final transformation to be done before returning result:
List<String> stringList4 = stringSet.stream().collect(collectingAndThen(
toCollection(ArrayList::new),Collections::unmodifiableList));
One point to note is that the method Collections::unmodifiableList
returns an unmodifiable view of the specified list, as per doc. An unmodifiable view collection is a collection that is unmodifiable and is also a view onto a backing collection. Note that changes to the backing collection might still be possible, and if they occur, they are visible through the unmodifiable view. But the collector method Collectors.unmodifiableList
returns truly immutable list in Java 10.
Taking @chrissr's answer and running with it, this code can be implemented into a nice category on NSUserDefaults
to save and retrieve custom objects:
@interface NSUserDefaults (NSUserDefaultsExtensions)
- (void)saveCustomObject:(id<NSCoding>)object
key:(NSString *)key;
- (id<NSCoding>)loadCustomObjectWithKey:(NSString *)key;
@end
@implementation NSUserDefaults (NSUserDefaultsExtensions)
- (void)saveCustomObject:(id<NSCoding>)object
key:(NSString *)key {
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
[self setObject:encodedObject forKey:key];
[self synchronize];
}
- (id<NSCoding>)loadCustomObjectWithKey:(NSString *)key {
NSData *encodedObject = [self objectForKey:key];
id<NSCoding> object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
return object;
}
@end
Usage:
[[NSUserDefaults standardUserDefaults] saveCustomObject:myObject key:@"myKey"];
I think you have found an example where auto-boxing doesn't really work. Because Arrays.asList(T... a)
has a varargs parameter the compiler apparently considers the int[] and returns a List<int[]>
with a single element in it.
You should change the method into this:
public int getTheNumber(Integer[] factors) {
ArrayList<Integer> f = new ArrayList<Integer>(Arrays.asList(factors));
Collections.sort(f);
return f.get(0) * f.get(f.size() - 1);
}
and possibly add this for compatibility
public int getTheNumber(int[] factors) {
Integer[] factorsInteger = new Integer[factors.length];
for(int ii=0; ii<factors.length; ++ii) {
factorsInteger[ii] = factors[ii];
}
return getTheNumber(factorsInteger);
}
You asked why, and the other answers, imo, don't really say why it's ok to call your super's constructor, but only if it's the very first line. The reason is that you're not really calling the constructor. In C++, the equivalent syntax is
MySubClass: MyClass {
public:
MySubClass(int a, int b): MyClass(a+b)
{
}
};
When you see the initializer clause on its own like that, before the open brace, you know it's special. It runs before any of the rest of the constructor runs and in fact before any of the member variables are initialized. It's not that different for Java. There's a way to get some code (other constructors) to run before the constructor really starts, before any members of the subclass are initialized. And that way is to put the "call" (eg super
) on the very first line. (In a way, that super
or this
is kind of before the first open brace, even though you type it after, because it will be executed before you get to the point that everything is fully constructed.) Any other code after the open brace (like int c = a + b;
) makes the compiler say "oh, ok, no other constructors, we can initialize everything then." So it runs off and initializes your super class and your members and whatnot and then starts executing the code after the open brace.
If, a few lines later, it meets some code saying "oh yeah when you're constructing this object, here are the parameters I want you to pass along to the constructor for the base class", it's too late and it doesn't make any sense. So you get a compiler error.
Make sure that your Spring form mentions the modelAttribute="<Model Name"
.
Example:
@Controller
@RequestMapping("/greeting.html")
public class GreetingController {
@ModelAttribute("greeting")
public Greeting getGreetingObject() {
return new Greeting();
}
/**
* GET
*
*
*/
@RequestMapping(method = RequestMethod.GET)
public String handleRequest() {
return "greeting";
}
/**
* POST
*
*
*/
@RequestMapping(method = RequestMethod.POST)
public ModelAndView processSubmit(@ModelAttribute("greeting") Greeting greeting, BindingResult result){
ModelAndView mv = new ModelAndView();
mv.addObject("greeting", greeting);
return mv;
}
}
In your JSP :
<form:form modelAttribute="greeting" method="POST" action="greeting.html">
Collections.singletonList(messageBody)
If you'd need to have a list of one item!
Collections is from java.util package.
I second Nat's answer, except I would use a loop instead of creating and immediately tossing the implicit List from asList(elements):
static public Set<T> setOf(T ... elements) {
Set set=new HashSet<T>(elements.size());
for(T elm: elements) { set.add(elm); }
return set;
}
Yes. By default, ASP.NET MVC checks first in \Views\[Controller_Dir]\
, but after that, if it doesn't find the view, it checks in \Views\Shared
.
The shared directory is there specifically to share Views across multiple controllers. Just add your View to the Shared subdirectory and you're good to go.
If you do return View("~/Views/Wherever/SomeDir/MyView.aspx")
You can return any View you'd like.
Check out C# 3.0's Collection Initializers.
var list = new List<string> { "test1", "test2", "test3" };
Though I haven't personally tested, I have good reason to believe that the above stated AT COMMAND solution will work for XP, 2000 and Server 2003. Per my and Bryant's testing, we've identified that the same approach does not work with Vista or Windows Server 2008 -- most probably due to added security and the /interactive switch being deprecated.
However, I came across this article which demonstrates the use of PSTools from SysInternals (which was acquired by Microsoft in July, 2006.) I launched the command line via the following and suddenly I was running under the Local Admin Account like magic:
psexec -i -s cmd.exe
PSTools works well. It's a lightweight, well-documented set of tools which provides an appropriate solution to my problem.
Many thanks to those who offered help.
In the iframe: So that means you have to add some code in the iframe page. Simply add this script to your code IN THE IFRAME:
<body onload="parent.alertsize(document.body.scrollHeight);">
In the holding page: In the page holding the iframe (in my case with ID="myiframe") add a small javascript:
<script>
function alertsize(pixels){
pixels+=32;
document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
What happens now is that when the iframe is loaded it triggers a javascript in the parent window, which in this case is the page holding the iframe.
To that JavaScript function it sends how many pixels its (iframe) height is.
The parent window takes the number, adds 32 to it to avoid scrollbars, and sets the iframe height to the new number.
That's it, nothing else is needed.
But if you like to know some more small tricks keep on reading...
DYNAMIC HEIGHT IN THE IFRAME? If you like me like to toggle content the iframe height will change (without the page reloading and triggering the onload). I usually add a very simple toggle script I found online:
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
}
</script>
to that script just add:
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
parent.alertsize(document.body.scrollHeight); // ADD THIS LINE!
}
</script>
How you use the above script is easy:
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
For those that like to just cut and paste and go from there here is the two pages. In my case I had them in the same folder, but it should work cross domain too (I think...)
Complete holding page code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>THE IFRAME HOLDER</title>
<script>
function alertsize(pixels){
pixels+=32;
document.getElementById('myiframe').style.height=pixels+"px";
}
</script>
</head>
<body style="background:silver;">
<iframe src='theiframe.htm' style='width:458px;background:white;' frameborder='0' id="myiframe" scrolling="auto"></iframe>
</body>
</html>
Complete iframe code: (this iframe named "theiframe.htm")
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
<title>IFRAME CONTENT</title>
<script>
function toggle(obj) {
var el = document.getElementById(obj);
if ( el.style.display != 'block' ) el.style.display = 'block';
else el.style.display = 'none';
parent.alertsize(document.body.scrollHeight);
}
</script>
</head>
<body onload="parent.alertsize(document.body.scrollHeight);">
<a href="javascript:toggle('moreheight')">toggle height?</a><br />
<div style="display:none;" id="moreheight">
more height!<br />
more height!<br />
more height!<br />
</div>
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
text<br />
THE END
</body>
</html>
Another reason this could be happening is when you UPGRADE an SDK.
If you simply delete the group, and then drag and drop the new folder to project, the "Library Search Path" would have both the SDKs. To solve, simply delete the old SDK path.
To inspect your localStorage items you may type console.log(localStorage);
in your javascript console (firebug for example or in new FF versions the shipped js console).
You can use this line of Code to get rid of the browsers localStorage contents. Just execute it in your javascript console:
localStorage.clear();
Try the following:
<a asp-controller="Users" asp-action="Index"></a>
(Valid for ASP.NET 5 and MVC 6)
I figured out the answer to the question I had that brought me to this page. Since no one has actually suggested the answer to my question, I thought I'd post it.
class k:
pass
a = k()
k2 = a.__class__
a2 = k2()
At this point, a and a2 are both instances of the same class (class k).
DB::statement("your query")
I used it for add index to column in migration
This gets the size by forcing the array into a scalar context, in which it is evaluated as its size:
print scalar @arr;
This is another way of forcing the array into a scalar context, since it's being assigned to a scalar variable:
my $arrSize = @arr;
This gets the index of the last element in the array, so it's actually the size minus 1 (assuming indexes start at 0, which is adjustable in Perl although doing so is usually a bad idea):
print $#arr;
This last one isn't really good to use for getting the array size. It would be useful if you just want to get the last element of the array:
my $lastElement = $arr[$#arr];
Also, as you can see here on Stack Overflow, this construct isn't handled correctly by most syntax highlighters...
These examples are fine, I wanted to point out that you can achieve the same result using an Intent. The intent opens the Contacts app with the fields you provide already filled in.
It's up to the user to save the newly created contact.
You can read about it here: https://developer.android.com/training/contacts-provider/modify-data.html
Intent contactIntent = new Intent(ContactsContract.Intents.Insert.ACTION);
contactIntent.setType(ContactsContract.RawContacts.CONTENT_TYPE);
contactIntent
.putExtra(ContactsContract.Intents.Insert.NAME, "Contact Name")
.putExtra(ContactsContract.Intents.Insert.PHONE, "5555555555");
startActivityForResult(contactIntent, 1);
startActivityForResult() gives you the opportunity to see the result.
I've noticed the resultCode works on >5.0 devices,
but I have an older Samsung (<5) that always returns RESULT_CANCELLED (0).
Which I understand is the default return if an activity doesn't expect to return anything.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (requestCode == 1)
{
if (resultCode == Activity.RESULT_OK) {
Toast.makeText(this, "Added Contact", Toast.LENGTH_SHORT).show();
}
if (resultCode == Activity.RESULT_CANCELED) {
Toast.makeText(this, "Cancelled Added Contact", Toast.LENGTH_SHORT).show();
}
}
}
You're looking for UPDATE not insert.
UPDATE mytable
SET table_column = 'test';
UPDATE will change the values of existing rows (and can include a WHERE to make it only affect specific rows), whereas INSERT is adding a new row (which makes it look like it changed only the last row, but in effect is adding a new row with that value).
best solution TNX to Drew Chapin and all of you too:
I just want to add that if you don't inheritently know the name of a domain controller, you can get the closest one, pass it's hostname to the -Server argument.
$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
Get-ADUser -Server $dc.HostName[0] `
-Filter { EmailAddress -Like "*Smith_Karla*" } `
-Properties EmailAddress
my script:
$dc = Get-ADDomainController -DomainName example.com -Discover -NextClosestSite
Get-ADUser -Server $dc.HostName[0] ` -Filter { EmailAddress -Like "*Smith_Karla*" } ` -Properties EmailAddress | Export-CSV "C:\Scripts\Email.csv
The <button>
element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:
<button type="button">
to override default submission behaviorevent.preventDefault()
in the onSubmit event to prevent form submissionInsert extra type
attribute to your button markup:
<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>
Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:
$(document).ready(function () {
// Listen to click event on the submit button
$('#button').click(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
In this improvement, we listen to the submit event emitted from the <form>
element:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
$.post("process.php", {
name: name,
email: email
}).complete(function() {
console.log("Success");
});
});
});
.serialize()
to serialize your form, but remember to add name
attributes to your input:The name
attribute is required for .serialize()
to work, as per jQuery's documentation:
For a form element's value to be included in the serialized string, the element must have a name attribute.
<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">
And then in your JS:
$(document).ready(function () {
// Listen to submit event on the <form> itself!
$('#main').submit(function (e) {
// Prevent form submission which refreshes page
e.preventDefault();
// Serialize data
var formData = $(this).serialize();
// Make AJAX request
$.post("process.php", formData).complete(function() {
console.log("Success");
});
});
});
SIMPLE method may not be the best for all cases
<%
if (Session["Utype"].ToString() == "1")
{
%>
<li><a href="../forms/student.aspx"><i class="fa fa-users"></i><span>STUDENT DETAILS</span></a></li>
<li><a href="../forms/UserManage.aspx"><i class="fa fa-user-plus"></i><span>USER MANAGEMENT</span></a></li>
<%
}
else
{
%>
<li><a href="../forms/Package.aspx"><i class="fa fa-object-group"></i><span>PACKAGE</span></a></li>
<%
}
%>
Your code was fine except for the Base 64 encoding bit (which you mentioned was a test), the reason the output may not have made sense is that you were displaying a raw byte array (doing toString() on a byte array returns its internal Java reference, not the String representation of the contents). Here's a version that's just a teeny bit cleaned up and which prints "kyle boon" as the decoded string:
import java.security.MessageDigest;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
public class TripleDESTest {
public static void main(String[] args) throws Exception {
String text = "kyle boon";
byte[] codedtext = new TripleDESTest().encrypt(text);
String decodedtext = new TripleDESTest().decrypt(codedtext);
System.out.println(codedtext); // this is a byte array, you'll just see a reference to an array
System.out.println(decodedtext); // This correctly shows "kyle boon"
}
public byte[] encrypt(String message) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
.getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
final byte[] plainTextBytes = message.getBytes("utf-8");
final byte[] cipherText = cipher.doFinal(plainTextBytes);
// final String encodedCipherText = new sun.misc.BASE64Encoder()
// .encode(cipherText);
return cipherText;
}
public String decrypt(byte[] message) throws Exception {
final MessageDigest md = MessageDigest.getInstance("md5");
final byte[] digestOfPassword = md.digest("HG58YZ3CR9"
.getBytes("utf-8"));
final byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
for (int j = 0, k = 16; j < 8;) {
keyBytes[k++] = keyBytes[j++];
}
final SecretKey key = new SecretKeySpec(keyBytes, "DESede");
final IvParameterSpec iv = new IvParameterSpec(new byte[8]);
final Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
decipher.init(Cipher.DECRYPT_MODE, key, iv);
// final byte[] encData = new
// sun.misc.BASE64Decoder().decodeBuffer(message);
final byte[] plainText = decipher.doFinal(message);
return new String(plainText, "UTF-8");
}
}
This Error hit me after installing RVM correctly. Solution: re-boot Terminal.
Reference RailsCast's RVM Install tutorial.
In a more general case:
N( A union B) = N(A) + N(B) - N(A intersect B)
= COUNTIFS(A1:A196,"Yes",J1:J196,"Agree")+COUNTIFS(A1:A196,"No",J1:J196,"Agree")-A1:A196,"Yes",A1:A196,"No")
I think you can simple call like this, this will give you result value.
this.$route.query.page
Look image $route is object in Vue Instance and you can access with this keyword and next you can select object properties like above one :
Have a look Vue-router document for selecting queries value :
Recently I started using the Mac Pc for android development. When I go to
Android Studio => File => Other setting => Preference for New Projects..
I was not able to find plugin option in the setting page.
Later while clicking option on the toolbar, I clicked on "SDK Manager" it prompted the Settings where the Plugin option was visible and I was able to add the plugins from here.
[
Let us say your jsfunctions.js file has a function "display" and this file is stored in C:/Scripts/Jsfunctions.js
jsfunctions.js
var display = function(name) {
print("Hello, I am a Javascript display function",name);
return "display function return"
}
Now, in your java code, I would recommend you to use Java8 Nashorn. In your java class,
import java.io.FileNotFoundException;
import java.io.FileReader;
import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
class Test {
public void runDisplay() {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
try {
engine.eval(new FileReader("C:/Scripts/Jsfunctions.js"));
Invocable invocable = (Invocable) engine;
Object result;
result = invocable.invokeFunction("display", helloWorld);
System.out.println(result);
System.out.println(result.getClass());
} catch (FileNotFoundException | NoSuchMethodException | ScriptException e) {
e.printStackTrace();
}
}
}
Note: Get the absolute path of your javascript file and replace in FileReader() and run the java code. It should work.
The PyMsgBox module does exactly this. It has message box functions that follow the naming conventions of JavaScript: alert(), confirm(), prompt() and password() (which is prompt() but uses * when you type). These function calls block until the user clicks an OK/Cancel button. It's a cross-platform, pure Python module with no dependencies outside of tkinter.
Install with: pip install PyMsgBox
Sample usage:
import pymsgbox
pymsgbox.alert('This is an alert!', 'Title')
response = pymsgbox.prompt('What is your name?')
Full documentation at http://pymsgbox.readthedocs.org/en/latest/
I updated my Android Studio to 2.3 and it asked me to update my gradle plugin to 3.3 that created issues with my running projects. I've gone through all the Stack solutions and nothing worked for me except this workaround: I changed my distribution url in gradle-wrapper.properties with this one.
distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-all.zip
(permanent link list here : https://services.gradle.org/distributions/)
My project is up and running.It just asked me to update to gradle build tools 25.0.0 which I did so. Everything is fine now :)
note: distributions gradle will change depended upon the version of the android studio.
For InteliJ IDEA 11.0 and above
Goto File --> Settings in the Settings window Editor --> Appearance
and tick Show line numbers check box.
I encountered this problem because the dataset was filtered wrongly and the resultant data frame was empty. Even the following caused the error to show:
ggplot(df, aes(x="", y = y, fill=grp))
because df
was empty.
Find the C file and Makefile implementation in below to meet your requirements
foo.c
main ()
{
int a = MAKE_DEFINE;
printf ("MAKE_DEFINE value:%d\n", a);
}
Makefile
all:
gcc -DMAKE_DEFINE=11 foo.c
Residuum did provide a correct answer to how you should get shell exec to find your script, but in regards to security, there are a couple of points.
I would imagine you don't want your shell script to be in your web root, as it would be visible to anyone with web access to your server.
I would recommend moving the shell script to outside of the webroot
<?php
$tempFolder = '/tmp';
$webRootFolder = '/var/www';
$scriptName = 'myscript.sh';
$moveCommand = "mv $webRootFolder/$scriptName $tempFolder/$scriptName";
$output = shell_exec($moveCommand);
?>
In regards to the:
i added www-data ALL=(ALL) NOPASSWD:ALL to /etc/sudoers works
You can modify this to only cover the specific commands in your script which require sudo. Otherwise, if none of the commands in your sh script require sudo to execute, you don't need to do this at all anyway.
Try running the script as the apache user (use the su command to switch to the apache user) and if you are not prompted for sudo or given permission denied, etc, it'll be fine.
ie:
sudo su apache (or www-data)
cd /var/www
sh ./myscript
Also... what brought me here was that I wanted to run a multi line shell script using commands that are dynamically generated. I wanted all of my commands to run in the same shell, which won't happen using multiple calls to shell_exec(). The answer to that one is to do it like Jenkins - create your dynamically generated multi line of commands, put it in a variable, save it to a file in a temp folder, execute that file (using shell_exec in() php as Jenkins is Java), then do whatever you want with the output, and delete the temp file
... voila
This is how Apple does it for classes like NSString:
In the header file:
enum {
PlayerStateOff,
PlayerStatePlaying,
PlayerStatePaused
};
typedef NSInteger PlayerState;
Refer to Coding Guidelines at http://developer.apple.com/
I'm using this since the begin and it always work. =)
System.setProperty("webdriver.chrome.driver", "C:\\pathto\\my\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("http://www.google.com");
this can be done this way
Overloaded Copy Constructor
/*
* Soumil Nitin SHah
* Github: https://github.com/soumilshah1995
*/
#include <iostream>
using namespace std;
class Matrix{
public:
/*
* Declare the Row and Column
*
*/
int r_size;
int c_size;
int **arr;
public:
/*
* Constructor and Destructor
*/
Matrix(int r_size, int c_size):r_size{r_size},c_size{c_size}
{
arr = new int*[r_size];
// This Creates a 2-D Pointers
for (int i=0 ;i < r_size; i++)
{
arr[i] = new int[c_size];
}
// Initialize all the Vector to 0 initially
for (int row=0; row<r_size; row ++)
{
for (int column=0; column < c_size; column ++)
{
arr[row][column] = 0;
}
}
std::cout << "Constructor -- creating Array Size ::" << r_size << " " << c_size << endl;
}
~Matrix()
{
std::cout << "Destructpr -- Deleting Array Size ::" << r_size <<" " << c_size << endl;
}
Matrix(const Matrix &source):Matrix(source.r_size, source.c_size)
{
for (int row=0; row<source.r_size; row ++)
{
for (int column=0; column < source.c_size; column ++)
{
arr[row][column] = source.arr[row][column];
}
}
cout << "Copy Constructor " << endl;
}
public:
/*
* Operator Overloading
*/
friend std::ostream &operator<<(std::ostream &os, Matrix & rhs)
{
int rowCounter = 0;
int columnCOUNTER = 0;
int globalCounter = 0;
for (int row =0; row < rhs.r_size; row ++)
{
for (int column=0; column < rhs.c_size ; column++)
{
globalCounter = globalCounter + 1;
}
rowCounter = rowCounter + 1;
}
os << "Total There are " << globalCounter << " Elements" << endl;
os << "Array Elements are as follow -------" << endl;
os << "\n";
for (int row =0; row < rhs.r_size; row ++)
{
for (int column=0; column < rhs.c_size ; column++)
{
os << rhs.arr[row][column] << " ";
}
os <<"\n";
}
return os;
}
void operator()(int row, int column , int Data)
{
arr[row][column] = Data;
}
int &operator()(int row, int column)
{
return arr[row][column];
}
Matrix &operator=(Matrix &rhs)
{
cout << "Assingment Operator called " << endl;cout <<"\n";
if(this == &rhs)
{
return *this;
} else
{
delete [] arr;
arr = new int*[r_size];
// This Creates a 2-D Pointers
for (int i=0 ;i < r_size; i++)
{
arr[i] = new int[c_size];
}
// Initialize all the Vector to 0 initially
for (int row=0; row<r_size; row ++)
{
for (int column=0; column < c_size; column ++)
{
arr[row][column] = rhs.arr[row][column];
}
}
return *this;
}
}
};
int main()
{
Matrix m1(3,3); // Initialize Matrix 3x3
cout << m1;cout << "\n";
m1(0,0,1);
m1(0,1,2);
m1(0,2,3);
m1(1,0,4);
m1(1,1,5);
m1(1,2,6);
m1(2,0,7);
m1(2,1,8);
m1(2,2,9);
cout << m1;cout <<"\n"; // print Matrix
cout << "Element at Position (1,2) : " << m1(1,2) << endl;
Matrix m2(3,3);
m2 = m1;
cout << m2;cout <<"\n";
print(m2);
return 0;
}
Have a look at GitHub - gspread.
I found it to be very easy to use and since you can retrieve a whole column by
first_col = worksheet.col_values(1)
and a whole row by
second_row = worksheet.row_values(2)
you can more or less build some basic select ...
where ... = ...
easily.
If you want to give your user all read permissions, you could use:
EXEC sp_addrolemember N'db_datareader', N'your-user-name'
That adds the default db_datareader
role (read permission on all tables) to that user.
There's also a db_datawriter
role - which gives your user all WRITE permissions (INSERT, UPDATE, DELETE) on all tables:
EXEC sp_addrolemember N'db_datawriter', N'your-user-name'
If you need to be more granular, you can use the GRANT
command:
GRANT SELECT, INSERT, UPDATE ON dbo.YourTable TO YourUserName
GRANT SELECT, INSERT ON dbo.YourTable2 TO YourUserName
GRANT SELECT, DELETE ON dbo.YourTable3 TO YourUserName
and so forth - you can granularly give SELECT, INSERT, UPDATE, DELETE permission on specific tables.
This is all very well documented in the MSDN Books Online for SQL Server.
And yes, you can also do it graphically - in SSMS, go to your database, then Security > Users
, right-click on that user you want to give permissions to, then Properties
adn at the bottom you see "Database role memberships" where you can add the user to db roles.
You may try the following if your database does not have any data OR you have another away to restore that data. You will need to know the Ubuntu server root password but not the mysql root password.
It is highly probably that many of us have installed "mysql_secure_installation" as this is a best practice. Navigate to bin directory where mysql_secure_installation exist. It can be found in the /bin directory on Ubuntu systems. By rerunning the installer, you will be prompted about whether to change root database password.
The method is to use another byte along with a bitwise AND to mask out the target bit.
I used convention from my classes here where "0" is the most significant bit and "7" is the least.
public static class ByteExtensions
{
// Assume 0 is the MSB andd 7 is the LSB.
public static bool GetBit(this byte byt, int index)
{
if (index < 0 || index > 7)
throw new ArgumentOutOfRangeException();
int shift = 7 - index;
// Get a single bit in the proper position.
byte bitMask = (byte)(1 << shift);
// Mask out the appropriate bit.
byte masked = (byte)(byt & bitMask);
// If masked != 0, then the masked out bit is 1.
// Otherwise, masked will be 0.
return masked != 0;
}
}
jquery function is most important
<script>
$(function(){
var stickyHeaderTop = $('#stickytypeheader').offset().top;
$(window).scroll(function(){
if( $(window).scrollTop() > stickyHeaderTop ) {
$('#stickytypeheader').css({position: 'fixed', top: '0px'});
$('#sticky').css('display', 'block');
} else {
$('#stickytypeheader').css({position: 'static', top: '0px'});
$('#sticky').css('display', 'none');
}
});
});
</script>
Then use JQuery Lib...
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
Now use HTML
<div id="header">
<p>This text is non sticky</p>
<p>This text is non sticky</p>
<p>This text is non sticky</p>
<p>This text is non sticky</p>
</div>
<div id="stickytypeheader">
<table width="100%">
<tr>
<td><a href="http://growthpages.com/">Growth pages</a></td>
<td><a href="http://google.com/">Google</a></td>
<td><a href="http://yahoo.com/">Yahoo</a></td>
<td><a href="http://www.bing.com/">Bing</a></td>
<td><a href="#">Visitor</a></td>
</tr>
</table>
</div>
<div id="content">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna
aliqua. Ut enim ad minim veniam, quis nostrud exercitation
ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis
aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt
mollit anim id est laborum.</p>
</div>
Check DEMO HERE
Initialize empty frame with column names
import pandas as pd
col_names = ['A', 'B', 'C']
my_df = pd.DataFrame(columns = col_names)
my_df
Add a new record to a frame
my_df.loc[len(my_df)] = [2, 4, 5]
You also might want to pass a dictionary:
my_dic = {'A':2, 'B':4, 'C':5}
my_df.loc[len(my_df)] = my_dic
Append another frame to your existing frame
col_names = ['A', 'B', 'C']
my_df2 = pd.DataFrame(columns = col_names)
my_df = my_df.append(my_df2)
Performance considerations
If you are adding rows inside a loop consider performance issues. For around the first 1000 records "my_df.loc" performance is better, but it gradually becomes slower by increasing the number of records in the loop.
If you plan to do thins inside a big loop (say 10M? records or so), you are better off using a mixture of these two; fill a dataframe with iloc until the size gets around 1000, then append it to the original dataframe, and empty the temp dataframe. This would boost your performance by around 10 times.
I'd look into using the System.TimeZoneInfo class if you are in .NET 3.5. See http://msdn.microsoft.com/en-us/library/system.timezoneinfo.aspx. This should take into account the daylight savings changes correctly.
// Coordinated Universal Time string from
// DateTime.Now.ToUniversalTime().ToString("u");
string date = "2009-02-25 16:13:00Z";
// Local .NET timeZone.
DateTime localDateTime = DateTime.Parse(date);
DateTime utcDateTime = localDateTime.ToUniversalTime();
// ID from:
// "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows NT\CurrentVersion\Time Zone"
// See http://msdn.microsoft.com/en-us/library/system.timezoneinfo.id.aspx
string nzTimeZoneKey = "New Zealand Standard Time";
TimeZoneInfo nzTimeZone = TimeZoneInfo.FindSystemTimeZoneById(nzTimeZoneKey);
DateTime nzDateTime = TimeZoneInfo.ConvertTimeFromUtc(utcDateTime, nzTimeZone);
Rob Heiser suggested checking out your java version by using 'java -version'.
That will identify the Java version that will be commonly found and used. Doing dev work, you can often have more than one version installed (I currently have 2 JREs - 6 and 7 - and may soon have 8).
http://www.coderanch.com/t/453224/java/java/java-version-work-setting-path
java -version will look for java.exe in the System32 directory in Windows. That's where a JRE will install it.
I'm assuming that IE either simply looks for java and that automatically starts checking in System32 or it'll use the path and hit whichever java.exe comes first in your path (if you tamper with the path to point to another JRE).
Also from what SLaks said, I would disagree with one thing. There is likely slightly better performance out of 64-it IE in 64-bit environments. So there is some reason for using it.
SELECT ColumnA, COUNT( * )
FROM Table
GROUP BY ColumnA
HAVING COUNT( * ) > 1
Here is another take on the same thing which worked better for the situation I was in. It solves the problem where you have more than one remote, would like to clone all branches in remote source
to remote destination
but without having to check them all out beforehand.
(The problem I had with Daniel's solution was that it would refuse to checkout a tracking branch from the source
remote if I had previously checked it out already, ie, it would not update my local branch before the push)
git push destination +refs/remotes/source/*:refs/heads/*
Note: If you are not using direct CLI, you must escape the asterisks:
git push destination +refs/remotes/source/\*:refs/heads/\*
this will push all branches in remote source
to a head branch in destination
, possibly doing a non-fast-forward push. You still have to push tags separately.
I know this is old, but I just wanted to point out for NETMF (.Net MicroFramework), you can easily do this:
string response = Resources.GetString(Resources.StringResources.MyFileName);
Since NETMF doesn't have GetManifestResourceStream
In Ubuntu /etc/init.d has been replaced by /usr/lib/systemd. Scripts can still be started and stoped by 'service'. But the primary command is now 'systemctl'. The chkconfig command was left behind, and now you do this with systemctl.
So instead of:
chkconfig enable apache2
You should look for the service name, and then enable it
systemctl status apache2
systemctl enable apache2.service
Systemd has become more friendly about figuring out if you have a systemd script, or an /etc/init.d script, and doing the right thing.
Execute the GetEventIdsByEventDate() method and save the results in a variable, and then you can use the .Contains() method
This is what I finally came up with, which works great!
{=SUM(IF((ISTEXT('Worksheet Name!A:A))+(ISTEXT('CCSA Associates'!E:E)),1,0))-1}
Don't forget since it is an array to type the formula above without the "{}", and to CTRL + SHIFT + ENTER instead of just ENTER for the "{}" to appear and for it to be entered properly.
If I understand the question, you may interested in this example in the Matplotlib gallery.
Yann's comment above provides a similar example.
Edit - Link above fixed. Corresponding code copied from the Matplotlib gallery:
from mpl_toolkits.axes_grid1 import host_subplot
import mpl_toolkits.axisartist as AA
import matplotlib.pyplot as plt
host = host_subplot(111, axes_class=AA.Axes)
plt.subplots_adjust(right=0.75)
par1 = host.twinx()
par2 = host.twinx()
offset = 60
new_fixed_axis = par2.get_grid_helper().new_fixed_axis
par2.axis["right"] = new_fixed_axis(loc="right", axes=par2,
offset=(offset, 0))
par2.axis["right"].toggle(all=True)
host.set_xlim(0, 2)
host.set_ylim(0, 2)
host.set_xlabel("Distance")
host.set_ylabel("Density")
par1.set_ylabel("Temperature")
par2.set_ylabel("Velocity")
p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature")
p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity")
par1.set_ylim(0, 4)
par2.set_ylim(1, 65)
host.legend()
host.axis["left"].label.set_color(p1.get_color())
par1.axis["right"].label.set_color(p2.get_color())
par2.axis["right"].label.set_color(p3.get_color())
plt.draw()
plt.show()
#plt.savefig("Test")
I've tested it using the following code:
$emails = ['[email protected]', '[email protected]','[email protected]'];
Mail::send('emails.welcome', [], function($message) use ($emails)
{
$message->to($emails)->subject('This is test e-mail');
});
var_dump( Mail:: failures());
exit;
Result - empty array for failures.
But of course you need to configure your app/config/mail.php
properly. So first make sure you can send e-mail just to one user and then test your code with many users.
Moreover using this simple code none of my e-mails were delivered to free mail accounts, I got only emails to inboxes that I have on my paid hosting accounts, so probably they were caught by some filters (it's maybe simple topic/content issue but I mentioned it just in case you haven't received some of e-mails) .
Template for a simple but counted loop:
set loopcount=[Number of times]
:loop
[Commands you want to repeat]
set /a loopcount=loopcount-1
if %loopcount%==0 goto exitloop
goto loop
:exitloop
Example: Say "Hello World!" 5 times:
@echo off
set loopcount=5
:loop
echo Hello World!
set /a loopcount=loopcount-1
if %loopcount%==0 goto exitloop
goto loop
:exitloop
pause
This example will output:
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Press any key to continue . . .
I had the same issue and got the 'other element would receive the click' error for a displayed, visible element. I found no other solution that to trigger the click with a javascript.
I replaced:
WebElement el = webDriver.findElement(By.id("undo-alert"));
WebElement closeButton = el.findElement(By.className("close"));
// The following throws 'Element is not clickable at point ... Other element
// would receive the click'
closeButton.click();
with:
((JavascriptExecutor) webDriver).executeScript(
"$('#undo-alert').find('.close').click();"
);
and it all worked out fine
The understanding I have about mipmap is more or less like this:
When an image needs to be drawn, given we have different screen sizes are resolutions, some scaling will have to take part.
If you have an image that is ok for a low end cell phone, when you scale it to the size of a 10" tablet you have to "invent" pixels that don't actually exist. This is done with some interpolation algorithm. The more amount of pixels that have to be invented, the longer the process takes and quality starts to fail. Best quality is obtained with more complex algorithms that take longer (average of surrounding pixles vs copy the nearest pixel for example).
To reduce the number of pixels that have to be invented, with mipmap you provide different sizes/rsolutions of the same image, and the system will choose the nearest image to the resolution that has to be rendered and do the scaling from there. This should reduce the number of invented pixels saving resources to be used in calculating these pixels to provide a good quality image.
I read about this in an article explaining a performance problem in libgdx when scaling images:
[^a-zA-Z0-9]
is a character class matches any non-alphanumeric characters.
Alternatively, [^\w\d]
does the same thing.
Usage:
string regExp = "[^\w\d]";
string tmp = Regex.Replace(n, regExp, "");
I realize this is an old question, but I use a much simpler way. Typically I just grab the list that I need, either by query or copying an existing list or whatever, then remove the duplicates. We will assume for this answer that your list is already in column C, row 4, as per the original question. This method works for whatever size list you have and you can select header yes or no.
Dim rng as range
Range("C4").Select
Set rng = Range(Selection, Selection.End(xlDown))
rng.RemoveDuplicates Columns:=1, Header:=xlYes
first you don't need to add the classRules
explicitly since required
is automatically detected by the jquery.validate plugin.
so you can use this code :
$('#form').submit(function (e) {
e.preventDefault();
var $form = $(this);
// check if the input is valid using a 'valid' property
if (!$form.valid) return false;
$.ajax({
type: 'POST',
url: 'add.php',
data: $('#form').serialize(),
success: function (response) {
$('#answers').html(response);
},
});
});
Tested for PHP 5.3
As i see here, Anonymous Function could help you: http://php.net/manual/en/functions.anonymous.php
What you'll probably need and it's not said before it's how to pass a function without wrapping it inside a on-the-fly-created function. As you'll see later, you'll need to pass the function's name written in a string as a parameter, check its "callability" and then call it.
The function to do check:
if( is_callable( $string_function_name ) ){
/*perform the call*/
}
Then, to call it, use this piece of code (if you need parameters also, put them on an array), seen at : http://php.net/manual/en/function.call-user-func.php
call_user_func_array( "string_holding_the_name_of_your_function", $arrayOfParameters );
as it follows (in a similar, parameterless, way):
function funToBeCalled(){
print("----------------------i'm here");
}
function wrapCaller($fun){
if( is_callable($fun)){
print("called");
call_user_func($fun);
}else{
print($fun." not called");
}
}
wrapCaller("funToBeCalled");
wrapCaller("cannot call me");
Here's a class explaining how to do something similar :
<?php
class HolderValuesOrFunctionsAsString{
private $functions = array();
private $vars = array();
function __set($name,$data){
if(is_callable($data))
$this->functions[$name] = $data;
else
$this->vars[$name] = $data;
}
function __get($name){
$t = $this->vars[$name];
if(isset($t))
return $t;
else{
$t = $this->$functions[$name];
if( isset($t))
return $t;
}
}
function __call($method,$args=null){
$fun = $this->functions[$method];
if(isset($fun)){
call_user_func_array($fun,$args);
} else {
// error out
print("ERROR: Funciton not found: ". $method);
}
}
}
?>
and an example of usage
<?php
/*create a sample function*/
function sayHello($some = "all"){
?>
<br>hello to <?=$some?><br>
<?php
}
$obj = new HolderValuesOrFunctionsAsString;
/*do the assignement*/
$obj->justPrintSomething = 'sayHello'; /*note that the given
"sayHello" it's a string ! */
/*now call it*/
$obj->justPrintSomething(); /*will print: "hello to all" and
a break-line, for html purpose*/
/*if the string assigned is not denoting a defined method
, it's treat as a simple value*/
$obj->justPrintSomething = 'thisFunctionJustNotExistsLOL';
echo $obj->justPrintSomething; /*what do you expect to print?
just that string*/
/*N.B.: "justPrintSomething" is treated as a variable now!
as the __set 's override specify"*/
/*after the assignement, the what is the function's destiny assigned before ? It still works, because it's held on a different array*/
$obj->justPrintSomething("Jack Sparrow");
/*You can use that "variable", ie "justPrintSomething", in both ways !! so you can call "justPrintSomething" passing itself as a parameter*/
$obj->justPrintSomething( $obj->justPrintSomething );
/*prints: "hello to thisFunctionJustNotExistsLOL" and a break-line*/
/*in fact, "justPrintSomething" it's a name used to identify both
a value (into the dictionary of values) or a function-name
(into the dictionary of functions)*/
?>
string = "firstName:name1, lastName:last1";
This will work:
var fields = string.split(', '),
fieldObject = {};
if( typeof fields === 'object') ){
fields.each(function(field) {
var c = property.split(':');
fieldObject[c[0]] = c[1];
});
}
However it's not efficient. What happens when you have something like this:
string = "firstName:name1, lastName:last1, profileUrl:http://localhost/site/profile/1";
split()
will split 'http'. So i suggest you use a special delimiter like pipe
string = "firstName|name1, lastName|last1";
var fields = string.split(', '),
fieldObject = {};
if( typeof fields === 'object') ){
fields.each(function(field) {
var c = property.split('|');
fieldObject[c[0]] = c[1];
});
}
If you want to use each of the lines of the file as command-line params for your application you can use the xargs command.
xargs -a <params_file> <command>
A params file with:
a
b
c
d
and the file tr.py:
import sys
print sys.argv
The execution of
xargs -a params ./tr.py
gives the result:
['./tr.py', 'a', 'b', 'c', 'd']
Well u have used Pojo Entity so u can do this. u need to get object of that and have to set data.
myList.get(3).setEmail("email");
that way u can do that. or u can set other param too.
Make sure the format of the cell is set to 'general' not 'text' (right click on cell and choose format cell)
Formula should look something like this:
=1+2
Another simple solution for this case using jQuery. Keep in mind it's not a good practice to use inline javascript.
I've added IDs to html on the total price and on the buttons. Here is the jQuery.
$('#two').click(function(){
$('#count').val('2');
$('#total').text('Product price: $1000');
});
$('#four').click(function(){
$('#count').val('4');
$('#total').text('Product price: $2000');
});
That's because it's not a textarea any longer. It's replaced with an iframe (and whatnot), and the serialize function only gets data from form fields.
Add a hidden field to the form:
<input type="hidden" id="question_html" name="question_html" />
Before posting the form, get the data from the editor and put in the hidden field:
$('#question_html').val(tinyMCE.get('question_text').getContent());
(The editor would of course take care of this itself if you posted the form normally, but as you are scraping the form and sending the data yourself without using the form, the onsubmit event on the form is never triggered.)
For code readability reasons I believe returning true/false should:
return
followed by another keyword (true
or false
)My solution is return $(true)
or return $(false)
as shown:
is_directory()
{
if [ -d "${1}" ]; then
return $(true)
else
return $(false)
fi
}
Not sure why, but you can wrap DateTime.ToUniversalTime in a try / catch and achieve the same result in more code.
Good luck.
<form>
cannot go inside <p>
, no. The browser is going to abruptly close your <p>
element when it hits the opening <form>
tag as it tries to handle what it thinks is an unclosed paragraph element:
<p>Read this sentence
</p><form style='display:inline;'>
Add this in your application.properties
file
server.port= 8080
create table demotable(group_id number, name varchar2(100));
insert into demotable values(1,'David');
insert into demotable values(1,'John');
insert into demotable values(1,'Alan');
insert into demotable values(1,'David');
insert into demotable values(2,'Julie');
insert into demotable values(2,'Charles');
commit;
select group_id,
(select listagg(column_value, ',') within group (order by column_value) from table(coll_names)) as names
from (
select group_id, collect(distinct name) as coll_names
from demotable
group by group_id
)
GROUP_ID NAMES
1 Alan,David,John
2 Charles,Julie
The answers above are good, but insufficient if you have more than 1 project (.csproj) in the same folder.
First, you easily add the "PackageReference" tag to the .csproj file (either manually, by using the nuget package manager or by using the dotnet add package command).
But then, you need to run the "restore" command manually so you can tell it which project you are trying to restore (if I just clicked the restore button that popped up, nothing happened). You can do that by running:
dotnet restore Project-File-Name.csproj
And that installs the package
malloc
is for allocating memory on the free-store. If you have a string literal that you do not want to modify the following is ok:
char *literal = "foo";
However, if you want to be able to modify it, use it as a buffer to hold a line of input and so on, use malloc
:
char *buf = (char*) malloc(BUFSIZE); /* define BUFSIZE before */
// ...
free(buf);
Write a file
When saving a file to internal storage, you can acquire the appropriate directory as a File by calling one of two methods:
getFilesDir()
Returns a File representing an internal directory for your app.
getCacheDir()
Returns a File representing an internal directory for your
app's temporary cache files.
Be sure to delete each file once it is no longer needed and implement a reasonable
size limit for the amount of memory you use at any given time, such as 1MB.
Caution: If the system runs low on storage, it may delete your cache files without warning.
public static class HelperExtensions
{
//Convert Image to byte[] array:
public static byte[] ToByteArray(this Image imageIn)
{
var ms = new MemoryStream();
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms.ToArray();
}
//Convert byte[] array to Image:
public static Image ToImage(this byte[] byteArrayIn)
{
var ms = new MemoryStream(byteArrayIn);
var returnImage = Image.FromStream(ms);
return returnImage;
}
}
RecyclerView's Adapter doesn't come with many methods otherwise available in ListView's adapter. But your swap can be implemented quite simply as:
class MyRecyclerAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
List<Data> data;
...
public void swap(ArrayList<Data> datas)
{
data.clear();
data.addAll(datas);
notifyDataSetChanged();
}
}
Also there is a difference between
list.clear();
list.add(data);
and
list = newList;
The first is reusing the same list object. The other is dereferencing and referencing the list. The old list object which can no longer be reached will be garbage collected but not without first piling up heap memory. This would be the same as initializing new adapter everytime you want to swap data.
<select name="FakeName" id="Fake-ID" aria-required="true" required> <?php $options=nl2br(file_get_contents("employees.txt")); $options=explode("<br />",$options); foreach ($options as $item_array) { echo "<option value='".$item_array"'>".$item_array"</option>"; } ?> </select>
Simple way is to get the process id of mongodb and kill it. Please note DO NOT USE kill -9 pid for this as it may cause damage to the database.
so, 1. get the pid of mongodb
$ pgrep mongo
you will get pid of mongo, Now
$ kill
You may use kill -15 as well
I had this error when i was using the azure storage as a static website, the js files that are copied had the content type as text/plain; charset=utf-8
and i changed the content type to application/javascript
It started working.
SELECT * from SOME_TABLE where NAME like '%[^A-Z]%'
Or some other expression instead of A-Z
I have jus implement this library:https://github.com/jose78/go-collection. This is an example about how to use the Foreach loop:
package main
import (
"fmt"
col "github.com/jose78/go-collection/collections"
)
type user struct {
name string
age int
id int
}
func main() {
newList := col.ListType{user{"Alvaro", 6, 1}, user{"Sofia", 3, 2}}
newList = append(newList, user{"Mon", 0, 3})
newList.Foreach(simpleLoop)
if err := newList.Foreach(simpleLoopWithError); err != nil{
fmt.Printf("This error >>> %v <<< was produced", err )
}
}
var simpleLoop col.FnForeachList = func(mapper interface{}, index int) {
fmt.Printf("%d.- item:%v\n", index, mapper)
}
var simpleLoopWithError col.FnForeachList = func(mapper interface{}, index int) {
if index > 1{
panic(fmt.Sprintf("Error produced with index == %d\n", index))
}
fmt.Printf("%d.- item:%v\n", index, mapper)
}
The result of this execution should be:
0.- item:{Alvaro 6 1}
1.- item:{Sofia 3 2}
2.- item:{Mon 0 3}
0.- item:{Alvaro 6 1}
1.- item:{Sofia 3 2}
Recovered in f Error produced with index == 2
ERROR: Error produced with index == 2
This error >>> Error produced with index == 2
<<< was produced
INADDR_ANY
instructs listening socket to bind to all available interfaces. It's the same as trying to bind to inet_addr("0.0.0.0")
.
For completeness I'll also mention that there is also IN6ADDR_ANY_INIT for IPv6 and it's the same as trying to bind to ::
address for IPv6 socket.
#include <netinet/in.h>
struct in6_addr addr = IN6ADDR_ANY_INIT;
Also, note that when you bind IPv6 socket to to IN6ADDR_ANY_INIT
your socket will bind to all IPv6 interfaces, and should be able to accept connections from IPv4 clients as well (though IPv6-mapped addresses).
For those who are dynamically applying classes (i.e. active): Simply add a "div" tag inside the "a" tag with an href attribute:
<a href='your-link'>
<div>
<span>your link name</span>
</div>
</a>
Tested with Angular2 RC2
I tried a code-snippet similar to yours and it works for me ;) see [(ngModel)] = "str" in my template If you push the button, the console logs the current content of the textarea-field. Hope it helps
textarea-component.ts
import {Component} from '@angular/core';
@Component({
selector: 'textarea-comp',
template: `
<textarea cols="30" rows="4" [(ngModel)] = "str"></textarea>
<p><button (click)="pushMe()">pushMeToLog</button></p>
`
})
export class TextAreaComponent {
str: string;
pushMe() {
console.log( "TextAreaComponent::str: " + this.str);
}
}
If you use .Net 4.5 you can also use standard .Net json serializer:
using System.Runtime.Serialization.Json;
...
Stream jsonSource = ...; // serializer will read data stream
var s = new DataContractJsonSerializer(typeof(string[][]));
var j = (string[][])s.ReadObject(jsonSource);
In .Net 4.5 and older you can use JavaScriptSerializer class:
using System.Web.Script.Serialization;
...
JavaScriptSerializer serializer = new JavaScriptSerializer();
string[][] list = serializer.Deserialize<string[][]>(json);
Previously provided solutions are not that optimal. The kubernetes team itself has provided a solution a while ago, called stern.
stern app1
It is also matching regular expressions and does tail and -f (follow) by default. A nice benefit is, that it shows you the pod which generated the log as well.
app1-12381266dad-3233c foobar log
app1-99348234asd-959cc foobar log2
Grab the go-binary for linux or install via brew for OSX.
https://kubernetes.io/blog/2016/10/tail-kubernetes-with-stern/
Dependency required for jersey restful service and Tomcat is the server. where ${jersey.version} is 2.29.1
<dependency>
<groupId>javax.enterprise</groupId>
<artifactId>cdi-api</artifactId>
<version>2.0.SP1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>${jersey.version}</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
<version>${jersey.version}</version>
</dependency>
The basic code will be as follows:
@RequestScoped
@Path("test")
public class RESTEndpoint {
@GET
public String getMessage() {
If you're currently on the branch you want to rename:
git branch -m new_name
Or else:
git branch -m old_name new_name
You can check with:
git branch -a
As you can see, only the local name changed Now, to change the name also in the remote you must do:
git push origin :old_name
This removes the branch, then upload it with the new name:
git push origin new_name
import re
if re.search('(?i)Mandy Pande:', line):
...
Recycler View in Horizontal Dynamic.
Recycler View Implementation
RecyclerView musicList = findViewById(R.id.MusicList);
// RecyclerView musiclist = findViewById(R.id.MusicList1);
// RecyclerView musicLIST = findViewById(R.id.MusicList2);
LinearLayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
musicList.setLayoutManager(layoutManager);
String[] names = {"RAP", "CH SHB", "Faheem", "Anum", "Shoaib", "Laiba", "Zoki", "Komal", "Sultan","Mansoob Gull"};
musicList.setAdapter(new ProgrammingAdapter(names));'
Adapter class for recycler view, in which there is is a view holder for holding view of that recycler
public class ProgrammingAdapter
extendsRecyclerView.Adapter<ProgrammingAdapter.programmingViewHolder> {
private String[] data;
public ProgrammingAdapter(String[] data)
{
this.data = data;
}
@Override
public programmingViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.list_item_layout, parent, false);
return new programmingViewHolder(view);
}
@Override
public void onBindViewHolder(@NonNull programmingViewHolder holder, int position) {
String title = data[position];
holder.textV.setText(title);
}
@Override
public int getItemCount() {
return data.length;
}
public class programmingViewHolder extends RecyclerView.ViewHolder{
ImageView img;
TextView textV;
public programmingViewHolder(View itemView) {
super(itemView);
img = itemView.findViewById(R.id.img);
textV = itemView.findViewById(R.id.textt);
}
}
This is an older thread, but I just searched and found it. I am new to using Web Developer Tools: primarily Firefox Developer Tools (Firefox v.51), but also Chrome DevTools (Chrome v.56)].
I wasn't able to run functions from the Developer Tools console, but I then found this
https://developer.mozilla.org/en-US/docs/Tools/Scratchpad
and I was able to add code to the Scratchpad, highlight and run a function, outputted to console per the attched screenshot.
I also added the Chrome "Scratch JS" extension: it looks like it provides the same functionality as the Scratchpad in Firefox Developer Tools (screenshot below).
https://chrome.google.com/webstore/detail/scratch-js/alploljligeomonipppgaahpkenfnfkn
Image 1 (Firefox): http://imgur.com/a/ofkOp
Image 2 (Chrome): http://imgur.com/a/dLnRX
My two cents showing how to use the Google Charts API to solve this problem.
first, create a class to hold your parameters:
public class PkRk {
public int pk { get; set; }
public int rk { get; set; }
}
then, use the Html.Action
passing the parameters:
Html.Action("PkRkAction", new { pkrk = new PkRk { pk=400, rk=500} })
and use in Controller:
public ActionResult PkRkAction(PkRk pkrk) {
return PartialView(pkrk);
}
Jenkins creates a user Jenkins on the system. The ssh key must be generated for the Jenkins user. Here are the steps:
sudo su jenkins -s /bin/bash
cd ~
mkdir .ssh // may already exist
cd .ssh
ssh-keygen
Now you can create a Jenkins credential using the SSH key On Jenkins dashboard Add Credentials
select this option
Private Key: From the Jenkins master ~/.ssh
LIBS = -lkernel32 -luser32 -lgdi32 -lopengl32
CFLAGS = -Wall
# Should be equivalent to your list of C files, if you don't build selectively
SRC=$(wildcard *.c)
test: $(SRC)
gcc -o $@ $^ $(CFLAGS) $(LIBS)
New lists can be made by simply adding lists together.
list1 = ['value1','value2','value3']
list2 = ['value0']
newlist=list2+list1
print(newlist)
If you're looking a way to convert autogenerated comment from Add Documentation
action (available under cmd-shift-/) you might find it useful too:
function run(input, parameters) {
var lines = input[0].split('\n');
var line1 = lines[0];
var prefixRe = /^( *)\/\/\/?(.*)/gm;
var prefix = prefixRe.test(line1) ? line1.replace(prefixRe, "$1") : ""
var result = prefix + "/*\n";
lines.forEach(function(line) {
result += prefix + line.replace(prefixRe, "$2") + '\n';
});
result += '\n' + prefix + ' */';
return result;
}
Rest the same as in @Charles Robertson answer:
The link mentioned by Subimage was right on the money for me. It suggested changing the virtual host tag, ie, from <VirtualHost myserver.example.com:443>
to <VirtualHost _default_:443>
Error code:
ssl_error_rx_record_too_long
This usually means the implementation of SSL on your server is not correct. The error is usually caused by a server side problem which the server administrator will need to investigate.
Below are some things we recommend trying.
Ensure that port 443 is open and enabled on your server. This is the standard port for https communications.
If SSL is using a non-standard port then FireFox 3 can sometimes give this error. Ensure SSL is running on port 443.
If using Apache2 check that you are using port 443 for SSL. This can be done by setting the ports.conf file as follows
Listen 80 Listen 443 https
Make sure you do not have more than one SSL certificate sharing the same IP. Please ensure that all SSL certificates utilise their own dedicated IP.
If using Apache2 check your vhost config. Some users have reported changing
<VirtualHost>
to_default_
resolved the error.
That fixed my problem. It's rare that I google an error message and get the first hit with the right answer! :-)
In addition to the above, these are some other solutions that other folks have found were causing the issue:
Make sure that your SSL certificate is not expired
Try to specify the Cipher:
SSLCipherSuite ALL:!aNULL:!ADH:!eNULL:!LOW:!EXP:RC4+RSA:+HIGH:+MEDIUM:+SSLv3
The command palette
tells you the colours and their order when col = somefactor
. It can also be used to set the colours as well.
palette()
[1] "black" "red" "green3" "blue" "cyan" "magenta" "yellow" "gray"
In order to see that in your graph you could use a legend.
legend('topright', legend = levels(iris$Species), col = 1:3, cex = 0.8, pch = 1)
You'll notice that I only specified the new colours with 3 numbers. This will work like using a factor. I could have used the factor originally used to colour the points as well. This would make everything logically flow together... but I just wanted to show you can use a variety of things.
You could also be specific about the colours. Try ?rainbow
for starters and go from there. You can specify your own or have R do it for you. As long as you use the same method for each you're OK.
As Below Doc specify
dividend % divisor
Returns the remainder of one number divided by another.
https://docs.microsoft.com/en-us/sql/t-sql/language-elements/modulo-transact-sql#syntax
For Example
13 % 2 return 1
Next part is <>
which denotes Not equals.
Therefor what your statement mean is Remainder of ID when it divided by 2 not equals to 0
Be careful because this is not going to work in Oracle database. Same Expression will be like below.
MOD(ID, 2) <> 0
I was just going to do this as a comment on the accepted answer but it got too funky (I hate not having line breaks)
ah, so the difference is that in general, Map has certain methods associated with it. but there are different ways or creating a map, such as a HashMap, and these different ways provide unique methods that not all maps have.
Exactly--and you always want to use the most general interface you possibly can. Consider ArrayList vs LinkedList. Huge difference in how you use them, but if you use "List" you can switch between them readily.
In fact, you can replace the right-hand side of the initializer with a more dynamic statement. how about something like this:
List collection;
if(keepSorted)
collection=new LinkedList();
else
collection=new ArrayList();
This way if you are going to fill in the collection with an insertion sort, you would use a linked list (an insertion sort into an array list is criminal.) But if you don't need to keep it sorted and are just appending, you use an ArrayList (More efficient for other operations).
This is a pretty big stretch here because collections aren't the best example, but in OO design one of the most important concepts is using the interface facade to access different objects with the exact same code.
Edit responding to comment:
As for your map comment below, Yes using the "Map" interface restricts you to only those methods unless you cast the collection back from Map to HashMap (which COMPLETELY defeats the purpose).
Often what you will do is create an object and fill it in using it's specific type (HashMap), in some kind of "create" or "initialize" method, but that method will return a "Map" that doesn't need to be manipulated as a HashMap any more.
If you ever have to cast by the way, you are probably using the wrong interface or your code isn't structured well enough. Note that it is acceptable to have one section of your code treat it as a "HashMap" while the other treats it as a "Map", but this should flow "down". so that you are never casting.
Also notice the semi-neat aspect of roles indicated by interfaces. A LinkedList makes a good stack or queue, an ArrayList makes a good stack but a horrific queue (again, a remove would cause a shift of the entire list) so LinkedList implements the Queue interface, ArrayList does not.
You've nearly got it. The problem is that the Class Under Test (CUT) is not built for unit testing - it has not really been TDD'd.
Think of it like this…
In the unit test
@Spy
on it@Mock
all of the other class/service/database (i.e. external dependencies) In order to avoid executing code that you are not strictly testing, you could abstract that code away into something that can be @Mock
ed.
In this very simple example, a function that creates an object will be difficult to test
public void doSomethingCool(String foo) {
MyObject obj = new MyObject(foo);
// can't do much with obj in a unit test unless it is returned
}
But a function that uses a service to get MyObject is easy to test, as we have abstracted the difficult/impossible to test code into something that makes this method testable.
public void doSomethingCool(String foo) {
MyObject obj = MyObjectService.getMeAnObject(foo);
}
as MyObjectService can be mocked and also verified that .getMeAnObject() is called with the foo variable.
Try this:
CGFloat statusBarHeight = [[UIApplication sharedApplication] statusBarFrame].size.height;
What you need to do is configure Fiddler to work as a "reverse proxy"
There are instructions on 2 different ways you can do this on Fiddler's website. Here is a copy of the steps:
Step #0
Before either of the following options will work, you must enable other computers to connect to Fiddler. To do so, click Tools > Fiddler Options > Connections and tick the "Allow remote computers to connect" checkbox. Then close Fiddler.
Option #1: Configure Fiddler as a Reverse-Proxy
Fiddler can be configured so that any traffic sent to http://127.0.0.1:8888
is automatically sent to a different port on the same machine. To set this configuration:
http://127.0.0.1:8888
Option #2: Write a FiddlerScript rule
Alternatively, you can write a rule that does the same thing.
Say you're running a website on port 80 of a machine named WEBSERVER. You're connecting to the website using Internet Explorer Mobile Edition on a Windows SmartPhone device for which you cannot configure the web proxy. You want to capture the traffic from the phone and the server's response.
http://webserver:8888
Requests from the SmartPhone will appear in Fiddler. The requests are forwarded from port 8888 to port 80 where the webserver is running. The responses are sent back through Fiddler to the SmartPhone, which has no idea that the content originally came from port 80.
I agree with HanClinto's post higher up in this discussion. I generally use regular expressions to string-match input text. And this is a vain effort, as, like you originally mentioned you have to explicitly account for every trick form of writing popular on the net in your "blocked" list.
On a side note, while others are debating the ethics of censorship, I must agree that some form is necessary on the web. Some people simply enjoy posting vulgarity because it can be instantly offensive to a large body of people, and requires absolutely no thought on the author's part.
Thank you for the ideas.
HanClinto rules!
This allows to send text message through existing app. phoneNumber - is String. If you do not wish to specify phone number, use empty string "".
Intent sendIntent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("smsto", phoneNumber, null));
sendIntent.putExtra("sms_body", "text message");
startActivity(sendIntent);
I just experienced this same issue, trying to enable CORS globally. However I found out it does work, however only when the request contains a Origin
header value. If you omit the origin
header value, the response will not contain a Access-Control-Allow-Origin
.
I used a chrome plugin called DHC to test my GET request. It allowed me to add the Origin
header easily.
SELECT COALESCE(IF(myColumn = 1,COUNT(DISTINCT NumberColumn),NULL),0) column1,
COALESCE(CASE WHEN myColumn = 1 THEN COUNT(DISTINCT NumberColumn) ELSE NULL END,0) AS column2
FROM AD_CurrentView
Query scopes may help you to let your code more readable.
http://laravel.com/docs/eloquent#query-scopes
Updating this answer with some example:
In your model, create scopes methods like this:
public function scopeActive($query)
{
return $query->where('active', '=', 1);
}
public function scopeThat($query)
{
return $query->where('that', '=', 1);
}
Then, you can call this scopes while building your query:
$users = User::active()->that()->get();
Here is a simple and more update format of getting the data:
$now = new \DateTime('now');
$month = $now->format('m');
$year = $now->format('Y');
I did exactly the same issue using the dependency below:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.44</version>
</dependency>
I just change to version 46 and everything works.
isset()
will return true if the variable has been initialised. If you have a form field with its name
value set to userName
, when that form is submitted the value will always be "set", although there may not be any data in it.
Instead, trim()
the string and test its length
if("" == trim($_POST['userName'])){
$username = 'Anonymous';
}
using :<line number>
you can navigate to any line, thus :1
takes you to the first line.
If you are using Outlook 2010, you can define your own style and select your formatting you want, in the Format options there is one option for Language, here you can specify the language and specify whether you want spell checker to ignore the text with this style.
With this style you can now paste the code as text and select your new style. Outlook will not correct the text and will not perform the spell check on it.
Below is the summary of the style I have defined for emailing the code snippets.
Do not check spelling or grammar, Border:
Box: (Single solid line, Orange, 0.5 pt Line width)
Pattern: Clear (Custom Color(RGB(253,253,217))), Style: Linked, Automatically update, Quick Style
Based on: HTML Preformatted
This answer provide interesting commands based on git am
and presented using examples, step by step.
git log --pretty=email -p --reverse --full-index --binary
git am
Example: Extract history of file3
, file4
and file5
my_repo
+-- dirA
¦ +-- file1
¦ +-- file2
+-- dirB ^
¦ +-- subdir | To be moved
¦ ¦ +-- file3 | with history
¦ ¦ +-- file4 |
¦ +-- file5 v
+-- dirC
+-- file6
+-- file7
Clean the temporary directory destination
export historydir=/tmp/mail/dir # Absolute path
rm -rf "$historydir" # Caution when cleaning
Clean your the repo source
git commit ... # Commit your working files
rm .gitignore # Disable gitignore
git clean -n # Simulate removal
git clean -f # Remove untracked file
git checkout .gitignore # Restore gitignore
Extract history of each file in email format
cd my_repo/dirB
find -name .git -prune -o -type d -o -exec bash -c 'mkdir -p "$historydir/${0%/*}" && git log --pretty=email -p --stat --reverse --full-index --binary -- "$0" > "$historydir/$0"' {} ';'
Unfortunately option --follow
or --find-copies-harder
cannot be combined with --reverse
. This is why history is cut when file is renamed (or when a parent directory is renamed).
After: Temporary history in email format
/tmp/mail/dir
+-- subdir
¦ +-- file3
¦ +-- file4
+-- file5
Suppose you want to move these three files in this other repo (can be the same repo).
my_other_repo
+-- dirF
¦ +-- file55
¦ +-- file56
+-- dirB # New tree
¦ +-- dirB1 # was subdir
¦ ¦ +-- file33 # was file3
¦ ¦ +-- file44 # was file4
¦ +-- dirB2 # new dir
¦ +-- file5 # = file5
+-- dirH
+-- file77
Therefore reorganize your files:
cd /tmp/mail/dir
mkdir dirB
mv subdir dirB/dirB1
mv dirB/dirB1/file3 dirB/dirB1/file33
mv dirB/dirB1/file4 dirB/dirB1/file44
mkdir dirB/dirB2
mv file5 dirB/dirB2
Your temporary history is now:
/tmp/mail/dir
+-- dirB
+-- dirB1
¦ +-- file33
¦ +-- file44
+-- dirB2
+-- file5
Change also filenames within the history:
cd "$historydir"
find * -type f -exec bash -c 'sed "/^diff --git a\|^--- a\|^+++ b/s:\( [ab]\)/[^ ]*:\1/$0:g" -i "$0"' {} ';'
Note: This rewrites the history to reflect the change of path and filename.
(i.e. the change of the new location/name within the new repo)
Your other repo is:
my_other_repo
+-- dirF
¦ +-- file55
¦ +-- file56
+-- dirH
+-- file77
Apply commits from temporary history files:
cd my_other_repo
find "$historydir" -type f -exec cat {} + | git am
Your other repo is now:
my_other_repo
+-- dirF
¦ +-- file55
¦ +-- file56
+-- dirB ^
¦ +-- dirB1 | New files
¦ ¦ +-- file33 | with
¦ ¦ +-- file44 | history
¦ +-- dirB2 | kept
¦ +-- file5 v
+-- dirH
+-- file77
Use git status
to see amount of commits ready to be pushed :-)
Note: As the history has been rewritten to reflect the path and filename change:
(i.e. compared to the location/name within the previous repo)
git mv
to change the location/filename.git log --follow
to access full history.To list the files having been renamed:
find -name .git -prune -o -exec git log --pretty=tformat:'' --numstat --follow {} ';' | grep '=>'
More customizations: You can complete the command git log
using options --find-copies-harder
or --reverse
. You can also remove the first two columns using cut -f3-
and grepping complete pattern '{.* => .*}'.
find -name .git -prune -o -exec git log --pretty=tformat:'' --numstat --follow --find-copies-harder --reverse {} ';' | cut -f3- | grep '{.* => .*}'
In modern browsers you can use :placeholder-shown
to target the empty input (not to be confused with ::placeholder
).
input:placeholder-shown {
border: 1px solid red; /* Red border only if the input is empty */
}
More info and browser support: https://css-tricks.com/almanac/selectors/p/placeholder-shown/
Also, to "increment" string, when update, use CONCAT
update dbo.test set foo=CONCAT(foo, 'bar') where 1=1
For compare hashed password with the plain text password string you can use the PHP password_verify
if(password_verify('1234567', $crypt_password_string)) {
// in case if "$crypt_password_string" actually hides "1234567"
}
In latest Ruby versions Hash instance has a key?
method:
{a: 1}.key?(:a)
=> true
Be sure to use the symbol key or a string key depending on what you have in your hash:
{'a' => 2}.key?(:a)
=> false
You have to use UPDATE instead of INSERT:
For Example:
UPDATE table1 SET col_a='k1', col_b='foo' WHERE key_col='1';
UPDATE table1 SET col_a='k2', col_b='bar' WHERE key_col='2';
Lukas Knuth have good solution, but on android 4.0.4 on Samsung Galaxy SII I still look zoom controls. And I solve it via
if (zoom_controll!=null && zoom_controll.getZoomControls()!=null)
{
// Hide the controlls AFTER they where made visible by the default implementation.
zoom_controll.getZoomControls().setVisibility(View.GONE);
}
instead of
if (zoom_controll != null){
// Hide the controlls AFTER they where made visible by the default implementation.
zoom_controll.setVisible(false);
}
To ensure success with a full path use recurse=yes
- name: ensure custom facts directory exists
file: >
path=/etc/ansible/facts.d
recurse=yes
state=directory
I work behind a firewall on windows and I have the Same problem. But I managed to fix it:
cmd
then hit Enter (displays the command prompt)netstat
In the results returned, find your Proxy address :
TCP YOURMACHINENAME:PORT DISTANTMACHINE1:PORT
TCP YOURMACHINENAME:PORT DISTANTMACHINE2:PORT
TCP YOURMACHINENAME:PORT DISTANTMACHINE3:PORT
Your proxy address is one of the DISTANTMACHINEx
inside your <div></div>
element you can call the $(document).ready(function(){});
execute a command, something like
<div id="div1">
<script>
$(document).ready(function(){
//do something
});
</script>
</div>
and you can do the same to other divs that you have. this was suitable if you loading your div via partial view
If you want to get list of changed files:
git diff-tree --no-commit-id --name-only -r <commit-ish>
If you want to get list of all files in a commit, you can use
git ls-tree --name-only -r <commit-ish>
Easiest solution, provide a value of ' ' for the username field (which you can still call 'username').
If the value can be populated by user-inputted values, as is usually the case for a form that you are validating, provide a value of ' ' when it is not already set. In PHP,
if(trim($username) == ''){$username = ' ';}
<input type='text' value = '$username' name = 'Username' />
I actually think autocompletion for username and password effectively gifts access to all your accounts to anyone who accesses your computer, regardless of how obscure your passwords are...
Very simple code for swapping two variables:
static void Main(string[] args)
{
Console.WriteLine("Prof.Owais ahmed");
Console.WriteLine("Swapping two variables");
Console.WriteLine("Enter your first number ");
int x = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter your first number ");
int y = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("your vlaue of x is="+x+"\nyour value of y is="+y);
int z = x;
x = y;
y = z;
Console.WriteLine("after Swapping value of x is="+x+"/nyour value of y is="+y);
Console.ReadLine();
}
For Python 3+ version
install mysql-connector
as:
pip3 install mysql-connector
Sample Python DB connection code:
import mysql.connector
db_connection = mysql.connector.connect(
host="localhost",
user="root",
passwd=""
)
print(db_connection)
Output:
> <mysql.connector.connection.MySQLConnection object at > 0x000002338A4C6B00>
This means, database is correctly connected.
Add this code after updating the list
Suppose:
The ArrayAdapter<String> variable name is dataAdapter, and the List variable name is keys.
Swift 4+
NotificationCenter.default.addObserver(forName: UIApplication.userDidTakeScreenshotNotification, object: nil, queue: OperationQueue.main) { notification in
//you can do anything you want here.
}
by using this observer you can find out when user takes a screenshot, but you can not prevent him.
If you are targeting pre-Lollipop devices, you can use Shadow-Layout, since it easy and you can use it in different kind of layouts.
Add shadow-layout to your Gradle file:
dependencies {
compile 'com.github.dmytrodanylyk.shadow-layout:library:1.0.1'
}
At the top the xml layout where you have your button, add to the top:
xmlns:app="http://schemas.android.com/apk/res-auto"
it will make available the custom attributes.
Then you put a shadow layout around you Button:
<com.dd.ShadowLayout
android:layout_marginTop="16dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:sl_shadowRadius="4dp"
app:sl_shadowColor="#AA000000"
app:sl_dx="0dp"
app:sl_dy="0dp"
app:sl_cornerRadius="56dp">
<YourButton
.... />
</com.dd.ShadowLayout>
You can then tweak the app:
settings to match your required shadow.
Hope it helps.
Maybe you are looking for something like this. If you want to select the complete line when it contains both "foo" and "baz" at the same time, this RegEx will comply that:
.*(foo)+.*(baz)+|.*(baz)+.*(foo)+.*
An alternative solution would be to create a servlet that sends a redirect to the desired default webapp and map that servlet to all urls in the ROOT webapp.
package com.example.servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RedirectServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.sendRedirect("/myRootWebapp");
}
}
Add the above class to
CATALINA_BASE/webapps/ROOT/WEB-INF/classes/com/example/servlet
.
And add the following to CATALINA_BASE/webapps/ROOT/WEB-INF/web.xml
:
<servlet>
<display-name>Redirect</display-name>
<servlet-name>Redirect</servlet-name>
<servlet-class>com.example.servlet.RedirectServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Redirect</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
And if desired you could easily modify the RedirectServlet to accept an init param to allow you to set the default webapp without having to modify the source.
I'm not sure if doing this would have any negative implications, but I did test this and it does seem to work.
You should use require_once and include_once. Inside parent.php use
include_once 'database.php';
And inside child1.php and child2.php use
include_once 'parent.php';
Just adding that using the first approach it can be done as -
pd.DataFrame(list(map(list, zip(lst1,lst2,lst3))))
SQL Alchemy session objects have their own execute
method:
result = db.session.execute('SELECT * FROM my_table WHERE my_column = :val', {'val': 5})
All your application queries should be going through a session object, whether they're raw SQL or not. This ensures that the queries are properly managed by a transaction, which allows multiple queries in the same request to be committed or rolled back as a single unit. Going outside the transaction using the engine or the connection puts you at much greater risk of subtle, possibly hard to detect bugs that can leave you with corrupted data. Each request should be associated with only one transaction, and using db.session
will ensure this is the case for your application.
Also take note that execute
is designed for parameterized queries. Use parameters, like :val
in the example, for any inputs to the query to protect yourself from SQL injection attacks. You can provide the value for these parameters by passing a dict
as the second argument, where each key is the name of the parameter as it appears in the query. The exact syntax of the parameter itself may be different depending on your database, but all of the major relational databases support them in some form.
Assuming it's a SELECT
query, this will return an iterable of RowProxy
objects.
You can access individual columns with a variety of techniques:
for r in result:
print(r[0]) # Access by positional index
print(r['my_column']) # Access by column name as a string
r_dict = dict(r.items()) # convert to dict keyed by column names
Personally, I prefer to convert the results into namedtuple
s:
from collections import namedtuple
Record = namedtuple('Record', result.keys())
records = [Record(*r) for r in result.fetchall()]
for r in records:
print(r.my_column)
print(r)
If you're not using the Flask-SQLAlchemy extension, you can still easily use a session:
import sqlalchemy
from sqlalchemy.orm import sessionmaker, scoped_session
engine = sqlalchemy.create_engine('my connection string')
Session = scoped_session(sessionmaker(bind=engine))
s = Session()
result = s.execute('SELECT * FROM my_table WHERE my_column = :val', {'val': 5})
you can simply do like that in the html part:
<span>Heading Text</span>
and in the css you can make it as an h1 block using display:
span{
display:block;
font-size:20px;
}
you will get it as a h1 without bold ,
if you want it bold just add this to the css:
font-weight:bold;
You could go into the designer of the web form and change the "webcontrols" to be "public" instead of "protected" but I'm not sure how safe that is. I prefer to make hidden inputs and have some jQuery set the values into those hidden inputs, then create public properties in the web form's class (code behind), and access the values that way.
I would strongly suggest using an npm package implementing correctly the base64 specification.
The best one I know is rfc4648
The problem is that btoa and atob use binary strings instead of Uint8Array and trying to convert to and from it is cumbersome. Also there is a lot of bad packages in npm for that. I lose a lot of time before finding that one.
The creators of that specific package did a simple thing: they took the specification of Base64 (which is here by the way) and implemented it correctly from the beginning to the end. (Including other formats in the specification that are also useful like Base64-url, Base32, etc ...) That doesn't seem a lot but apparently that was too much to ask to the bunch of other libraries.
So yeah, I know I'm doing a bit of proselytism but if you want to avoid losing your time too just use rfc4648.
Google's libs-for-android has a nice libraries for managing image and file cache.
Here's the example of the duplicate delete problem that occurs with std::unique(). On a LINUX machine, the program crashes. Read the comments for details.
// Main10.cpp
//
// Illustration of duplicate delete and memory leak in a vector<int*> after calling std::unique.
// On a LINUX machine, it crashes the progam because of the duplicate delete.
//
// INPUT : {1, 2, 2, 3}
// OUTPUT: {1, 2, 3, 3}
//
// The two 3's are actually pointers to the same 3 integer in the HEAP, which is BAD
// because if you delete both int* pointers, you are deleting the same memory
// location twice.
//
//
// Never mind the fact that we ignore the "dupPosition" returned by std::unique(),
// but in any sensible program that "cleans up after istelf" you want to call deletex
// on all int* poitners to avoid memory leaks.
//
//
// NOW IF you replace std::unique() with ptgi::unique(), all of the the problems disappear.
// Why? Because ptgi:unique merely reshuffles the data:
// OUTPUT: {1, 2, 3, 2}
// The ptgi:unique has swapped the last two elements, so all of the original elements in
// the INPUT are STILL in the OUTPUT.
//
// 130215 [email protected]
//============================================================================
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
#include "ptgi_unique.hpp"
// functor used by std::unique to remove adjacent elts from vector<int*>
struct EqualToVectorOfIntegerStar: public std::equal_to<int *>
{
bool operator() (const int* arg1, const int* arg2) const
{
return (*arg1 == *arg2);
}
};
void printVector( const std::string& msg, const std::vector<int*>& vnums);
int main()
{
int inums [] = { 1, 2, 2, 3 };
std::vector<int*> vnums;
// convert C array into vector of pointers to integers
for (size_t inx = 0; inx < 4; ++ inx)
vnums.push_back( new int(inums[inx]) );
printVector("BEFORE UNIQ", vnums);
// INPUT : 1, 2A, 2B, 3
std::unique( vnums.begin(), vnums.end(), EqualToVectorOfIntegerStar() );
// OUTPUT: 1, 2A, 3, 3 }
printVector("AFTER UNIQ", vnums);
// now we delete 3 twice, and we have a memory leak because 2B is not deleted.
for (size_t inx = 0; inx < vnums.size(); ++inx)
{
delete(vnums[inx]);
}
}
// print a line of the form "msg: 1,2,3,..,5,6,7\n", where 1..7 are the numbers in vnums vector
// PS: you may pass "hello world" (const char *) because of implicit (automatic) conversion
// from "const char *" to std::string conversion.
void printVector( const std::string& msg, const std::vector<int*>& vnums)
{
std::cout << msg << ": ";
for (size_t inx = 0; inx < vnums.size(); ++inx)
{
// insert comma separator before current elt, but ONLY after first elt
if (inx > 0)
std::cout << ",";
std::cout << *vnums[inx];
}
std::cout << "\n";
}
WordPress include tags, categories and taxonomies in search results
This code is taken from http://atiblog.com/custom-search-results/
Some functions here are taken from twentynineteen theme.Because it is made on this theme.
This code example will help you to include tags, categories or any custom taxonomy in your search. And show the posts contaning these tags or categories.
You need to modify your search.php of your theme to do so.
<?php
$search=get_search_query();
$all_categories = get_terms( array('taxonomy' => 'category','hide_empty' => true) );
$all_tags = get_terms( array('taxonomy' => 'post_tag','hide_empty' => true) );
//if you have any custom taxonomy
$all_custom_taxonomy = get_terms( array('taxonomy' => 'your-taxonomy-slug','hide_empty' => true) );
$mcat=array();
$mtag=array();
$mcustom_taxonomy=array();
foreach($all_categories as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mcat,$all->term_id);
}
}
foreach($all_tags as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mtag,$all->term_id);
}
}
foreach($all_custom_taxonomy as $all){
$par=$all->name;
if (strpos($par, $search) !== false) {
array_push($mcustom_taxonomy,$all->term_id);
}
}
$matched_posts=array();
$args1= array( 'post_status' => 'publish','posts_per_page' => -1,'tax_query' =>array('relation' => 'OR',array('taxonomy' => 'category','field' => 'term_id','terms' =>$mcat),array('taxonomy' => 'post_tag','field' => 'term_id','terms' =>$mtag),array('taxonomy' => 'custom_taxonomy','field' => 'term_id','terms' =>$mcustom_taxonomy)));
$the_query = new WP_Query( $args1 );
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
array_push($matched_posts,get_the_id());
//echo '<li>' . get_the_id() . '</li>';
}
wp_reset_postdata();
} else {
}
?>
<?php
// now we will do the normal wordpress search
$query2 = new WP_Query( array( 's' => $search,'posts_per_page' => -1 ) );
if ( $query2->have_posts() ) {
while ( $query2->have_posts() ) {
$query2->the_post();
array_push($matched_posts,get_the_id());
}
wp_reset_postdata();
} else {
}
$matched_posts= array_unique($matched_posts);
$matched_posts=array_values(array_filter($matched_posts));
//print_r($matched_posts);
?>
<?php
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$query3 = new WP_Query( array( 'post_type'=>'any','post__in' => $matched_posts ,'paged' => $paged) );
if ( $query3->have_posts() ) {
while ( $query3->have_posts() ) {
$query3->the_post();
get_template_part( 'template-parts/content/content', 'excerpt' );
}
twentynineteen_the_posts_navigation();
wp_reset_postdata();
} else {
}
?>
Is there a step missing?
Yes. You need to create the directory:
mkdir ${HOME}/.ssh
Additionally, SSH requires you to set the permissions so that only you (the owner) can access anything in ~/.ssh:
% chmod 700 ~/.ssh
Should the
.ssh
dir be generated when I use thessh-keygen
command?
No. This command generates an SSH key pair but will fail if it cannot write to the required directory:
% ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/xxx/.ssh/id_rsa): /Users/tmp/does_not_exist
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
open /Users/tmp/does_not_exist failed: No such file or directory.
Saving the key failed: /Users/tmp/does_not_exist.
Once you've created your keys, you should also restrict who can read those key files to just yourself:
% chmod -R go-wrx ~/.ssh/*
You need other headers, not only access-control-allow-origin. If your request have the "Access-Control-Allow-Origin" header, you must copy it into the response headers, If doesn't, you must check the "Origin" header and copy it into the response. If your request doesn't have Access-Control-Allow-Origin not Origin headers, you must return "*".
You can read the complete explanation here: http://www.html5rocks.com/en/tutorials/cors/#toc-adding-cors-support-to-the-server
and this is the function I'm using to write cross domain headers:
func writeCrossDomainHeaders(w http.ResponseWriter, req *http.Request) {
// Cross domain headers
if acrh, ok := req.Header["Access-Control-Request-Headers"]; ok {
w.Header().Set("Access-Control-Allow-Headers", acrh[0])
}
w.Header().Set("Access-Control-Allow-Credentials", "True")
if acao, ok := req.Header["Access-Control-Allow-Origin"]; ok {
w.Header().Set("Access-Control-Allow-Origin", acao[0])
} else {
if _, oko := req.Header["Origin"]; oko {
w.Header().Set("Access-Control-Allow-Origin", req.Header["Origin"][0])
} else {
w.Header().Set("Access-Control-Allow-Origin", "*")
}
}
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
w.Header().Set("Connection", "Close")
}
You can make a json object like:
globalVariable={example_attribute:"SomeValue"};
in fileA.js
And access it from fileB.js like:
globalVariable.example_attribute
strtok
maintains a static, internal reference pointing to the next available token in the string; if you pass it a NULL pointer, it will work from that internal reference.
This is the reason strtok
isn't re-entrant; as soon as you pass it a new pointer, that old internal reference gets clobbered.
Faced the same problem, I was not able to run wordpress docker container with mysql version 8 as its default authentication mechanism is caching_sha2_password instead of mysql_native_password.
In order to fix this problem we must reset default authentication mechanism to mysql_native_password.
Find my.cnf file in your mysql installation, usually on a linux machine it is at the following location - /etc/mysql
Edit my.cnf file and add following line just under heading [mysqld]
default_authentication_plugin= mysql_native_password
Save the file then log into mysql command line using root user
run command FLUSH PRIVILEGES;
It does depend on the HTTP headers sent with the CSS files as both of the previous answers state - as long as you don't append any cachebusting stuff to the href. e.g.
<link href="/stylesheets/mycss.css?some_var_to_bust_cache=24312345" rel="stylesheet" type="text/css" />
Some frameworks (e.g. rails) put these in by default.
However If you get something like firebug or fiddler, you can see exactly what your browser is downloading on each request - which is expecially useful for finding out what your browser is doing, as opposed to just what it should be doing.
All browsers should respect the cache headers in the same way, unless configured to ignore them (but there are bound to be exceptions)
There is a parse_dates
parameter for read_csv
which allows you to define the names of the columns you want treated as dates or datetimes:
date_cols = ['col1', 'col2']
pd.read_csv(file, sep='\t', header=None, names=headers, parse_dates=date_cols)
Before actually answering your question:
Parameters in a URL (e.g. key=listOfUsers/user1
) are GET
parameters and you shouldn't be using them for POST
requests. A quick explanation of the difference between GET and POST can be found here.
In your case, to make use of REST principles, you should probably have:
http://ip:5000/users
http://ip:5000/users/<user_id>
Then, on each URL, you can define the behaviour of different HTTP methods (GET
, POST
, PUT
, DELETE
). For example, on /users/<user_id>
, you want the following:
GET /users/<user_id> - return the information for <user_id>
POST /users/<user_id> - modify/update the information for <user_id> by providing the data
PUT - I will omit this for now as it is similar enough to `POST` at this level of depth
DELETE /users/<user_id> - delete user with ID <user_id>
So, in your example, you want do a POST
to /users/user_1
with the POST data being "John"
. Then the XPath expression or whatever other way you want to access your data should be hidden from the user and not tightly couple to the URL. This way, if you decide to change the way you store and access data, instead of all your URL's changing, you will simply have to change the code on the server-side.
Now, the answer to your question: Below is a basic semi-pseudocode of how you can achieve what I mentioned above:
from flask import Flask
from flask import request
app = Flask(__name__)
@app.route('/users/<user_id>', methods = ['GET', 'POST', 'DELETE'])
def user(user_id):
if request.method == 'GET':
"""return the information for <user_id>"""
.
.
.
if request.method == 'POST':
"""modify/update the information for <user_id>"""
# you can use <user_id>, which is a str but could
# changed to be int or whatever you want, along
# with your lxml knowledge to make the required
# changes
data = request.form # a multidict containing POST data
.
.
.
if request.method == 'DELETE':
"""delete user with ID <user_id>"""
.
.
.
else:
# POST Error 405 Method Not Allowed
.
.
.
There are a lot of other things to consider like the POST
request content-type but I think what I've said so far should be a reasonable starting point. I know I haven't directly answered the exact question you were asking but I hope this helps you. I will make some edits/additions later as well.
Thanks and I hope this is helpful. Please do let me know if I have gotten something wrong.
I know this is very old question but I had the same requirement and just discovered that after c#6 you can use static in using for classes to import.
I hope this helps someone....
using static yourNameSpace.YourClass;
The above works,(having an original document with mixed pages of 11' and 16' wide). However auto rotate needs to be off otherwise landscape pages are saved with page white top and bottom, so dont work in full screen view.
Solution is to re open the new PDF in acrobat and crop the first image (carefully to avoid white border), then select page range i.e. all, this then applies to all pages. job done !
Use Libre Office API Here is an example
libreoffice --headless --convert-to html docx-file-path --outdir html-dir-path
They have the same speed. Maybe in some special architecture what he/she said is right, but in the x86 family at least I know they are the same. Because for doing this the CPU will do a substraction (a - b) and then check the flags of the flag register. Two bits of that register are called ZF (zero Flag) and SF (sign flag), and it is done in one cycle, because it will do it with one mask operation.
If you don't encounter any permission errors with
pip install -U numpy
try:
pip install --user -U numpy
If you're looking for some ESP alternatives, you should have a look at Mailjet for Microsoft Azure too! As a global email service and infrastructure provider, they enable you to send, deliver and track transactional and marketing emails via their APIs, SMTP Relay or UI all from one single platform, thought both for developers and emails owners.
Disclaimer: I’m working at Mailjet as a Developer Evangelist.
Nginx prefers prefix-based location matches (not involving regular expression), that's why in your code block, /stash redirects are going to /.
The algorithm used by Nginx to select which location to use is described thoroughly here: https://www.digitalocean.com/community/tutorials/understanding-nginx-server-and-location-block-selection-algorithms#matching-location-blocks
Just tell git to not assume it is changed never matter what:
git update-index --assume-unchanged src/file/to/ignore
yes, you can remove the files from the git repository. But if your team all use the same IDE or you are by yourself, you probably don't want to do that. For yourself, you want to have an ok starting point to resume working, for your teammates as well.
There is no installcheck element in the bootstrapper package manifest shipped with Visual C++. Guess Microsoft wants to always install if you set it as a prerequisite.
Of course you can still call MsiQueryProductState to check if the VC redist package is installed via MSI, The package code can be found by running
wmic product get
at command line, or if you are already at wmic:root\cli, run
product where "Caption like '%C++ 2012%'"
Here is my CORS middleware:
<?php namespace App\Http\Middleware;
use Closure;
class CORS {
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
header("Access-Control-Allow-Origin: *");
// ALLOW OPTIONS METHOD
$headers = [
'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
];
if($request->getMethod() == "OPTIONS") {
// The client-side application can set only headers allowed in Access-Control-Allow-Headers
return Response::make('OK', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value)
$response->header($key, $value);
return $response;
}
}
To use CORS middleware you have to register it first in your app\Http\Kernel.php file like this:
protected $routeMiddleware = [
//other middlewares
'cors' => 'App\Http\Middleware\CORS',
];
Then you can use it in your routes
Route::get('example', array('middleware' => 'cors', 'uses' => 'ExampleController@dummy'));
We had the same issues, it was because we had wrong version of Oracle VM Virtual Box. Make sure you uninstall wrong version and re-install Compatible Oracle VM Virtual Box.
A bit manual searching but its an alternative way...
Find the Oracle home or where the installation files for Oracle is installed on your linux server.
cd / <-- Goto root directory
find . -print| grep -i dbm*.sql
Result varies on how you installed Oracle but mine displays this
/db/oracle
Goto the folder
less /db/oracle/db1/sqlplus/doc/README.htm
scroll down and you should see something like this
SQL*Plus Release Notes - Release 11.2.0.2
Use Dim
'd variables
Dim rng as Range
Set
the variable to the required range. There are many ways to refer to a single-cell range:
Set rng = Range("A1")
Set rng = Cells(1, 1)
Set rng = Range("NamedRange")
Or a multi-cell range:
Set rng = Range("A1:B10")
Set rng = Range("A1", "B10")
Set rng = Range(Cells(1, 1), Cells(10, 2))
Set rng = Range("AnotherNamedRange")
Set rng = Range("A1").Resize(10, 2)
You can use the shortcut to the Evaluate
method, but this is less efficient and should generally be avoided in production code.
Set rng = [A1]
Set rng = [A1:B10]
All the above examples refer to cells on the active sheet. Unless you specifically want to work only with the active sheet, it is better to Dim a Worksheet
variable too:
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
Set rng = ws.Cells(1, 1)
With ws
Set rng = .Range(.Cells(1, 1), .Cells(2, 10))
End With
If you do want to work with the ActiveSheet
, for clarity it's best to be explicit. But take care, as some Worksheet
methods change the active sheet.
Set rng = ActiveSheet.Range("A1")
Again, this refers to the active workbook. Unless you specifically want to work only with the ActiveWorkbook
or ThisWorkbook
, it is better to Dim a Workbook
variable too.
Dim wb As Workbook
Set wb = Application.Workbooks("Book1")
Set rng = wb.Worksheets("Sheet1").Range("A1")
If you do want to work with the ActiveWorkbook
, for clarity it's best to be explicit. But take care, as many WorkBook
methods change the active book.
Set rng = ActiveWorkbook.Worksheets("Sheet1").Range("A1")
You can also use the ThisWorkbook
object to refer to the book containing the running code.
Set rng = ThisWorkbook.Worksheets("Sheet1").Range("A1")
A common (bad) piece of code is to open a book, get some data then close again
This is bad:
Sub foo()
Dim v as Variant
Workbooks("Book1.xlsx").Sheets(1).Range("A1").Clear
Workbooks.Open("C:\Path\To\SomeClosedBook.xlsx")
v = ActiveWorkbook.Sheets(1).Range("A1").Value
Workbooks("SomeAlreadyOpenBook.xlsx").Activate
ActiveWorkbook.Sheets("SomeSheet").Range("A1").Value = v
Workbooks(2).Activate
ActiveWorkbook.Close()
End Sub
And it would be better like:
Sub foo()
Dim v as Variant
Dim wb1 as Workbook
Dim wb2 as Workbook
Set wb1 = Workbooks("SomeAlreadyOpenBook.xlsx")
Set wb2 = Workbooks.Open("C:\Path\To\SomeClosedBook.xlsx")
v = wb2.Sheets("SomeSheet").Range("A1").Value
wb1.Sheets("SomeOtherSheet").Range("A1").Value = v
wb2.Close()
End Sub
Pass ranges to your Sub
s and Function
s as Range variables:
Sub ClearRange(r as Range)
r.ClearContents
'....
End Sub
Sub MyMacro()
Dim rng as Range
Set rng = ThisWorkbook.Worksheets("SomeSheet").Range("A1:B10")
ClearRange rng
End Sub
You should also apply Methods (such as Find
and Copy
) to variables:
Dim rng1 As Range
Dim rng2 As Range
Set rng1 = ThisWorkbook.Worksheets("SomeSheet").Range("A1:A10")
Set rng2 = ThisWorkbook.Worksheets("SomeSheet").Range("B1:B10")
rng1.Copy rng2
If you are looping over a range of cells it is often better (faster) to copy the range values to a variant array first and loop over that:
Dim dat As Variant
Dim rng As Range
Dim i As Long
Set rng = ThisWorkbook.Worksheets("SomeSheet").Range("A1:A10000")
dat = rng.Value ' dat is now array (1 to 10000, 1 to 1)
for i = LBound(dat, 1) to UBound(dat, 1)
dat(i,1) = dat(i, 1) * 10 ' Or whatever operation you need to perform
next
rng.Value = dat ' put new values back on sheet
This is a small taster for what's possible.
Use insertAdjacentHTML(). It works with all current browsers, even with IE11.
var mylist = document.getElementById('mylist');_x000D_
mylist.insertAdjacentHTML('beforeend', '<li>third</li>');
_x000D_
<ul id="mylist">_x000D_
<li>first</li>_x000D_
<li>second</li>_x000D_
</ul>
_x000D_
To plot multiple graphs on the same figure you will have to do:
from numpy import *
import math
import matplotlib.pyplot as plt
t = linspace(0, 2*math.pi, 400)
a = sin(t)
b = cos(t)
c = a + b
plt.plot(t, a, 'r') # plotting t, a separately
plt.plot(t, b, 'b') # plotting t, b separately
plt.plot(t, c, 'g') # plotting t, c separately
plt.show()
Specify paths
--app
--one
one.module.ts
--services
--two
two.module.ts
--services
Create Service with new folder in module ONE
ng g service one/services/myNewServiceFolderName/serviceOne --module one/one
--one
one.module.ts // service imported and added to providers.
--services
--myNewServiceFolderName
serviceOne.service.ts
serviceOne.service.spec.ts
You can checkout remote branch /n git fetch && git checkout remotebranch
If you like namespace constant, you can leverage struct, Friday Q&A 2011-08-19: Namespaced Constants and Functions
// in the header
extern const struct MANotifyingArrayNotificationsStruct
{
NSString *didAddObject;
NSString *didChangeObject;
NSString *didRemoveObject;
} MANotifyingArrayNotifications;
// in the implementation
const struct MANotifyingArrayNotificationsStruct MANotifyingArrayNotifications = {
.didAddObject = @"didAddObject",
.didChangeObject = @"didChangeObject",
.didRemoveObject = @"didRemoveObject"
};
i guess the simplest way which doesn't require any operators is
if($_GET){
//do something if $_GET is set
}
if(!$_GET){
//do something if $_GET is NOT set
}
Given a column of numbers:
lst = []
cols = ['A']
for a in range(100, 105):
lst.append([a])
df = pd.DataFrame(lst, columns=cols, index=range(5))
df
A
0 100
1 101
2 102
3 103
4 104
You can reference the previous row with shift:
df['Change'] = df.A - df.A.shift(1)
df
A Change
0 100 NaN
1 101 1.0
2 102 1.0
3 103 1.0
4 104 1.0
I was just having the same issue...
To resolve the problem (at least in my case) ensure you have included the lib folder in your bundle classpath:
Manifest-Version: 1.0
...
Bundle-ClassPath: lib/gson-1.6.jar,
.
...
Or if you want to include all jar's in the folder:
Bundle-ClassPath: lib/
You will still need to place the jar files on the java build path as shown above. Then your imported jar's should appear in the folder "Referenced Libraries"
sort()
was deprecated for DataFrames in favor of either:
sort_values()
to sort by column(s)sort_index()
to sort by the index sort()
was deprecated (but still available) in Pandas with release 0.17 (2015-10-09) with the introduction of sort_values()
and sort_index()
. It was removed from Pandas with release 0.20 (2017-05-05).
I need the upgrade cell but I want close the keyboard. If I use
let indexPath = NSIndexPath(forRow: path, inSection: 1)
tableView.beginUpdates()
tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Automatic) //try other animations
tableView.endUpdates()
the keyboard disappear
You'd use a self-join on a table that "refers" to itself - e.g. a table of employees where managerid is a foreign-key to employeeid on that same table.
Example:
SELECT E.name, ME.name AS manager
FROM dbo.Employees E
LEFT JOIN dbo.Employees ME
ON ME.employeeid = E.managerid
Using jQuery I could load image with the check on it's existence. Added src to a plane base64 hash string with original image height width and then replaced it with the required url.
$('[data-src]').each(function() {
var $image_place_holder_element = $(this);
var image_url = $(this).data('src');
$("<div class='hidden-class' />").load(image_url, function(response, status, xhr) {
if (!(status == "error")) {
$image_place_holder_element.removeClass('image-placeholder');
$image_place_holder_element.attr('src', image_url);
}
}).remove();
});
Of course I used and modified few stack answers. Hope it helps someone.
For Mac OS X, save your CSV file in "Windows Comma Separated (.csv)" format.
Here you go:
var yourArray = [String]()
The above also works for other types and not just strings. It's just an example.
Adding Values to It
I presume you'll eventually want to add a value to it!
yourArray.append("String Value")
Or
let someString = "You can also pass a string variable, like this!"
yourArray.append(someString)
Add by Inserting
Once you have a few values, you can insert new values instead of appending. For example, if you wanted to insert new objects at the beginning of the array (instead of appending them to the end):
yourArray.insert("Hey, I'm first!", atIndex: 0)
Or you can use variables to make your insert more flexible:
let lineCutter = "I'm going to be first soon."
let positionToInsertAt = 0
yourArray.insert(lineCutter, atIndex: positionToInsertAt)
You May Eventually Want to Remove Some Stuff
var yourOtherArray = ["MonkeysRule", "RemoveMe", "SwiftRules"]
yourOtherArray.remove(at: 1)
The above works great when you know where in the array the value is (that is, when you know its index value). As the index values begin at 0, the second entry will be at index 1.
Removing Values Without Knowing the Index
But what if you don't? What if yourOtherArray has hundreds of values and all you know is you want to remove the one equal to "RemoveMe"?
if let indexValue = yourOtherArray.index(of: "RemoveMe") {
yourOtherArray.remove(at: indexValue)
}
This should get you started!
public async Task<Product> GetValue(int id)
{
Product Products = await _context.Products.AsNoTracking().FirstOrDefaultAsync(x => x.Id == id);
return Products;
}
AsNoTracking()
With my solution you're able to get something similar:
Here is bulletproff solution:
Your html:
<input class='calendarIcon'/>
Your SVG: i used fa-calendar-alt
(any IDE may open svg image as shown below)
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 448 512"><path d="M148 288h-40c-6.6 0-12-5.4-12-12v-40c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v40c0 6.6-5.4 12-12 12zm108-12v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 96v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm-96 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm192 0v-40c0-6.6-5.4-12-12-12h-40c-6.6 0-12 5.4-12 12v40c0 6.6 5.4 12 12 12h40c6.6 0 12-5.4 12-12zm96-260v352c0 26.5-21.5 48-48 48H48c-26.5 0-48-21.5-48-48V112c0-26.5 21.5-48 48-48h48V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h128V12c0-6.6 5.4-12 12-12h40c6.6 0 12 5.4 12 12v52h48c26.5 0 48 21.5 48 48zm-48 346V160H48v298c0 3.3 2.7 6 6 6h340c3.3 0 6-2.7 6-6z"/></svg>
To use it at css background-image you gotta encode the svg to address valid string. I used this tool
As far as you got all stuff you need, you're coming to css
.calendarIcon{
//your url will be something like this:
background-image: url("data:image/svg+xml,***<here place encoded svg>***");
background-repeat: no-repeat;
}
Note: these styling wont have any effect on encoded svg image
.{
fill: #f00; //neither this
background-color: #f00; //nor this
}
because all changes over the image must be applied directly to its svg code
<svg xmlns="" path="" fill="#f00"/></svg>
To achive the location righthand i copied some Bootstrap spacing and my final css get the next look:
.calendarIcon{
background-image: url("data:image/svg+xml,%3Csvg...svg%3E");
background-repeat: no-repeat;
padding-right: calc(1.5em + 0.75rem);
background-position: center right calc(0.375em + 0.1875rem);
background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
}
Quick fix that works for me. Navigate to the root directory of your folder from command line (cmd). then once you are on your root directory, type:
code .
Then, press enter. Note the ".", don't forget it. Now try to debug and see if you get the same error.
Slightly shorter code using insertRow
and insertCell
:
function tableCreate(){_x000D_
var body = document.body,_x000D_
tbl = document.createElement('table');_x000D_
tbl.style.width = '100px';_x000D_
tbl.style.border = '1px solid black';_x000D_
_x000D_
for(var i = 0; i < 3; i++){_x000D_
var tr = tbl.insertRow();_x000D_
for(var j = 0; j < 2; j++){_x000D_
if(i == 2 && j == 1){_x000D_
break;_x000D_
} else {_x000D_
var td = tr.insertCell();_x000D_
td.appendChild(document.createTextNode('Cell'));_x000D_
td.style.border = '1px solid black';_x000D_
if(i == 1 && j == 1){_x000D_
td.setAttribute('rowSpan', '2');_x000D_
}_x000D_
}_x000D_
}_x000D_
}_x000D_
body.appendChild(tbl);_x000D_
}_x000D_
tableCreate();
_x000D_
Also, this doesn't use some "bad practices", such as setting a border
attribute instead of using CSS, and it accesses the body
through document.body
instead of document.getElementsByTagName('body')[0]
;
This is not a new answer, but it helped me to understand the different aspects of the answers above (and it is too much for a comment).
Using Git Bash just try:
me@pc MINGW64 /c/Test
$ ls -al
total 16
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:35 ./
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:11 ../
me@pc MINGW64 /c/Test
$ git init
Initialized empty Git repository in C:/Test/.git/
me@pc MINGW64 /c/Test (master)
$ ls -al
total 20
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:35 ./
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:11 ../
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:35 .git/
me@pc MINGW64 /c/Test (master)
$ cd .git
me@pc MINGW64 /c/Test/.git (GIT_DIR!)
$ ls -al
total 15
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:35 ./
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:35 ../
-rw-r--r-- 1 myid 1049089 130 Apr 1 11:35 config
-rw-r--r-- 1 myid 1049089 73 Apr 1 11:35 description
-rw-r--r-- 1 myid 1049089 23 Apr 1 11:35 HEAD
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:35 hooks/
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:35 info/
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:35 objects/
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:35 refs/
Same with git --bare
:
me@pc MINGW64 /c/Test
$ ls -al
total 16
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:36 ./
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:11 ../
me@pc MINGW64 /c/Test
$ git init --bare
Initialized empty Git repository in C:/Test/
me@pc MINGW64 /c/Test (BARE:master)
$ ls -al
total 23
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:36 ./
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:11 ../
-rw-r--r-- 1 myid 1049089 104 Apr 1 11:36 config
-rw-r--r-- 1 myid 1049089 73 Apr 1 11:36 description
-rw-r--r-- 1 myid 1049089 23 Apr 1 11:36 HEAD
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:36 hooks/
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:36 info/
drwxr-xr-x 1 myid 1049089 0 Apr 1 11:36 objects/
You just have to define that Animal implements Comparable<Animal>
i.e. public class Animal implements Comparable<Animal>
. And then you have to implement the compareTo(Animal other)
method that way you like it.
@Override
public int compareTo(Animal other) {
return Integer.compare(this.year_discovered, other.year_discovered);
}
Using this implementation of compareTo
, animals with a higher year_discovered
will get ordered higher. I hope you get the idea of Comparable
and compareTo
with this example.
# index dictionary by list of key names
def fn1():
print "One"
def fn2():
print "Two"
def fn3():
print "Three"
fndict = {"A": fn1, "B": fn2, "C": fn3}
keynames = ["A", "B", "C"]
fndict[keynames[1]]()
# keynames[1] = "B", so output of this code is
# Two
You can change this one parent attribute ="android:style/Theme.Holo.Light.DarkActionBar"
Another way of creating and initializing an array of objects. This is similar to the example which @Amol has posted above, except this one uses constructors. A dash of polymorphism sprinkled in, I couldn't resist.
IUser[] userArray = new IUser[]
{
new DummyUser("[email protected]", "Gibberish"),
new SmartyUser("[email protected]", "Italian", "Engineer")
};
Classes for context:
interface IUser
{
string EMail { get; } // immutable, so get only an no set
string Language { get; }
}
public class DummyUser : IUser
{
public DummyUser(string email, string language)
{
m_email = email;
m_language = language;
}
private string m_email;
public string EMail
{
get { return m_email; }
}
private string m_language;
public string Language
{
get { return m_language; }
}
}
public class SmartyUser : IUser
{
public SmartyUser(string email, string language, string occupation)
{
m_email = email;
m_language = language;
m_occupation = occupation;
}
private string m_email;
public string EMail
{
get { return m_email; }
}
private string m_language;
public string Language
{
get { return m_language; }
}
private string m_occupation;
}
See the below code (taken from this post)
Put this code in a Module in VBA (Developer Tab -> Visual Basic)
Dim TimerActive As Boolean
Sub StartTimer()
Start_Timer
End Sub
Private Sub Start_Timer()
TimerActive = True
Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End Sub
Private Sub Stop_Timer()
TimerActive = False
End Sub
Private Sub Timer()
If TimerActive Then
ActiveSheet.Cells(1, 1).Value = Time
Application.OnTime Now() + TimeValue("00:01:00"), "Timer"
End If
End Sub
You can invoke the "StartTimer" function when the workbook opens and have it repeat every minute by adding the below code to your workbooks Visual Basic "This.Workbook" class in the Visual Basic editor.
Private Sub Workbook_Open()
Module1.StartTimer
End Sub
Now, every time 1 minute passes the Timer procedure will be invoked, and set cell A1 equal to the current time.
To be able to automatically throw an error when x become less than zero throughout the function. You can use class descriptors. Here is an example:
class LessThanZeroException(Exception):
pass
class variable(object):
def __init__(self, value=0):
self.__x = value
def __set__(self, obj, value):
if value < 0:
raise LessThanZeroException('x is less than zero')
self.__x = value
def __get__(self, obj, objType):
return self.__x
class MyClass(object):
x = variable()
>>> m = MyClass()
>>> m.x = 10
>>> m.x -= 20
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "my.py", line 7, in __set__
raise LessThanZeroException('x is less than zero')
LessThanZeroException: x is less than zero
Remove the course_enrollment_settings.base_price
immediately after CASE
:
SELECT
CASE
WHEN course_enrollment_settings.base_price = 0 THEN 1
...
END
CASE
has two different forms, as detailed in the manual. Here, you want the second form since you're using search conditions.
use onPause()
method to do what you want to do on home button.
For static files like pdfs, Word docs, etc. just use Express's static function in your config:
// Express config
var app = express().configure(function () {
this.use('/public', express.static('public')); // <-- This right here
});
And then just put all your files inside that 'public' folder, for example:
/public/docs/my_word_doc.docx
And then a regular old link will allow the user to download it:
<a href="public/docs/my_word_doc.docx">My Word Doc</a>
Here is an example for VueJS
index.page
<template>
<div>
<div ref="topScroll" class="top-scroll" @scroll.passive="handleScroll">
<div
:style="{
width: `${contentWidth}px`,
height: '12px'
}"
/>
</div>
<div ref="content" class="content" @scroll.passive="handleScroll">
<div
:style="{
width: `${contentWidth}px`
}"
>
Lorem ipsum dolor sit amet, ipsum dictum vulputate molestie id magna,
nunc laoreet maecenas, molestie ipsum donec lectus ut et sit, aut ut ut
viverra vivamus mollis in, integer diam purus penatibus. Augue consequat
quis phasellus non, congue tristique ac arcu cras ligula congue, elit
hendrerit lectus faucibus arcu ligula a, id hendrerit dolor nec nec
placerat. Vel ornare tincidunt tincidunt, erat amet mollis quisque, odio
cursus gravida libero aliquam duis, dolor sed nulla dignissim praesent
erat, voluptatem pede aliquam. Ut et tellus mi fermentum varius, feugiat
nullam nunc ultrices, ullamcorper pede, nunc vestibulum, scelerisque
nunc lectus integer. Nec id scelerisque vestibulum, elit sit, cursus
neque varius. Fusce in, nunc donec, volutpat mauris wisi sem, non
sapien. Pellentesque nisl, lectus eros hendrerit dui. In metus aptent
consectetuer, sociosqu massa mus fermentum mauris dis, donec erat nunc
orci.
</div>
</div>
</div>
</template>
<script>
export default {
data() {
return {
contentWidth: 1000
}
},
methods: {
handleScroll(event) {
if (event.target._prevClass === 'content') {
this.$refs.topScroll.scrollLeft = this.$refs.content.scrollLeft
} else {
this.$refs.content.scrollLeft = this.$refs.topScroll.scrollLeft
}
}
}
}
</script>
<style lang="scss" scoped>
.top-scroll,
.content {
overflow: auto;
max-width: 100%;
}
.top-scroll {
margin-top: 50px;
}
</style>
TAKE NOTE on the height: 12px
.. I made it 12px so it will be noticed on Mac Users as well. But w/ windows, 0.1px is good enough
If you have a url and your php supports it, you could just call file_get_contents:
$response = file_get_contents('http://example.com/path/to/api/call?param1=5');
if $response is JSON, use json_decode to turn it into php array:
$response = json_decode($response);
if $response is XML, use simple_xml class:
$response = new SimpleXMLElement($response);
I have added below code to terminate tasks you can use it. You may change the retry numbers.
package com.xxx.test.schedulers;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextClosedEvent;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
import org.springframework.stereotype.Component;
import com.xxx.core.XProvLogger;
@Component
class ContextClosedHandler implements ApplicationListener<ContextClosedEvent> , ApplicationContextAware,BeanPostProcessor{
private ApplicationContext context;
public Logger logger = XProvLogger.getInstance().x;
public void onApplicationEvent(ContextClosedEvent event) {
Map<String, ThreadPoolTaskScheduler> schedulers = context.getBeansOfType(ThreadPoolTaskScheduler.class);
for (ThreadPoolTaskScheduler scheduler : schedulers.values()) {
scheduler.getScheduledExecutor().shutdown();
try {
scheduler.getScheduledExecutor().awaitTermination(20000, TimeUnit.MILLISECONDS);
if(scheduler.getScheduledExecutor().isTerminated() || scheduler.getScheduledExecutor().isShutdown())
logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has stoped");
else{
logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has not stoped normally and will be shut down immediately");
scheduler.getScheduledExecutor().shutdownNow();
logger.info("Scheduler "+scheduler.getThreadNamePrefix() + " has shut down immediately");
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Map<String, ThreadPoolTaskExecutor> executers = context.getBeansOfType(ThreadPoolTaskExecutor.class);
for (ThreadPoolTaskExecutor executor: executers.values()) {
int retryCount = 0;
while(executor.getActiveCount()>0 && ++retryCount<51){
try {
logger.info("Executer "+executor.getThreadNamePrefix()+" is still working with active " + executor.getActiveCount()+" work. Retry count is "+retryCount);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if(!(retryCount<51))
logger.info("Executer "+executor.getThreadNamePrefix()+" is still working.Since Retry count exceeded max value "+retryCount+", will be killed immediately");
executor.shutdown();
logger.info("Executer "+executor.getThreadNamePrefix()+" with active " + executor.getActiveCount()+" work has killed");
}
}
@Override
public void setApplicationContext(ApplicationContext context)
throws BeansException {
this.context = context;
}
@Override
public Object postProcessAfterInitialization(Object object, String arg1)
throws BeansException {
return object;
}
@Override
public Object postProcessBeforeInitialization(Object object, String arg1)
throws BeansException {
if(object instanceof ThreadPoolTaskScheduler)
((ThreadPoolTaskScheduler)object).setWaitForTasksToCompleteOnShutdown(true);
if(object instanceof ThreadPoolTaskExecutor)
((ThreadPoolTaskExecutor)object).setWaitForTasksToCompleteOnShutdown(true);
return object;
}
}
An example to help you get off the ground.
for f in *.jpg; do mv "$f" "$(echo "$f" | sed s/IMG/VACATION/)"; done
In this example, I am assuming that all your image files contain the string IMG
and you want to replace IMG
with VACATION
.
The shell automatically evaluates *.jpg
to all the matching files.
The second argument of mv
(the new name of the file) is the output of the sed
command that replaces IMG
with VACATION
.
If your filenames include whitespace pay careful attention to the "$f"
notation. You need the double-quotes to preserve the whitespace.
you do not need to know pts number, just type:
ps all | grep bash
then:
kill pid1 pid2 pid3 ...
In my case, what I concerned about is the C: drive disk space. So what I did is copy the ".avd" folder(not file) to other drive, and leave the ".ini" file there but change it to point to the moved
Having $line
as it is now, you can simply split the string based on at least one whitespace separator
my @answer = split(' ', $line); # creates an @answer array
then
print("@answer\n"); # print array on one line
or
print("$_\n") for (@answer); # print each element on one line
I prefer using ()
for split
, print
and for
.
Try a "binary search". Delete half the code and try again. If the error is still there, delete half the remaining code. If the error is not there, put what you deleted back in, and delete half of that. Repeat.
You should be able to narrow it down to a few line fairly quickly. My experience has been that at this point, you will notice some stupid malformed string.
It may be expedient to perform this on a saved version of the HTML output to the browser, if you're not sure which server-side resource the error is in.
I think that error from Nginx is indicating that the connection was closed by your nodejs server (i.e., "upstream"). How is nodejs configured?
Your original plan sounds fine to me. You'll probably find more browser quirks dealing with dynamically managing the <source>
elements, as indicated here by the W3 spec note:
Dynamically modifying a source element and its attribute when the element is already inserted in a video or audio element will have no effect. To change what is playing, just use the src attribute on the media element directly, possibly making use of the canPlayType() method to pick from amongst available resources. Generally, manipulating source elements manually after the document has been parsed is an unncessarily[sic] complicated approach.
http://dev.w3.org/html5/spec/Overview.html#the-source-element
X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!
There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.
Source: classroomm.com
my experience tells me that missing persistence.xml,will generate the same exception too.
i caught the same error msg today when i tried to run a jar package packed by ant.
when i used jar tvf to check the content of the jar file, i realized that "ant" forgot to pack the persistnece.xml for me.
after I manually repacked the jar file ,the error msg disappered.
so i believe maybe you should try simplely putting META-INF under src directory and placing your persistence.xml there.
as @Pointy said you don't cache images with javascript, the browser does that. so this may be what you are asking for and may not be... but you can preload images using javascript. By putting all of the images you want to preload into an array and putting all of the images in that array into hidden img elements, you effectively preload (or cache) the images.
var images = [
'/path/to/image1.png',
'/path/to/image2.png'
];
$(images).each(function() {
var image = $('<img />').attr('src', this);
});
Use
git status
to check what's going on.
Then
git checkout master
git merge --squash bugfix
git add (add which files you want or use wildcard command like ".")
Then
git commit -m "message"
And now last but not the least
git push -u origin master
Here origin
can be other remote you prefer.
The above responses are the better, but just for completeness, when you are in a component you can access the history object inside the VueRouter with: this.$router.history. That means we can listen to changes with:
this.$router.listen((newLocation) =>{console.log(newLocation);})
I think this is mainly useful when used along with this.$router.currentRoute.path
You can check what I am talking about placing a debugger
instruction in your code and begin playing with the Chrome DevTools Console.
Use this to get your current time in specified format :
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
System.out.print(dateFormat.format(System.currentTimeMillis())); }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
public partial class CS : System.Web.UI.Page
{
protected void ExportCSV(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
//Build the CSV file data as a Comma separated string.
string csv = string.Empty;
foreach (DataColumn column in dt.Columns)
{
//Add the Header row for CSV file.
csv += column.ColumnName + ',';
}
//Add new line.
csv += "\r\n";
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
//Add the Data rows.
csv += row[column.ColumnName].ToString().Replace(",", ";") + ',';
}
//Add new line.
csv += "\r\n";
}
//Download the CSV file.
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=SqlExport.csv");
Response.Charset = "";
Response.ContentType = "application/text";
Response.Output.Write(csv);
Response.Flush();
Response.End();
}
}
}
}
}
}