Here's an article from MSDN on a guide for how to write text to a file:
http://msdn.microsoft.com/en-us/library/8bh11f1k.aspx
I'd start there, then post additional, more specific questions as you continue your development.
For others out there, I got a similar error message due to trying to run a .Net 4 app in a .Net 2 app pool. Changing the .Net FX version for the app pool fixed it for me.
As of BS3 there's a .center-block
helper class. From the docs:
// Classes
.center-block {
display: block;
margin-left: auto;
margin-right: auto;
}
// Usage as mixins
.element {
.center-block();
}
There is hidden complexity in this seemingly simple problem. All the answers given have some issues.
Create .col-centred
class, but there is a major gotcha.
.col-centred {
float: none !important;
margin: 0 auto;
}
<!-- Bootstrap 3 -->
<div class="col-lg-6 col-centred">
Centred content.
</div>
<!-- Bootstrap 2 -->
<div class="span-6 col-centred">
Centred content.
</div>
The Gotcha
Bootstrap requires columns add up to 12. If they do not they will overlap, which is a problem. In this case the centred column will overlap the column above it. Visually the page may look the same, but mouse events will not work on the column being overlapped (you can't hover or click links, for example). This is because mouse events are registering on the centred column that's overlapping the elements you try to click.
The Fixes
You can resolve this issue by using a clearfix
element. Using z-index
to bring the centred column to the bottom will not work because it will be overlapped itself, and consequently mouse events will work on it.
<div class="row">
<div class="col-lg-12">
I get overlapped by `col-lg-7 centered` unless there's a clearfix.
</div>
<div class="clearfix"></div>
<div class="col-lg-7 centred">
</div>
</div>
Or you can isolate the centred column in its own row.
<div class="row">
<div class="col-lg-12">
</div>
</div>
<div class="row">
<div class="col-lg-7 centred">
Look I am in my own row.
</div>
</div>
<!-- Bootstrap 3 -->
<div class="col-lg-6 col-lg-offset-3">
Centred content.
</div>
<!-- Bootstrap 2 -->
<div class="span-6 span-offset-3">
Centred content.
</div>
The first problem is that your centred column must be an even number because the offset value must divide evenly by 2 for the layout to be centered (left/right).
Secondly, as some have commented, using offsets is a bad idea. This is because when the browser resizes the offset will turn into blank space, pushing the actual content down the page.
This is the best solution in my opinion. No hacking required and you don't mess around with the grid, which could cause unintended consequences, as per solutions 1 and 2.
.col-centred {
margin: 0 auto;
}
<div class="row">
<div class="col-lg-12">
<div class="centred">
Look I am in my own row.
</div>
</div>
</div>
This works.
<html>
<head>
<script type = "text/javascript">
function write_below(form)
{
var input = document.forms.write.input_to_write.value;
document.getElementById('write_here').innerHTML="Your input was:"+input;
return false;
}
</script>
</head>
<!--Insert more code here-->
<body>
<form name='write' onsubmit='return write_below(this);'>
<input type = "text" name='input_to_write'>
<input type = "button" value = "submit" />
</form>
<div id='write_here'></div></body>
</html>
Returning false from the function never posts it to other page,but does edit the html content.
add simply way
<div id='cssmenu'>
<ul>
<li class=''><a href='1.html'><span>1</span></a></li>
<li class=''><a href='2.html'><span>2</span></a></li>
<li class='' style="float:right;"><a href='3.html'><span>3</span></a></li>
</ul>
</div>
$("document").ready(function(){
$(function() {
$('.cssmenu a[href="' + location.pathname.split("/")[location.pathname.split("/").length-1] + '"]').parent().addClass('active');
});
});
The string $.datepicker.regional['it']
not translate all words.
For translate the datepicker you must specify some variables:
$.datepicker.regional['it'] = {
closeText: 'Chiudi', // set a close button text
currentText: 'Oggi', // set today text
monthNames: ['Gennaio','Febbraio','Marzo','Aprile','Maggio','Giugno', 'Luglio','Agosto','Settembre','Ottobre','Novembre','Dicembre'], // set month names
monthNamesShort: ['Gen','Feb','Mar','Apr','Mag','Giu','Lug','Ago','Set','Ott','Nov','Dic'], // set short month names
dayNames: ['Domenica','Lunedì','Martedì','Mercoledì','Giovedì','Venerdì','Sabato'], // set days names
dayNamesShort: ['Dom','Lun','Mar','Mer','Gio','Ven','Sab'], // set short day names
dayNamesMin: ['Do','Lu','Ma','Me','Gio','Ve','Sa'], // set more short days names
dateFormat: 'dd/mm/yy' // set format date
};
$.datepicker.setDefaults($.datepicker.regional['it']);
$(".datepicker").datepicker();
In this case your datepicker is properly translated.
This will fail (amongst other cases) when the target mailserver uses greylisting.
Greylisting: SMTP server refuses delivery the first time a previously unknown client connects, allows next time(s); this keeps some percentage of spambots out, while allowing legitimate use - as it is expected that a legitimate mail sender will retry, which is what normal mail transfer agents will do.
However, if your code only checks on the server once, a server with greylisting will deny delivery (as your client is connecting for the first time); unless you check again in a little while, you may be incorrectly rejecting valid e-mail addresses.
Try Ctrl + K + D (don't lift the Ctrl key in between).
If you want to set a custom drawable file use this code snippet
fun setCustomStatusBar(){
if (Build.VERSION.SDK_INT >= 21) {
val decor = window.decorView
decor.viewTreeObserver.addOnPreDrawListener(object :
ViewTreeObserver.OnPreDrawListener {
override fun onPreDraw(): Boolean {
decor.viewTreeObserver.removeOnPreDrawListener(this)
val statusBar = decor.findViewById<View>
(android.R.id.statusBarBackground)
statusBar.setBackgroundResource(R.drawable.bg_statusbar)
return true
}
})
}
}
This will change all worksheet objects' names (from the perspective of the VBA editor) to match that of their sheet names (from the perspective of Excel):
Sub ZZ_Reset_Sheet_CodeNames()
'Changes the internal object name (codename) of each sheet to it's conventional name (based on it's sheet name)
Dim varItem As Variant
For Each varItem In ThisWorkbook.VBProject.VBComponents
'Type 100 is a worksheet
If varItem.Type = 100 And varItem.Name <> "ThisWorkbook" Then
varItem.Name = varItem.Properties("Name").Value
End If
Next
End Sub
It is important to note that the object name (codename) "(Name)" is being overridden by the property name "Name", and so it must be referenced as a sub-property.
You could make a remove
function so that you wouldn't have to think about it every time:
function removeElement(id) {
var elem = document.getElementById(id);
return elem.parentNode.removeChild(elem);
}
from Xlib import X, display
d = display.Display()
s = d.screen()
root = s.root
root.warp_pointer(300,300)
d.sync()
That isn't too easy to do with CSS, as it's not a behavioral language (ie JavaScript), the only easy way would be to use a JavaScript OnClick Event on your anchor and to return it as false, this is probably the shortest code you could use for that:
<a href="page.html" onclick="return false">page link</a>
I resolved it by Myproject--->java Resource---->libraries-->JRE System Libraries[java-1.6] click on this go to its "property" select "Classpath Container" change the Execution Environment to java-1.8(jdk1.8.0-35) (that is latest)
If you need a list, not a generator, use list():
from itertools import chain
x = [["a","b"], ["c"]]
y = list(chain(*x))
What you can do to resolve your conflict is
svn resolve --accept working -R <path>
where <path>
is where you have your conflict (can be the root of your repo).
Explanations:
resolve
asks svn
to resolve the conflictaccept working
specifies to keep your working files-R
stands for recursiveHope this helps.
EDIT:
To sum up what was said in the comments below:
<path>
should be the directory in conflict (C:\DevBranch\
in the case of the OP)svn switch
commandSwitch working copy to new branch/tag
option at branch creation0xe0434352 is the SEH code for a CLR exception. If you don't understand what that means, stop and read A Crash Course on the Depths of Win32™ Structured Exception Handling. So your process is not handling a CLR exception. Don't shoot the messenger, KERNELBASE.DLL is just the unfortunate victim. The perpetrator is MyApp.exe.
There should be a minidump of the crash in DrWatson folders with a full stack, it will contain everything you need to root cause the issue.
I suggest you wire up, in your myapp.exe code, AppDomain.UnhandledException
and Application.ThreadException
, as appropriate.
Try configuration at /config/application.rb:
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options, :delete, :put, :patch], credentials: true
end
end
You are trying to assign a value to a function, which is not possible in C. Try the comparison operator instead:
if (strcmp("hello", "hello") == 0)
Use options(scipen=5)
or some other high enough number. The scipen option determines how likely R is to switch to scientific notation, the higher the value the less likely it is to switch. Set the option before making your plot, if it still has scientific notation, set it to a higher number.
you can specify fields like this:
LOAD XML LOCAL INFILE '/pathtofile/file.xml'
INTO TABLE my_tablename(personal_number, firstname, ...);
Facebook uses MQTT instead of HTTP. Push is better than polling. Through HTTP we need to poll the server continuously but via MQTT server pushes the message to clients.
Comparision between MQTT and HTTP: http://www.youtube.com/watch?v=-KNPXPmx88E
Note: my answers best fits for mobile devices.
You may use DateInterval for this purpose;
$currentDate = new \DateTime(); //creates today timestamp
$currentDate->add(new \DateInterval('P5Y')); //this means 5 Years
and you can now format it;
$currentDate->format('Y-m-d');
This one was helpful to me because I wanted to see the build targets required (and their dependencies) by the make target. I know that make targets cannot begin with a "." character. I don't know what languages are supported, so I went with egrep's bracket expressions.
cat Makefile | egrep "^[[:alnum:][:punct:]]{0,}:[[:space:]]{0,}[[:alnum:][:punct:][:space:]]{0,}$"
I found the solution! Just copy the sheet with your named variables. Then delete the original sheet. The copied sheet will now have the same named variables, but with a local scope (scope= the copied sheet).
However, I don't know how to change from local variables to global..
I do this in node.js (on Windows 10) by opening 2 separate cmd instances and running each program in each instance.
This has the advantage that writing to the console is easily visible for each script.
I see that in python can do the same: 2 shells.
You can run multiple instances of IDLE/Python shell at the same time. So open IDLE and run the server code and then open up IDLE again, which will start a separate instance and then run your client code.
React 16.3 added a new convenient way to handle this by creating a ref in component's constructor and use it like below:
class MyForm extends Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
componentDidMount() {
this.textInput.current.focus();
}
render() {
return(
<div>
<input ref={this.textInput} />
</div>
);
}
}
For more details about React.createRef
, you can check this article in React blog.
Update:
Starting from React 16.8, useRef
hook can be used in function components to achieve the same result:
import React, { useEffect, useRef } from 'react';
const MyForm = () => {
const textInput = useRef(null);
useEffect(() => {
textInput.current.focus();
}, []);
return (
<div>
<input ref={textInput} />
</div>
);
};
Back in the day I found that Rdb, the former DEC product now supported by Oracle allowed the column alias to be used in the GROUP BY. Mainstream Oracle through version 11 does not allow the column alias to be used in the GROUP BY. Not sure what Postgresql, SQL Server, MySQL, etc will or won't allow. YMMV.
Use the string.substring(from, to)
API. In your case, use string.substring(0,8).
I was parsing JSON from a REST API call and got this error. It turns out the API had become "fussier" (eg about order of parameters etc) and so was returning malformed results. Check that you are getting what you expect :)
Here Blank mean what you are meaning.
A line contains full of whitespaces or a line contains nothing.
If you want to match a line which contains nothing then use '/^$/'.
The original question was for MySQL and SQL in general. The example below is for the new versions of MySQL. Unfortunately, a generic query that would work on any SQL server is not possible. Some servers do no support CTE, others do not have substring_index, yet others have built-in functions for splitting a string into multiple rows.
--- the answer follows ---
Recursive queries are convenient when the server does not provide built-in functionality. They can also be the bottleneck.
The following query was written and tested on MySQL version 8.0.16. It will not work on version 5.7-. The old versions do not support Common Table Expression (CTE) and thus recursive queries.
with recursive
input as (
select 1 as id, 'a,b,c' as names
union
select 2, 'b'
),
recurs as (
select id, 1 as pos, names as remain, substring_index( names, ',', 1 ) as name
from input
union all
select id, pos + 1, substring( remain, char_length( name ) + 2 ),
substring_index( substring( remain, char_length( name ) + 2 ), ',', 1 )
from recurs
where char_length( remain ) > char_length( name )
)
select id, name
from recurs
order by id, pos;
Place this in the AppServiceProvider in the boot() method
if($this->app->environment('production')) {
\URL::forceScheme('https');
}
Your code is just fine. The reason you're getting a black screen is because there's nothing on your second view controller.
Try something like:
secondViewController.view.backgroundColor = UIColor.redColor();
Now the view controller it shows should be red.
To actually do something with secondViewController
, create a subclass of UIViewController
and instead of
let secondViewController:UIViewController = UIViewController()
create an instance of your second view controller:
//If using code
let secondViewController = MyCustomViewController.alloc()
//If using storyboard, assuming you have a view controller with storyboard ID "MyCustomViewController"
let secondViewController = self.storyboard.instantiateViewControllerWithIdentifier("MyCustomViewController") as UIViewController
A full training pass over the entire dataset such that each example has been seen once. Thus, an epoch represents N/batch size training iterations, where N is the total number of examples.
A single update of a model's weights during training. An iteration consists of computing the gradients of the parameters with respect to the loss on a single batch of data.
as bonus:
The set of examples used in one iteration (that is, one gradient update) of model training.
See also batch size.
source: https://developers.google.com/machine-learning/glossary/
int var1 = int.Parse(ds.Tables[0].Rows[0][3].ToString());
int var2 = int.Parse(ds.Tables[0].Rows[0][4].ToString());
I didn't find any with cURL so I wrote a wrapper around node-libcurl and can be found at https://www.npmjs.com/package/vps-rest-client.
To make a POST is like so:
var host = 'https://api.budgetvm.com/v2/dns/record';
var key = 'some___key';
var domain_id = 'some___id';
var rest = require('vps-rest-client');
var client = rest.createClient(key, {
verbose: false
});
var post = {
domain: domain_id,
record: 'test.example.net',
type: 'A',
content: '111.111.111.111'
};
client.post(host, post).then(function(resp) {
console.info(resp);
if (resp.success === true) {
// some action
}
client.close();
}).catch((err) => console.info(err));
How about:
self.tableView.reloadRowsAtIndexPaths([NSIndexPath(rowNumber)], withRowAnimation: UITableViewRowAnimation.Top)
Follow the tutorial you listed above for setting up your key preferences in iterm2.
you can set a password to your vba code but this can be quite easily broken up.
you can also create an addin and compile it into a DLL. See here for more information. That's at least the most secure way to protect your code.
Regards,
Per issue 12987, Blundell's answer crashes (at least on my 2.3 VM). Instead, I intercept a call to console.log with a special prefix:
// intercept calls to console.log
web.setWebChromeClient(new WebChromeClient() {
public boolean onConsoleMessage(ConsoleMessage cmsg)
{
// check secret prefix
if (cmsg.message().startsWith("MAGIC"))
{
String msg = cmsg.message().substring(5); // strip off prefix
/* process HTML */
return true;
}
return false;
}
});
// inject the JavaScript on page load
web.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String address)
{
// have the page spill its guts, with a secret prefix
view.loadUrl("javascript:console.log('MAGIC'+document.getElementsByTagName('html')[0].innerHTML);");
}
});
web.loadUrl("http://www.google.com");
There are a few ways. One of the simplest is to create a my-paths.pth
file (as described here). This is just a file with the extension .pth
that you put into your system site-packages
directory. On each line of the file you put one directory name, so you can put a line in there with /path/to/the/
and it will add that directory to the path.
You could also use the PYTHONPATH environment variable, which is like the system PATH variable but contains directories that will be added to sys.path
. See the documentation.
Note that no matter what you do, sys.path
contains directories not files. You can't "add a file to sys.path
". You always add its directory and then you can import the file.
If you're passing a value, however, things are different. You can force a value to be passed by reference. This allows you to pass an integer to a method, for example, and have the method modify the integer on your behalf.
Try this:
String[] columnDetail = column.split("\t", -1);
Read the Javadoc on String.split(java.lang.String, int) for an explanation about the limit parameter of split function:
split
public String[] split(String regex, int limit)
Splits this string around matches of the given regular expression.
The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string. The substrings in the array are in the order in which they occur in this string. If the expression does not match any part of the input then the resulting array has just one element, namely this string.
The limit parameter controls the number of times the pattern is applied and therefore affects the length of the resulting array. If the limit n is greater than zero then the pattern will be applied at most n - 1 times, the array's length will be no greater than n, and the array's last entry will contain all input beyond the last matched delimiter. If n is non-positive then the pattern will be applied as many times as possible and the array can have any length. If n is zero then the pattern will be applied as many times as possible, the array can have any length, and trailing empty strings will be discarded.
The string "boo:and:foo", for example, yields the following results with these parameters:
Regex Limit Result
: 2 { "boo", "and:foo" }
: 5 { "boo", "and", "foo" }
: -2 { "boo", "and", "foo" }
o 5 { "b", "", ":and:f", "", "" }
o -2 { "b", "", ":and:f", "", "" }
o 0 { "b", "", ":and:f" }
When the last few fields (I guest that's your situation) are missing, you will get the column like this:
field1\tfield2\tfield3\t\t
If no limit is set to split(), the limit is 0, which will lead to that "trailing empty strings will be discarded". So you can just get just 3 fields, {"field1", "field2", "field3"}.
When limit is set to -1, a non-positive value, trailing empty strings will not be discarded. So you can get 5 fields with the last two being empty string, {"field1", "field2", "field3", "", ""}.
To check if a string represents a path or a file programatically, you should use API methods such as isFile(), isDirectory().
How does system understand whether there's a file or a folder?
I guess, the file and folder entries are kept in a data structure and it's managed by the file system.
You can set specific cache-headers for a whole folder in either your root web.config
:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!-- Note the use of the 'location' tag to specify which
folder this applies to-->
<location path="images">
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:15" />
</staticContent>
</system.webServer>
</location>
</configuration>
Or you can specify these in a web.config
file in the content folder:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="00:00:15" />
</staticContent>
</system.webServer>
</configuration>
I'm not aware of a built in mechanism to target specific file types.
Answers above are shown how to remove an array and here is how to pull an object from an array.
Reference: https://docs.mongodb.com/manual/reference/operator/update/pull/
db.survey.update( // select your doc in moongo
{ }, // your query, usually match by _id
{ $pull: { results: { $elemMatch: { score: 8 , item: "B" } } } }, // item(s) to match from array you want to pull/remove
{ multi: true } // set this to true if you want to remove multiple elements.
)
Trying to write a REST API from scratch is not a simple task. There are many issues to factor and you will need to write a lot of code to process requests and data coming from the caller, authentication, retrieval of data and sending back responses.
Your best bet is to use a framework that already has this functionality ready and tested for you.
Some suggestions are:
Phalcon - REST API building - Easy to use all in one framework with huge performance
Apigility - A one size fits all API handling framework by Zend Technologies
Laravel API Building Tutorial
and many more. Simple searches on Bitbucket/Github will give you a lot of resources to start with.
Also, you have to change your approach when using Map myVariable as described in the documentation to eleminate nulls:
From documentation:
com.fasterxml.jackson.annotation.JsonInclude
@JacksonAnnotation
@Target(value={ANNOTATION_TYPE, FIELD, METHOD, PARAMETER, TYPE})
@Retention(value=RUNTIME)
Annotation used to indicate when value of the annotated property (when used for a field, method or constructor parameter), or all properties of the annotated class, is to be serialized. Without annotation property values are always included, but by using this annotation one can specify simple exclusion rules to reduce amount of properties to write out.
*Note that the main inclusion criteria (one annotated with value) is checked on Java object level, for the annotated type, and NOT on JSON output -- so even with Include.NON_NULL it is possible that JSON null values are output, if object reference in question is not `null`. An example is java.util.concurrent.atomic.AtomicReference instance constructed to reference null value: such a value would be serialized as JSON null, and not filtered out.
To base inclusion on value of contained value(s), you will typically also need to specify content() annotation; for example, specifying only value as Include.NON_EMPTY for a {link java.util.Map} would exclude Maps with no values, but would include Maps with `null` values. To exclude Map with only `null` value, you would use both annotations like so:
public class Bean {
@JsonInclude(value=Include.NON_EMPTY, content=Include.NON_NULL)
public Map<String,String> entries;
}
Similarly you could Maps that only contain "empty" elements, or "non-default" values (see Include.NON_EMPTY and Include.NON_DEFAULT for more details).
In addition to `Map`s, `content` concept is also supported for referential types (like java.util.concurrent.atomic.AtomicReference). Note that `content` is NOT currently (as of Jackson 2.9) supported for arrays or java.util.Collections, but supported may be added in future versions.
Since:
2.0
class ArrayComparator implements Comparator<Comparable[]> {
private final int columnToSort;
private final boolean ascending;
public ArrayComparator(int columnToSort, boolean ascending) {
this.columnToSort = columnToSort;
this.ascending = ascending;
}
public int compare(Comparable[] c1, Comparable[] c2) {
int cmp = c1[columnToSort].compareTo(c2[columnToSort]);
return ascending ? cmp : -cmp;
}
}
This way you can handle any type of data in those arrays (as long as they're Comparable) and you can sort any column in ascending or descending order.
String[][] data = getData();
Arrays.sort(data, new ArrayComparator(0, true));
PS: make sure you check for ArrayIndexOutOfBounds
and others.
EDIT: The above solution would only be helpful if you are able to actually store a java.util.Date
in the first column or if your date format allows you to use plain String comparison for those values. Otherwise, you need to convert that String to a Date, and you can achieve that using a callback interface (as a general solution). Here's an enhanced version:
class ArrayComparator implements Comparator<Object[]> {
private static Converter DEFAULT_CONVERTER = new Converter() {
@Override
public Comparable convert(Object o) {
// simply assume the object is Comparable
return (Comparable) o;
}
};
private final int columnToSort;
private final boolean ascending;
private final Converter converter;
public ArrayComparator(int columnToSort, boolean ascending) {
this(columnToSort, ascending, DEFAULT_CONVERTER);
}
public ArrayComparator(int columnToSort, boolean ascending, Converter converter) {
this.columnToSort = columnToSort;
this.ascending = ascending;
this.converter = converter;
}
public int compare(Object[] o1, Object[] o2) {
Comparable c1 = converter.convert(o1[columnToSort]);
Comparable c2 = converter.convert(o2[columnToSort]);
int cmp = c1.compareTo(c2);
return ascending ? cmp : -cmp;
}
}
interface Converter {
Comparable convert(Object o);
}
class DateConverter implements Converter {
private static final DateFormat df = new SimpleDateFormat("yyyy.MM.dd hh:mm");
@Override
public Comparable convert(Object o) {
try {
return df.parse(o.toString());
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
}
}
And at this point, you can sort on your first column with:
Arrays.sort(data, new ArrayComparator(0, true, new DateConverter());
I skipped the checks for nulls and other error handling issues.
I agree this is starting to look like a framework already. :)
Last (hopefully) edit: I only now realize that your date format allows you to use plain String comparison. If that is the case, you don't need the "enhanced version".
You can configure property inclusion, and numerous other settings, via application.properties
:
spring.jackson.default-property-inclusion=non_null
There's a table in the documentation that lists all of the properties that can be used.
If you want more control, you can also customize Spring Boot's configuration programatically using a Jackson2ObjectMapperBuilderCustomizer
bean, as described in the documentation:
The context’s
Jackson2ObjectMapperBuilder
can be customized by one or moreJackson2ObjectMapperBuilderCustomizer
beans. Such customizer beans can be ordered (Boot’s own customizer has an order of 0), letting additional customization be applied both before and after Boot’s customization.
Lastly, if you don't want any of Boot's configuration and want to take complete control over how the ObjectMapper
is configured, declare your own Jackson2ObjectMapperBuilder
bean:
@Bean
Jackson2ObjectMapperBuilder objectMapperBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
// Configure the builder to suit your needs
return builder;
}
CHARINDEX()
searches for a substring within a larger string, and returns the position of the match, or 0 if no match is found
if CHARINDEX('ME',@mainString) > 0
begin
--do something
end
Edit or from daniels answer, if you're wanting to find a word (and not subcomponents of words), your CHARINDEX
call would look like:
CHARINDEX(' ME ',' ' + REPLACE(REPLACE(@mainString,',',' '),'.',' ') + ' ')
(Add more recursive REPLACE() calls for any other punctuation that may occur)
For a script working with Python 2 (tested versions 2.7.3 and 2.6.8) and Python 3 (3.2.3 and 3.3.2+) try:
#! /usr/bin/env python
try:
# For Python 3.0 and later
from urllib.request import urlopen
except ImportError:
# Fall back to Python 2's urllib2
from urllib2 import urlopen
html = urlopen("http://www.google.com/")
print(html.read())
Try to replace your initialization code with:
ProcessStartInfo info
= new ProcessStartInfo(@"C:\Program Files\Internet Explorer\iexplore.exe");
Using non full filepath on Process.Start
only works if the file is found in System32 folder.
printf
outputs to the standard output stream (stdout
)
fprintf
goes to a file handle (FILE*
)
sprintf
goes to a buffer you allocated. (char*
)
You can definitely use the section tag as a container. It is there to group content in a more semantically significant way than with a div or as the html5 spec says:
The section element represents a generic section of a document or application. A section, in this context, is a thematic grouping of content, typically with a heading. http://www.w3.org/TR/html5/sections.html#the-section-element
Note for ES2+
Starting with ES 1.5.3 the delete-by-query API is deprecated, and is completely removed since ES 2.0
Instead of the API, the Delete By Query is now a plugin.
In order to use the Delete By Query plugin you must install the plugin on all nodes of the cluster:
sudo bin/plugin install delete-by-query
All of the nodes must be restarted after the installation.
The usage of the plugin is the same as the old API. You don't need to change anything in your queries - this plugin will just make them work.
*For complete information regarding WHY the API was removed you can read more here.
Swift 3.0 Version
if you want to present new controller.
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "controllerIdentifier") as! YourController
self.present(viewController, animated: true, completion: nil)
and if you want to push to another controller (if it is in navigation)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let viewController = storyboard.instantiateViewController(withIdentifier: "controllerIdentifier") as! YourController
self.navigationController?.pushViewController(viewController, animated: true)
if you build an MVC project, its included by default. otherwise, what Nick said.
I found this function on a blog
ggplotRegression <- function (fit) {
`require(ggplot2)
ggplot(fit$model, aes_string(x = names(fit$model)[2], y = names(fit$model)[1])) +
geom_point() +
stat_smooth(method = "lm", col = "red") +
labs(title = paste("Adj R2 = ",signif(summary(fit)$adj.r.squared, 5),
"Intercept =",signif(fit$coef[[1]],5 ),
" Slope =",signif(fit$coef[[2]], 5),
" P =",signif(summary(fit)$coef[2,4], 5)))
}`
once you loaded the function you could simply
ggplotRegression(fit)
you can also go for ggplotregression( y ~ x + z + Q, data)
Hope this helps.
I know so many answers are already here, but no one answered it in a simple way.
Regarding fs-exra official documentation, you can do it very easy.
const fs = require('fs-extra')
// Copy file
fs.copySync('/tmp/myfile', '/tmp/mynewfile')
// Copy directory, even if it has subdirectories or files
fs.copySync('/tmp/mydir', '/tmp/mynewdir')
you can use
style="display:none"
Ex:
<asp:TextBox ID="txbProv" runat="server" style="display:none"></asp:TextBox>
Here is a special case if you want the first entry (or close to it) in an OrderedDict, without creating a list. (This has been updated to Python 3):
>>> from collections import OrderedDict
>>>
>>> d = OrderedDict()
>>> d["foo"] = "one"
>>> d["bar"] = "two"
>>> d["baz"] = "three"
>>> next(iter(d.items()))
('foo', 'one')
>>> next(iter(d.values()))
'one'
(The first time you say "next()", it really means "first.")
In my informal test, next(iter(d.items()))
with a small OrderedDict is only a tiny bit faster than items()[0]
. With an OrderedDict of 10,000 entries, next(iter(d.items()))
was about 200 times faster than items()[0]
.
BUT if you save the items() list once and then use the list a lot, that could be faster. Or if you repeatedly { create an items() iterator and step through it to to the position you want }, that could be slower.
On .Net Core 3.1 just follow Microsoft Doc that it is pretty simple: kestrel-aspnetcore-3.1
To summarize:
Add the below ConfigureServices section to CreateDefaultBuilder on Program.cs
:
// using Microsoft.Extensions.DependencyInjection;
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((context, services) =>
{
services.Configure<KestrelServerOptions>(
context.Configuration.GetSection("Kestrel"));
})
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
Add the below basic config to appsettings.json
file (more config options on Microsoft article):
"Kestrel": {
"EndPoints": {
"Http": {
"Url": "http://0.0.0.0:5002"
}
}
}
Open CMD or Console on your project Publish/Debug/Release binaries folder and run:
dotnet YourProject.dll
Enjoy exploring your site/api at your http://localhost:5002
If you add your site to "Local Intranet" in
Chrome > Options > Under the Hood > Change Proxy Settings > Security (tab) > Local Intranet/Sites > Advanced.
Add you site URL here and it will work.
Update for New Version of Chrome
Chrome > Settings > Advanced > System > Open Proxy Settings > Security (tab) > Local Intranet > Sites (button) > Advanced.
Like a lot of functions, this one can be used in many different ways to solve many different problems, I think of it as yet another tool in our toolbelts.
So far, the discussion has focused heavily on simply hiding an ID, but that is only one value, why not use it for lots of values! That is what I am doing, I use it to load up the values in a class only one view at a time, because html.beginform creates a new object and if your model object for that view already had some values passed to it, those values will be lost unless you provide a reference to those values in the beginform.
To see a great motivation for the html.hiddenfor, I recommend you see Passing data from a View to a Controller in .NET MVC - "@model" not highlighting
SELECT * FROM table ORDER BY id DESC LIMIT 50
save resources make one query, there is no need to make nested queries
MySQL 8.0.23 onwards now support CIDR notation also.
So, basically:
-- CIDR Notation
GRANT ... TO 'user'@'192.168.1.0/24' IDENTIFIED BY ...
-- Netmask Notation
GRANT ... TO 'user'@'192.168.1.0/255.255.255.0' IDENTIFIED BY ...
INSERT
syntax cannot have WHERE
clause. The only time you will find INSERT
has WHERE
clause is when you are using INSERT INTO...SELECT
statement.
The first syntax is already correct.
There is no way to declare a global variable in Transact-SQL. However, if all you want your variables for is to be accessible across batches of a single script, you can use the SQLCMD tool or the SQLCMD mode of SSMS and define that tool/mode-specific variables like this:
:setvar myvar 10
and then use them like this:
$(myvar)
To use SSMS's SQLCMD mode:
Using sqldf and standard sql to get the maximum values grouped by another variable
https://cran.r-project.org/web/packages/sqldf/sqldf.pdf
library(sqldf)
sqldf("select max(Value),Gene from df1 group by Gene")
or
Using the excellent Hmisc package for a groupby application of function (max) https://www.rdocumentation.org/packages/Hmisc/versions/4.0-3/topics/summarize
library(Hmisc)
summarize(df1$Value,df1$Gene,max)
If you are using fragments, you need to call hideKeyboard every time in onResume and onCreate if you want to hide the keyboard.
@Override
public void onResume() {
super.onResume();
Log.d(TAG, "SectionMyFragment onResume");
hideKeyboard();
}
private void hideKeyboard() {
if (getActivity() != null) {
InputMethodManager inputMethodManager = (InputMethodManager)
getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
if (inputMethodManager != null) {
if (getActivity().getCurrentFocus() != null) {
Log.d(TAG, "hideSoftInputFromWindow 1");
inputMethodManager.hideSoftInputFromWindow((getActivity().getCurrentFocus()).getWindowToken(), 0);
}
}
}
}
I re-installed node through this link and it fixed it.
I think the issue was that I somehow got node to be in my /usr/bin
instead of /usr/local/bin
.
class CallByName():
def method1(self):
pass
def method2(self):
pass
def method3(self):
pass
def get_method(self, method_name):
method = getattr(self, method_name)
return method()
callbyname = CallByName()
method1 = callbyname.get_method(method_name)
```
Oracle 9i+ (maybe 8i too) has FIRST/LAST aggregate functions, that make computation over groups of rows according to row's rank in group. Assuming all rows as one group, you'll get what you want without subqueries:
SELECT
max(MEMBSHIP_ID)
keep (
dense_rank first
order by paym_date desc NULLS LAST
) as LATEST_MEMBER_ID
FROM user_payment
WHERE user_id=1
Using Node.removeChild() does the job for you, simply use something like this:
var leftSection = document.getElementById('left-section');
leftSection.parentNode.removeChild(leftSection);
In DOM 4, the remove method applied, but there is a poor browser support according to W3C:
The method node.remove() is implemented in the DOM 4 specification. But because of poor browser support, you should not use it.
But you can use remove method if you using jQuery...
$('#left-section').remove(); //using remove method in jQuery
Also in new frameworks like you can use conditions to remove an element, for example *ngIf
in Angular and in React, rendering different views, depends on the conditions...
The :not
pseudo-class is not supported by IE. I'd got for something like this instead:
.registration_form_right input[type="text"],
.registration_form_right input[type="password"],
.registration_form_right input[type="submit"],
.registration_form_right input[type="button"] {
...
}
Some duplication there, but it's a small price to pay for higher compatibility.
I use PHP-ExcelReader to read xls files, and works great.
I have faced this issue when I introduced additional supporting libraries in my project IntelliJ IDEA
So for me "File" -> "Invalidate Caches...", and select "Invalidate and Restart" option to fix this.
Look at HKLM\SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5\
. One of these must be true:
Version
value in that key should be 3.5.30729.01SP
value in the same key should be 1In C# (taken from the first comment), you could do something along these lines:
const string name = @"SOFTWARE\Microsoft\NET Framework Setup\NDP\v3.5";
RegistryKey subKey = Registry.LocalMachine.OpenSubKey(name);
var version = subKey.GetValue("Version").ToString();
var servicePack = subKey.GetValue("SP").ToString();
This is what I did. Seems to work in forcing a new line, but I'm not an html/css guru by any measure.
<p> </p>
@Ali Shakiba your code needs some modification. Error part:
for (int i = 0; i < myArray.length; i++) {
myStatement.setString(i, myArray[i][1]);
myStatement.setString(i, myArray[i][2]);
}
Updated code:
String myArray[][] = {
{"1-1", "1-2"},
{"2-1", "2-2"},
{"3-1", "3-2"}
};
StringBuffer mySql = new StringBuffer("insert into MyTable (col1, col2) values (?, ?)");
for (int i = 0; i < myArray.length - 1; i++) {
mySql.append(", (?, ?)");
}
mysql.append(";"); //also add the terminator at the end of sql statement
myStatement = myConnection.prepareStatement(mySql.toString());
for (int i = 0; i < myArray.length; i++) {
myStatement.setString((2 * i) + 1, myArray[i][1]);
myStatement.setString((2 * i) + 2, myArray[i][2]);
}
myStatement.executeUpdate();
Heres my way of doing it, using square method. upside is it works with different values, but you need 2 spans.
.circle {_x000D_
display: inline-block;_x000D_
border: 1px solid black;_x000D_
border-radius: 50%;_x000D_
position: relative;_x000D_
padding: 5px;_x000D_
}_x000D_
.circle::after {_x000D_
content: '';_x000D_
display: block;_x000D_
padding-bottom: 100%;_x000D_
height: 0;_x000D_
opacity: 0;_x000D_
}_x000D_
.num {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
transform: translateY(-50%);_x000D_
}_x000D_
.width_holder {_x000D_
display: block;_x000D_
height: 0;_x000D_
overflow: hidden;_x000D_
}
_x000D_
<div class="circle">_x000D_
<span class="width_holder">1</span>_x000D_
<span class="num">1</span>_x000D_
</div>_x000D_
<div class="circle">_x000D_
<span class="width_holder">11</span>_x000D_
<span class="num">11</span>_x000D_
</div>_x000D_
<div class="circle">_x000D_
<span class="width_holder">11111</span>_x000D_
<span class="num">11111</span>_x000D_
</div>_x000D_
<div class="circle">_x000D_
<span class="width_holder">11111111</span>_x000D_
<span class="num">11111111</span>_x000D_
</div>
_x000D_
Try this, using mkdir:
if (!file_exists('path/to/directory')) {
mkdir('path/to/directory', 0777, true);
}
Note that 0777
is already the default mode for directories and may still be modified by the current umask.
Test Data
DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)
Query
SELECT ID
,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
FROM @Table1
WHERE ID = t.ID
FOR XML PATH(''), TYPE)
.value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID
Result Set
+--------------------------+
¦ ID ¦ List_Output ¦
¦----+---------------------¦
¦ 1 ¦ 100, 200, 300, 400 ¦
+--------------------------+
SQL Server 2017 and Later Versions
If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:
DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);
SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;
Result Set
+--------------------------+
¦ ID ¦ List_Output ¦
¦----+---------------------¦
¦ 1 ¦ 100, 200, 300, 400 ¦
+--------------------------+
The CSS content property along with ::after
and ::before
pseudo-elements have been introduced for this.
.item:hover a p.new-label:after{
content: 'ADD';
}
The best practice is to reference the WSDL and use it like a web service reference. It's easier and works better, but if you don't have the WSDL, the XSD definitions are a good piece of code.
If the task you want to pass parameters to is of type JavaExec
and you are using Gradle 5, for example the application plugin's run
task, then you can pass your parameters through the --args=...
command line option. For example gradle run --args="foo --bar=true"
.
Otherwise there is no convenient builtin way to do this, but there are 3 workarounds.
If the possible values are few and are known in advance, you can programmatically create a task for each of them:
void createTask(String platform) {
String taskName = "myTask_" + platform;
task (taskName) {
... do what you want
}
}
String[] platforms = ["macosx", "linux32", "linux64"];
for(String platform : platforms) {
createTask(platform);
}
You would then call your tasks the following way:
./gradlew myTask_macosx
A convenient hack is to pass the arguments through standard input, and have your task read from it:
./gradlew myTask <<<"arg1 arg2 arg\ in\ several\ parts"
with code below:
String[] splitIntoTokens(String commandLine) {
String regex = "(([\"']).*?\\2|(?:[^\\\\ ]+\\\\\\s+)+[^\\\\ ]+|\\S+)";
Matcher matcher = Pattern.compile(regex).matcher(commandLine);
ArrayList<String> result = new ArrayList<>();
while (matcher.find()) {
result.add(matcher.group());
}
return result.toArray();
}
task taskName, {
doFirst {
String typed = new Scanner(System.in).nextLine();
String[] parsed = splitIntoTokens(typed);
println ("Arguments received: " + parsed.join(" "))
... do what you want
}
}
You will also need to add the following lines at the top of your build script:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Scanner;
The last option is to pass a -P
parameter to Gradle:
./gradlew myTask -PmyArg=hello
You can then access it as myArg
in your build script:
task myTask {
doFirst {
println myArg
... do what you want
}
}
Credit to @789 for his answer on splitting arguments into tokens
You'll definitely want to check out this positioning article from 'A List Apart'. Helped demystify CSS positioning (which seemed insane to me, prior to this article).
Iterate over the Array. First initialize the maximum value to the first element of the array and then for each element optimize it if the element under consideration is greater.
Dim myStringArray() As String
*code*
redim myStringArray(size_of_your_array)
Then you can do something static like this:
myStringArray = { item_1, item_2, ... }
Or something iterative like this:
Dim x
For x = 0 To size_of_your_array
myStringArray(x) = data_source(x).Name
Next x
I'd go with the default arguments, especially since C++ doesn't let you chain constructors (so you end up having to duplicate the initialiser list, and possibly more, for each overload).
That said, there are some gotchas with default arguments, including the fact that constants may be inlined (and thereby become part of your class' binary interface). Another to watch out for is that adding default arguments can turn an explicit multi-argument constructor into an implicit one-argument constructor:
class Vehicle {
public:
Vehicle(int wheels, std::string name = "Mini");
};
Vehicle x = 5; // this compiles just fine... did you really want it to?
It's relative to default browser font-size unless you override it with a value in pt or px.
same issue on centos server 7, but this solved my problem:
node --max-old-space-size=X node_modules/@angular/cli/bin/ng build --prod
Where X = (2048 or 4096 or 8192 o..)
is the value of memory
Try / \([\s\S]*?\)/g
Where
(space) matches the character
(space) literally
\(
matches the character (
literally
[\s\S]
matches any character (\s
matches any whitespace character and \S
matches any non-whitespace character)
*?
matches between zero and unlimited times
\)
matches the character )
literally
g
matches globally
Code Example:
var str = "Hello, this is Mike (example)";
str = str.replace(/ \([\s\S]*?\)/g, '');
console.log(str);
_x000D_
.as-console-wrapper {top: 0}
_x000D_
You have to retrieve it from the HOST
header.
var host = req.get('host');
It is optional with HTTP 1.0, but required by 1.1. And, the app can always impose a requirement of its own.
If this is for supporting cross-origin requests, you would instead use the Origin
header.
var origin = req.get('origin');
Note that some cross-origin requests require validation through a "preflight" request:
req.options('/route', function (req, res) {
var origin = req.get('origin');
// ...
});
If you're looking for the client's IP, you can retrieve that with:
var userIP = req.socket.remoteAddress;
Note that, if your server is behind a proxy, this will likely give you the proxy's IP. Whether you can get the user's IP depends on what info the proxy passes along. But, it'll typically be in the headers as well.
although eval is not recommended, this works:
<!DOCTYPE html>
<html>
<body>
<h2>Convert a string written in JSON format, into a JavaScript function.</h2>
<p id="demo"></p>
<script>
function test(val){return val + " it's OK;}
var someVar = "yup";
var myObj = { "func": "test(someVar);" };
document.getElementById("demo").innerHTML = eval(myObj.func);
</script>
</body>
</html>
What fixed this for me was to move the .pem file within the apps directory. Soo say fooapp is the name of my app. I placed it directly in there.
You could make use of expect (man expect comes with examples).
This code will return "browser" and "browserVersion"
Works on 95% of 80+ browsers
var geckobrowsers;
var browser = "";
var browserVersion = 0;
var agent = navigator.userAgent + " ";
if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "5.0" && agent.indexOf("like Gecko") != -1){
geckobrowsers = agent.substring(agent.indexOf("like Gecko")+10).substring(agent.substring(agent.indexOf("like Gecko")+10).indexOf(") ")+2).replace("LG Browser", "LGBrowser").replace("360SE", "360SE/");
for(i = 0; i < 1; i++){
geckobrowsers = geckobrowsers.replace(geckobrowsers.substring(geckobrowsers.indexOf("("), geckobrowsers.indexOf(")")+1), "");
}
geckobrowsers = geckobrowsers.split(" ");
for(i = 0; i < geckobrowsers.length; i++){
if(geckobrowsers[i].indexOf("/") == -1)geckobrowsers[i] = "Chrome";
if(geckobrowsers[i].indexOf("/") != -1)geckobrowsers[i] = geckobrowsers[i].substring(0, geckobrowsers[i].indexOf("/"));
}
if(geckobrowsers.length < 4){
browser = geckobrowsers[0];
} else {
for(i = 0; i < geckobrowsers.length; i++){
if(geckobrowsers[i].indexOf("Chrome") == -1 && geckobrowsers[i].indexOf("Safari") == -1 && geckobrowsers[i].indexOf("Mobile") == -1 && geckobrowsers[i].indexOf("Version") == -1)browser = geckobrowsers[i];
}
}
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "5.0" && agent.indexOf("Gecko/") != -1){
browser = agent.substring(agent.substring(agent.indexOf("Gecko/")+6).indexOf(" ") + agent.indexOf("Gecko/")+6).substring(0, agent.substring(agent.substring(agent.indexOf("Gecko/")+6).indexOf(" ") + agent.indexOf("Gecko/")+6).indexOf("/"));
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "5.0" && agent.indexOf("Clecko/") != -1){
browser = agent.substring(agent.substring(agent.indexOf("Clecko/")+7).indexOf(" ") + agent.indexOf("Clecko/")+7).substring(0, agent.substring(agent.substring(agent.indexOf("Clecko/")+7).indexOf(" ") + agent.indexOf("Clecko/")+7).indexOf("/"));
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "5.0"){
browser = agent.substring(agent.indexOf("(")+1, agent.indexOf(";"));
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "4.0" && agent.indexOf(")")+1 == agent.length-1){
browser = agent.substring(agent.indexOf("(")+1, agent.indexOf(")")).split("; ")[agent.substring(agent.indexOf("(")+1, agent.indexOf(")")).split("; ").length-1];
} else if(agent.substring(agent.indexOf("Mozilla/")+8, agent.indexOf(" ")) == "4.0" && agent.indexOf(")")+1 != agent.length-1){
if(agent.substring(agent.indexOf(") ")+2).indexOf("/") != -1)browser = agent.substring(agent.indexOf(") ")+2, agent.indexOf(") ")+2+agent.substring(agent.indexOf(") ")+2).indexOf("/"));
if(agent.substring(agent.indexOf(") ")+2).indexOf("/") == -1)browser = agent.substring(agent.indexOf(") ")+2, agent.indexOf(") ")+2+agent.substring(agent.indexOf(") ")+2).indexOf(" "));
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else if(agent.substring(0, 6) == "Opera/"){
browser = "Opera";
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
if(agent.substring(agent.indexOf("(")+1).indexOf(";") != -1)os = agent.substring(agent.indexOf("(")+1, agent.indexOf("(")+1+agent.substring(agent.indexOf("(")+1).indexOf(";"));
if(agent.substring(agent.indexOf("(")+1).indexOf(";") == -1)os = agent.substring(agent.indexOf("(")+1, agent.indexOf("(")+1+agent.substring(agent.indexOf("(")+1).indexOf(")"));
} else if(agent.substring(0, agent.indexOf("/")) != "Mozilla" && agent.substring(0, agent.indexOf("/")) != "Opera"){
browser = agent.substring(0, agent.indexOf("/"));
browserVersion = agent.substring(agent.indexOf(browser)+browser.length+1, agent.indexOf(browser)+browser.length+1+agent.substring(agent.indexOf(browser)+browser.length+1).indexOf(" "));
} else {
browser = agent;
}
alert(browser + " v" + browserVersion);
On production servers I rename vendor
to vendor-<datetime>
, and during deployment will have two vendor dirs.
A HTTP cookie causes my system to choose the new vendor autoload.php
, and after testing I do a fully atomic/instant switch between them to disable the old vendor dir for all future requests, then I delete the previous dir a few days later.
This avoids any problem caused by filesystem caches I'm using in apache/php, and also allows any active PHP code to continue using the previous vendor dir.
Despite other answers recommending against it, I personally run composer install
on the server, since this is faster than rsync from my staging area (a VM on my laptop).
I use --no-dev --no-scripts --optimize-autoloader
. You should read the docs for each one to check if this is appropriate on your environment.
mysqli in PHP 5 is an object with some good functions that will allow you to speed up the insertion time for the answer above:
$mysqli->autocommit(FALSE);
$mysqli->multi_query($sqlCombined);
$mysqli->autocommit(TRUE);
Turning off autocommit when inserting many rows greatly speeds up insertion, so turn it off, then execute as mentioned above, or just make a string (sqlCombined) which is many insert statements separated by semi-colons and multi-query will handle them fine.
Linked list does guarantee sequential order.
Don't use linkedList.get(i), especially inside a sequential loop since it defeats the purpose of having a linked list and will be inefficient code.
Use ListIterator
ListIterator<Object> iterator = myLinkedList.listIterator();
while( iterator.hasNext()) {
System.out.println(iterator.next());
}
What you are looking for are all objects that have either a=false
or x=5
. In Django, |
serves as OR
operator between querysets:
results = Model.objects.filter(a=false)|Model.objects.filter(x=5)
function my_simple_crypt( $string, $action = 'e' ) {
// you may change these values to your own
$secret_key = 'my_simple_secret_key';
$secret_iv = 'my_simple_secret_iv';
$output = false;
$encrypt_method = "AES-256-CBC";
$key = hash( 'sha256', $secret_key );
$iv = substr( hash( 'sha256', $secret_iv ), 0, 16 );
if( $action == 'e' ) {
$output = base64_encode( openssl_encrypt( $string, $encrypt_method, $key, 0, $iv ) );
}
else if( $action == 'd' ){
$output = openssl_decrypt( base64_decode( $string ), $encrypt_method, $key, 0, $iv );
}
return $output;
}
we have to enable TCP/IP property in sql server configuration manager
You can use fall-through:
switch (pageid)
{
case "listing-page":
case "home-page":
alert("hello");
break;
case "details-page":
alert("goodbye");
break;
}
Why not something like
//array1: array of elements to be sorted
//array2: array with the indexes
array1 = array2.map((object, i) => array1[object]);
The map function may not be available on all versions of Javascript
You should always return the same type on all case condition:
In the first one you have an character and on the else you have an int.
You can use:
Select convert(varchar(11),isnull(totalamount,0))
or if you want with your solution:
Case when total_amount = 0 then '0'
else convert(varchar(11),isnull(total_amount, 0))
end as total_amount
I don't know if there's a 'proper' way to do it, but your snippet is on the right track: just add import foo
to foo.py, do inspect.getmembers(foo)
, and it should work fine.
import matplotlib.pyplot as plt
You can also run once in your code
plt.gray()
This will show the images in grayscale as default
im = array(Image.open('I_am_batman.jpg').convert('L'))
plt.imshow(im)
plt.show()
if you have this error :
configure: error: Either a previously installed pkg-config or "glib-2.0 >= 2.16" could not be found. Please set GLIB_CFLAGS and GLIB_LIBS to the correct values or pass --with-internal-glib to configure to use the bundled copy.
Instead of do this command :
$ ./configure && make install
Do that :
./configure --with-internal-glib && make install
Speaking as a mere mortal, I would stick with $str[0]
. As far as I'm concerned, it's quicker to grasp the meaning of $str[0]
at a glance than substr($str, 0, 1)
. This probably boils down to a matter of preference.
As far as performance goes, well, profile profile profile. :) Or you could peer into the PHP source code...
Since Express.js 3x the response object has a json() method which sets all the headers correctly for you and returns the response in JSON format.
Example:
res.json({"foo": "bar"});
For Kotlin and bindings the code is:
binding.spinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener{
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
}
}
There is a timeit
module which can be used to time the execution times of Python code.
It has detailed documentation and examples in Python documentation, 26.6. timeit — Measure execution time of small code snippets.
BufferedReader br = null;
try {
String fpath = Environment.getExternalStorageDirectory() + <your file name>;
try {
br = new BufferedReader(new FileReader(fpath));
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
String line = "";
while ((line = br.readLine()) != null) {
//Do something here
}
Check and uncheck the USB Debugging option in the device. If that doesn't work unplug and plug in the USB a couple of times.
At some point, the device should show a message box to ask you to authorize the computer. Click yes and then the device will be authorized.
if the name of node is for example : abcd then below query will work :
MATCH (n:abcd)
DETACH DELETE n
This will only delete the node with label "abcd" and all its relation-ships.
The syntax for using an alias in an update statement on SQL Server is as follows:
UPDATE Q
SET Q.TITLE = 'TEST'
FROM HOLD_TABLE Q
WHERE Q.ID = 101;
The alias should not be necessary here though.
You need to add binding in your sql output in order to found it readable. You can use the following code to print raw sql queries:
$users = User::where('status', 1);
$users_query = str_replace(array('?'), array('\'%s\''), $users->toSql());
$users_query = vsprintf($users_query, $users->getBindings());
dump($users_query);
$all_users = $users->get();
UILabel *textLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
[textLabel sizeToFit];
textLabel.numberOfLines = 0;
textLabel.text = @"Your String...";
Nine years later. If you know your time zone. I like the T
between date and time. And if you don't want microseconds.
Python <= 3.8
pip3 install pytz # needed!
python3
>>> import datetime
>>> import pytz
>>> datetime.datetime.now(pytz.timezone('Europe/Berlin')).isoformat('T', 'seconds')
'2020-11-09T18:23:28+01:00'
Tested on Ubuntu 18.04 and Python 3.6.9.
Python >= 3.9
pip3 install tzdata # only on Windows needed!
py -3
>>> import datetime
>>> import zoneinfo
>>> datetime.datetime.now(zoneinfo.ZoneInfo('Europe/Berlin')).isoformat('T', 'seconds')
'2020-11-09T18:39:36+01:00'
Tested on Windows 10 and Python 3.9.0.
EDIT: A more generic way of doing this that doesn't rely on the layout type (other than that it is a layout type which supports margins):
public static void setMargins (View v, int l, int t, int r, int b) {
if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
p.setMargins(l, t, r, b);
v.requestLayout();
}
}
You should check the docs for TextView. Basically, you'll want to get the TextView's LayoutParams object, and modify the margins, then set it back to the TextView. Assuming it's in a LinearLayout, try something like this:
TextView tv = (TextView)findViewById(R.id.my_text_view);
LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)tv.getLayoutParams();
params.setMargins(0, 0, 10, 0); //substitute parameters for left, top, right, bottom
tv.setLayoutParams(params);
I can't test it right now, so my casting may be off by a bit, but the LayoutParams are what need to be modified to change the margin.
Don't forget that if your TextView is inside, for example, a RelativeLayout, one should use RelativeLayout.LayoutParams instead of LinearLayout.LayoutParams
im use this code to and suggest you:
1) sudo sed -i -e 's|disco|eoan|g' /etc/apt/sources.list
2) sudo apt update
Based on what @J. Calleja said, you have two choices
If you want to random access the element of Mat, just simply use
Mat.at<data_Type>(row_num, col_num) = value;
If you want to continuous access, OpenCV provides Mat iterator compatible with STL iterator
and it's more C++
style
MatIterator_<double> it, end;
for( it = I.begin<double>(), end = I.end<double>(); it != end; ++it)
{
//do something here
}
or
for(int row = 0; row < mat.rows; ++row) {
float* p = mat.ptr(row); //pointer p points to the first place of each row
for(int col = 0; col < mat.cols; ++col) {
*p++; // operation here
}
}
If you have any difficulty to understand how Method 2 works, I borrow the picture from a blog post in the article Dynamic Two-dimensioned Arrays in C, which is much more intuitive and comprehensible.
See the picture below.
If you are using the following Windows versions or later: Windows Server 2012, Windows Server 2012 R2, or Windows 8.1 then MakeCert is now deprecated, and Microsoft recommends using the PowerShell Cmdlet New-SelfSignedCertificate.
If you're using an older version such as Windows 7, you'll need to stick with MakeCert or another solution. Some people suggest the Public Key Infrastructure Powershell (PSPKI) Module.
While you can create a self-signed code-signing certificate (SPC - Software Publisher Certificate) in one go, I prefer to do the following:
makecert -r -pe -n "CN=My CA" -ss CA -sr CurrentUser ^
-a sha256 -cy authority -sky signature -sv MyCA.pvk MyCA.cer
(^ = allow batch command-line to wrap line)
This creates a self-signed (-r) certificate, with an exportable private key (-pe). It's named "My CA", and should be put in the CA store for the current user. We're using the SHA-256 algorithm. The key is meant for signing (-sky).
The private key should be stored in the MyCA.pvk file, and the certificate in the MyCA.cer file.
Because there's no point in having a CA certificate if you don't trust it, you'll need to import it into the Windows certificate store. You can use the Certificates MMC snapin, but from the command line:
certutil -user -addstore Root MyCA.cer
makecert -pe -n "CN=My SPC" -a sha256 -cy end ^
-sky signature ^
-ic MyCA.cer -iv MyCA.pvk ^
-sv MySPC.pvk MySPC.cer
It is pretty much the same as above, but we're providing an issuer key and certificate (the -ic and -iv switches).
We'll also want to convert the certificate and key into a PFX file:
pvk2pfx -pvk MySPC.pvk -spc MySPC.cer -pfx MySPC.pfx
If you want to protect the PFX file, add the -po switch, otherwise PVK2PFX creates a PFX file with no passphrase.
signtool sign /v /f MySPC.pfx ^
/t http://timestamp.url MyExecutable.exe
(See why timestamps may matter)
If you import the PFX file into the certificate store (you can use PVKIMPRT or the MMC snapin), you can sign code as follows:
signtool sign /v /n "Me" /s SPC ^
/t http://timestamp.url MyExecutable.exe
Some possible timestamp URLs for signtool /t
are:
http://timestamp.verisign.com/scripts/timstamp.dll
http://timestamp.globalsign.com/scripts/timstamp.dll
http://timestamp.comodoca.com/authenticode
For those who are not .NET developers, you will need a copy of the Windows SDK and .NET framework. A current link is available here: SDK & .NET (which installs makecert in C:\Program Files\Microsoft SDKs\Windows\v7.1
). Your mileage may vary.
MakeCert is available from the Visual Studio Command Prompt. Visual Studio 2015 does have it, and it can be launched from the Start Menu in Windows 7 under "Developer Command Prompt for VS 2015" or "VS2015 x64 Native Tools Command Prompt" (probably all of them in the same folder).
Like this?
public static void Test()
{
using (var image = Image.FromFile(@"c:\logo.png"))
using (var newImage = ScaleImage(image, 300, 400))
{
newImage.Save(@"c:\test.png", ImageFormat.Png);
}
}
public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
{
var ratioX = (double)maxWidth / image.Width;
var ratioY = (double)maxHeight / image.Height;
var ratio = Math.Min(ratioX, ratioY);
var newWidth = (int)(image.Width * ratio);
var newHeight = (int)(image.Height * ratio);
var newImage = new Bitmap(newWidth, newHeight);
using (var graphics = Graphics.FromImage(newImage))
graphics.DrawImage(image, 0, 0, newWidth, newHeight);
return newImage;
}
This post is right from SAP on Sep 20, 2012.
In short, they are still working on a release of Crystal Reports that will support VS2012 (including support for Windows 8) It will come in the form of a service pack release that updates the version currently supporting VS2010. At that time they will drop 2010/2012 from the name and simply call it Crystal Reports Developer.
If you want to download that version you can find it here.
Further, service packs etc. when released can be found here.
I would also add that I am currently using Visual Studio 2012. As long as you don't edit existing reports they continue to compile and work fine. Even on Windows 8. When I need to modify a report I can still open the project with VS2010, do my work, save my changes, and then switch back to 2012. It's a little bit of a pain but the ability for VS2010 and VS2012 to co-exist is nice in this regard. I'm also using TFS2012 and so far it hasn't had a problem with me modifying files in 2010 on a "2012" solution.
You can only use column aliases in GROUP BY, ORDER BY, or HAVING clauses.
Standard SQL doesn't allow you to refer to a column alias in a WHERE clause. This restriction is imposed because when the WHERE code is executed, the column value may not yet be determined.
Copied from MySQL documentation
As pointed in the comments, using HAVING instead may do the work. Make sure to give a read at this question too: WHERE vs HAVING.
You are looking for a Sublime UI Theme, which modifies Sublime's User Interface (e.g.: side bar). It's different from a Color Theme/Scheme, which modifies only the code part of Sublime's window. I tested a lot of UI Themes and the one I liked the most was Theme - Soda. You can install it using Sublime's Package Control. To enable it, go to Preferences >> Settings - User and add this line:
"theme": "Soda Dark 3.sublime-theme",
Here is a printscreen of my Sublime Text 3 with Soda Dark UI Theme and Twilight default Color Scheme:
This one draws 2 lines which form a cross on the top left of the screen:
DrawView.java
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
public class DrawView extends View {
Paint paint = new Paint();
private void init() {
paint.setColor(Color.BLACK);
}
public DrawView(Context context) {
super(context);
init();
}
public DrawView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public DrawView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
@Override
public void onDraw(Canvas canvas) {
canvas.drawLine(0, 0, 20, 20, paint);
canvas.drawLine(20, 0, 0, 20, paint);
}
}
The activity to start it:
StartDraw.java
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
public class StartDraw extends Activity {
DrawView drawView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
drawView = new DrawView(this);
drawView.setBackgroundColor(Color.WHITE);
setContentView(drawView);
}
}
A complete example which leaves the fields as NULL-terminated strings in the original input buffer and provides access to them via an array of char pointers. The CSV processor has been confirmed to work with fields enclosed in "double quotes", ignoring any delimiter chars within them.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// adjust BUFFER_SIZE to suit longest line
#define BUFFER_SIZE 1024 * 1024
#define NUM_FIELDS 10
#define MAXERRS 5
#define RET_OK 0
#define RET_FAIL 1
#define FALSE 0
#define TRUE 1
// char* array will point to fields
char *pFields[NUM_FIELDS];
// field offsets into pFields array:
#define LP 0
#define IMIE 1
#define NAZWISKo 2
#define ULICA 3
#define NUMER 4
#define KOD 5
#define MIEJSCOw 6
#define TELEFON 7
#define EMAIL 8
#define DATA_UR 9
long loadFile(FILE *pFile, long *errcount);
static int loadValues(char *line, long lineno);
static char delim;
long loadFile(FILE *pFile, long *errcount){
char sInputBuf [BUFFER_SIZE];
long lineno = 0L;
if(pFile == NULL)
return RET_FAIL;
while (!feof(pFile)) {
// load line into static buffer
if(fgets(sInputBuf, BUFFER_SIZE-1, pFile)==NULL)
break;
// skip first line (headers)
if(++lineno==1)
continue;
// jump over empty lines
if(strlen(sInputBuf)==0)
continue;
// set pFields array pointers to null-terminated string fields in sInputBuf
if(loadValues(sInputBuf,lineno)==RET_FAIL){
(*errcount)++;
if(*errcount > MAXERRS)
break;
} else {
// On return pFields array pointers point to loaded fields ready for load into DB or whatever
// Fields can be accessed via pFields, e.g.
printf("lp=%s, imie=%s, data_ur=%s\n", pFields[LP], pFields[IMIE], pFields[DATA_UR]);
}
}
return lineno;
}
static int loadValues(char *line, long lineno){
if(line == NULL)
return RET_FAIL;
// chop of last char of input if it is a CR or LF (e.g.Windows file loading in Unix env.)
// can be removed if sure fgets has removed both CR and LF from end of line
if(*(line + strlen(line)-1) == '\r' || *(line + strlen(line)-1) == '\n')
*(line + strlen(line)-1) = '\0';
if(*(line + strlen(line)-1) == '\r' || *(line + strlen(line)-1 )== '\n')
*(line + strlen(line)-1) = '\0';
char *cptr = line;
int fld = 0;
int inquote = FALSE;
char ch;
pFields[fld]=cptr;
while((ch=*cptr) != '\0' && fld < NUM_FIELDS){
if(ch == '"') {
if(! inquote)
pFields[fld]=cptr+1;
else {
*cptr = '\0'; // zero out " and jump over it
}
inquote = ! inquote;
} else if(ch == delim && ! inquote){
*cptr = '\0'; // end of field, null terminate it
pFields[++fld]=cptr+1;
}
cptr++;
}
if(fld > NUM_FIELDS-1){
fprintf(stderr, "Expected field count (%d) exceeded on line %ld\n", NUM_FIELDS, lineno);
return RET_FAIL;
} else if (fld < NUM_FIELDS-1){
fprintf(stderr, "Expected field count (%d) not reached on line %ld\n", NUM_FIELDS, lineno);
return RET_FAIL;
}
return RET_OK;
}
int main(int argc, char **argv)
{
FILE *fp;
long errcount = 0L;
long lines = 0L;
if(argc!=3){
printf("Usage: %s csvfilepath delimiter\n", basename(argv[0]));
return (RET_FAIL);
}
if((delim=argv[2][0])=='\0'){
fprintf(stderr,"delimiter must be specified\n");
return (RET_FAIL);
}
fp = fopen(argv[1] , "r");
if(fp == NULL) {
fprintf(stderr,"Error opening file: %d\n",errno);
return(RET_FAIL);
}
lines=loadFile(fp,&errcount);
fclose(fp);
printf("Processed %ld lines, encountered %ld error(s)\n", lines, errcount);
if(errcount>0)
return(RET_FAIL);
return(RET_OK);
}
You can also use Url.Action for the path instead like so:
$.ajax({
url: "@Url.Action("Holiday", "Calendar", new { area = "", year= (val * 1) + 1 })",
type: "GET",
success: function (partialViewResult) {
$("#refTable").html(partialViewResult);
}
});
copy NUL EmptyFile.txt
DOS has a few special files (devices, actually) that exist in every directory, NUL
being the equivalent of UNIX's /dev/null
: it's a magic file that's always empty and throws away anything you write to it. Here's a list of some others; CON
is occasionally useful as well.
To avoid having any output at all, you can use
copy /y NUL EmptyFile.txt >NUL
/y
prevents copy
from asking a question you can't see when output goes to NUL
.
You can use this:
list=$(find /home/user/Desktop -name '*.pdf' -o -name '*.txt' -o -name '*.bmp')
Besides, you might want to use -iname
instead of -name
to catch files with ".PDF" (upper-case) extension as well.
Just select the code and
on Windows do Ctrl + Alt + L
on Linux do Ctrl + Windows Key + Alt + L
on Mac do CMD + Option + L
Same as nautic20's answer, just simply use MVC default model binding checkbox list with same name as a collection property of string/int/enum in ViewModel. That is it.
But one issue need to point out. In each checkbox component, you should not put "Id" in it which will affect MVC model binding.
Following code will work for model binding:
<% foreach (var item in Model.SampleObjectList)
{ %>
<tr>
<td><input type="checkbox" name="SelectedObjectIds" value="<%= item.Id%>" /></td>
<td><%= Html.Encode(item.Name)%></td>
</tr>
<% } %>
Following codes will not binding to model (difference here is it assigned id for each checkbox)
<% foreach (var item in Model.SampleObjectList)
{ %>
<tr>
<td><input type="checkbox" name="SelectedObjectIds" id="[some unique key]" value="<%= item.Id%>" /></td>
<td><%= Html.Encode(item.Name)%></td>
</tr>
<% } %>
In Rails:
"kirk douglas".titleize => "Kirk Douglas"
#this also works for 'kirk_douglas'
w/o Rails:
"kirk douglas".split(/ |\_/).map(&:capitalize).join(" ")
#OBJECT IT OUT
def titleize(str)
str.split(/ |\_/).map(&:capitalize).join(" ")
end
#OR MONKEY PATCH IT
class String
def titleize
self.split(/ |\_/).map(&:capitalize).join(" ")
end
end
w/o Rails (load rails's ActiveSupport to patch #titleize method to String
)
require 'active_support/core_ext'
"kirk douglas".titleize #=> "Kirk Douglas"
Rails's titleize
will convert things like dashes and underscores into spaces and can produce other unexpected results, especially with case-sensitive situations as pointed out by @JamesMcMahon:
"hEy lOok".titleize #=> "H Ey Lo Ok"
because it is meant to handle camel-cased code like:
"kirkDouglas".titleize #=> "Kirk Douglas"
To deal with this edge case you could clean your string with #downcase
first before running #titleize. Of course if you do that you will wipe out any camelCased word separations:
"kirkDouglas".downcase.titleize #=> "Kirkdouglas"
You should check API
for these questions.
You can use remove methods.
a.remove(1);
OR
a.remove("acbd");
You can use indexOf
But not working well in the last version of internet explorer.
Code:
function isInArray(value, array) {
return array.indexOf(value) > -1;
}
Execution:
isInArray(1, [1,2,3]); // true
I suggest you use the following code:
function inArray(needle, haystack) {
var length = haystack.length;
for (var i = 0; i < length; i++) {
if (haystack[i] == needle)
return true;
}
return false;
}
Go to the C drive->user->PcName->find .m2 and Paste the downloaded ojdbc jar file there, Server will automatically pick this.
Declare them before the while loop.
$hn = "";
$pid = "";
$datereg = "";
$prefix = "";
$fname = "";
$lname = "";
$age = "";
$sex = "";
You are getting the notice because the variables are declared and assigned inside the loop.
You can also have several workspaces - so you can connect to one and have set "A" of projects - and then connect to a different set when ever you like.
Go to control panel > Programs and feature > IISExpress > Repair
// change "name" and "value" according to your array data.
// Change "yourDataArrayName" name accroding to your array(NSArray).
let resultPredicate = NSPredicate(format: "SELF.name contains[c] %@", "value")
if let sortedDta = yourDataArrayName.filtered(using: resultPredicate) as? NSArray {
//enter code here.
print(sortedDta)
}
For your actual form, if you were to just post the results to your same page, it should probably work out all right. Try something like:
<form action=<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> method="POST>
If you're loading the PDF from a blob this is how you get the first page instead of the last page:
$im->readimageblob($blob);
$im->setiteratorindex(0);
This will also work,
f=open('in.txt','r')
for line in f:
parline = line[:-1].split(',')
Java Server Pages (JSP) is java technology which enables Web developers and designers to rapidly develop and easily maintain, information-rich, dynamic Web pages that leverage existing business systems. JSP technology separates the user interface from content generation, enabling designers to change the overall page layout without altering the underlying dynamic content.
Facelets is the first non JSP page declaration language designed for JSF (Java Server Faces) which provided a simpler and more powerful programming model to JSF developers as compare to JSP. It resolves different issues occurs in JSP for web applications development.
Here is a table that compares the features of scriplets and facelets:
Refer this:
@RequestMapping(value="download", method=RequestMethod.GET)
public void getDownload(HttpServletResponse response) {
// Get your file stream from wherever.
InputStream myStream = someClass.returnFile();
// Set the content type and attachment header.
response.addHeader("Content-disposition", "attachment;filename=myfilename.txt");
response.setContentType("txt/plain");
// Copy the stream to the response's output stream.
IOUtils.copy(myStream, response.getOutputStream());
response.flushBuffer();
}
Chiming in to recommend the use of the xmltodict library. It handled your xml text pretty well and I've used it for ingesting an xml file with almost a million records.
You can use:
sc.sparkContext.getConf.getAll
For example, I often have the following at the top of my Spark programs:
logger.info(sc.sparkContext.getConf.getAll.mkString("\n"))
A slightly simplified answer:
public class Book
{
private final String title;
public Book(String title)
{
this.title = title;
}
public Book()
{
this("Default Title");
}
...
}
We copy/paste html pages from our ERP to Excel using "paste special.. as html/unicode" and it works quite well with tables.
You can add a wrapper around promise functionality to return an Observable to observer.
import { of, Observable, defer } from 'rxjs';
import { map } from 'rxjs/operators';
function getTodos$(): Observable<any> {
return defer(()=>{
return fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => {
return json;
})
});
}
getTodos$().
subscribe(
(next)=>{
console.log('Data is:', next);
}
)
order[] is undefined that's why
Just define order[1]...[n] to = some value
this should fix it
Wrapping int primitive into Integer object will cost you some memory, but the difference will be only significant in very rare(memory demand) cases (array with 1000+ elements). I will not recommend using new Integer(int a) constructor this way. This will suffice :
Integer a = 3;
About comparision there is Math.signum(double d).
compare= (int) Math.signum(a-b);
Try using ReadSettings:
from readsettings import ReadSettings
data = ReadSettings("settings.json") # Load or create any json, yml, yaml or toml file
data["name"] = "value" # Set "name" to "value"
data["name"] # Returns: "value"
The problem with formulating an answer to this question is that you do not specify the desired output when the nullable datetime has no value. The following code will output DateTime.MinValue
in such a case, and unlike the currently accepted answer, will not throw an exception.
dt2.GetValueOrDefault().ToString(format);
This is an alternative:
- name: Install this only for local dev machine
pip: name=pyramid
delegate_to: localhost
PuTTY's plink has a command-line argument for a password. Some other suggestions have been made in the answers to this question: using Expect (which is available for Windows), or writing a launcher in Python with Paramiko.
Removing the xml declaration solved it
<?xml version='1.0' encoding='utf-8'?>
I do not know much about Java but URL query arguments should be separated by "&", not "?"
http://tools.ietf.org/html/rfc3986 is good place for reference using "sub-delim" as keyword. http://en.wikipedia.org/wiki/Query_string is another good source.
I think a much better method is to do this in the Program.cs file where you usually have Application.Run(form1), in this way you get a cleaner approach, Login form does not need to be coupled to Main form, you simply show the login and if it returns true you display the main form otherwise the error.
if ((Request.Headers["XYZComponent"] ?? "") == "true")
{
// header is present and set to "true"
}
If you want to modify the original array instead of returning a new array, use .push()
...
array1.push.apply(array1, array2);
array1.push.apply(array1, array3);
I used .apply
to push the individual members of arrays 2
and 3
at once.
or...
array1.push.apply(array1, array2.concat(array3));
To deal with large arrays, you can do this in batches.
for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
array1.push.apply(array1, to_add.slice(n, n+300));
}
If you do this a lot, create a method or function to handle it.
var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);
Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});
and use it like this:
array1.pushArrayMembers(array2, array3);
var push_apply = Function.apply.bind([].push);_x000D_
var slice_call = Function.call.bind([].slice);_x000D_
_x000D_
Object.defineProperty(Array.prototype, "pushArrayMembers", {_x000D_
value: function() {_x000D_
for (var i = 0; i < arguments.length; i++) {_x000D_
var to_add = arguments[i];_x000D_
for (var n = 0; n < to_add.length; n+=300) {_x000D_
push_apply(this, slice_call(to_add, n, n+300));_x000D_
}_x000D_
}_x000D_
}_x000D_
});_x000D_
_x000D_
var array1 = ['a','b','c'];_x000D_
var array2 = ['d','e','f'];_x000D_
var array3 = ['g','h','i'];_x000D_
_x000D_
array1.pushArrayMembers(array2, array3);_x000D_
_x000D_
document.body.textContent = JSON.stringify(array1, null, 4);
_x000D_
Update 2018-12-12 - Chrome App v Chrome Plugin - Most recent updates at top
With the deprecation of the Postman Chrome App, assuming that you are now using the Postman Native App, the options are now:
See below for full details on each option.
Personally, I still go for 2) Generate "Code" button/link as it allows me to see the variables without actually having to send.
1) Hover over variables with mouse
2) Generate "Code" button/link
Update: 2016-06-03
Whilst the method described above does work, in practice, I now normally use the "Generate Code" link on the Postman Request screen. The generated code, no matter what code language you choose, contains the substituted variables. Hitting the "Generate Code" link is just faster, additionally, you can see the substituted variables without actually making the request.
Original Answer below
To see the substituted variables in the Headers and Body, you need to use Chrome Developer tools. To enable Chrome Developer Tools from within Postman do the following, as per http://blog.getpostman.com/2015/06/13/debugging-postman-requests/.
I have copied the instructions from the link above in case the link gets broken in the future:
Type chrome://flags inside your Chrome URL window
Search for “packed” or try to find the “Enable debugging for packed apps”
Enable the setting
Restart Chrome
You can access the Developer Tools window by right clicking anywhere inside Postman and selecting “inspect element”. You can also go to chrome://inspect/#apps and then click “inspect” just below requester.html under the Postman heading.
Once enabled, you can use the Network Tools tab for even more information on your requests or the console while writing test scripts. If something goes wrong with your test scripts, it’ll show up here.
Difference between IaaS PaaS & SaaS
In the following tabular format we will be explaining the difference in context of
pizza as a service
Remember that running the command
git config --global core.excludesfile '~/.gitignore'
will just set up the global file, but will NOT create it.
For Windows check your Users directory for the .gitconfig
file, and edit it to your preferences. In my case It's like that:
[core]
excludesfile = c:/Users/myuser/Dropbox/Apps/Git/.gitignore
This isn't as easy to do as one might expect -- you can really only do vertical alignment if you know the height of your container. IF this is the case, you can do it with absolute positioning.
The concept is to set the top / left positions at 50%, and then use negative margins (set to half the height / width) to pull the container back to being centered.
Example: http://jsbin.com/ipawe/edit
Basic CSS:
#mydiv {
position: absolute;
top: 50%;
left: 50%;
height: 400px;
width: 700px;
margin-top: -200px; /* -(1/2 height) */
margin-left: -350px; /* -(1/2 width) */
}
<select id="myDropDown">
<option>html5</option>
<option>javascript</option>
<option>jquery</option>
<option>css</option>
<option>sencha</option>
</select>
By jQuery:
var myDropDown=$("#myDropDown");
var length = $('#myDropDown> option').length;
//open dropdown
myDropDown.attr('size',length);
//close dropdown
myDropDown.attr('size',0);
By javascript:
var myDropDown=document.getElementById("myDropDown");
var length = myDropDown.options.length;
//open dropdown
myDropDown.size = length;
//close dropdown
myDropDown.size = 0;
Copied from: Open close select
In addition to the very good points that others have made, I think there's another reason: what if the superclass does not have a superclass?
Since every class naturally extends (at least) Object
, super.whatever()
will always refer to a method in the superclass. But what if your class only extends Object
- what would super.super
refer to then? How should that behavior be handled - a compiler error, a NullPointer, etc?
I think the primary reason why this is not allowed is that it violates encapsulation, but this might be a small reason too.
To simplify leed25d's answer, use a combination of an alias and a function. For example:
function __GetIt {
cp ./path/to/stuff/$* .
}
alias GetIt='__GetIt'
If your error event handler takes the three arguments (xmlhttprequest, textstatus, and message) when a timeout happens, the status arg will be 'timeout'.
Per the jQuery documentation:
Possible values for the second argument (besides null) are "timeout", "error", "notmodified" and "parsererror".
You can handle your error accordingly then.
I created this fiddle that demonstrates this.
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 1000,
success: function(response) { alert(response); },
error: function(xmlhttprequest, textstatus, message) {
if(textstatus==="timeout") {
alert("got timeout");
} else {
alert(textstatus);
}
}
});?
With jsFiddle, you can test ajax calls -- it will wait 2 seconds before responding. I put the timeout setting at 1 second, so it should error out and pass back a textstatus of 'timeout' to the error handler.
Hope this helps!
When you use an ORDER BY
clause inside of a sub query used in conjunction with a UNION
mysql will optimise away the ORDER BY
clause.
This is because by default a UNION
returns an unordered list so therefore an ORDER BY
would do nothing.
The optimisation is mentioned in the docs and says:
To apply ORDER BY or LIMIT to an individual SELECT, place the clause inside the parentheses that enclose the SELECT:
(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10) UNION (SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);
However, use of ORDER BY for individual SELECT statements implies nothing about the order in which the rows appear in the final result because UNION by default produces an unordered set of rows. Therefore, the use of ORDER BY in this context is typically in conjunction with LIMIT, so that it is used to determine the subset of the selected rows to retrieve for the SELECT, even though it does not necessarily affect the order of those rows in the final UNION result. If ORDER BY appears without LIMIT in a SELECT, it is optimized away because it will have no effect anyway.
The last sentence of this is a bit misleading because it should have an effect. This optimisation causes a problem when you are in a situation where you need to order within the subquery.
To force MySQL to not do this optimisation you can add a LIMIT clause like so:
(SELECT 1 AS rank, id, add_date FROM my_table WHERE distance < 5 ORDER BY add_date LIMIT 9999999999)
UNION ALL
(SELECT 2 AS rank, id, add_date FROM my_table WHERE distance BETWEEN 5 AND 15 ORDER BY rank LIMIT 9999999999)
UNION ALL
(SELECT 3 AS rank, id, add_date from my_table WHERE distance BETWEEN 5 and 15 ORDER BY id LIMIT 9999999999)
A high LIMIT
means that you could add an OFFSET
on the overall query if you want to do something such as pagination.
This also gives you the added benefit of being able to ORDER BY
different columns for each union.
I finally invoked in sync mode by including the .Result
HttpResponseMessage response = null;
try
{
using (var client = new HttpClient())
{
response = client.PostAsync(
"http://localhost:8000/....",
new StringContent(myJson,Encoding.UTF8,"application/json")).Result;
if (response.IsSuccessStatusCode)
{
MessageBox.Show("OK");
}
else
{
MessageBox.Show("NOK");
}
}
}
catch (Exception ex)
{
MessageBox.Show("ERROR");
}
Run your program with
python -t script.py
This will warn you if you have mixed tabs and spaces.
On *nix systems, you can see where the tabs are by running
cat -A script.py
and you can automatically convert tabs to 4 spaces with the command
expand -t 4 script.py > fixed_script.py
PS. Be sure to use a programming editor (e.g. emacs, vim), not a word processor, when programming. You won't get this problem with a programming editor.
PPS. For emacs users, M-x whitespace-mode
will show the same info as cat -A
from within an emacs buffer!
One more bit of advice for anyone trying to build CGAL in particular, with statically linked Boost. It is not enough to define Boost_USE_STATIC_LIBS
; it gets overridden by the time Boost_DEBUG
outputs its value. The thing to do here is to check the "Advanced" checkbox and to enable CGAL_Boost_USE_STATIC_LIBS
.
This has happened to me also, after undating to IOS11 on my iPhone. When I try to connect to the corporate network it bring up the corporate cert and says it isn't trusted. I press the 'trust' button and the connection fails and the cert does not appear in the trusted certs list.
Yes. In fact, all instance methods in Java are virtual by default. Only certain methods are not virtual:
Here are some examples:
"Normal" virtual functions
The following example is from an old version of the wikipedia page mentioned in another answer.
import java.util.*;
public class Animal
{
public void eat()
{
System.out.println("I eat like a generic Animal.");
}
public static void main(String[] args)
{
List<Animal> animals = new LinkedList<Animal>();
animals.add(new Animal());
animals.add(new Fish());
animals.add(new Goldfish());
animals.add(new OtherAnimal());
for (Animal currentAnimal : animals)
{
currentAnimal.eat();
}
}
}
class Fish extends Animal
{
@Override
public void eat()
{
System.out.println("I eat like a fish!");
}
}
class Goldfish extends Fish
{
@Override
public void eat()
{
System.out.println("I eat like a goldfish!");
}
}
class OtherAnimal extends Animal {}
Output:
I eat like a generic Animal. I eat like a fish! I eat like a goldfish! I eat like a generic Animal.
Example with virtual functions with interfaces
Java interface methods are all virtual. They must be virtual because they rely on the implementing classes to provide the method implementations. The code to execute will only be selected at run time.
For example:
interface Bicycle { //the function applyBrakes() is virtual because
void applyBrakes(); //functions in interfaces are designed to be
} //overridden.
class ACMEBicycle implements Bicycle {
public void applyBrakes(){ //Here we implement applyBrakes()
System.out.println("Brakes applied"); //function
}
}
Example with virtual functions with abstract classes.
Similar to interfaces Abstract classes must contain virtual methods because they rely on the extending classes' implementation. For Example:
abstract class Dog {
final void bark() { //bark() is not virtual because it is
System.out.println("woof"); //final and if you tried to override it
} //you would get a compile time error.
abstract void jump(); //jump() is a "pure" virtual function
}
class MyDog extends Dog{
void jump(){
System.out.println("boing"); //here jump() is being overridden
}
}
public class Runner {
public static void main(String[] args) {
Dog dog = new MyDog(); // Create a MyDog and assign to plain Dog variable
dog.jump(); // calling the virtual function.
// MyDog.jump() will be executed
// although the variable is just a plain Dog.
}
}
In my case it was migrating from idea 2017 to 2018 and Lombok plugin was already there. All I did is added "Enable annotation processing options" entering preferences and check the box
If table is without partition then code will be,
Insert into table table_name
select col_a,col_b,col_c from another_table(source table)
--here any condition can be applied such as limit, group by, order by etc...
If table is with partitions then code will be,
set hive.exec.dynamic.partition=true;
set hive.exec.dynamic.partition.mode=nonstrict;
insert into table table_name
partition(partition_col1
, paritition_col2
)
select col_a,col_b,col_c,partition_col1,partition_col2
from another_table(source table)
--here any condition can be applied such as limit, group by, order by etc...
I had a similar issue, but I needed to be sure that the order of the ID is aligning to the order in the source file. My solution is using a VIEW for the BULK INSERT:
Keep your table as it is and create this VIEW (select everything except the ID column)
CREATE VIEW [dbo].[VW_Employee]
AS
SELECT [Name], [Address]
FROM [dbo].[Employee];
Your BULK INSERT should then look like:
BULK INSERT [dbo].[VW_Employee] FROM 'path\tempFile.csv '
WITH (FIRSTROW = 2,FIELDTERMINATOR = ',' , ROWTERMINATOR = '\n');
This question is very old, but I found myself studying for a Microsoft Certification, and in the study book it was suggested to use:
oldElement.replaceNode(newElement)
I looked it up and it seems to only be supported in IE. Doh..
I thought I'd just add it here as a funny side note ;)
The less well-known but extremely useful (and standard since C89 — meaning 'forever') functions in the C library provide the information in a single call. Actually, there are multiple functions — an embarrassment of riches. The relevant ones for this are:
7.21.5.3 The strcspn function
Synopsis
#include <string.h> size_t strcspn(const char *s1, const char *s2);
Description
The strcspn function computes the length of the maximum initial segment of the string pointed to by s1 which consists entirely of characters not from the string pointed to by s2.
Returns
The strcspn function returns the length of the segment.
7.21.5.4 The strpbrk function
Synopsis
#include <string.h> char *strpbrk(const char *s1, const char *s2);
Description
The strpbrk function locates the first occurrence in the string pointed to by s1 of any character from the string pointed to by s2.
Returns
The strpbrk function returns a pointer to the character, or a null pointer if no character from s2 occurs in s1.
The question asks about 'for each char in string ... if it is in list of invalid chars'.
With these functions, you can write:
size_t len = strlen(test);
size_t spn = strcspn(test, "invald");
if (spn != len) { ...there's a problem... }
Or:
if (strpbrk(test, "invald") != 0) { ...there's a problem... }
Which is better depends on what else you want to do. There is also the related strspn()
function which is sometimes useful (whitelist instead of blacklist).
user: USER
this.user = ({} as USER)
I'm using GIMP 2.8.1. I hope this will work for you:
Open the "Windows" menu and select "Single-Window Mode".
Simple ;)
If you intend to knowingly keep many plots in memory, but don't want to be warned about it, you can update your options prior to generating figures.
import matplotlib.pyplot as plt
plt.rcParams.update({'figure.max_open_warning': 0})
This will prevent the warning from being emitted without changing anything about the way memory is managed.
You want .charAt()
"mystring".charAt(2)
returns s
If you're hellbent on having a string there are a couple of ways to convert a char to a string:
String mychar = Character.toString("mystring".charAt(2));
Or
String mychar = ""+"mystring".charAt(2);
Or even
String mychar = String.valueOf("mystring".charAt(2));
For example.
I used all the above answers and it was giving me errors so I tried
adb shell monkey -p com.yourpackage.name -c android.intent.category.LAUNCHER 1
and it worked. One advantage is you dont have to specify your launcher activity if you use this command.
If you are mocking the behavior (with something like doNothing()
) there should really be no need to call to verify*()
. That said, here's my stab at re-writing your test method:
@PrepareForTest({InternalUtils.class})
@RunWith(PowerMockRunner.class)
public class InternalServiceTest { //Note the renaming of the test class.
public void testProcessOrder() {
//Variables
InternalService is = new InternalService();
Order order = mock(Order.class);
//Mock Behavior
when(order.isSuccessful()).thenReturn(true);
mockStatic(Internalutils.class);
doNothing().when(InternalUtils.class); //This is the preferred way
//to mock static void methods.
InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());
//Execute
is.processOrder(order);
//Verify
verifyStatic(InternalUtils.class); //Similar to how you mock static methods
//this is how you verify them.
InternalUtils.sendEmail(anyString(), anyString(), anyString(), anyString());
}
}
I grouped into four sections to better highlight what is going on:
I choose to declare any instance variables / method arguments / mock collaborators here. If it is something used in multiple tests, consider making it an instance variable of the test class.
This is where you define the behavior of all of your mocks. You're setting up return values and expectations here, prior to executing the code under test. Generally speaking, if you set the mock behavior here you wouldn't need to verify the behavior later.
Nothing fancy here; this just kicks off the code being tested. I like to give it its own section to call attention to it.
This is when you call any method starting with verify
or assert
. After the test is over, you check that the things you wanted to have happen actually did happen. That is the biggest mistake I see with your test method; you attempted to verify the method call before it was ever given a chance to run. Second to that is you never specified which static method you wanted to verify.
This is mostly personal preference on my part. There is a certain order you need to do things in but within each grouping there is a little wiggle room. This helps me quickly separate out what is happening where.
I also highly recommend going through the examples at the following sites as they are very robust and can help with the majority of the cases you'll need:
You could try..
comm -13 <(sort file1) <(sort file2) > file3
or
grep -Fxvf file1 file2 > file3
or
diff file1 file2 | grep "<" | sed 's/^<//g' > file3
or
join -v 2 <(sort file1) <(sort file2) > file3
if you did change the httpd.conf file located under conf_files folder, don't use windows notepad, you need a unix text editor, try TED pad, after making any changes to your httpd.conf file save it. ps: if you use a dos/windows editor you will end up with an "Error in Apache file changed" message. so do be careful.... Salam
Try installing it again with the stand alone installer https://software.intel.com/en-us/android/articles/intel-hardware-accelerated-execution-manager-end-user-license-agreement - assuming you have a CPU that supports Virtualization, have turned off antivirus and any hypervisor.
I suggest you truncate first, and then format:
double a = 123.4567;
double aTruncated = Math.Truncate(a * 100) / 100;
CultureInfo ci = new CultureInfo("de-DE");
string s = string.Format(ci, "{0:0.00}%", aTruncated);
Use the constant 100 for 2 digits truncate; use a 1 followed by as many zeros as digits after the decimal point you would like. Use the culture name you need to adjust the formatting result.
placeBets(betList, stakeAmt)
is an instance method not a static method. You need to create an instance of CBetfairAPI
first:
MyBetfair api = new MyBetfair();
ArrayList bets = api.placeBets(betList, stakeAmt);
in
keyword allows you to loop over a collection and check if there is a member in the collection that is equal to the element.
In this case string is nothing but a list of characters:
dog = "xdasds"
if "x" in dog:
print "Yes!"
You can check a substring too:
>>> 'x' in "xdasds"
True
>>> 'xd' in "xdasds"
True
>>>
>>>
>>> 'xa' in "xdasds"
False
Think collection:
>>> 'x' in ['x', 'd', 'a', 's', 'd', 's']
True
>>>
You can also test the set membership over user defined classes.
For user-defined classes which define the __contains__ method, x in y is true if and only if y.__contains__(x) is true.
As an alternative to sun.misc.BASE64Decoder
or non-core libraries, look at javax.mail.internet.MimeUtility.decode()
.
public static byte[] encode(byte[] b) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
OutputStream b64os = MimeUtility.encode(baos, "base64");
b64os.write(b);
b64os.close();
return baos.toByteArray();
}
public static byte[] decode(byte[] b) throws Exception {
ByteArrayInputStream bais = new ByteArrayInputStream(b);
InputStream b64is = MimeUtility.decode(bais, "base64");
byte[] tmp = new byte[b.length];
int n = b64is.read(tmp);
byte[] res = new byte[n];
System.arraycopy(tmp, 0, res, 0, n);
return res;
}
Link with full code: Encode/Decode to/from Base64