I'm facing same issue and resolving through
git add .
git commit -m "message"
git remote set-url origin https://[email protected]/aceofwings/RotairERP.git
then
git pull
It is known Chrome problem. According to Chrome and Chromium bug trackers there is no universal solution for this. This problem is not related with server type and version, it is right in Chrome.
Setting Content-Encoding
header to identity
solved this problem to me.
identity | Indicates the identity function (i.e. no compression, nor modification).
So, I can suggest, that in some cases Chrome can not perform gzip compress correctly.
Each instantiation and full specialization of std::atomic<> represents a type that different threads can simultaneously operate on (their instances), without raising undefined behavior:
Objects of atomic types are the only C++ objects that are free from data races; that is, if one thread writes to an atomic object while another thread reads from it, the behavior is well-defined.
In addition, accesses to atomic objects may establish inter-thread synchronization and order non-atomic memory accesses as specified by
std::memory_order
.
std::atomic<>
wraps operations that, in pre-C++ 11 times, had to be performed using (for example) interlocked functions with MSVC or atomic bultins in case of GCC.
Also, std::atomic<>
gives you more control by allowing various memory orders that specify synchronization and ordering constraints. If you want to read more about C++ 11 atomics and memory model, these links may be useful:
Note that, for typical use cases, you would probably use overloaded arithmetic operators or another set of them:
std::atomic<long> value(0);
value++; //This is an atomic op
value += 5; //And so is this
Because operator syntax does not allow you to specify the memory order, these operations will be performed with std::memory_order_seq_cst
, as this is the default order for all atomic operations in C++ 11. It guarantees sequential consistency (total global ordering) between all atomic operations.
In some cases, however, this may not be required (and nothing comes for free), so you may want to use more explicit form:
std::atomic<long> value {0};
value.fetch_add(1, std::memory_order_relaxed); // Atomic, but there are no synchronization or ordering constraints
value.fetch_add(5, std::memory_order_release); // Atomic, performs 'release' operation
Now, your example:
a = a + 12;
will not evaluate to a single atomic op: it will result in a.load()
(which is atomic itself), then addition between this value and 12
and a.store()
(also atomic) of final result. As I noted earlier, std::memory_order_seq_cst
will be used here.
However, if you write a += 12
, it will be an atomic operation (as I noted before) and is roughly equivalent to a.fetch_add(12, std::memory_order_seq_cst)
.
As for your comment:
A regular
int
has atomic loads and stores. Whats the point of wrapping it withatomic<>
?
Your statement is only true for architectures that provide such guarantee of atomicity for stores and/or loads. There are architectures that do not do this. Also, it is usually required that operations must be performed on word-/dword-aligned address to be atomic std::atomic<>
is something that is guaranteed to be atomic on every platform, without additional requirements. Moreover, it allows you to write code like this:
void* sharedData = nullptr;
std::atomic<int> ready_flag = 0;
// Thread 1
void produce()
{
sharedData = generateData();
ready_flag.store(1, std::memory_order_release);
}
// Thread 2
void consume()
{
while (ready_flag.load(std::memory_order_acquire) == 0)
{
std::this_thread::yield();
}
assert(sharedData != nullptr); // will never trigger
processData(sharedData);
}
Note that assertion condition will always be true (and thus, will never trigger), so you can always be sure that data is ready after while
loop exits. That is because:
store()
to the flag is performed after sharedData
is set (we assume that generateData()
always returns something useful, in particular, never returns NULL
) and uses std::memory_order_release
order:
memory_order_release
A store operation with this memory order performs the release operation: no reads or writes in the current thread can be reordered after this store. All writes in the current thread are visible in other threads that acquire the same atomic variable
sharedData
is used after while
loop exits, and thus after load()
from flag will return a non-zero value. load()
uses std::memory_order_acquire
order:
std::memory_order_acquire
A load operation with this memory order performs the acquire operation on the affected memory location: no reads or writes in the current thread can be reordered before this load. All writes in other threads that release the same atomic variable are visible in the current thread.
This gives you precise control over the synchronization and allows you to explicitly specify how your code may/may not/will/will not behave. This would not be possible if only guarantee was the atomicity itself. Especially when it comes to very interesting sync models like the release-consume ordering.
It looks like your Google Play registration payment didn’t process. This can happen sometimes if a card has expired, the credit card or credit card verification (CVC) number was entered incorrectly, or if your billing address doesn't match the address in your Google Payments account.
Here’s how you can find the details of your transaction:
Sign in to your Google Payments account at https://payments.google.com.
On the left menu, select the “Subscriptions and services” page.
On the “Other purchase activity” card, click View purchases.
Click the “Google Play” registration transaction to see your payment method.
You can click “Payment methods” on the left menu if you need to edit the addresses on your Google Payments account.
To add a new credit or debit card to your account, you can follow the instructions on the Google Payments Help Center (https://support.google.com/payments/answer/6220309).
Read the section from the Swing tutorial on Implementing a DocumentFilter for a more current solution.
This solution will work an any Document, not just a PlainDocument.
This is a more current solution than the one accepted.
you should change cr_date(str) to datetime object then you 'll change the date to the specific format:
cr_date = '2013-10-31 18:23:29.000227'
cr_date = datetime.datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
cr_date = cr_date.strftime("%m/%d/%Y")
You first have to tell Gnuplot to use a style that uses points, e.g. with points
or with linespoints
. Try for example:
plot sin(x) with points
Output:
Now try:
plot sin(x) with points pointtype 5
Output:
You may also want to look at the output from the test
command which shows you the capabilities of the current terminal. Here are the capabilities for my pngairo terminal:
setTimeout(callback,t)
is used to run callback after at least t millisecond. The actual delay depends on many external factors like OS timer granularity and system load.
So, there is a possibility that it will be called slightly after the set time, but will never be called before.
A timer can't span more than 24.8 days.
The solution I used was to create a javascript function that uses jquery:
This will populate a dropdown object on the HTML page. Please let me know where this can be optimized - but works fine as is.
function util_PopulateDropDownListAndSelect(sourceListObject, sourceListTextFieldName, targetDropDownName, valueToSelect)
{
var options = '';
// Create the list of HTML Options
for (i = 0; i < sourceListObject.List.length; i++)
{
options += "<option value='" + sourceListObject.List[i][sourceListTextFieldName] + "'>" + sourceListObject.List[i][sourceListTextFieldName] + "</option>\r\n";
}
// Assign the options to the HTML Select container
$('select#' + targetDropDownName)[0].innerHTML = options;
// Set the option to be Selected
$('#' + targetDropDownName).val(valueToSelect);
// Refresh the HTML Select so it displays the Selected option
$('#' + targetDropDownName).selectmenu('refresh')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
A simple solution but it gets the job done, assigns a known length and precision and avoids the chance of going exponential format (which is a risk when you use %g):
// Since we are only interested in 3 decimal places, this function
// can avoid any potential miniscule floating point differences
// which can return false when using "=="
int DoubleEquals(double i, double j)
{
return (fabs(i - j) < 0.000001);
}
void PrintMaxThreeDecimal(double d)
{
if (DoubleEquals(d, floor(d)))
printf("%.0f", d);
else if (DoubleEquals(d * 10, floor(d * 10)))
printf("%.1f", d);
else if (DoubleEquals(d * 100, floor(d* 100)))
printf("%.2f", d);
else
printf("%.3f", d);
}
Add or remove "elses" if you want a max of 2 decimals; 4 decimals; etc.
For example if you wanted 2 decimals:
void PrintMaxTwoDecimal(double d)
{
if (DoubleEquals(d, floor(d)))
printf("%.0f", d);
else if (DoubleEquals(d * 10, floor(d * 10)))
printf("%.1f", d);
else
printf("%.2f", d);
}
If you want to specify the minimum width to keep fields aligned, increment as necessary, for example:
void PrintAlignedMaxThreeDecimal(double d)
{
if (DoubleEquals(d, floor(d)))
printf("%7.0f", d);
else if (DoubleEquals(d * 10, floor(d * 10)))
printf("%9.1f", d);
else if (DoubleEquals(d * 100, floor(d* 100)))
printf("%10.2f", d);
else
printf("%11.3f", d);
}
You could also convert that to a function where you pass the desired width of the field:
void PrintAlignedWidthMaxThreeDecimal(int w, double d)
{
if (DoubleEquals(d, floor(d)))
printf("%*.0f", w-4, d);
else if (DoubleEquals(d * 10, floor(d * 10)))
printf("%*.1f", w-2, d);
else if (DoubleEquals(d * 100, floor(d* 100)))
printf("%*.2f", w-1, d);
else
printf("%*.3f", w, d);
}
Joining fails if the DataFrames have some column names in common. The simplest way around it is to include an lsuffix
or rsuffix
keyword like so:
restaurant_review_frame.join(restaurant_ids_dataframe, on='business_id', how='left', lsuffix="_review")
This way, the columns have distinct names. The documentation addresses this very problem.
Or, you could get around this by simply deleting the offending columns before you join. If, for example, the stars in restaurant_ids_dataframe
are redundant to the stars in restaurant_review_frame
, you could del restaurant_ids_dataframe['stars']
.
This answer is late, but I was having the same issue. I found something that works.
In eclipse Project Explorer, right click the project name -> select "Run As" -> "Maven Build..."
In the goals, enter spring-boot:run
then click Run button.
I have the STS plug-in (i.e. SpringSource Tool Suite), so on some projects I will get a "Spring Boot App" option under Run As. But, it doesn't always show up for some reason. I use the above workaround for those.
Here is a reference that explains how to run Spring boot apps:
Spring boot tutorial
It's an interesting question, because it shows that there are a lot of different approaches to achieve the same result. Below I show three different implementations.
Default methods in Collection Framework: Java 8 added some methods to the collections classes, that are not directly related to the Stream API. Using these methods, you can significantly simplify the implementation of the non-stream implementation:
Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
Map<String, DataSet> result = new HashMap<>();
multiDataPoints.forEach(pt ->
pt.keyToData.forEach((key, value) ->
result.computeIfAbsent(
key, k -> new DataSet(k, new ArrayList<>()))
.dataPoints.add(new DataPoint(pt.timestamp, value))));
return result.values();
}
Stream API with flatten and intermediate data structure: The following implementation is almost identical to the solution provided by Stuart Marks. In contrast to his solution, the following implementation uses an anonymous inner class as intermediate data structure.
Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
return multiDataPoints.stream()
.flatMap(mdp -> mdp.keyToData.entrySet().stream().map(e ->
new Object() {
String key = e.getKey();
DataPoint dataPoint = new DataPoint(mdp.timestamp, e.getValue());
}))
.collect(
collectingAndThen(
groupingBy(t -> t.key, mapping(t -> t.dataPoint, toList())),
m -> m.entrySet().stream().map(e -> new DataSet(e.getKey(), e.getValue())).collect(toList())));
}
Stream API with map merging: Instead of flattening the original data structures, you can also create a Map for each MultiDataPoint, and then merge all maps into a single map with a reduce operation. The code is a bit simpler than the above solution:
Collection<DataSet> convert(List<MultiDataPoint> multiDataPoints) {
return multiDataPoints.stream()
.map(mdp -> mdp.keyToData.entrySet().stream()
.collect(toMap(e -> e.getKey(), e -> asList(new DataPoint(mdp.timestamp, e.getValue())))))
.reduce(new HashMap<>(), mapMerger())
.entrySet().stream()
.map(e -> new DataSet(e.getKey(), e.getValue()))
.collect(toList());
}
You can find an implementation of the map merger within the Collectors class. Unfortunately, it is a bit tricky to access it from the outside. Following is an alternative implementation of the map merger:
<K, V> BinaryOperator<Map<K, List<V>>> mapMerger() {
return (lhs, rhs) -> {
Map<K, List<V>> result = new HashMap<>();
lhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
rhs.forEach((key, value) -> result.computeIfAbsent(key, k -> new ArrayList<>()).addAll(value));
return result;
};
}
Codes starting with 4 (4xx) are meant for client errors. Maybe 400 (Bad Request) could be suitable to this case? Definition in http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html says:
"The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications. "
inside the Android manifest file of your project, find the activity declaration of whose you want to fix the orientation and add the following piece of code ,
android:screenOrientation="landscape"
for landscape orientation and for portrait add the following code,
android:screenOrientation="portrait"
Here is an answer proposal:
http://www.greenvilleweb.us/how-to-web-design/problem-with-ie-9-caching-ajax-get-request/
The idea is to add a parameter to your ajax query containing for example the current date an time, so the browser will not be able to cache it.
Have a look on the link, it is well explained.
Just a note for other users searching for answers for thie error. Another common issue is:
You generally cannot call an
@transactional
method from within the same class.
(There are ways and means using AspectJ but refactoring will be way easier)
So you'll need a calling class and class that holds the @transactional
methods.
Basic Structure Here is an example of a JUnit output file, showing a skip and failed result, as well as a single passed result.
<?xml version="1.0" encoding="UTF-8"?>
<testsuites>
<testsuite name="JUnitXmlReporter" errors="0" tests="0" failures="0" time="0" timestamp="2013-05-24T10:23:58" />
<testsuite name="JUnitXmlReporter.constructor" errors="0" skipped="1" tests="3" failures="1" time="0.006" timestamp="2013-05-24T10:23:58">
<properties>
<property name="java.vendor" value="Sun Microsystems Inc." />
<property name="compiler.debug" value="on" />
<property name="project.jdk.classpath" value="jdk.classpath.1.6" />
</properties>
<testcase classname="JUnitXmlReporter.constructor" name="should default path to an empty string" time="0.006">
<failure message="test failure">Assertion failed</failure>
</testcase>
<testcase classname="JUnitXmlReporter.constructor" name="should default consolidate to true" time="0">
<skipped />
</testcase>
<testcase classname="JUnitXmlReporter.constructor" name="should default useDotNotation to true" time="0" />
</testsuite>
</testsuites>
Below is the documented structure of a typical JUnit XML report. Notice that a report can contain 1 or more test suite. Each test suite has a set of properties (recording environment information). Each test suite also contains 1 or more test case and each test case will either contain a skipped, failure or error node if the test did not pass. If the test case has passed, then it will not contain any nodes. For more details of which attributes are valid for each node please consult the following section "Schema".
<testsuites> => the aggregated result of all junit testfiles
<testsuite> => the output from a single TestSuite
<properties> => the defined properties at test execution
<property> => name/value pair for a single property
...
</properties>
<error></error> => optional information, in place of a test case - normally if the tests in the suite could not be found etc.
<testcase> => the results from executing a test method
<system-out> => data written to System.out during the test run
<system-err> => data written to System.err during the test run
<skipped/> => test was skipped
<failure> => test failed
<error> => test encountered an error
</testcase>
...
</testsuite>
...
</testsuites>
Go to SDK Manager and see if there are any updates on the emulator & build tools that need to be updated.
I had similiar problem and this is how I solved it:
In index.html
file I've added manifest:
<html manifest="cache.manifest">
In <head>
section included script updating the cache:
<script type="text/javascript" src="update_cache.js"></script>
In <body>
section I've inserted onload function:
<body onload="checkForUpdate()">
In cache.manifest
I've put all files I want to cache. It is important now that it works in my case (Apache) just by updating each time the "version" comment. It is also an option to name files with "?ver=001" or something at the end of name but it's not needed. Changing just # version 1.01
triggers cache update event.
CACHE MANIFEST
# version 1.01
style.css
imgs/logo.png
#all other files
It's important to include 1., 2. and 3. points only in index.html. Otherwise
GET http://foo.bar/resource.ext net::ERR_FAILED
occurs because every "child" file tries to cache the page while the page is already cached.
In update_cache.js
file I've put this code:
function checkForUpdate()
{
if (window.applicationCache != undefined && window.applicationCache != null)
{
window.applicationCache.addEventListener('updateready', updateApplication);
}
}
function updateApplication(event)
{
if (window.applicationCache.status != 4) return;
window.applicationCache.removeEventListener('updateready', updateApplication);
window.applicationCache.swapCache();
window.location.reload();
}
Now you just change files and in manifest you have to update version comment. Now visiting index.html page will update the cache.
The parts of solution aren't mine but I've found them through internet and put together so that it works.
Have you tried CompoundButton
? CompoundButton has the checkable property that exactly matches your need. Replace ImageButtons with these.
<CompoundButton android:id="@+id/buttonhome"
android:layout_width="80dp"
android:layout_height="36dp"
android:background="@drawable/homeselector"/>
Change selector xml to the following. May need some modification but be sure to use state_checked
in place of state_pressed
.
<?xml version="1.0" encoding="UTF-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:drawable="@drawable/homehover" />
<item android:state_checked="true" android:state_enabled="true"
android:drawable="@drawable/homehover" />
<item android:state_focused="true" android:state_enabled="true"
android:drawable="@drawable/homehover" />
<item android:state_enabled="true" android:drawable="@drawable/home" />
</selector>
In CompoundButton.OnCheckedChangeListener
you need to check and uncheck other based on your conditions.
mButton1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged (CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
// Uncheck others.
}
}
});
Similarly set a OnCheckedChangeListener
to each button, which will uncheck other buttons when it is checked. Hope this Helps.
Move it to the Trusted Sites zone by either adding it to a Trusted Sites list or local setting. This will move it out of Intranet Zone and will not be rendered in Compat. View.
If both application have the same signature (meaning that both APPS are yours and signed with the same key), you can call your other app activity as follows:
Intent LaunchIntent = getActivity().getPackageManager().getLaunchIntentForPackage(CALC_PACKAGE_NAME);
startActivity(LaunchIntent);
Hope it helps.
Angular hasn't provided a way to signal when a page finished loading, maybe because "finished" depends on your application. For example, if you have hierarchical tree of partials, one loading the others. "Finish" would mean that all of them have been loaded. Any framework would have a hard time analyzing your code and understanding that everything is done, or still waited upon. For that, you would have to provide application-specific logic to check and determine that.
In the first code block, you're never using the str
parameter. Did you mean to say the following?
testFunc = function(str, callback) {
$.ajax({
type: 'POST',
url: 'http://www.myurl.com',
data: str,
success: callback
});
}
There is a "variant" to pax' answer... ;-)
int i = -1;
for(String s : stringArray) {
doSomethingWith(s, ++i);
}
I'm working on an open-source project called Todoc which analyzes words to produce proper documentation output automatically when saving a file. It respects existing comments and is really fast and fluid.
As stated above to define a map as constant is not possible. But you can declare a global variable which is a struct that contains a map.
The Initialization would look like this:
var romanNumeralDict = struct {
m map[int]string
}{m: map[int]string {
1000: "M",
900: "CM",
//YOUR VALUES HERE
}}
func main() {
d := 1000
fmt.Printf("Value of Key (%d): %s", d, romanNumeralDict.m[1000])
}
The answers listed are partial according to me. I have linked below two examples of how to do this in Angular and with JQuery.
This solution has the following features:
JQuery: http://plnkr.co/edit/VZ0o2FJQHTmOMfSPRqpH?p=preview
$("input").blur(function() {
if ($(this).attr("data-selected-all")) {
//Remove atribute to allow select all again on focus
$(this).removeAttr("data-selected-all");
}
});
$("input").click(function() {
if (!$(this).attr("data-selected-all")) {
try {
$(this).selectionStart = 0;
$(this).selectionEnd = $(this).value.length + 1;
//add atribute allowing normal selecting post focus
$(this).attr("data-selected-all", true);
} catch (err) {
$(this).select();
//add atribute allowing normal selecting post focus
$(this).attr("data-selected-all", true);
}
}
});
Angular: http://plnkr.co/edit/llcyAf?p=preview
var app = angular.module('app', []);
//add select-all-on-click to any input to use directive
app.directive('selectAllOnClick', [function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var hasSelectedAll = false;
element.on('click', function($event) {
if (!hasSelectedAll) {
try {
//iOS, Safari, thows exception on Chrome etc
this.selectionStart = 0;
this.selectionEnd = this.value.length + 1;
hasSelectedAll = true;
} catch (err) {
//Non iOS option if not supported, e.g. Chrome
this.select();
hasSelectedAll = true;
}
}
});
//On blur reset hasSelectedAll to allow full select
element.on('blur', function($event) {
hasSelectedAll = false;
});
}
};
}]);
Based on the very elegant callback pipe solution proposed above, it is possible to generalize it a bit further by allowing additional filter parameters to be passed along. We then have :
callback.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'callback',
pure: false
})
export class CallbackPipe implements PipeTransform {
transform(items: any[], callback: (item: any, callbackArgs?: any[]) => boolean, callbackArgs?: any[]): any {
if (!items || !callback) {
return items;
}
return items.filter(item => callback(item, callbackArgs));
}
}
component
filterSomething(something: Something, filterArgs: any[]) {
const firstArg = filterArgs[0];
const secondArg = filterArgs[1];
...
return <some condition based on something, firstArg, secondArg, etc.>;
}
html
<li *ngFor="let s of somethings | callback : filterSomething : [<whatWillBecomeFirstArg>, <whatWillBecomeSecondArg>, ...]">
{{s.aProperty}}
</li>
import os
for subdir, dirs, files in os.walk('./'):
for file in files:
do some stuff
print file
You can improve this code with del dirs[:]
which will be like following .
import os
for subdir, dirs, files in os.walk('./'):
del dirs[:]
for file in files:
do some stuff
print file
Or even better if you could point os.walk with current working directory .
import os
cwd = os.getcwd()
for subdir, dirs, files in os.walk(cwd, topdown=True):
del dirs[:] # remove the sub directories.
for file in files:
do some stuff
print file
If not HTML
, then UTF-8
is not recommended. koi8-r
and windows-1251
only without problems. So use html mail.
$headers['Content-Type']='text/html; charset=UTF-8';
$body='<html><head><meta charset="UTF-8"><title>ESP Notufy - ESP ?????????</title></head><body>'.$text.'</body></html>';
$mail_object=& Mail::factory('smtp',
array ('host' => $host,
'auth' => true,
'username' => $username,
'password' => $password));
$mail_object->send($recipents, $headers, $body);
}
Install npm => sudo apt-get install npm
Install n => sudo npm install n -g
latest version of node => sudo n latest
Specific version of node you can
List available node versions => n ls
Install a specific version => sudo n 4.5.0
Output the images in a lossless format such as PNG:
ffmpeg.exe -i 10fps.h264 -r 10 -f image2 10fps.h264_%03d.png
Edit/Update: Not quite sure why I originally gave a strange filename example (with a possibly made-up extension).
I have since found that
-vsync 0
is simpler than-r 10
because it avoids needing to know the frame rate.This is something like what I currently use:
mkdir stills ffmpeg -i my-film.mp4 -vsync 0 -f image2 stills/my-film-%06d.png
To extract only the key frames (which are likely to be of higher quality post-edit):
ffmpeg -skip_frame nokey -i my-film.mp4 -vsync 0 -f image2 stills/my-film-%06d.png
Then use another program (where you can more precisely specify quality, subsampling and DCT method – e.g. GIMP) to convert the PNGs you want to JPEG.
It is possible to obtain slightly sharper images in JPEG format this way than is possible with -qmin 1 -q:v 1
and outputting as JPEG directly from ffmpeg
.
SciChart for Android is a relative newcomer, but brings extremely fast high performance real-time charting to the Android platform.
SciChart is a commercial control but available under royalty free distribution / per developer licensing. There is also free licensing available for educational use with some conditions.
Some useful links can be found below:
Disclosure: I am the tech lead on the SciChart project!
install the dependencies:
npm install jquery --save
npm install tether --save
npm install bootstrap@version --save;
next, add scripts in your angular-cli.json
"scripts": [
"../node_modules/jquery/dist/jquery.min.js",
"../node_modules/tether/dist/js/tether.js",
"../node_modules/bootstrap/dist/js/bootstrap.min.js",
"script.js"
]
then, create a script.js
$("[data-toggle=tooltip]").tooltip();
now restart your server.
index.html
<!DOCTYPE html>
<html>
<body>
<form action="submit.php" method="POST">
First name: <input type="text" name="firstname" /><br /><br />
Last name: <input type="text" name="lastname" /><br />
<input type="submit" value="Submit" />
</form>
</body>
</html>
After that one more file which page you want to display after pressing the submit button
submit.php
<html>
<body>
Your First Name is - <?php echo $_POST["firstname"]; ?><br>
Your Last Name is - <?php echo $_POST["lastname"]; ?>
</body>
</html>
From .NET 2.0 you shouldn't need to do this. If you do not explicitly set the Proxy property on a web request it uses the value of the static WebRequest.DefaultWebProxy. If you wanted to change the proxy being used by all subsequent WebRequests, you can set this static DefaultWebProxy property.
The default behaviour of WebRequest.DefaultWebProxy is to use the same underlying settings as used by Internet Explorer.
If you wanted to use different proxy settings to the current user then you would need to code
WebRequest webRequest = WebRequest.Create("http://stackoverflow.com/");
webRequest.Proxy = new WebProxy("http://proxyserver:80/",true);
or
WebRequest.DefaultWebProxy = new WebProxy("http://proxyserver:80/",true);
You should also remember the object model for proxies includes the concept that the proxy can be different depending on the destination hostname. This can make things a bit confusing when debugging and checking the property of webRequest.Proxy. Call
webRequest.Proxy.GetProxy(new Uri("http://google.com.au"))
to see the actual details of the proxy server that would be used.
There seems to be some debate about whether you can set webRequest.Proxy
or WebRequest.DefaultWebProxy = null
to prevent the use of any proxy. This seems to work OK for me but you could set it to new DefaultProxy()
with no parameters to get the required behaviour. Another thing to check is that if a proxy element exists in your applications config file, the .NET Framework will NOT use the proxy settings in Internet Explorer.
The MSDN Magazine article Take the Burden Off Users with Automatic Configuration in .NET gives further details of what is happening under the hood.
DataRow rw = table.AsEnumerable().FirstOrDefault(tt => tt.Field<string>("Author") == "Name");
if (rw != null)
{
// row exists
}
add to your using clause :
using System.Linq;
and add :
System.Data.DataSetExtensions
to references.
I need to share, as I spent too much time looking for a solution
Here was the solution : https://unix.stackexchange.com/a/351742/215375
I was using this command :
ssh-keygen -o -t rsa -b 4096 -C "[email protected]"
gnome-keyring does not support the generated key.
Removing the -o
argument solved the problem.
You can check for empty string (when stderr is empty)
- name: Check script
shell: . {{ venv_name }}/bin/activate && myscritp.py
args:
chdir: "{{ home }}"
sudo_user: "{{ user }}"
register: test_myscript
- debug: msg='myscritp is Ok'
when: test_myscript.stderr == ""
If you want to check for fail:
- debug: msg='myscritp has error: {{test_myscript.stderr}}'
when: test_myscript.stderr != ""
Also look at this stackoverflow question
From the itertools
recipes:
from itertools import tee
def pairwise(iterable):
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = tee(iterable)
next(b, None)
return zip(a, b)
for v, w in pairwise(a):
...
The input in the markup is missing "type"
, the input (text I assume) has the attribute name="name"
and ID="cname"
, the provided code by Ayo calls the input named "cname"* where it should be "name".
You don't have to load the whole product. Magentos collections are very powerful and smart.
$collection = Mage::getModel('catalog/product')->getCollection();
$collection->addAttributeToFilter('entity_id', $product->getId());
$collection->addAttributeToSelect('manufacturer');
$product = $collection->getFirstItem();
$manufacturer = $product->getAttributeText('manufacturer');
At the moment you call getFirstItem() the query will be executed and the result product is very minimal:
[status] => 1
[entity_id] => 38901
[type_id] => configurable
[attribute_set_id] => 9
[manufacturer] => 492
[manufacturer_value] => JETTE
[is_salable] => 1
[stock_item (Varien_Object)] => Array
(
[is_in_stock] => 1
)
it is better to use CONCAT function in PostgreSQL for concatenation
eg : select CONCAT(first_name,last_name) from person where pid = 136
if you are using column_a || ' ' || column_b for concatenation for 2 column , if any of the value in column_a or column_b is null query will return null value. which may not be preferred in all cases.. so instead of this
||
use
CONCAT
it will return relevant value if either of them have value
For windows machine (I'm on windows 10), if CTRL + C (Cancel/Abort) Command on cli doesn't work, and the screen shows up like this:
Try to hit ENTER first (or any key would do) and then CTRL + C and the current process would ask if you want to terminate the batch job:
Perhaps CTRL+C only terminates the parent process while npm start runs with other child processes. Quite unsure why you have to hit that extra key though prior to CTRL+ C, but it works better than having to close the command line and start again.
A related issue you might want to check: https://github.com/mysticatea/npm-run-all/issues/74
You want the (standard) POSIXt
type from base R that can be had in 'compact form' as a POSIXct
(which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt
(which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)
Quick example:
R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10 # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79
$min
[1] 39
$hour
[1] 18
$mday
[1] 25
$mon
[1] 11
$year
[1] 109
$wday
[1] 5
$yday
[1] 358
$isdst
[1] 0
attr(,"tzone")
[1] "America/Chicago" "CST" "CDT"
R>
As for reading them in, see help(strptime)
As for difference, easy too:
R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R>
Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.
If you are sure you want to remove all commit history, simply delete the .git
directory in your project root (note that it's hidden). Then initialize a new repository in the same folder and link it to the GitHub repository:
git init
git remote add origin [email protected]:user/repo
now commit your current version of code
git add *
git commit -am 'message'
and finally force the update to GitHub:
git push -f origin master
However, I suggest backing up the history (the .git
folder in the repository) before taking these steps!
Yes, it's possible, e.g. using the implicit conversion from RAW to BLOB:
insert into blob_fun values(1, hextoraw('453d7a34'));
453d7a34
is a string of hexadecimal values, which is first explicitly converted to the RAW data type and then inserted into the BLOB column. The result is a BLOB value of 4 bytes.
Partitioning data is often used for distributing load horizontally, this has performance benefit, and helps in organizing data in a logical fashion. Example: if we are dealing with a large employee
table and often run queries with WHERE
clauses that restrict the results to a particular country or department . For a faster query response Hive table can be PARTITIONED BY (country STRING, DEPT STRING)
. Partitioning tables changes how Hive structures the data storage and Hive will now create subdirectories reflecting the partitioning structure like
.../employees/country=ABC/DEPT=XYZ.
If query limits for employee from country=ABC
, it will only scan the contents of one directory country=ABC
. This can dramatically improve query performance, but only if the partitioning scheme reflects common filtering. Partitioning feature is very useful in Hive, however, a design that creates too many partitions may optimize some queries, but be detrimental for other important queries. Other drawback is having too many partitions is the large number of Hadoop files and directories that are created unnecessarily and overhead to NameNode since it must keep all metadata for the file system in memory.
Bucketing is another technique for decomposing data sets into more manageable parts. For example, suppose a table using date
as the top-level partition and employee_id
as the second-level partition leads to too many small partitions. Instead, if we bucket the employee table and use employee_id
as the bucketing column, the value of this column will be hashed by a user-defined number into buckets. Records with the same employee_id
will always be stored in the same bucket. Assuming the number of employee_id
is much greater than the number of buckets, each bucket will have many employee_id
. While creating table you can specify like CLUSTERED BY (employee_id) INTO XX BUCKETS;
where XX is the number of buckets . Bucketing has several advantages. The number of buckets is fixed so it does not fluctuate with data. If two tables are bucketed by employee_id
, Hive can create a logically correct sampling. Bucketing also aids in doing efficient map-side joins etc.
You can simply do:
if hi == hi:
print "hi"
elif hi != bye:
print "no hi"
From iOS8 Apple provide new UIAlertController
class which you can use instead of UIAlertView which is now deprecated, it is also stated in deprecation message:
UIAlertView is deprecated. Use UIAlertController with a preferredStyle of UIAlertControllerStyleAlert instead
So you should use something like this
UIAlertController * alert = [UIAlertController
alertControllerWithTitle:@"Title"
message:@"Message"
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction* yesButton = [UIAlertAction
actionWithTitle:@"Yes, please"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
//Handle your yes please button action here
}];
UIAlertAction* noButton = [UIAlertAction
actionWithTitle:@"No, thanks"
style:UIAlertActionStyleDefault
handler:^(UIAlertAction * action) {
//Handle no, thanks button
}];
[alert addAction:yesButton];
[alert addAction:noButton];
[self presentViewController:alert animated:YES completion:nil];
You can easily achieve this with the use of jQuery .toggle().
$("#btnDisplay").click(function() {
$("#div1").toggle();
$("#div2").toggle();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="div1">
First Div
</div>
<div id="div2" style="display: none;">
Second Div
</div>
<button id="btnDisplay">Display</button>
Are you running a 64 bit system with the database running 32 bit but the console running 64 bit? There are no MS Access drivers that run 64 bit and would report an error identical to the one your reported.
function omit(obj, key) {
const {[key]:ignore, ...rest} = obj;
return rest;
}
You can use ES6 spread operators like this. And to remove your key simply call
const newJson = omit(myjsonobj, "otherIndustry");
Its always better if you maintain pure function when you deal with type=object
in javascript.
SELECT
employees.id,
CONCAT(employees.f_name," ",employees.l_name) AS 'Full Name', genders.gender_name AS 'Sex',
depts.dept_name AS 'Team Name',
pay_grades.pay_grade_name AS 'Band',
designations.designation_name AS 'Role'
FROM employees
LEFT JOIN genders ON employees.gender_id = genders.id
LEFT JOIN depts ON employees.dept_id = depts.id
LEFT JOIN pay_grades ON employees.pay_grade_id = pay_grades.id
LEFT JOIN designations ON employees.designation_id = designations.id
ORDER BY employees.id;
You can JOIN multiple TABLES like this example above.
There's JS function to deal with &#xxxx styled entities:
function at GitHub
// encode(decode) html text into html entity
var decodeHtmlEntity = function(str) {
return str.replace(/&#(\d+);/g, function(match, dec) {
return String.fromCharCode(dec);
});
};
var encodeHtmlEntity = function(str) {
var buf = [];
for (var i=str.length-1;i>=0;i--) {
buf.unshift(['&#', str[i].charCodeAt(), ';'].join(''));
}
return buf.join('');
};
var entity = '高级程序设计';
var str = '??????';
console.log(decodeHtmlEntity(entity) === str);
console.log(encodeHtmlEntity(str) === entity);
// output:
// true
// true
For people wondering about a Servlet/JSP implementation here's how you go about doing it... I will be explaining uploadimage below also.
1) First make sure you have added the filebrowser and uploadimage variable to your config.js file. Make you also have the uploadimage and filebrowser folder inside the plugins folder too.
2) This part is where it tripped me up:
The Ckeditor website documentation says you need to use these two methods:
function getUrlParam( paramName ) {
var reParam = new RegExp( '(?:[\?&]|&)' + paramName + '=([^&]+)', 'i' );
var match = window.location.search.match( reParam );
return ( match && match.length > 1 ) ? match[1] : null;
}
function returnFileUrl() {
var funcNum = getUrlParam( 'CKEditorFuncNum' );
var fileUrl = 'https://patiliyo.com/wp-content/uploads/2017/07/ruyada-kedi-gormek.jpg';
window.opener.CKEDITOR.tools.callFunction( funcNum, fileUrl );
window.close();
}
What they don't mention is that these methods have to be on a different page and not the page where you are clicking the browse server button from.
So if you have ckeditor initialized in page editor.jsp then you need to create a file browser (with basic html/css/javascript) in page filebrowser.jsp.
editor.jsp (all you need is this in your script tag) This page will open filebrowser.jsp in a mini window when you click on the browse server button.
CKEDITOR.replace( 'editor', {
filebrowserBrowseUrl: '../filebrowser.jsp', //jsp page with jquery to call servlet and get image files to view
filebrowserUploadUrl: '../UploadImage', //servlet
});
filebrowser.jsp (is the custom file browser you built which will contain the methods mentioned above)
<head>
<script src="../../ckeditor/ckeditor.js"></script>
</head>
<body>
<script>
function getUrlParam( paramName ) {
var reParam = new RegExp( '(?:[\?&]|&)' + paramName + '=([^&]+)', 'i' );
var match = window.location.search.match( reParam );
return ( match && match.length > 1 ) ? match[1] : null;
}
function returnFileUrl() {
var funcNum = getUrlParam( 'CKEditorFuncNum' );
var fileUrl = 'https://patiliyo.com/wp-content/uploads/2017/07/ruyada-kedi-gormek.jpg';
window.opener.CKEDITOR.tools.callFunction( funcNum, fileUrl );
window.close();
}
//when this window opens it will load all the images which you send from the FileBrowser Servlet.
getImages();
function getImages(){
$.get("../FileBrowser", function(responseJson) {
//do something with responseJson (like create <img> tags and update the src attributes)
});
}
//you call this function and pass 'fileUrl' when user clicks on an image that you loaded into this window from a servlet
returnFileUrl();
</script>
</body>
3) The FileBrowser Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Images i = new Images();
List<ImageObject> images = i.getImages(); //get images from your database or some cloud service or whatever (easier if they are in a url ready format)
String json = new Gson().toJson(images);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
4) UploadImage Servlet
Go back to your config.js file for ckeditor and add the following line:
//https://docs.ckeditor.com/ckeditor4/latest/guide/dev_file_upload.html
config.uploadUrl = '/UploadImage';
Then you can drag and drop files also:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Images i = new Images();
//do whatever you usually do to upload your image to your server (in my case i uploaded to google cloud storage and saved the url in a database.
//Now this part is important. You need to return the response in json format. And it has to look like this:
// https://docs.ckeditor.com/ckeditor4/latest/guide/dev_file_upload.html
// response must be in this format:
// {
// "uploaded": 1,
// "fileName": "example.png",
// "url": "https://www.cats.com/example.png"
// }
String image = "https://www.cats.com/example.png";
ImageObject objResponse = i.getCkEditorObjectResponse(image);
String json = new Gson().toJson(objResponse);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
}
And that's all folks. Hope it helps someone.
scanf
(and cousins) have one slightly strange characteristic: white space in (most placed in) the format string matches an arbitrary amount of white space in the input. As it happens, at least in the default "C" locale, a new-line is classified as white space.
This means the trailing '\n'
is trying to match not only a new-line, but any succeeding white-space as well. It won't be considered matched until you signal the end of the input, or else enter some non-white space character.
One way to deal with that is something like this:
scanf("%2000s %2000[^\n]%c", a, b, c);
if (c=='\n')
// we read the whole line
else
// the rest of the line was more than 2000 characters long. `c` contains a
// character from the input, and there's potentially more after that as well.
Depending on the situation, you might also want to check the return value from scanf
, which tells you the number of conversions that were successful. In this case, you'd be looking for 3
to indicate that all the conversions were successful.
Here are 3 more suggestions or techniques:
You can add an additional field to tell if the struct has been populated or it is empty. I intentionally named it ready
and not empty
because the zero value of a bool
is false
, so if you create a new struct like Session{}
its ready
field will be automatically false
and it will tell you the truth: that the struct is not-yet ready (it's empty).
type Session struct {
ready bool
playerId string
beehive string
timestamp time.Time
}
When you initialize the struct, you have to set ready
to true
. Your isEmpty()
method isn't needed anymore (although you can create one if you want to) because you can just test the ready
field itself.
var s Session
if !s.ready {
// do stuff (populate s)
}
Significance of this one additional bool
field increases as the struct grows bigger or if it contains fields which are not comparable (e.g. slice, map
and function values).
This is similar to the previous suggestion, but it uses the zero value of an existing field which is considered invalid when the struct is not empty. Usability of this is implementation dependant.
For example if in your example your playerId
cannot be the empty string
""
, you can use it to test if your struct is empty like this:
var s Session
if s.playerId == "" {
// do stuff (populate s, give proper value to playerId)
}
In this case it's worth incorporating this check into an isEmpty()
method because this check is implementation dependant:
func (s Session) isEmpty() bool {
return s.playerId == ""
}
And using it:
if s.isEmpty() {
// do stuff (populate s, give proper value to playerId)
}
The second suggestion is to use a Pointer to your struct: *Session
. Pointers can have nil
values, so you can test for it:
var s *Session
if s == nil {
s = new(Session)
// do stuff (populate s)
}
String x = JComboBox.getSelectedItem().toString();
will convert any value weather it is Integer, Double, Long, Short into text on the other hand,
String x = String.valueOf(JComboBox.getSelectedItem());
will avoid null values, and convert the selected item from object to string
I had to remove .idea and target folders and after reading all comments this worked for me:
git rm -r .idea
git rm -r target
git commit -m 'removed .idea folder'
and then push to master
To center a view in Framelayout, there are some available tricks. The simplest one I used for my Webview and Progressbar(very similar to your two object layout), I just added android:layout_gravity="center"
Here is complete XML in case if someone else needs the same thing to do
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".WebviewPDFActivity"
android:layout_gravity="center"
>
<WebView
android:id="@+id/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
<ProgressBar
android:id="@+id/progress_circular"
android:layout_width="250dp"
android:layout_height="250dp"
android:visibility="visible"
android:layout_gravity="center"
/>
</FrameLayout>
Here is my output
So, the idea is to convert character numbers (in single quotes, e.g. '8') to integer expression. For instance char c = '8'; int i = c - '0' //would yield integer 8; And sum up all the converted numbers by the principle that 908=9*100+0*10+8, which is done in a loop.
char t[5] = {'-', '9', '0', '8', '\0'}; //Should be terminated properly.
int s = 1;
int i = -1;
int res = 0;
if (c[0] == '-') {
s = -1;
i = 0;
}
while (c[++i] != '\0') { //iterate until the array end
res = res*10 + (c[i] - '0'); //generating the integer according to read parsed numbers.
}
res = res*s; //answer: -908
Step 1:Create an XML File:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/btnClickEvent"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Me" />
</LinearLayout>
Step 2:Create MainActivity:
package com.scancode.acutesoft.telephonymanagerapp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends Activity implements View.OnClickListener {
Button btnClickEvent;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnClickEvent = (Button) findViewById(R.id.btnClickEvent);
btnClickEvent.setOnClickListener(MainActivity.this);
}
@Override
public void onClick(View v) {
//Your Logic
}
}
HappyCoding!
Tasks are stored in 3 locations: 1 file system location and 2 registry locations.
C:\Windows\System32\Tasks
HKLM\Software\Microsoft\Windows NT\CurrentVersion\Schedule\Taskcache\Tasks
HKLM\Software\Microsoft\Windows NT\CurrentVersion\Schedule\Taskcache\Tree
So, you need to delete a corrupted task in these 3 locations.
From a Spring point of view, none of the HttpMessageConverter
instances registered with the RestTemplate
can convert text/html
content to a ProductList
object. The method of interest is HttpMessageConverter#canRead(Class, MediaType)
. The implementation for all of the above returns false
, including Jaxb2RootElementHttpMessageConverter
.
Since no HttpMessageConverter
can read your HTTP response, processing fails with an exception.
If you can control the server response, modify it to set the Content-type
to application/xml
, text/xml
, or something matching application/*+xml
.
If you don't control the server response, you'll need to write and register your own HttpMessageConverter
(which can extend the Spring classes, see AbstractXmlHttpMessageConverter
and its sub classes) that can read and convert text/html
.
Change to your variable types private
to public
This is simple and more readable.
For example
Not Working;
class A{
private $var1="valuevar1";
private $var2="valuevar2";
public function tojson(){
return json_encode($this)
}
}
It is Working;
class A{
public $var1="valuevar1";
public $var2="valuevar2";
public function tojson(){
return json_encode($this)
}
}
Given a parent class named Parent
and a child class named Child
, you can do something like this:
class Parent {
public:
virtual void print(int x);
};
class Child : public Parent {
void print(int x) override;
};
void Parent::print(int x) {
// some default behavior
}
void Child::print(int x) {
// use Parent's print method; implicitly passes 'this' to Parent::print
Parent::print(x);
}
Note that Parent
is the class's actual name and not a keyword.
Thanks a ton for Bhaskar Karambelkar's answer which explains in detail and fixed my issue. But also I would like to re phrase the answer in three simple steps for someone who is in a hurry to fix
wsdlLocation= "http://localhost/wsdl/yourwsdlname.wsdl"
Create an xml file jax-ws-catalog.xml under META-INF as below
<catalog xmlns="urn:oasis:names:tc:entity:xmlns:xml:catalog"
prefer="system">
<system systemId="http://localhost/wsdl/yourwsdlname.wsdl" uri="wsdl/yourwsdlname.wsdl" />
</catalog>
Now package your jar. No more reference to the local directory, it's all packaged and referenced within
After adding files to the stage, you need to commit them with git commit -m "comment"
after git add .
. Finally, to push them to a remote repository, you need to git push <remote_repo> <local_branch>
.
First let me mention that you probably don't want to create a file object that eventually can be opened for reading OR writing, depending on a non-reproducible condition. You need to know which methods can be used, reading or writing, which depends on what you want to do with the fileobject.
That said, you can do it as That One Random Scrub proposed, using try: ... except:. Actually that is the proposed way, according to the python motto "It's easier to ask for forgiveness than permission".
But you can also easily test for existence:
import os
# open file for reading
fn = raw_input("Enter file to open: ")
if os.path.exists(fn):
fh = open(fn, "r")
else:
fh = open(fn, "w")
Note: use raw_input() instead of input(), because input() will try to execute the entered text. If you accidently want to test for file "import", you'd get a SyntaxError.
color: transparent;
make the tricks for me
#videos-part:before{
font-size: 35px;
line-height: 33px;
width: 16px;
color: transparent;
content: 'AS YOU LIKE';
background-image: url('data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjwhRE9DVFlQRSBzdmcgIFBVQkxJQyAnLS8vVzNDLy9EVEQgU1ZHIDEuMS8vRU4nICAnaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkJz48c3ZnIGVuYWJsZS1iYWNrZ3JvdW5kPSJuZXcgMCAwIDUwIDUwIiBoZWlnaHQ9IjUwcHgiIGlkPSJMYXllcl8xIiB2ZXJzaW9uPSIxLjEiIHZpZXdCb3g9IjAgMCA1MCA1MCIgd2lkdGg9IjUwcHgiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxwYXRoIGQ9Ik04LDE0TDQsNDloNDJsLTQtMzVIOHoiIGZpbGw9Im5vbmUiIHN0cm9rZT0iIzAwMDAwMCIgc3Ryb2tlLWxpbmVjYXA9InJvdW5kIiBzdHJva2UtbWl0ZXJsaW1pdD0iMTAiIHN0cm9rZS13aWR0aD0iMiIvPjxyZWN0IGZpbGw9Im5vbmUiIGhlaWdodD0iNTAiIHdpZHRoPSI1MCIvPjxwYXRoIGQ9Ik0zNCwxOWMwLTEuMjQxLDAtNi43NTksMC04ICBjMC00Ljk3MS00LjAyOS05LTktOXMtOSw0LjAyOS05LDljMCwxLjI0MSwwLDYuNzU5LDAsOCIgZmlsbD0ibm9uZSIgc3Ryb2tlPSIjMDAwMDAwIiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1taXRlcmxpbWl0PSIxMCIgc3Ryb2tlLXdpZHRoPSIyIi8+PGNpcmNsZSBjeD0iMzQiIGN5PSIxOSIgcj0iMiIvPjxjaXJjbGUgY3g9IjE2IiBjeT0iMTkiIHI9IjIiLz48L3N2Zz4=');
background-size: 25px;
background-repeat: no-repeat;
}
built-in types in Python have built in names:
>>> s = "hallo"
>>> type(s) is str
True
>>> s = {}
>>> type(s) is dict
True
btw note the is operator. However, type checking (if you want to call it that) is usually done by wrapping a type-specific test in a try-except clause, as it's not so much the type of the variable that's important, but whether you can do a certain something with it or not.
Save the following script as something like findPK.sql.
set verify off
accept TABLE_NAME char prompt 'Table name>'
SELECT cols.column_name
FROM all_constraints cons NATURAL JOIN all_cons_columns cols
WHERE cons.constraint_type = 'P' AND table_name = UPPER('&TABLE_NAME');
It can then be called using
@findPK
We encountered this error today. This is how we debugged and fixed it.
Package went to invalid state due to this error ORA-01775
.
With the error line number , We went thru the package
body code and found the code which was trying to insert data into a table
.
We ran below queries to check if the above table
and synonym
exists.
SELECT * FROM DBA_TABLES WHERE TABLE_NAME = '&TABLE_NAME'; -- No rows returned
SELECT * FROM DBA_SYNONYMS WHERE SYNONYM_NAME = '&SYNONYM_NAME'; -- 1 row returned
With this we concluded that the table needs to be re- created. As the synonym
was pointing to a table
that did not exist.
DBA team re-created the table and this fixed the issue.
$q->where("a = 1")
->andWhere("b = 1 OR b = 2")
->andWhere("c = 2 OR c = 2")
;
This issue (https://bugs.eclipse.org/394042) is fixed in m2e 1.5.0 which is available for Eclipse Kepler and Luna from this p2 repo :
http://download.eclipse.org/technology/m2e/releases/1.5
If you also use m2e-wtp, you'll need to install m2e-wtp 1.1.0 as well :
Alternatively, just GROUP BY
the hour and day:
SELECT CAST(Startdate as DATE) as 'StartDate',
CAST(DATEPART(Hour, StartDate) as varchar) + ':00' as 'Hour',
COUNT(*) as 'Ct'
FROM #Events
GROUP BY CAST(Startdate as DATE), DATEPART(Hour, StartDate)
ORDER BY CAST(Startdate as DATE) ASC
output:
StartDate Hour Ct
2007-01-01 0:00 3
2007-01-02 5:00 2
2007-01-03 4:00 1
2007-01-07 3:00 1
Another reason, Check your Developer account is connected with xCode
This is the code I use for that:
ArrayList copy = new ArrayList (original.size());
Collections.copy(copy, original);
Hope is usefull for you
I think a better approach than setting the platform's default character set, especially as you seem to have restrictions on affecting the application deployment, let alone the platform, is to call the much safer String.getBytes("charsetName")
. That way your application is not dependent on things beyond its control.
I personally feel that String.getBytes()
should be deprecated, as it has caused serious problems in a number of cases I have seen, where the developer did not account for the default charset possibly changing.
A very simple check you can do with Cell formulas:
Sheet 1 (new - old)
=(if(AND(Ref_New<>"";Ref_Old="");Ref_New;"")
Sheet 2 (old - new)
=(if(AND(Ref_Old<>"";Ref_New="");Ref_Old;"")
This formulas should work for an ENGLISH Excel. For other languages they need to be translated. (For German i can assist)
You need to open all three Excel Documents, then copy the first formula into A1 of your sheet 1 and the second into A1 of sheet 2. Now click in A1 of the first cell and mark "Ref_New", now you can select your reference, go to the new file and click in the A1, go back to sheet1 and do the same for "Ref_Old" with the old file. Replace also the other "Ref_New".
Doe the same for Sheet two.
Now copy the formaula form A1 over the complete range where zour data is in the old and the new file.
But two cases are not covered here:
To cover this two cases also, you should create your own function, means learn VBA. A very useful Excel page is cpearson.com
viewWillAppear:animated:
, one of the most confusing methods in the iOS SDKs in my opinion, is never be invoked in such a situation, i.e., application switching. That method is only invoked according to the relationship between the view controller's view and the application's window, i.e., the message is sent to a view controller only if its view appears on the application's window, not on the screen.
When your application goes background, obviously the topmost views of the application window are no longer visible to the user. In your application window's perspective, however, they are still the topmost views and therefore they did not disappear from the window. Rather, those views disappeared because the application window disappeared. They did not disappeared because they disappeared from the window.
Therefore, when the user switches back to your application, they obviously seem to appear on the screen, because the window appears again. But from the window's perspective, they haven't disappeared at all. Therefore the view controllers never get the viewWillAppear:animated
message.
From other answers here, I was kind of confused with how git rebase -i
could be used to remove a commit, so I hope it's OK to jot down my test case here (very similar to the OP).
Here is a bash
script that you can paste in to create a test repository in the /tmp
folder:
set -x
rm -rf /tmp/myrepo*
cd /tmp
mkdir myrepo_git
cd myrepo_git
git init
git config user.name me
git config user.email [email protected]
mkdir folder
echo aaaa >> folder/file.txt
git add folder/file.txt
git commit -m "1st git commit"
echo bbbb >> folder/file.txt
git add folder/file.txt
git commit -m "2nd git commit"
echo cccc >> folder/file.txt
git add folder/file.txt
git commit -m "3rd git commit"
echo dddd >> folder/file.txt
git add folder/file.txt
git commit -m "4th git commit"
echo eeee >> folder/file.txt
git add folder/file.txt
git commit -m "5th git commit"
At this point, we have a file.txt
with these contents:
aaaa
bbbb
cccc
dddd
eeee
At this point, HEAD is at the 5th commit, HEAD~1 would be the 4th - and HEAD~4 would be the 1st commit (so HEAD~5 wouldn't exist). Let's say we want to remove the 3rd commit - we can issue this command in the myrepo_git
directory:
git rebase -i HEAD~4
(Note that git rebase -i HEAD~5
results with "fatal: Needed a single revision; invalid upstream HEAD~5".) A text editor (see screenshot in @Dennis' answer) will open with these contents:
pick 5978582 2nd git commit
pick 448c212 3rd git commit
pick b50213c 4th git commit
pick a9c8fa1 5th git commit
# Rebase b916e7f..a9c8fa1 onto b916e7f
# ...
So we get all commits since (but not including) our requested HEAD~4. Delete the line pick 448c212 3rd git commit
and save the file; you'll get this response from git rebase
:
error: could not apply b50213c... 4th git commit
When you have resolved this problem run "git rebase --continue".
If you would prefer to skip this patch, instead run "git rebase --skip".
To check out the original branch and stop rebasing run "git rebase --abort".
Could not apply b50213c... 4th git commit
At this point open myrepo_git/folder/file.txt
in a text editor; you'll see it has been modified:
aaaa
bbbb
<<<<<<< HEAD
=======
cccc
dddd
>>>>>>> b50213c... 4th git commit
Basically, git
sees that when HEAD got to 2nd commit, there was content of aaaa
+ bbbb
; and then it has a patch of added cccc
+dddd
which it doesn't know how to append to the existing content.
So here git
cannot decide for you - it is you who has to make a decision: by removing the 3rd commit, you either keep the changes introduced by it (here, the line cccc
) -- or you don't. If you don't, simply remove the extra lines - including the cccc
- in folder/file.txt
using a text editor, so it looks like this:
aaaa
bbbb
dddd
... and then save folder/file.txt
. Now you can issue the following commands in myrepo_git
directory:
$ nano folder/file.txt # text editor - edit, save
$ git rebase --continue
folder/file.txt: needs merge
You must edit all merge conflicts and then
mark them as resolved using git add
Ah - so in order to mark that we've solved the conflict, we must git add
the folder/file.txt
, before doing git rebase --continue
:
$ git add folder/file.txt
$ git rebase --continue
Here a text editor opens again, showing the line 4th git commit
- here we have a chance to change the commit message (which in this case could be meaningfully changed to 4th (and removed 3rd) commit
or similar). Let's say you don't want to - so just exit the text editor without saving; once you do that, you'll get:
$ git rebase --continue
[detached HEAD b8275fc] 4th git commit
1 file changed, 1 insertion(+)
Successfully rebased and updated refs/heads/master.
At this point, now you have a history like this (which you could also inspect with say gitk .
or other tools) of the contents of folder/file.txt
(with, apparently, unchanged timestamps of the original commits):
1st git commit | +aaaa
----------------------------------------------
2nd git commit | aaaa
| +bbbb
----------------------------------------------
4th git commit | aaaa
| bbbb
| +dddd
----------------------------------------------
5th git commit | aaaa
| bbbb
| dddd
| +eeee
And if previously, we decided to keep the line cccc
(the contents of the 3rd git commit that we removed), we would have had:
1st git commit | +aaaa
----------------------------------------------
2nd git commit | aaaa
| +bbbb
----------------------------------------------
4th git commit | aaaa
| bbbb
| +cccc
| +dddd
----------------------------------------------
5th git commit | aaaa
| bbbb
| cccc
| dddd
| +eeee
Well, this was the kind of reading I hoped I'd have found, to start grokking how git rebase
works in terms of deleting commits/revisions; so hope it might help others too...
And in 2016.....I do this (which works in all browsers and does not create "illegal" html).
For the drop-down select that is to show/hide different values add that value as a data attribute.
<select id="animal">
<option value="1" selected="selected">Dog</option>
<option value="2">Cat</option>
</select>
<select id="name">
<option value=""></option>
<option value="1" data-attribute="1">Rover</option>
<option value="2" selected="selected" data-attribute="1">Lassie</option>
<option value="3" data-attribute="1">Spot</option>
<option value="4" data-attribute="2">Tiger</option>
<option value="5" data-attribute="2">Fluffy</option>
</select>
Then in your jQuery add a change event to the first drop-down select to filter the second drop-down.
$("#animal").change( function() {
filterSelectOptions($("#name"), "data-attribute", $(this).val());
});
And the magic part is this little jQuery utility.
function filterSelectOptions(selectElement, attributeName, attributeValue) {
if (selectElement.data("currentFilter") != attributeValue) {
selectElement.data("currentFilter", attributeValue);
var originalHTML = selectElement.data("originalHTML");
if (originalHTML)
selectElement.html(originalHTML)
else {
var clone = selectElement.clone();
clone.children("option[selected]").removeAttr("selected");
selectElement.data("originalHTML", clone.html());
}
if (attributeValue) {
selectElement.children("option:not([" + attributeName + "='" + attributeValue + "'],:not([" + attributeName + "]))").remove();
}
}
}
This little gem tracks the current filter, if different it restores the original select (all items) and then removes the filtered items. If the filter item is empty we see all items.
Maybe the above methods work... I tried some and didn't for me. What did was this :
Run this in terminal :
/usr/libexec/java_home
On python 3.5+ there is an easier way to achieve a shallow copy by using the ** unpackaging operator. Defined by Pep 448.
>>>dict1 = {"key1": "value1", "key2": "value2"}
>>>dict2 = {**dict1}
>>>print(dict2)
{'key1': 'value1', 'key2': 'value2'}
>>>dict2["key2"] = "WHY?!"
>>>print(dict1)
{'key1': 'value1', 'key2': 'value2'}
>>>print(dict2)
{'key1': 'value1', 'key2': 'WHY?!'}
** unpackages the dictionary into a new dictionary that is then assigned to dict2.
We can also confirm that each dictionary has a distinct id.
>>>id(dict1)
178192816
>>>id(dict2)
178192600
If a deep copy is needed then copy.deepcopy() is still the way to go.
The below code working for me on array coming from ajax call .
$form = $request->input('form');
$rules = array(
'facebook_account' => 'url',
'youtube_account' => 'url',
'twitter_account' => 'url',
'instagram_account' => 'url',
'snapchat_account' => 'url',
'website' => 'url',
);
$validation = Validator::make($form, $rules);
if ($validation->fails()) {
return Response::make(['error' => $validation->errors()], 400);
}
Can't change the default browser, but try this (found online a while ago). Add a bookmark in Safari called "Open in Chrome" with the following.
javascript:location.href=%22googlechrome%22+location.href.substring(4);
Will open the current page in Chrome. Not as convenient, but maybe someone will find it useful.
Works for me.
1- Select LinearLayout findViewById
LinearLayout llayout =(LinearLayout) findViewById(R.id.llayoutId);
2- Set color from R.color.colorId
llayout.setBackgroundColor(getResources().getColor(R.color.colorId));
Use Manatee.Json https://github.com/gregsdennis/Manatee.Json/wiki/Usage
And you can convert the entire object to a string, filename.json is expected to be located in documents folder.
var text = File.ReadAllText("filename.json");
var json = JsonValue.Parse(text);
while (JsonValue.Null != null)
{
Console.WriteLine(json.ToString());
}
Console.ReadLine();
Use HTML Form "elements" attribute:
$.each($("form").elements, function(){
console.log($(this));
});
Now it's not necessary to provide such names as "input, textarea, select ..." etc.
Perhaps I'm misunderstanding the intent of your question, so correct me if I'm wrong, but can't you apply the culture settings globally once, and then not worry about customizing every write statement?
Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture("en-GB");
If you using JavaScript to test your Regex, try \\.
instead of \.
.
It acts on the same way because JS remove first backslash.
here is a pure-javascript, minimalistic approach. I use JQuery but you can use any library (or even no libraries at all).
<html>
<head>
<title>An example</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
function call_counter(url, pk) {
window.open(url);
$.get('YOUR_VIEW_HERE/'+pk+'/', function (data) {
alert("counter updated!");
});
}
</script>
</head>
<body>
<button onclick="call_counter('http://www.google.com', 12345);">
I update object 12345
</button>
<button onclick="call_counter('http://www.yahoo.com', 999);">
I update object 999
</button>
</body>
</html>
Alternative approach
Instead of placing the JavaScript code, you can change your link in this way:
<a target="_blank"
class="btn btn-info pull-right"
href="{% url YOUR_VIEW column_3_item.pk %}/?next={{column_3_item.link_for_item|urlencode:''}}">
Check It Out
</a>
and in your views.py
:
def YOUR_VIEW_DEF(request, pk):
YOUR_OBJECT.objects.filter(pk=pk).update(views=F('views')+1)
return HttpResponseRedirect(request.GET.get('next')))
Since this question was asked/last answered, support for non string key types for maps for json Marshal/UnMarshal has been added through the use of TextMarshaler and TextUnmarshaler interfaces here. You could just implement these interfaces for your key types and then json.Marshal
would work as expected.
package main
import (
"encoding/json"
"fmt"
"strconv"
)
// Num wraps the int value so that we can implement the TextMarshaler and TextUnmarshaler
type Num int
func (n *Num) UnmarshalText(text []byte) error {
i, err := strconv.Atoi(string(text))
if err != nil {
return err
}
*n = Num(i)
return nil
}
func (n Num) MarshalText() (text []byte, err error) {
return []byte(strconv.Itoa(int(n))), nil
}
type Foo struct {
Number Num `json:"number"`
Title string `json:"title"`
}
func main() {
datas := make(map[Num]Foo)
for i := 0; i < 10; i++ {
datas[Num(i)] = Foo{Number: 1, Title: "test"}
}
jsonString, err := json.Marshal(datas)
if err != nil {
panic(err)
}
fmt.Println(datas)
fmt.Println(jsonString)
m := make(map[Num]Foo)
err = json.Unmarshal(jsonString, &m)
if err != nil {
panic(err)
}
fmt.Println(m)
}
Output:
map[1:{1 test} 2:{1 test} 4:{1 test} 7:{1 test} 8:{1 test} 9:{1 test} 0:{1 test} 3:{1 test} 5:{1 test} 6:{1 test}]
[123 34 48 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 49 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 50 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 51 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 52 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 53 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 54 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 55 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 56 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 44 34 57 34 58 123 34 110 117 109 98 101 114 34 58 34 49 34 44 34 116 105 116 108 101 34 58 34 116 101 115 116 34 125 125]
map[4:{1 test} 5:{1 test} 6:{1 test} 7:{1 test} 0:{1 test} 2:{1 test} 3:{1 test} 1:{1 test} 8:{1 test} 9:{1 test}]
From other post:
find /c "string" file >NUL
if %errorlevel% equ 1 goto notfound
echo found
goto done
:notfound
echo notfound
goto done
:done
Use the /i switch when you want case insensitive checking:
find /i /c "string" file >NUL
Or something like: if not found write to file.
find /c "%%P" file.txt || ( echo %%P >> newfile.txt )
Or something like: if found write to file.
find /c "%%P" file.txt && ( echo %%P >> newfile.txt )
Or something like:
find /c "%%P" file.txt && ( echo found ) || ( echo not found )
Update: note that the currently accepted answer perpetuates a common misunderstanding about the behaviour of git push
, which hasn't been corrected despite a comment pointing it out.
Your summary of what remotes are - like a nickname for the URL of a repository - is correct.
So why does the URL not git://[email protected]/peter/first_app.git but in the other syntax -- what syntax is it? Why must it end with .git? I tried not using .git at the end and it works too. If not .git, what else can it be? The git at the beginner seems to be a user account on the git server?
The two URLs that you've mentioned indicate that two different transport protocols should be used. The one beginning with git://
is for the git protocol, which is usually only used for read-only access to repositories. The other one, [email protected]:peter/first_app.git
, is one of the different ways of specifying access to a repository over SSH - this is the "scp-style syntax" described in the documentation. That the username in the scp-style syntax is git
is because of the way that GitHub deals with identifying users - essentially that username is ignored, and the user is identified based on the SSH key-pair that they used to authenticate.
As for the verbosity of git push origin master
, you've noticed that after the first push, you can then just do git push
. This is because of a series of difficult-to-remember-but-generally-helpful defaults :)
remote.master.url
in your case) is used. If that's not set up, then origin
is used.master
, master:my-experiment
, etc.) specified, then git defaults to pushing every local branch that has the same name as a branch on the remote. If you just have a branch called master
in common between your repository and the remote one, that'll be the same as pushing your master
to the remote master
.Personally, since I tend to have many topic branches (and often several remotes) I always use the form:
git push origin master
... to avoid accidentally pushing other branches.
In reply to your comments on one of the other answers, it sounds to me as if are learning about git in a top-down way very effectively - you've discovered that the defaults work, and your question is asking about why ;) To be more serious, git can be used essentially as simply as SVN, but knowing a bit about remotes and branches means you can use it much more flexibily and this can really change the way you work for the better. Your remark about a semester course makes me think of something Scott Chacon said in a podcast interview - students are taught about all kinds of basic tools in computer science and software engineering, but very rarely version control. Distributed version control systems such as git and Mercurial are now so important, and so flexible, that it would be worth teaching courses on them to give people a good grounding.
My view is that with git
, this learning curve is absolutely worth it - working with lots of topic branches, merging them easily, and pushing and pulling them about between different repositories is fantastically useful once you become confident with the system. It's just unfortunate that:
I had to catch all three events related to pressing keys in order to prevent the form from being submitted:
var preventSubmit = function(event) {
if(event.keyCode == 13) {
console.log("caught ya!");
event.preventDefault();
//event.stopPropagation();
return false;
}
}
$("#search").keypress(preventSubmit);
$("#search").keydown(preventSubmit);
$("#search").keyup(preventSubmit);
You can combine all the above into a nice compact version:
$('#search').bind('keypress keydown keyup', function(e){
if(e.keyCode == 13) { e.preventDefault(); }
});
Use the RIGHT()
function: http://msdn.microsoft.com/en-us/library/ms177532(v=sql.105).aspx
SELECT RIGHT( '1234567890', 4 ); -- returns '7890'
Use the "indirect" function on conditional formatting.
=INDIRECT("g"&ROW())="X"
=$A$1:$Z$1500
(or however wide/long you want the conditional formatting to extend depending on your worksheet)For every row in the G column that has an X, it will now turn to the format you specified. If there isn't an X in the column, the row won't be formatted.
You can repeat this to do multiple row formatting depending on a column value. Just change either the g
column or x
specific text in the formula and set different formats.
For example, if you add a new rule with the formula, =INDIRECT("h"&ROW())="CAR"
, then it will format every row that has CAR
in the H Column as the format you specified.
For versions of .Net where you can use LINQ OrderBy
and ThenBy
(or ThenByDescending
if needed):
using System.Linq;
....
List<SomeClass>() a;
List<SomeClass> b = a.OrderBy(x => x.x).ThenBy(x => x.y).ToList();
Note: for .Net 2.0 (or if you can't use LINQ) see Hans Passant answer to this question.
Following code works for me :)
HomeWatcher mHomeWatcher = new HomeWatcher(this);
mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() {
@Override
public void onHomePressed() {
// do something here...
}
@Override
public void onHomeLongPressed() {
}
});
mHomeWatcher.startWatch();
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
public class HomeWatcher {
static final String TAG = "hg";
private Context mContext;
private IntentFilter mFilter;
private OnHomePressedListener mListener;
private InnerReceiver mReceiver;
public HomeWatcher(Context context) {
mContext = context;
mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
}
public void setOnHomePressedListener(OnHomePressedListener listener) {
mListener = listener;
mReceiver = new InnerReceiver();
}
public void startWatch() {
if (mReceiver != null) {
mContext.registerReceiver(mReceiver, mFilter);
}
}
public void stopWatch() {
if (mReceiver != null) {
mContext.unregisterReceiver(mReceiver);
}
}
class InnerReceiver extends BroadcastReceiver {
final String SYSTEM_DIALOG_REASON_KEY = "reason";
final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
if (reason != null) {
Log.e(TAG, "action:" + action + ",reason:" + reason);
if (mListener != null) {
if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
mListener.onHomePressed();
} else if (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
mListener.onHomeLongPressed();
}
}
}
}
}
}
}
public interface OnHomePressedListener {
void onHomePressed();
void onHomeLongPressed();
}
Void: the type modifier void states that the main method does not return any value. All parameters to a method are declared inside a prior of parenthesis. Here String args[ ] declares a parameter named args which contains an array of objects of the class type string.
import base64
from PIL import Image
from io import BytesIO
with open("image.jpg", "rb") as image_file:
data = base64.b64encode(image_file.read())
im = Image.open(BytesIO(base64.b64decode(data)))
im.save('image1.png', 'PNG')
If you want to get the ASCII value of a character, or just convert it into an int, you need to cast from a char to an int.
What's casting? Casting is when we explicitly convert from one primitve data type, or a class, to another. Here's a brief example.
public class char_to_int
{
public static void main(String args[])
{
char myChar = 'a';
int i = (int) myChar; // cast from a char to an int
System.out.println ("ASCII value - " + i);
}
In this example, we have a character ('a'), and we cast it to an integer. Printing this integer out will give us the ASCII value of 'a'.
I'm not familiar with c++, but a quick look at the documentation suggests that this should work:
//cin>>CC; cin>>RR; already done
vector<vector<int> > matrix;
for(int i = 0; i<RR; i++)
{
vector<int> myvector;
for(int j = 0; j<CC; j++)
{
int tempVal = 0;
cout<<"Enter the number for Matrix 1";
cin>>tempVal;
myvector.push_back(tempVal);
}
matrix.push_back(myvector);
}
Similar problem for me. My class name was different to my file name. The connectionstring generated had the class name and not the file name in. Solution for me was just to rename my file to match the class name.
You could use the Toolkit, no need for ImageIO
Image image = Toolkit.getDefaultToolkit().getImage(file.getAbsolutePath());
int width = image.getWidth(null);
int height = image.getHeight(null);
If you don't want to handle the loading of the image do
ImageIcon imageIcon = new ImageIcon(file.getAbsolutePath());
int height = imageIcon.getIconHeight();
int width = imageIcon.getIconWidth();
Use document.scrollTop
to change the position of the document. Set the scrollTop
of the document
equal to the bottom
of the featured section of your site
Pythonic way of iterating over a file and converting to int:
for line in open(fname):
if line.strip(): # line contains eol character(s)
n = int(line) # assuming single integer on each line
What you're trying to do is slightly more complicated, but still not straight-forward:
h = open(fname)
for line in h:
if line.strip():
[int(next(h).strip()) for _ in range(4)] # list of integers
This way it processes 5 lines at the time. Use h.next()
instead of next(h)
prior to Python 2.6.
The reason you had ValueError
is because int
cannot convert an empty string to the integer. In this case you'd need to either check the content of the string before conversion, or except an error:
try:
int('')
except ValueError:
pass # or whatever
The .exe is the program. The .dll is a library that a .exe (or another .dll) may call into.
What sakthivignesh says can be true in that one .exe can use another as if it were a library, and this is done (for example) with some COM components. In this case, the "slave" .exe is a separate program (strictly speaking, a separate process - perhaps running on a separate machine), but one that accepts and handles requests from other programs/components/whatever.
However, if you just pick a random .exe and .dll from a folder in your Program Files, odds are that COM isn't relevant - they are just a program and its dynamically-linked libraries.
Using Win32 APIs, a program can load and use a DLL using the LoadLibrary and GetProcAddress API functions, IIRC. There were similar functions in Win16.
COM is in many ways an evolution of the DLL idea, originally concieved as the basis for OLE2, whereas .NET is the descendant of COM. DLLs have been around since Windows 1, IIRC. They were originally a way of sharing binary code (particularly system APIs) between multiple running programs in order to minimise memory use.
I do not have enough reputation to give a comment to Pleerock, therefor do I have to create an answer. I am sorry for that, but he put some good effort in it and I would like to answer him.
Pleerock, you created the perfect example to show why those constants should be independent from interfaces and independent from inheritance. For the client of the application is it not important that there is a technical difference between those implementation of cars. They are the same for the client, just cars. So, the client wants to look at them from that perspective, which is an interface like I_Somecar. Throughout the application will the client use only one perspective and not different ones for each different car brand.
If a client wants to compare cars prior to buying he can have a method like this:
public List<Decision> compareCars(List<I_Somecar> pCars);
An interface is a contract about behaviour and shows different objects from one perspective. The way you design it, will every car brand have its own line of inheritance. Although it is in reality quite correct, because cars can be that different that it can be like comparing completely different type of objects, in the end there is choice between different cars. And that is the perspective of the interface all brands have to share. The choice of constants should not make this impossible. Please, consider the answer of Zarkonnen.
Also, I noticed one more difference between .load and .ready. I am opening a child window and I am performing some work when child window opens. .load is called only first time when I open the window and if I don't close the window then .load will not be called again. however, .ready is called every time irrespective of close the child window or not.
i was looking information about how to do a POST request. I need to specify that mi request is a POST request because, i'm working with RESTful web services that only uses POST methods, and if the request isn't post, when i try to do the request i receive an HTTP error 405. I assure that my code isn't wrong doing the next: I create a method in my web service that is called through GET request and i point my application to consume that web service method and it works. My code is the next:
URL server = null;
URLConnection conexion = null;
BufferedReader reader = null;
server = new URL("http://localhost:8089/myApp/resources/webService");
conexion = server.openConnection();
reader = new BufferedReader(new InputStreamReader(server.openStream()));
System.out.println(reader.readLine());
This is an expansion of one of the solutions provided in Jakub's answer
I was faced with a situation where the commits I needed to roll back were somewhat complex, with several of the commits being merge commits, and I needed to avoid rewriting history. I was not able to use a series of git revert
commands because I eventually ran into conflicts between the reversion changes being added. I ended up using the following steps.
First, check out the contents of the target commit while leaving HEAD at the tip of the branch:
$ git checkout -f <target-commit> -- .
(The -- makes sure <target-commit>
is interpreted as a commit rather than a file; the . refers to the current directory.)
Then, determine what files were added in the commits being rolled back, and thus need to be deleted:
$ git diff --name-status --cached <target-commit>
Files that were added should show up with an "A" at the beginning of the line, and there should be no other differences. Now, if any files need to be removed, stage these files for removal:
$ git rm <filespec>[ <filespec> ...]
Finally, commit the reversion:
$ git commit -m 'revert to <target-commit>'
If desired, make sure that we're back to the desired state:
$git diff <target-commit> <current-commit>
There should be no differences.
Swift 2.0 & iOS 7+ / iOS 8+ / iOS 9+
public class Helper {
public class var isIpad:Bool {
if #available(iOS 8.0, *) {
return UIScreen.mainScreen().traitCollection.userInterfaceIdiom == .Pad
} else {
return UIDevice.currentDevice().userInterfaceIdiom == .Pad
}
}
public class var isIphone:Bool {
if #available(iOS 8.0, *) {
return UIScreen.mainScreen().traitCollection.userInterfaceIdiom == .Phone
} else {
return UIDevice.currentDevice().userInterfaceIdiom == .Phone
}
}
}
Use :
if Helper.isIpad {
}
OR
guard Helper.isIpad else {
return
}
Thanks @user3378170
To add to ScottTx's answer, here's the actual code to start the service if you're doing it the Microsoft way (ie. using a Setup project etc...)
(excuse the VB.net code, but this is what I'm stuck with)
Private Sub ServiceInstaller1_AfterInstall(ByVal sender As System.Object, ByVal e As System.Configuration.Install.InstallEventArgs) Handles ServiceInstaller1.AfterInstall
Dim sc As New ServiceController()
sc.ServiceName = ServiceInstaller1.ServiceName
If sc.Status = ServiceControllerStatus.Stopped Then
Try
' Start the service, and wait until its status is "Running".
sc.Start()
sc.WaitForStatus(ServiceControllerStatus.Running)
' TODO: log status of service here: sc.Status
Catch ex As Exception
' TODO: log an error here: "Could not start service: ex.Message"
Throw
End Try
End If
End Sub
To create the above event handler, go to the ProjectInstaller designer where the 2 controlls are. Click on the ServiceInstaller1 control. Go to the properties window under events and there you'll find the AfterInstall event.
Note: Don't put the above code under the AfterInstall event for ServiceProcessInstaller1. It won't work, coming from experience. :)
Code to simply get the contents as text instead of html:
'html_text' parameter is the string which you will pass in this function to get the text
from bs4 import BeautifulSoup
soup = BeautifulSoup(html_text, 'lxml')
text = soup.get_text()
print(text)
Leading 0 day
SELECT FORMAT(GetDate(), 'dd')
You haven't at time of writing described what you are going to do with the response or what its content type is. An answer already contains a very basic usage of MSXML2.XMLHTTP
(I recommend the more explicit MSXML2.XMLHTTP.3.0
progID) however you may need to do different things with the response, it may not be text.
The XMLHTTP also has a responseBody
property which is a byte array version of the reponse and there is a responseStream
which is an IStream
wrapper for the response.
Note that in a server-side requirement (e.g., VBScript hosted in ASP) you would use MSXML.ServerXMLHTTP.3.0
or WinHttp.WinHttpRequest.5.1
(which has a near identical interface).
Here is an example of using XmlHttp to fetch a PDF file and store it:-
Dim oXMLHTTP
Dim oStream
Set oXMLHTTP = CreateObject("MSXML2.XMLHTTP.3.0")
oXMLHTTP.Open "GET", "http://someserver/folder/file.pdf", False
oXMLHTTP.Send
If oXMLHTTP.Status = 200 Then
Set oStream = CreateObject("ADODB.Stream")
oStream.Open
oStream.Type = 1
oStream.Write oXMLHTTP.responseBody
oStream.SaveToFile "c:\somefolder\file.pdf"
oStream.Close
End If
Next to the performance issues, there is another one very important which I'd call code maintainability and extendibility.
If a T is POD and you start preferring initialization list, then if one time T will change to a non-POD type, you won't need to change anything around initialization to avoid unnecessary constructor calls because it is already optimised.
If type T does have default constructor and one or more user-defined constructors and one time you decide to remove or hide the default one, then if initialization list was used, you don't need to update code if your user-defined constructors because they are already correctly implemented.
Same with const members or reference members, let's say initially T is defined as follows:
struct T
{
T() { a = 5; }
private:
int a;
};
Next, you decide to qualify a as const, if you would use initialization list from the beginning, then this was a single line change, but having the T defined as above, it also requires to dig the constructor definition to remove assignment:
struct T
{
T() : a(5) {} // 2. that requires changes here too
private:
const int a; // 1. one line change
};
It's not a secret that maintenance is far easier and less error-prone if code was written not by a "code monkey" but by an engineer who makes decisions based on deeper consideration about what he is doing.
Here is complete answer for Angular 6+ based on @ryanrain answer:
From angular-cli doc, json can be considered as assets and accessed from standard import without use of ajax request.
Let's suppose you add your json files into "your-json-dir" directory:
add "your-json-dir" into angular.json file (:
"assets": [
"src/assets",
"src/your-json-dir"
]
create or edit typings.d.ts file (at your project root) and add the following content:
declare module "*.json" {
const value: any;
export default value;
}
This will allow import of ".json" modules without typescript error.
in your controller/service/anything else file, simply import the file by using this relative path:
import * as myJson from 'your-json-dir/your-json-file.json';
On input:
step="any"
class="two-decimals"
On script:
$(".two-decimals").change(function(){
this.value = parseFloat(this.value).toFixed(2);
});
SQL stands for Structured Query Language, and it is a programming language designed for querying data from a database. MySQL is a relational database management system, which is a completely different thing.
MySQL is an open-source platform that uses SQL, just like MSSQL, which is Microsoft's product (not open-source) that uses SQL for database management.
You can use these links to download Visual Studio 2015
Community Edition:
And for anyone in the future who might be looking for the other editions here are the links for them as well:
Professional Edition:
Enterprise Edition:
Differences in SOAP versions
Both SOAP Version 1.1 and SOAP Version 1.2 are World Wide Web Consortium (W3C) standards. Web services can be deployed that support not only SOAP 1.1 but also support SOAP 1.2. Some changes from SOAP 1.1 that were made to the SOAP 1.2 specification are significant, while other changes are minor.
The SOAP 1.2 specification introduces several changes to SOAP 1.1. This information is not intended to be an in-depth description of all the new or changed features for SOAP 1.1 and SOAP 1.2. Instead, this information highlights some of the more important differences between the current versions of SOAP.
The changes to the SOAP 1.2 specification that are significant include the following updates: SOAP 1.1 is based on XML 1.0. SOAP 1.2 is based on XML Information Set (XML Infoset). The XML information set (infoset) provides a way to describe the XML document with XSD schema. However, the infoset does not necessarily serialize the document with XML 1.0 serialization on which SOAP 1.1 is based.. This new way to describe the XML document helps reveal other serialization formats, such as a binary protocol format. You can use the binary protocol format to compact the message into a compact format, where some of the verbose tagging information might not be required.
In SOAP 1.2 , you can use the specification of a binding to an underlying protocol to determine which XML serialization is used in the underlying protocol data units. The HTTP binding that is specified in SOAP 1.2 - Part 2 uses XML 1.0 as the serialization of the SOAP message infoset.
SOAP 1.2 provides the ability to officially define transport protocols, other than using HTTP, as long as the vendor conforms to the binding framework that is defined in SOAP 1.2. While HTTP is ubiquitous, it is not as reliable as other transports including TCP/IP and MQ. SOAP 1.2 provides a more specific definition of the SOAP processing model that removes many of the ambiguities that might lead to interoperability errors in the absence of the Web Services-Interoperability (WS-I) profiles. The goal is to significantly reduce the chances of interoperability issues between different vendors that use SOAP 1.2 implementations. SOAP with Attachments API for Java (SAAJ) can also stand alone as a simple mechanism to issue SOAP requests. A major change to the SAAJ specification is the ability to represent SOAP 1.1 messages and the additional SOAP 1.2 formatted messages. For example, SAAJ Version 1.3 introduces a new set of constants and methods that are more conducive to SOAP 1.2 (such as getRole(), getRelay()) on SOAP header elements. There are also additional methods on the factories for SAAJ to create appropriate SOAP 1.1 or SOAP 1.2 messages. The XML namespaces for the envelope and encoding schemas have changed for SOAP 1.2. These changes distinguish SOAP processors from SOAP 1.1 and SOAP 1.2 messages and supports changes in the SOAP schema, without affecting existing implementations. Java Architecture for XML Web Services (JAX-WS) introduces the ability to support both SOAP 1.1 and SOAP 1.2. Because JAX-RPC introduced a requirement to manipulate a SOAP message as it traversed through the run time, there became a need to represent this message in its appropriate SOAP context. In JAX-WS, a number of additional enhancements result from the support for SAAJ 1.3.
There is not difine POST AND GET method for particular android....but all here is differance
GET The GET method appends name/value pairs to the URL, allowing you to retrieve a resource representation. The big issue with this is that the length of a URL is limited (roughly 3000 char) resulting in data loss should you have to much stuff in the form on your page, so this method only works if there is a small number parameters.
What does this mean for me? Basically this renders the GET method worthless to most developers in most situations. Here is another way of looking at it: the URL could be truncated (and most likely will be give today's data-centric sites) if the form uses a large number of parameters, or if the parameters contain large amounts of data. Also, parameters passed on the URL are visible in the address field of the browser (YIKES!!!) not the best place for any kind of sensitive (or even non-sensitive) data to be shown because you are just begging the curious user to mess with it.
POST The alternative to the GET method is the POST method. This method packages the name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the forms output, basically its a no-brainer on which one to use. POST is also more secure but certainly not safe. Although HTTP fully supports CRUD, HTML 4 only supports issuing GET and POST requests through its various elements. This limitation has held Web applications back from making full use of HTTP, and to work around it, most applications overload POST to take care of everything but resource retrieval.
If it is just about the color and there is no specific need for JavaScript, you could also convert them to a font. This link gives you an opportunity to create a font based on the SVG. However, it is not possible to use img attributes afterwards - like "alt". This also limits the accessibility of your website for blind people and so on.
When the user presses the tab button the user will be taken through the form in the order 1, 2, and 3 as indicated in the example below.
For example:
Name: <input name="name" tabindex="1" />
Age: <input name="age" tabindex="3" />
Email: <input name="email" tabindex="2" />
Another solution is to use a state and lifecycle hooks in the routed component and a search statement in the to
property of the <Link />
component. The search parameters can later be accessed via new URLSearchParams()
;
<Link
key={id}
to={{
pathname: this.props.match.url + '/' + foo,
search: '?foo=' + foo
}} />
<Route path="/details/:foo" component={DetailsPage}/>
export default class DetailsPage extends Component {
state = {
foo: ''
}
componentDidMount () {
this.parseQueryParams();
}
componentDidUpdate() {
this.parseQueryParams();
}
parseQueryParams () {
const query = new URLSearchParams(this.props.location.search);
for (let param of query.entries()) {
if (this.state.foo!== param[1]) {
this.setState({foo: param[1]});
}
}
}
render() {
return(
<div>
<h2>{this.state.foo}</h2>
</div>
)
}
}
Use In
instead of =
select * from dbo.books
where isbn in (select isbn from dbo.lending
where act between @fdate and @tdate
and stat ='close'
)
or you can use Exists
SELECT t1.*,t2.*
FROM books t1
WHERE EXISTS ( SELECT * FROM dbo.lending t2 WHERE t1.isbn = t2.isbn and
t2.act between @fdate and @tdate and t2.stat ='close' )
Have you tried:
SELECT Cast( 2.555 as decimal(53,8))
This would return 2.55500000
. Is that what you want?
UPDATE:
Apparently you can also use SQL_VARIANT_PROPERTY to find the precision and scale of a value. Example:
SELECT SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Precision'),
SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Scale')
returns 8|7
You may be able to use this in your conversion process...
As mentioned Pascal MARTIN, you should replace the '\' with DIRECTORY_SEPARATOR for example:
$filename = BASE_PATH . DIRECTORY_SEPARATOR . str_replace('\\', DIRECTORY_SEPARATOR, $class) . '.php';
include($filename);
Also I would suggest you to reorganize the dirrectory structure, to make the code more readable. This could be an alternative:
Directory structure:
ProjectRoot
|- lib
File: /ProjectRoot/lib/Person/Barnes/David/Class1.php
<?php
namespace Person\Barnes\David
class Class1
{
public function __construct()
{
echo __CLASS__;
}
}
?>
File: /ProjectRoot/test.php
define('BASE_PATH', realpath(dirname(__FILE__)));
function my_autoloader($class)
{
$filename = BASE_PATH . '/lib/' . str_replace('\\', '/', $class) . '.php';
include($filename);
}
spl_autoload_register('my_autoloader');
use Person\Barnes\David as MyPerson;
$class = new MyPerson\Class1();
One straightforward way to convert an ISO 8601-like date string to a UNIX timestamp or datetime.datetime
object in all supported Python versions without installing third-party modules is to use the date parser of SQLite.
#!/usr/bin/env python
from __future__ import with_statement, division, print_function
import sqlite3
import datetime
testtimes = [
"2016-08-25T16:01:26.123456Z",
"2016-08-25T16:01:29",
]
db = sqlite3.connect(":memory:")
c = db.cursor()
for timestring in testtimes:
c.execute("SELECT strftime('%s', ?)", (timestring,))
converted = c.fetchone()[0]
print("%s is %s after epoch" % (timestring, converted))
dt = datetime.datetime.fromtimestamp(int(converted))
print("datetime is %s" % dt)
Output:
2016-08-25T16:01:26.123456Z is 1472140886 after epoch
datetime is 2016-08-25 12:01:26
2016-08-25T16:01:29 is 1472140889 after epoch
datetime is 2016-08-25 12:01:29
The format of favicon must be square otherwise the browser will stretch it. Unfortunatelly, Internet Explorer < 11 do not support .gif, or .png filetypes, but only Microsoft's .ico format. You can use some "favicon generator" app like: http://favicon-generator.org/
For those who are having this issue through a VS client side once successfully added a service reference and trying to execute the first call got this exception: “The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel” If you are using (like my case) an endpoint URL with the IP address and got this exception, then you should probably need to re-add the service reference doing this steps:
Try again :). Thanks
Use this:
word = raw_input("Please enter a single word : ")
while True:
if " " in word:
word = raw_input("Please enter a single word : ")
else:
print "Thanks"
break
With C++17 or later, there's the standard header <filesystem>
with
function
std::filesystem::create_directories
which should be used in modern C++ programs.
The C++ standard functions do not have the POSIX-specific explicit
permissions (mode) argument, though.
However, here's a C function that can be compiled with C++ compilers.
/*
@(#)File: mkpath.c
@(#)Purpose: Create all directories in path
@(#)Author: J Leffler
@(#)Copyright: (C) JLSS 1990-2020
@(#)Derivation: mkpath.c 1.16 2020/06/19 15:08:10
*/
/*TABSTOP=4*/
#include "posixver.h"
#include "mkpath.h"
#include "emalloc.h"
#include <errno.h>
#include <string.h>
/* "sysstat.h" == <sys/stat.h> with fixup for (old) Windows - inc mode_t */
#include "sysstat.h"
typedef struct stat Stat;
static int do_mkdir(const char *path, mode_t mode)
{
Stat st;
int status = 0;
if (stat(path, &st) != 0)
{
/* Directory does not exist. EEXIST for race condition */
if (mkdir(path, mode) != 0 && errno != EEXIST)
status = -1;
}
else if (!S_ISDIR(st.st_mode))
{
errno = ENOTDIR;
status = -1;
}
return(status);
}
/**
** mkpath - ensure all directories in path exist
** Algorithm takes the pessimistic view and works top-down to ensure
** each directory in path exists, rather than optimistically creating
** the last element and working backwards.
*/
int mkpath(const char *path, mode_t mode)
{
char *pp;
char *sp;
int status;
char *copypath = STRDUP(path);
status = 0;
pp = copypath;
while (status == 0 && (sp = strchr(pp, '/')) != 0)
{
if (sp != pp)
{
/* Neither root nor double slash in path */
*sp = '\0';
status = do_mkdir(copypath, mode);
*sp = '/';
}
pp = sp + 1;
}
if (status == 0)
status = do_mkdir(path, mode);
FREE(copypath);
return (status);
}
#ifdef TEST
#include <stdio.h>
#include <unistd.h>
/*
** Stress test with parallel running of mkpath() function.
** Before the EEXIST test, code would fail.
** With the EEXIST test, code does not fail.
**
** Test shell script
** PREFIX=mkpath.$$
** NAME=./$PREFIX/sa/32/ad/13/23/13/12/13/sd/ds/ww/qq/ss/dd/zz/xx/dd/rr/ff/ff/ss/ss/ss/ss/ss/ss/ss/ss
** : ${MKPATH:=mkpath}
** ./$MKPATH $NAME &
** [...repeat a dozen times or so...]
** ./$MKPATH $NAME &
** wait
** rm -fr ./$PREFIX/
*/
int main(int argc, char **argv)
{
int i;
for (i = 1; i < argc; i++)
{
for (int j = 0; j < 20; j++)
{
if (fork() == 0)
{
int rc = mkpath(argv[i], 0777);
if (rc != 0)
fprintf(stderr, "%d: failed to create (%d: %s): %s\n",
(int)getpid(), errno, strerror(errno), argv[i]);
exit(rc == 0 ? EXIT_SUCCESS : EXIT_FAILURE);
}
}
int status;
int fail = 0;
while (wait(&status) != -1)
{
if (WEXITSTATUS(status) != 0)
fail = 1;
}
if (fail == 0)
printf("created: %s\n", argv[i]);
}
return(0);
}
#endif /* TEST */
The macros STRDUP()
and FREE()
are error-checking versions of
strdup()
and free()
, declared in emalloc.h
(and implemented in
emalloc.c
and estrdup.c
).
The "sysstat.h"
header deals with broken versions of <sys/stat.h>
and can be replaced by <sys/stat.h>
on modern Unix systems (but there
were many issues back in 1990).
And "mkpath.h"
declares mkpath()
.
The change between v1.12 (original version of the answer) and v1.13
(amended version of the answer) was the test for EEXIST
in
do_mkdir()
.
This was pointed out as necessary by
Switch — thank
you, Switch.
The test code has been upgraded and reproduced the problem on a MacBook
Pro (2.3GHz Intel Core i7, running Mac OS X 10.7.4), and suggests that
the problem is fixed in the revision (but testing can only show the
presence of bugs, never their absence).
The code shown is now v1.16; there have been cosmetic or administrative
changes made since v1.13 (such as use mkpath.h
instead of jlss.h
and
include <unistd.h>
unconditionally in the test code only).
It's reasonable to argue that "sysstat.h"
should be replaced by
<sys/stat.h>
unless you have an unusually recalcitrant system.
(You are hereby given permission to use this code for any purpose with attribution.)
This code is available in my SOQ
(Stack Overflow Questions) repository on GitHub as files mkpath.c
and
mkpath.h
(etc.) in the
src/so-0067-5039
sub-directory.
You have to use the contents()
method:
$("#myiframe").contents().find("#myContent")
Source: http://simple.procoding.net/2008/03/21/how-to-access-iframe-in-jquery/
API Doc: https://api.jquery.com/contents/
Android throws an exception if you fail to pass the height or width of a view. Instead of creating a new LayoutParams object, use the original one, so that all other set parameters are kept. Note that the type of LayoutParams returned by getLayoutParams is that of the parent layout, not the view you are resizing.
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) someLayout.getLayoutParams();
params.height = 130;
someLayout.setLayoutParams(params);
You can do this as well. Can be faster for quick calculations:
echo $[2+2]
This works and is fairly fast since it does the linear searching using the builtin list.index()
method and ==
operator:
def contains(sub, pri):
M, N = len(pri), len(sub)
i, LAST = 0, M-N+1
while True:
try:
found = pri.index(sub[0], i, LAST) # find first elem in sub
except ValueError:
return False
if pri[found:found+N] == sub:
return [found, found+N-1]
else:
i = found+1
You can use -
$isTouch = isset($variable);
It will return true
if the $variable
is defined. if the variable is not defined it will return false
.
Note : Returns TRUE if var exists and has value other than NULL, FALSE otherwise.
If you want to check for false
, 0
etc You can then use empty()
-
$isTouch = empty($variable);
empty()
works for -
For files in a directory, you can use things like:
if exist *.csv echo "csv file found"
or
if not exist *.csv goto nofile
It depends on whether default path is set for data and log files or not.
If the path is set explicitly at Properties
=> Database Settings
=> Database default locations
then SQL server stores it at Software\Microsoft\MSSQLServer\MSSQLServer
in DefaultData
and DefaultLog
values.
However, if these parameters aren't set explicitly, SQL server uses Data and Log paths of master database.
Bellow is the script that covers both cases. This is simplified version of the query that SQL Management Studio runs.
Also, note that I use xp_instance_regread
instead of xp_regread
, so this script will work for any instance, default or named.
declare @DefaultData nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultData', @DefaultData output
declare @DefaultLog nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'DefaultLog', @DefaultLog output
declare @DefaultBackup nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer', N'BackupDirectory', @DefaultBackup output
declare @MasterData nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer\Parameters', N'SqlArg0', @MasterData output
select @MasterData=substring(@MasterData, 3, 255)
select @MasterData=substring(@MasterData, 1, len(@MasterData) - charindex('\', reverse(@MasterData)))
declare @MasterLog nvarchar(512)
exec master.dbo.xp_instance_regread N'HKEY_LOCAL_MACHINE', N'Software\Microsoft\MSSQLServer\MSSQLServer\Parameters', N'SqlArg2', @MasterLog output
select @MasterLog=substring(@MasterLog, 3, 255)
select @MasterLog=substring(@MasterLog, 1, len(@MasterLog) - charindex('\', reverse(@MasterLog)))
select
isnull(@DefaultData, @MasterData) DefaultData,
isnull(@DefaultLog, @MasterLog) DefaultLog,
isnull(@DefaultBackup, @MasterLog) DefaultBackup
You can achieve the same result by using SMO. Bellow is C# sample, but you can use any other .NET language or PowerShell.
using (var connection = new SqlConnection("Data Source=.;Integrated Security=SSPI"))
{
var serverConnection = new ServerConnection(connection);
var server = new Server(serverConnection);
var defaultDataPath = string.IsNullOrEmpty(server.Settings.DefaultFile) ? server.MasterDBPath : server.Settings.DefaultFile;
var defaultLogPath = string.IsNullOrEmpty(server.Settings.DefaultLog) ? server.MasterDBLogPath : server.Settings.DefaultLog;
}
It is so much simpler in SQL Server 2012 and above, assuming you have default paths set (which is probably always a right thing to do):
select
InstanceDefaultDataPath = serverproperty('InstanceDefaultDataPath'),
InstanceDefaultLogPath = serverproperty('InstanceDefaultLogPath')
This link should satisfy your curiosity.
Basically (forgetting your third example which is bad), the different between 1 and 2 is that 1 allocates space for a pointer to the array.
But in the code, you can manipulate them as pointers all the same -- only thing, you cannot reallocate the second.
I'm not sure whether you think about:
select * from friend f
where not exists (
select 1 from likes l where f.id1 = l.id and f.id2 = l.id2
)
it works only if id1 is related with id1 and id2 with id2 not both.
Yes, you need to use global foo
if you are going to write to it.
foo = []
def bar():
global foo
...
foo = [1]
In Mercurial you use hg log --keyword
to search for keywords in the commit messages and hg log --user
to search for a particular user. See hg help log
for other ways to limit the log.
Simple Right Click and go to Properties Option of any project on your Existing application and see the Application option on Left menu and then click on Application option see target Framework to see current Framework version .
SELECT CONCAT(LOWER(LAST_NAME), UPPER(LAST_NAME)
INITCAP(LAST_NAME), HIRE DATE AS ‘up_low_init_hdate’)
FROM EMPLOYEES
WHERE HIRE DATE = 1995
To see all tables:
.tables
To see a particular table:
.schema [tablename]
Here's a fairly self-contained example. It turns a button red after 5sec.
public void SetAlarm()
{
final Button button = buttons[2]; // replace with a button from your own UI
BroadcastReceiver receiver = new BroadcastReceiver() {
@Override public void onReceive( Context context, Intent _ )
{
button.setBackgroundColor( Color.RED );
context.unregisterReceiver( this ); // this == BroadcastReceiver, not Activity
}
};
this.registerReceiver( receiver, new IntentFilter("com.blah.blah.somemessage") );
PendingIntent pintent = PendingIntent.getBroadcast( this, 0, new Intent("com.blah.blah.somemessage"), 0 );
AlarmManager manager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
// set alarm to fire 5 sec (1000*5) from now (SystemClock.elapsedRealtime())
manager.set( AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime() + 1000*5, pintent );
}
Remember though that the AlarmManager fires even when your application is not running. If you call this function and hit the Home button, wait 5 sec, then go back into your app, the button will have turned red.
I don't know what kind of behavior you would get if your app isn't in memory at all, so be careful with what kind of state you try to preserve.
This is how to easily convert from an ISO string to a SQL-Server datetime
:
INSERT INTO time_data (ImportateDateTime) VALUES (CAST(CONVERT(datetimeoffset,'2019-09-13 22:06:26.527000') AS datetime))
Source https://www.sqlservercurry.com/2010/04/convert-character-string-iso-date-to.html
Spring-integration example, routing based on a an Enum field:
public class BookOrder {
public enum OrderType { DELIVERY, PICKUP } //enum
public BookOrder(..., OrderType orderType) //orderType
...
config:
<router expression="payload.orderType" input-channel="processOrder">
<mapping value="DELIVERY" channel="delivery"/>
<mapping value="PICKUP" channel="pickup"/>
</router>
You need more memory.
Here's why I say that:
I'm using VirtualBox on Windows to run Ubuntu 10.10 as a guest. I installed Eclipse and the Android SDK on the VM. My physical box has 4 GB of memory, but when I first configured the Ubuntu virtual machine, I only gave it 1 GB. The emulator took about 15 minutes to launch. Then, I changed my configuration to give the VM 2 GB and the emulator was running in less than a minute.
thanks patrice-n! this code worked to get both queued and running jobs and their parameters:
import hudson.model.Job
import hudson.model.ParametersAction
import hudson.model.Queue
import jenkins.model.Jenkins
println("================================================")
for (Job job : Jenkins.instanceOrNull.getAllItems(Job.class)) {
if (job.isInQueue()) {
println("------------------------------------------------")
println("InQueue " + job.name)
Queue.Item queue = job.getQueueItem()
if (queue != null) {
println(queue.params)
}
}
if (job.isBuilding()) {
println("------------------------------------------------")
println("Building " + job.name)
def build = job.getBuilds().getLastBuild()
def parameters = build?.getAllActions().find{ it instanceof ParametersAction }?.parameters
parameters.each {
def dump = it.dump()
println "parameter ${it.name}: ${dump}"
}
}
}
println("================================================")
This code works for me:
#!/bin/sh
argc=$#
echo $argc
if [ $argc -eq 0 -o $argc -eq 1 ]; then
echo "foo"
else
echo "bar"
fi
I don't think sh supports "==". Use "=" to compare strings and -eq to compare ints.
man test
for more details.
The problem may be if you are using older version of jQuery. Because older versions of jQuery have 'live' method instead of 'on'
This will return true only if host responds to ping. Works on windows and linux
def ping(host):
"""
Returns True if host (str) responds to a ping request.
NB on windows ping returns true for success and host unreachable
"""
param = '-n' if platform.system().lower()=='windows' else '-c'
result = False
try:
out = subprocess.check_output(['ping', param, '1', host])
#ping exit code 0
if 'Reply from {}'.format(host) in str(out):
result = True
except subprocess.CalledProcessError:
#ping exit code not 0
result = False
#print(str(out))
return result
I agree with Petar Ivanov but it is best if we implement in following way:
public String replace(String str, int index, char replace){
if(str==null){
return str;
}else if(index<0 || index>=str.length()){
return str;
}
char[] chars = str.toCharArray();
chars[index] = replace;
return String.valueOf(chars);
}
You can do it simply like;
HTML
<input id="checkbox" type="checkbox" />
jQuery
$(document).ready(function () {
var ckbox = $('#checkbox');
$('input').on('click',function () {
if (ckbox.is(':checked')) {
alert('You have Checked it');
} else {
alert('You Un-Checked it');
}
});
});
or even simpler;
$("#checkbox").attr("checked") ? alert("Checked") : alert("Unchecked");
If the checkbox
is checked it will return true
otherwise undefined
Assuming you actually mean timestamp
because there is no datetime
in Postgres
Cast the timestamp column to a date, that will remove the time part:
select *
from the_table
where the_timestamp_column::date = date '2015-07-15';
This will return all rows from July, 15th.
Note that the above will not use an index on the_timestamp_column
. If performance is critical, you need to either create an index on that expression or use a range condition:
select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
and the_timestamp_column < timestamp '2015-07-16 00:00:00';
I've found this solution by googling. I have just had this problem and it solved it.
My mistake was to put a project in other location out of the workspace, and share this workspace between several computers, where the paths difer. I learned that, when a project is out of workspace, its location is saved in workspace/.metadata/.plugins/org.eclipse.core.resources/.projects/PROJECTNAME/.location
Deleting .location and reimporting the project into workspace solved the issue. Hope this helps.
You can simply use the following command:-
tail -NUMBER_OF_LINES FILE_NAME
e.g tail -100 test.log
In case, if you want the output of the above in a separate file then you can pipes as follows:-
tail -NUMBER_OF_LINES FILE_NAME > OUTPUT_FILE_NAME
e.g tail -100 test.log > output.log
If you want the position relative to the document then:
$("#myTable").offset().top;
but often you will want the position relative to the closest positioned parent:
$("#myTable").position().top;
Change localhost:8080 to localhost:3306.
Using @Adrian Frühwirth answer:
function strip {
local STRING=${1#$"$2"}
echo ${STRING%$"$2"}
}
use it like this
HELLO=":hello:"
HELLO=$(strip "$HELLO" ":")
echo $HELLO # hello
Note: Calling a lifecycle method from another one is not a good practice. In below example I tried to achieve that your onNewIntent will be always called irrespective of your Activity type.
OnNewIntent() always get called for singleTop/Task activities except for the first time when activity is created. At that time onCreate is called providing to solution for few queries asked on this thread.
You can invoke onNewIntent always by putting it into onCreate method like
@Override
public void onCreate(Bundle savedState){
super.onCreate(savedState);
onNewIntent(getIntent());
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
//code
}
ElementTree is not too smart about namespaces. You need to give the .find()
, findall()
and iterfind()
methods an explicit namespace dictionary. This is not documented very well:
namespaces = {'owl': 'http://www.w3.org/2002/07/owl#'} # add more as needed
root.findall('owl:Class', namespaces)
Prefixes are only looked up in the namespaces
parameter you pass in. This means you can use any namespace prefix you like; the API splits off the owl:
part, looks up the corresponding namespace URL in the namespaces
dictionary, then changes the search to look for the XPath expression {http://www.w3.org/2002/07/owl}Class
instead. You can use the same syntax yourself too of course:
root.findall('{http://www.w3.org/2002/07/owl#}Class')
If you can switch to the lxml
library things are better; that library supports the same ElementTree API, but collects namespaces for you in a .nsmap
attribute on elements.
According to docs :
Foo mock = mock(Foo.class, CALLS_REAL_METHODS);
// this calls the real implementation of Foo.getSomething()
value = mock.getSomething();
when(mock.getSomething()).thenReturn(fakeValue);
// now fakeValue is returned
value = mock.getSomething();
You can use the short version:
File.write('/path/to/file', 'Some glorious content')
It returns the length written; see ::write for more details and options.
To append to the file, if it already exists, use:
File.write('/path/to/file', 'Some glorious content', mode: 'a')
The common way is to load the row to update:
$post = Post::find($id);
I your case
$post = Post::find(3);
$post->title = "Updated title";
$post->save();
But in one step (just update) you can do this:
$affectedRows = Post::where("id", 3)->update(["title" => "Updated title"]);
If you happen to be using the Ruby on Rails' jQuery gem jquery-rails
and for some reason you can't refactor your legacy code, the last version that still supports is 2.1.3
and you can lock it by using the following syntax on your Gemfile
:
gem 'jquery-rails', '~> 2.1', '= 2.1.3'
then you can use the following command to update:
bundle update jquery-rails
I hope that help others facing a similar issue.
Map.Entry interface helps us iterating a Map class
Check this simple example:
public class MapDemo {
public static void main(String[] args) {
Map<Integer,String> map=new HashMap();
map.put(1, "Kamran");
map.put(2, "Ali");
map.put(3, "From");
map.put(4, "Dir");
map.put(5, "Lower");
for(Map.Entry m:map.entrySet()){
System.out.println(m.getKey()+" "+m.getValue());
}
}
}
In Year 2019, we can use Javascript's ES6 Spread syntax to do it concisely and efficiently
data = [...data, {"label": 2, "value": 13}]
Examples
var data = [_x000D_
{"label" : "1", "value" : 12},_x000D_
{"label" : "1", "value" : 12},_x000D_
{"label" : "1", "value" : 12},_x000D_
];_x000D_
_x000D_
data = [...data, {"label" : "2", "value" : 14}] _x000D_
console.log(data)
_x000D_
For your case (i know it was in 2011), we can do it with map() & forEach() like below
var lab = ["1","2","3","4"];_x000D_
var val = [42,55,51,22];_x000D_
_x000D_
//Using forEach()_x000D_
var data = [];_x000D_
val.forEach((v,i) => _x000D_
data= [...data, {"label": lab[i], "value":v}]_x000D_
)_x000D_
_x000D_
//Using map()_x000D_
var dataMap = val.map((v,i) => _x000D_
({"label": lab[i], "value":v})_x000D_
)_x000D_
_x000D_
console.log('data: ', data);_x000D_
console.log('dataMap : ', dataMap);
_x000D_
SIMPLE
It's a prefix to indicate the number is in hexadecimal rather than in some other base. The C programming language uses it to tell compiler.
Example :
0x6400
translates to 6*16^3 + 4*16^2 + 0*16^1 +0*16^0 = 25600.
When compiler reads 0x6400
, It understands the number is hexadecimal with the help of 0x term. Usually we can understand by (6400)16 or (6400)8
or any base ..
Hope Helped in some way.
Good day,
Simply pass your word into the following function:
function highlight_words(word) {
const page = document.body.innerHTML;
document.body.innerHTML = page.replace(new RegExp(word, "gi"), (match) => `<mark>${match}</mark>`);
}
Usage:
highlight_words("hello")
This will highlight all instances of the word on the page.
This will work:
find . -name "*.DS_Store" -type f -exec git-rm {} \;
It deletes all files whose names end with .DS_Store
, including ._.DS_Store
.
Use replace(/\s+/g,'')
,
for example:
const stripped = ' My String With A Lot Whitespace '.replace(/\s+/g, '')// 'MyStringWithALotWhitespace'
The value for an annotation must be a compile time constant, so there is no simple way of doing what you are trying to do.
See also here: How to supply value to an annotation from a Constant java
It is possible to use some compile time tools (ant, maven?) to config it if the value is known before you try to run the program.
You could use the built-in exec statement, eg.:
exec("try: \n \t if sam[0] != 'harry': \n \t\t print('hello', sam) \nexcept: pass")
Where \n
is a newline and \t
is used as indentation (a tab).
Also, you should count the spaces you use, so your indentation matches exactly.
However, as all the other answers already said, this is of course only to be used when you really have to put it on one line.
exec
is quite a dangerous statement (especially when building a webapp) since it allows execution of arbitrary Python code.
You can use the set() function to convert an iterable into a set, and then use standard set update operator (|=) to add the unique values from your new set into the existing one.
>>> a = { 1, 2, 3 }
>>> b = ( 3, 4, 5 )
>>> a |= set(b)
>>> a
set([1, 2, 3, 4, 5])
There is a difference between each parameter.
The -DskipTests
skip running tests phase, it means at the end of this process you will have your tests compiled.
The -Dmaven.test.skip=true
skip compiling and running tests phase.
As the parameter -Dmaven.test.skip=true
skip compiling you don't have the tests artifact.
For more information just read the surfire documentation: http://maven.apache.org/plugins-archives/maven-surefire-plugin-2.12.4/examples/skipping-test.html
Proper use of RuntimeException?
From Unchecked Exceptions -- The Controversy:
If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
Note that an unchecked exception is one derived from RuntimeException
and a checked exception is one derived from Exception
.
Why throw a RuntimeException
if a client cannot do anything to recover from the exception? The article explains:
Runtime exceptions represent problems that are the result of a programming problem, and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way. Such problems include arithmetic exceptions, such as dividing by zero; pointer exceptions, such as trying to access an object through a null reference; and indexing exceptions, such as attempting to access an array element through an index that is too large or too small.
Try to see if SQL snap-ins are present:
get-pssnapin -Registered
Name : SqlServerCmdletSnapin100
PSVersion : 2.0
Description : This is a PowerShell snap-in that includes various SQL Server cmdlets.
Name : SqlServerProviderSnapin100
PSVersion : 2.0
Description : SQL Server Provider
If so
Add-PSSnapin SqlServerCmdletSnapin100 # here lives Invoke-SqlCmd
Add-PSSnapin SqlServerProviderSnapin100
then you can do something like this:
invoke-sqlcmd -inputfile "c:\mysqlfile.sql" -serverinstance "servername\serverinstance" -database "mydatabase" # the parameter -database can be omitted based on what your sql script does.
Try the solution using the FileReader
class:
function getBase64(file) {
var reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function () {
console.log(reader.result);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
var file = document.querySelector('#files > input[type="file"]').files[0];
getBase64(file); // prints the base64 string
Notice that .files[0]
is a File
type, which is a sublcass of Blob
. Thus it can be used with FileReader
.
See the complete working example.
I use favico.js in my projects.
It allows to change the favicon to a range of predefined shapes and also custom ones.
Internally it uses canvas
for rendering and base64
data URL for icon encoding.
The library also has nice features: icon badges and animations; purportedly, you can even stream the webcam video into the icon :)
Wikipedia is built on MediaWiki, and here's the MediaWiki API.
Consider the following:
class Bad(object):
def __eq__(self, other):
return True
c = Bad()
c is None # False, equivalent to id(c) == id(None)
c == None # True, equivalent to c.__eq__(None)
In case all your source and replacement strings are just one character long, you can simply use the TRANSLATE
function:
SELECT translate('THIS IS UPPERCASE', 'THISUP', 'thisup')
FROM DUAL
See the Oracle documentation for details.
Question already answered by the OP, but I am posting this answer for anyone having similar problem, retting to
Could not input open file: composer.phar
error message.
Simply go to your project directory/folder and do a
composer update
Assuming this is where you have your web application:
/Library/WebServer/Documents/zendframework
change directory to it, and then run composer update
.
1. A client downloads javascript code MyCode.js from http://siteA - the origin.
The code that does the downloading - your html script tag or xhr from javascript or whatever - came from, let's say, http://siteZ. And, when the browser requests MyCode.js, it sends an Origin: header saying "Origin: http://siteZ", because it can see that you're requesting to siteA and siteZ != siteA. (You cannot stop or interfere with this.)
2. The response header of MyCode.js contains Access-Control-Allow-Origin: http://siteB, which I thought meant that MyCode.js was allowed to make cross-origin references to the site B.
no. It means, Only siteB is allowed to do this request. So your request for MyCode.js from siteZ gets an error instead, and the browser typically gives you nothing. But if you make your server return A-C-A-O: siteZ instead, you'll get MyCode.js . Or if it sends '*', that'll work, that'll let everybody in. Or if the server always sends the string from the Origin: header... but... for security, if you're afraid of hackers, your server should only allow origins on a shortlist, that are allowed to make those requests.
Then, MyCode.js comes from siteA. When it makes requests to siteB, they are all cross-origin, the browser sends Origin: siteA, and siteB has to take the siteA, recognize it's on the short list of allowed requesters, and send back A-C-A-O: siteA. Only then will the browser let your script get the result of those requests.
You still have to wrap it in an ISERROR, but you could use MATCH()
instead of VLOOKUP()
:
Returns the relative position of an item in an array that matches a specified value in a specified order. Use MATCH instead of one of the LOOKUP functions when you need the position of an item in a range instead of the item itself.
Here's a complete example, assuming you're looking for the word "key" in a range of cells:
=IF(ISERROR(MATCH("key",A5:A16,FALSE)),"missing","found")
The FALSE
is necessary to force an exact match, otherwise it will look for the closest value.
Got the same error recently but was able to fixed it by ensuring to close every wcf client call. eg.
WCFServiceClient client = new WCFServiceClient ();
//More codes here
// Always close the client.
client.Close();
or
using(WCFServiceClient client = new WCFServiceClient ())
{
//More codes here
}