Just because this is what I got when I Googled this error, my problem was that I had
if (value < other.value)
return -1;
else if (value >= other.value)
return 1;
else
return 0;
the value >= other.value
should (obviously) actually be value > other.value
so that you can actually return 0 with equal objects.
I am using nano editor in a Raspberry Pi with Italian OS language and Italian keyboard. Don't know the exact reason, but in this environment the shortcut is:
Ctrl+-
WHERE something IS NULL
and
WHERE something IS NOT NULL
You should use a callback parameter:
function Typer(callback)
{
var srcText = 'EXAMPLE ';
var i = 0;
var result = srcText[i];
var interval = setInterval(function() {
if(i == srcText.length - 1) {
clearInterval(interval);
callback();
return;
}
i++;
result += srcText[i].replace("\n", "<br />");
$("#message").html(result);
},
100);
return true;
}
function playBGM () {
alert("Play BGM function");
$('#bgm').get(0).play();
}
Typer(function () {
playBGM();
});
// or one-liner: Typer(playBGM);
So, you pass a function as parameter (callback
) that will be called in that if
before return
.
Also, this is a good article about callbacks.
function Typer(callback)_x000D_
{_x000D_
var srcText = 'EXAMPLE ';_x000D_
var i = 0;_x000D_
var result = srcText[i];_x000D_
var interval = setInterval(function() {_x000D_
if(i == srcText.length - 1) {_x000D_
clearInterval(interval);_x000D_
callback();_x000D_
return;_x000D_
}_x000D_
i++;_x000D_
result += srcText[i].replace("\n", "<br />");_x000D_
$("#message").html(result);_x000D_
},_x000D_
100);_x000D_
return true;_x000D_
_x000D_
_x000D_
}_x000D_
_x000D_
function playBGM () {_x000D_
alert("Play BGM function");_x000D_
$('#bgm').get(0).play();_x000D_
}_x000D_
_x000D_
Typer(function () {_x000D_
playBGM();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>_x000D_
<div id="message">_x000D_
</div>_x000D_
<audio id="bgm" src="http://www.freesfx.co.uk/rx2/mp3s/9/10780_1381246351.mp3">_x000D_
</audio>
_x000D_
On Python 3 numpy.genfromtxt
expects a bytes stream. Use the following:
numpy.genfromtxt(io.BytesIO(x.encode()))
In the mongo shell:
use [database];
db.dropDatabase();
And to remove the users:
db.dropAllUsers();
You can also try using parameters directive for making your build parameterized and accessing parameters:
Doc: Pipeline syntax: Parameters
Example:
pipeline{
agent { node { label 'test' } }
options { skipDefaultCheckout() }
parameters {
string(name: 'suiteFile', defaultValue: '', description: 'Suite File')
}
stages{
stage('Initialize'){
steps{
echo "${params.suiteFile}"
}
}
}
This is working for me (i use laravel 5.6).
$collection = MyModel::all()->groupBy('column');
If you want to convert the collection to plain php array, you can use toArray()
$array = MyModel::all()->groupBy('column')->toArray();
Looks file you use the .mkdirs()
method on a File
object: http://www.roseindia.net/java/beginners/java-create-directory.shtml
// Create a directory; all non-existent ancestor directories are
// automatically created
success = (new File("../potentially/long/pathname/without/all/dirs")).mkdirs();
if (!success) {
// Directory creation failed
}
The And
operator evaluates both sides, where AndAlso
evaluates the right side if and only if the left side is true.
An example:
If mystring IsNot Nothing And mystring.Contains("Foo") Then
' bla bla
End If
The above throws an exception if mystring = Nothing
If mystring IsNot Nothing AndAlso mystring.Contains("Foo") Then
' bla bla
End If
This one does not throw an exception.
So if you come from the C# world, you should use AndAlso
like you would use &&
.
More info here: http://www.panopticoncentral.net/2003/08/18/the-ballad-of-andalso-and-orelse/
The HTML4 spec for the <input>
element specifies the following script events are available:
onfocus, onblur, onselect, onchange, onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup
here's an example that bind's to all these events and shows what's going on http://jsfiddle.net/pxfunc/zJ7Lf/
I think you can filter out which events are truly relevent to your situation and detect what the text value was before and after the event to determine a change
I'm guessing you're using jQuery.get or some other jQuery ajax function to load the modal. You can show the indicator before the ajax call, and hide it when the ajax completes. Something like
$('#indicator').show();
$('#someModal').get(anUrl, someData, function() { $('#indicator').hide(); });
Simply just divide the numbers, it gives yuh the decimal format and even the numerical format. using S<->D
For example: 11/3 gives you 3.666667 and 3 2/3 (Swap using S<->D). Here the '2' from 2/3 is your mod value.
Similarly 18/6 gives you 14.833333 and 14 5/6 (Swap using S<->D). Here the '5' from 5/6 is your mod value.
just a matter of taste but if you prefer accessing the variable or function directly like this:
<div id="playlist-icon" back-img="playlist.icon">
instead of interpolating like this:
<div id="playlist-icon" back-img="{{playlist.icon}}">
then you can define the directive a bit differently with scope.$watch
which will do $parse
on the
attribute
angular.module('myApp', [])
.directive('bgImage', function(){
return function(scope, element, attrs) {
scope.$watch(attrs.bgImage, function(value) {
element.css({
'background-image': 'url(' + value +')',
'background-size' : 'cover'
});
});
};
})
there is more background on this here: AngularJS : Difference between the $observe and $watch methods
You can do it like this
new DirectoryInfo(path).GetFiles().Where(Current => Regex.IsMatch(Current.Extension, "\\.(aspx|ascx)", RegexOptions.IgnoreCase)
If you only want the position, vp.getCurrentItem()
will give it to you, no need to apply the onPageChangeListener() for that purpose alone.
The expression df1$id %in% idNums1
produces a logical vector. To negate it, you need to negate the whole vector:
!(df1$id %in% idNums1)
If you know a variable is empty, you could use it as a comment. Of course if it is not empty it will mess up your command.
ls -l ${1# -F is turned off} -a /etc
In addition to Alex's answer:
Note that http://server/resource/id?force_delete=true identifies a different resource than http://server/resource/id. For example, it is a huge difference whether you delete /customers/?status=old or /customers/.
<select id="ddlvalue" name="ddlvaluename">
<option value='0' disabled selected>Select Value</option>
<option value='1' >Value 1</option>
<option value='2' >Value 2</option>
</select>
<input type="submit" id="btn_submit" value="click me"/>
<script>
$('#btn_submit').on('click',function(){
$('#ddlvalue').val(0);
});
</script>
format
is definitely the most elegant way, but afaik you can't use that with python's logging
module, so here's how you can do it using the %
formatting:
formatter = logging.Formatter(
fmt='%(asctime)s | %(name)-20s | %(levelname)-10s | %(message)s',
)
Here, the -
indicates left-alignment, and the number before s
indicates the fixed width.
Some sample output:
2017-03-14 14:43:42,581 | this-app | INFO | running main
2017-03-14 14:43:42,581 | this-app.aux | DEBUG | 5 is an int!
2017-03-14 14:43:42,581 | this-app.aux | INFO | hello
2017-03-14 14:43:42,581 | this-app | ERROR | failed running main
More info at the docs here: https://docs.python.org/2/library/stdtypes.html#string-formatting-operations
You can also use
var XLSX = require('xlsx');
var workbook = XLSX.readFile('Master.xlsx');
var sheet_name_list = workbook.SheetNames;
console.log(XLSX.utils.sheet_to_json(workbook.Sheets[sheet_name_list[0]]))
SELECT id, GROUP_CONCAT(name SEPARATOR ' ') FROM table GROUP BY id;
:- In MySQL, you can get the concatenated values of expression combinations . To eliminate duplicate values, use the DISTINCT clause. To sort values in the result, use the ORDER BY clause. To sort in reverse order, add the DESC (descending) keyword to the name of the column you are sorting by in the ORDER BY clause. The default is ascending order; this may be specified explicitly using the ASC keyword. The default separator between values in a group is comma (“,”). To specify a separator explicitly, use SEPARATOR followed by the string literal value that should be inserted between group values. To eliminate the separator altogether, specify SEPARATOR ''.
GROUP_CONCAT([DISTINCT] expr [,expr ...]
[ORDER BY {unsigned_integer | col_name | expr}
[ASC | DESC] [,col_name ...]]
[SEPARATOR str_val])
OR
mysql> SELECT student_name,
-> GROUP_CONCAT(DISTINCT test_score
-> ORDER BY test_score DESC SEPARATOR ' ')
-> FROM student
-> GROUP BY student_name;
The correct command is the following one.
VBoxManage internalcommands sethduuid "/home/user/VirtualBox VMs/drupal/drupal.vhd"
The path for the virtual disk contains a space, so it must be enclosed in double quotes to avoid it is parsed as two parameters.
Use the DataFrame returned by:
yourDF.orderBy(account)
There is no explicit way to use partitionBy
on a DataFrame, only on a PairRDD, but when you sort a DataFrame, it will use that in it's LogicalPlan and that will help when you need to make calculations on each Account.
I just stumbled upon the same exact issue, with a dataframe that I want to partition by account.
I assume that when you say "want to have the data partitioned so that all of the transactions for an account are in the same Spark partition", you want it for scale and performance, but your code doesn't depend on it (like using mapPartitions()
etc), right?
Have the certificate and bundle copied in one .crt file and make sure that there is a blank line between the certificates in the file.
This worked for me on a GitLab server after trying everything on the Internet.
deploy:
resources:
limits:
cpus: '0.001'
memory: 50M
reservations:
cpus: '0.0001'
memory: 20M
More: https://docs.docker.com/compose/compose-file/compose-file-v3/#resources
In you specific case:
version: "3"
services:
node:
image: USER/Your-Pre-Built-Image
environment:
- VIRTUAL_HOST=localhost
volumes:
- logs:/app/out/
command: ["npm","start"]
cap_drop:
- NET_ADMIN
- SYS_ADMIN
deploy:
resources:
limits:
cpus: '0.001'
memory: 50M
reservations:
cpus: '0.0001'
memory: 20M
volumes:
- logs
networks:
default:
driver: overlay
Note:
Also Note: Networks in Swarm mode do not bridge. If you would like to connect internally only, you have to attach to the network. You can 1) specify an external network within an other compose file, or have to create the network with --attachable parameter (docker network create -d overlay My-Network --attachable) Otherwise you have to publish the port like this:
ports:
- 80:80
According to wiki https://en.wikipedia.org/wiki/Heap%27s_algorithm
Heap's algorithm generates all possible permutations of n objects. It was first proposed by B. R. Heap in 1963. The algorithm minimizes movement: it generates each permutation from the previous one by interchanging a single pair of elements; the other n-2 elements are not disturbed. In a 1977 review of permutation-generating algorithms, Robert Sedgewick concluded that it was at that time the most effective algorithm for generating permutations by computer.
So if we want to do it in recursive manner, Sudo code is bellow.
procedure generate(n : integer, A : array of any):
if n = 1 then
output(A)
else
for i := 0; i < n - 1; i += 1 do
generate(n - 1, A)
if n is even then
swap(A[i], A[n-1])
else
swap(A[0], A[n-1])
end if
end for
generate(n - 1, A)
end if
java code:
public static void printAllPermutations(
int n, int[] elements, char delimiter) {
if (n == 1) {
printArray(elements, delimiter);
} else {
for (int i = 0; i < n - 1; i++) {
printAllPermutations(n - 1, elements, delimiter);
if (n % 2 == 0) {
swap(elements, i, n - 1);
} else {
swap(elements, 0, n - 1);
}
}
printAllPermutations(n - 1, elements, delimiter);
}
}
private static void printArray(int[] input, char delimiter) {
int i = 0;
for (; i < input.length; i++) {
System.out.print(input[i]);
}
System.out.print(delimiter);
}
private static void swap(int[] input, int a, int b) {
int tmp = input[a];
input[a] = input[b];
input[b] = tmp;
}
public static void main(String[] args) {
int[] input = new int[]{0,1,2,3};
printAllPermutations(input.length, input, ',');
}
As far as your question goes: no, if activating from .ini
is not enough and you can't upgrade PHP, there's not much you can do. Some modules, but not all, can be added without recompilation (zypper install php5-soap
, yum install php-soap
). If it is not enough, try installing some PEAR class for interpreted SOAP support (NuSOAP, etc.).
In general, the double-dash --switches
are designed to be used when recompiling PHP from scratch.
You would download the PHP source package (as a compressed .tgz
tarball, say), expand it somewhere and then, e.g. under Linux, run the configure script
./configure --prefix ...
The configure
command used by your PHP may be shown with phpinfo()
. Repeating it identical should give you an exact copy of the PHP you now have installed. Adding --enable-soap
will then enable SOAP in addition to everything else.
That said, if you aren't familiar with PHP recompilation, don't do it. It also requires several ancillary libraries that you might, or might not, have available - freetype
, gd
, libjpeg
, XML
, expat
, and so on and so forth (it's not enough they are installed; they must be a developer version, i.e. with headers and so on; in most distributions, having libjpeg
installed might not be enough, and you might need libjpeg-dev
also).
I have to keep a separate virtual machine with everything installed for my recompilation purposes.
No, it's not possible in java.
You can do this way .. But try to avoid it.
String one, two, three;
one = two = three = "";
Different tools may interpret the meaning of @Nullable
differently. For example, the Checker Framework and FindBugs handle @Nullable
differently.
I just ran into a similar problem and devised a small optimization for the case where no object in the list meets the requirement.(for my use-case this resulted in major performance improvement):
Along with the list test_list, I keep an additional set test_value_set which consists of values of the list that I need to filter on. So here the else part of agf's solution becomes very-fast.
why not use
background-color: #ff0000;
opacity: 0.5;
filter: alpha(opacity=50); /* in IE */
if you target a color for a text or probably an element, this should be a lot easier to do.
The literal answer to your question (to do exactly what you asked, changing only the wrapper, not the functions or the function calls) is simply to alter the line
func(args)
to read
func(*args)
This tells Python to take the list given (in this case, args
) and pass its contents to the function as positional arguments.
This trick works on both "sides" of the function call, so a function defined like this:
def func2(*args):
return sum(args)
would be able to accept as many positional arguments as you throw at it, and place them all into a list called args
.
I hope this helps to clarify things a little. Note that this is all possible with dicts/keyword arguments as well, using **
instead of *
.
You are missing the selector in the .on
function:
.on(eventType, selector, function)
This selector is very important!
If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler
See jQuery 1.9 .live() is not a function for more details.
$('#hello').hide('slide', {direction: 'left'}, 1000);
requires the jQuery-ui library. See http://www.jqueryui.com
I've just faced the same issue and I came to believe that the other answers are a bit more complicated than they need to be, so here's my approach for those who don't want to rely on more libraries or decorators:
A CORS request actually consists of two HTTP requests. A preflight request and then an actual request that is only made if the preflight passes successfully.
Before the actual cross domain POST
request, the browser will issue an OPTIONS
request. This response should not return any body, but only some reassuring headers telling the browser that it's alright to do this cross-domain request and it's not part of some cross site scripting attack.
I wrote a Python function to build this response using the make_response
function from the flask
module.
def _build_cors_prelight_response():
response = make_response()
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add("Access-Control-Allow-Headers", "*")
response.headers.add("Access-Control-Allow-Methods", "*")
return response
This response is a wildcard one that works for all requests. If you want the additional security gained by CORS, you have to provide a whitelist of origins, headers and methods.
This response will convince your (Chrome) browser to go ahead and do the actual request.
When serving the actual request you have to add one CORS header - otherwise the browser won't return the response to the invoking JavaScript code. Instead the request will fail on the client-side. Example with jsonify
response = jsonify({"order_id": 123, "status": "shipped"}
response.headers.add("Access-Control-Allow-Origin", "*")
return response
I also wrote a function for that.
def _corsify_actual_response(response):
response.headers.add("Access-Control-Allow-Origin", "*")
return response
allowing you to return a one-liner.
from flask import Flask, request, jsonify, make_response
from models import OrderModel
flask_app = Flask(__name__)
@flask_app.route("/api/orders", methods=["POST", "OPTIONS"])
def api_create_order():
if request.method == "OPTIONS": # CORS preflight
return _build_cors_prelight_response()
elif request.method == "POST": # The actual request following the preflight
order = OrderModel.create(...) # Whatever.
return _corsify_actual_response(jsonify(order.to_dict()))
else
raise RuntimeError("Weird - don't know how to handle method {}".format(request.method))
def _build_cors_prelight_response():
response = make_response()
response.headers.add("Access-Control-Allow-Origin", "*")
response.headers.add('Access-Control-Allow-Headers', "*")
response.headers.add('Access-Control-Allow-Methods', "*")
return response
def _corsify_actual_response(response):
response.headers.add("Access-Control-Allow-Origin", "*")
return response
An example (axios_example.js) using Axios in Node.js:
const axios = require('axios');
const express = require('express');
const app = express();
const port = process.env.PORT || 5000;
app.get('/search', function(req, res) {
let query = req.query.queryStr;
let url = `https://your.service.org?query=${query}`;
axios({
method:'get',
url,
auth: {
username: 'the_username',
password: 'the_password'
}
})
.then(function (response) {
res.send(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
});
var server = app.listen(port);
Be sure in your project directory you do:
npm init
npm install express
npm install axios
node axios_example.js
You can then test the Node.js REST API using your browser at: http://localhost:5000/search?queryStr=xxxxxxxxx
Similarly you can do post, such as:
axios({
method: 'post',
url: 'https://your.service.org/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
Similarly you can use SuperAgent.
superagent.get('https://your.service.org?query=xxxx')
.end((err, response) => {
if (err) { return console.log(err); }
res.send(JSON.stringify(response.body));
});
And if you want to do basic authentication:
superagent.get('https://your.service.org?query=xxxx')
.auth('the_username', 'the_password')
.end((err, response) => {
if (err) { return console.log(err); }
res.send(JSON.stringify(response.body));
});
For java 7 and up:
Path path = Paths.get("/your/path/string");
Files.createDirectories(path);
It seems unnecessary to check for existence of the dir or file before creating, from createDirectories javadocs:
Creates a directory by creating all nonexistent parent directories first. Unlike the createDirectory method, an exception is not thrown if the directory could not be created because it already exists. The attrs parameter is optional file-attributes to set atomically when creating the nonexistent directories. Each file attribute is identified by its name. If more than one attribute of the same name is included in the array then all but the last occurrence is ignored.
If this method fails, then it may do so after creating some, but not all, of the parent directories.
Little bit late to the party but had some problems with getting something useful out from a ReadableStream
produced from a Odata $batch request using the Sharepoint Framework.
Had similar issues as OP, but the solution in my case was to use a different conversion method than .json()
. In my case .text()
worked like a charm. Some fiddling was however necessary to get some useful JSON from the textfile.
For those using Airbrake, there's a solid response above but it wouldn't work for me without tweaking:
Works for some memory addresses but not others, not sure why...
In order to use jQuery inside Angular only declare the $ as following: declare var $: any;
Check the column collation. This script might change the collation to the table default. Add the current collation to the script.
Since I see lots of comments about people having problems with the plugin, I thought I'd mention the work around that I use.
I just use one of the online sites for XML viewing (I use https://codebeautify.org/xmlviewer, but there are plenty out there) as follows:
I don't know if it qualifies as answering the OP's question exactly, but it's very simple and easy for anyone who is having problems with the plugin.
You need antMatcher
for multiple HttpSecurity
, see Spring Security Reference:
5.7 Multiple HttpSecurity
We can configure multiple HttpSecurity instances just as we can have multiple
<http>
blocks. The key is to extend theWebSecurityConfigurationAdapter
multiple times. For example, the following is an example of having a different configuration for URL’s that start with/api/
.@EnableWebSecurity public class MultiHttpSecurityConfig { @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) { 1 auth .inMemoryAuthentication() .withUser("user").password("password").roles("USER").and() .withUser("admin").password("password").roles("USER", "ADMIN"); } @Configuration @Order(1) 2 public static class ApiWebSecurityConfigurationAdapter extends WebSecurityConfigurerAdapter { protected void configure(HttpSecurity http) throws Exception { http .antMatcher("/api/**") 3 .authorizeRequests() .anyRequest().hasRole("ADMIN") .and() .httpBasic(); } } @Configuration 4 public static class FormLoginWebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .anyRequest().authenticated() .and() .formLogin(); } } }
1 Configure Authentication as normal
2 Create an instance of
WebSecurityConfigurerAdapter
that contains@Order
to specify whichWebSecurityConfigurerAdapter
should be considered first.3 The
http.antMatcher
states that thisHttpSecurity
will only be applicable to URLs that start with/api/
4 Create another instance of
WebSecurityConfigurerAdapter
. If the URL does not start with/api/
this configuration will be used. This configuration is considered afterApiWebSecurityConfigurationAdapter
since it has an@Order
value after1
(no@Order
defaults to last).
In your case you need no antMatcher
, because you have only one configuration. Your modified code:
http
.authorizeRequests()
.antMatchers("/high_level_url_A/sub_level_1").hasRole('USER')
.antMatchers("/high_level_url_A/sub_level_2").hasRole('USER2')
.somethingElse() // for /high_level_url_A/**
.antMatchers("/high_level_url_A/**").authenticated()
.antMatchers("/high_level_url_B/sub_level_1").permitAll()
.antMatchers("/high_level_url_B/sub_level_2").hasRole('USER3')
.somethingElse() // for /high_level_url_B/**
.antMatchers("/high_level_url_B/**").authenticated()
.anyRequest().permitAll()
Just to not leave out the 10.6+ option for enumerating keys and values using blocks...
[dict enumerateKeysAndObjectsUsingBlock:^(id key, id object, BOOL *stop) {
NSLog(@"%@ = %@", key, object);
}];
If you want the actions to happen concurrently:
[dict enumerateKeysAndObjectsWithOptions:NSEnumerationConcurrent
usingBlock:^(id key, id object, BOOL *stop) {
NSLog(@"%@ = %@", key, object);
}];
open /Applications/PyCharm\ CE.app/
opens up the primary Pycharm Dialogue box to choose the project..
worked for me with macOS 10.13.6
& Pycharm 2018.1
Using the keyword "use" is for shortening namespace literals. You can use both with aliasing and without it. Without aliasing you must use last part of full namespace.
<?php
use foo\bar\lastPart;
$obj=new lastPart\AnyClass(); //If there's not the line above, a fatal error will be encountered.
?>
Two things you need to do, if you want to make a custom button design.
1st is: create a xml resource file in drawable folder (Example: btn_shape_rectangle.xml) then copy and paste the code there.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="16dp"
android:shape="rectangle">
<solid
android:color="#fff"/>
<stroke
android:width="1dp"
android:color="#000000"
/>
<corners android:radius="10dp" />
</shape>
2nd is go to your layout button where you want to implement this design. just link up it. Example: android:background="@drawable/btn_shape_rectangle"
You can change shape color radius what design you want can do.
Hope it will works and help you. Happy Coding
After lots and lots of installing and uninstalling for a whole day and trying every packages for every answers in here, the only thing that worked for me was:
This somehow install something that is needed for Wamp as well.
Best way for this is
function a(){
var d=2;
var c=3;
var f=4;
return {d:d,c:c,f:f}
}
Then use
a().f
return 4
in ES6 you can use this code
function a(){
var d=2;
var c=3;
var f=4;
return {d,c,f}
}
Just special-case it. If you see a numerator of 0 and a denominator of 0, pretend like it has the values you really want.
I have created a libray for pick image from camera or galley and cropping also
Try this,
ImagePro.Java
public class ImagePro
{
public static String TAG = "ImagePro";
Activity activity;
Uri mImageCaptureUri;
public static int CAMERA_CODE = 64;
public static int GALLERY_CODE = 74;
public static int CROPPING_CODE = 84;
private final static int REQUEST_PERMISSION_REQ_CODE = 704;
public ImagePro(Activity activity) {
this.activity = activity;
this.outPutFile = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSION_REQ_CODE);
}
}
private void LogToast(String message) {
try {
Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
Log.d(TAG, message);
}
private void Toast(String message) {
try {
Toast.makeText(activity, message, Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
private void Log(String message) {
Log.d(TAG, message);
}
/**
* This function return captured image path
*
* @param requestCode on activity result requestCode
* @param resultCode on activity result resultCode
* @param intent on activity result intent
* @return ImageDetails values
*/
public ImageDetails getImagePath(int requestCode, int resultCode, Intent intent) {
ImageDetails imageDetails = new ImageDetails();
if(resultCode == Activity.RESULT_OK) {
if(requestCode == CAMERA_CODE) {
imageDetails.setUri(mImageCaptureUri);
imageDetails.setPath(mImageCaptureUri.getPath());
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), mImageCaptureUri);
} catch (IOException e) {
LogToast(e.getMessage());
e.printStackTrace();
}
imageDetails.setBitmap(bitmap);
imageDetails.setFile(new File(mImageCaptureUri.getPath()));
} else if(requestCode == GALLERY_CODE) {
Uri uri = intent.getData();
imageDetails.setUri(uri);
Bitmap bitmap = null;
try {
bitmap = MediaStore.Images.Media.getBitmap(activity.getContentResolver(), uri);
} catch (IOException e) {
LogToast(e.getMessage());
e.printStackTrace();
}
imageDetails.setBitmap(bitmap);
imageDetails.setFile(new File(uri.getPath()));
imageDetails.setPath(uri.getPath());
} else if(requestCode == CROPPING_CODE) {
try {
if(outPutFile.exists()){
imageDetails.setUri(Uri.fromFile(outPutFile));
imageDetails.setFile(outPutFile);
imageDetails.setPath(outPutFile.getPath());
Bitmap photo = decodeFile(outPutFile);
imageDetails.setBitmap(photo);
}
else {
LogToast("Error while save image");
}
} catch (Exception e) {
e.printStackTrace();
LogToast(e.getMessage());
}
}
} else {
LogToast("user cancelled.");
}
return imageDetails;
}
/**
* Open image pick dialog.<br/>
* CAMERA_CODE</br>
* GALLERY_CODE
*/
public void openImagePickOption() {
final CharSequence[] items = { "Capture Photo", "Choose from Gallery", "Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int item) {
if (items[item].equals("Capture Photo")) {
captureImage();
} else if (items[item].equals("Choose from Gallery")) {
pickImage();
} else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
/**
* decode from file to bitmap
* @param f file
* @return Bitmap data
*/
private Bitmap decodeFile(File f) {
try {
// decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(new FileInputStream(f), null, o);
// Find the correct scale value. It should be the power of 2.
final int REQUIRED_SIZE = 512;
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
} catch (FileNotFoundException e) {
Log(e.getMessage());
}
return null;
}
/**
* Capture image using camera <br/>
* REQUEST_CODE = ImagePro.CAMERA_CODE
*/
public void captureImage() {
if(activity != null) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp1.jpg");
mImageCaptureUri = Uri.fromFile(f);
intent.putExtra(MediaStore.EXTRA_OUTPUT, mImageCaptureUri);
activity.startActivityForResult(intent, CAMERA_CODE);
} else {
LogToast("Activity not assigned");
}
}
/**
* pick image from gallery
*/
public void pickImage() {
Intent i = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
activity.startActivityForResult(i, GALLERY_CODE);
}
/**
* cropping the uri image
* @param uri - open cropping dialog using the uri data
*/
public void croppingImage(Uri uri) {
CroppingIMG(uri);
}
int CROP_IMG_X=512;
int CROP_IMG_Y=512;
public void croppingImage(Uri uri, int cropX, int cropY) {
CROP_IMG_X = cropX;
CROP_IMG_Y = cropY;
CroppingIMG(uri);
}
File outPutFile=null;
private void CroppingIMG(Uri uri) {
final ArrayList<CroppingOption> cropOptions = new ArrayList<>();
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setType("image/*");
List<ResolveInfo> list = activity.getPackageManager().queryIntentActivities( intent, 0 );
int size = list.size();
if (size == 0) {
LogToast("Can't find image croping app");
} else {
intent.setData(uri);
intent.putExtra("outputX", CROP_IMG_X);
intent.putExtra("outputY", CROP_IMG_Y);
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("scale", true);
//Create output file here
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(outPutFile));
if (size == 1) {
Intent i = new Intent(intent);
ResolveInfo res = list.get(0);
i.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
activity.startActivityForResult(i, CROPPING_CODE);
} else {
for (ResolveInfo res : list) {
final CroppingOption co = new CroppingOption();
co.title = activity.getPackageManager().getApplicationLabel(res.activityInfo.applicationInfo);
co.icon = activity.getPackageManager().getApplicationIcon(res.activityInfo.applicationInfo);
co.appIntent = new Intent(intent);
co.appIntent.setComponent( new ComponentName(res.activityInfo.packageName, res.activityInfo.name));
cropOptions.add(co);
}
CropingOptionAdapter adapter = new CropingOptionAdapter(activity.getApplicationContext(), cropOptions);
AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle("Choose Cropping App");
builder.setCancelable(false);
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item ) {
activity.startActivityForResult( cropOptions.get(item).appIntent, CROPPING_CODE);
}
});
builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
@Override
public void onCancel( DialogInterface dialog ) {
if (mImageCaptureUri != null ) {
activity.getContentResolver().delete(mImageCaptureUri, null, null );
mImageCaptureUri = null;
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
}
/**
* Capture image using camera<br/>
* REQUEST_CODE = User defined code<br/>
* <br/>
* @param iRequestCode User defined code
*/
public void captureImage(int iRequestCode) {
CAMERA_CODE = iRequestCode;
captureImage();
}
/**
* get path, bitmap, file and uri from image details object
*/
public class ImageDetails {
String path="";
Bitmap bitmap=null;
File file=null;
Uri uri=null;
public Uri getUri() {
return uri;
}
public void setUri(Uri uri) {
this.uri = uri;
}
public String getPath() {
return path;
}
public void setPath(String path) {
this.path = path;
}
public Bitmap getBitmap() {
return bitmap;
}
public void setBitmap(Bitmap bitmap) {
this.bitmap = bitmap;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
}
/**
* Created by DP on 7/12/2016.
*/
public class CroppingOption {
public CharSequence title;
public Drawable icon;
public Intent appIntent;
}
public class CropingOptionAdapter extends ArrayAdapter {
private ArrayList<CroppingOption> mOptions;
private LayoutInflater mInflater;
public CropingOptionAdapter(Context context, ArrayList<CroppingOption> options) {
super(context, R.layout.croping_selector, options);
mOptions = options;
mInflater = LayoutInflater.from(context);
}
@Override
public View getView(int position, View convertView, ViewGroup group) {
if (convertView == null)
convertView = mInflater.inflate(R.layout.croping_selector, null);
CroppingOption item = mOptions.get(position);
if (item != null) {
((ImageView) convertView.findViewById(R.id.img_icon)).setImageDrawable(item.icon);
((TextView) convertView.findViewById(R.id.txt_name)).setText(item.title);
return convertView;
}
return null;
}
}
}
MainActivity.java
ImagePro imagePro;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imagePro = new ImagePro(this);
}
public void onClickUploadImageButton(View view) {
imagePro.openImagePickOption();
}
onActivityResult
if(requestCode == CAMERA_CODE && resultCode == RESULT_OK) {
imageDetails = imagePro.getImagePath(CAMERA_CODE, RESULT_OK, data);
ivCrop.setImageBitmap(imageDetails.getBitmap());
//imageDetails.getPath(), imageDetails.getBitmap(), imageDetails.getUri(), imageDetails.getFile
}
It's not an answer, but...
To get datetime
components individually, better use datetime.timetuple:
time = datetime.now()
time.timetuple()
#-> time.struct_time(
# tm_year=2014, tm_mon=9, tm_mday=7,
# tm_hour=2, tm_min=38, tm_sec=5,
# tm_wday=6, tm_yday=250, tm_isdst=-1
#)
It's now easy to get the parts:
ts = time.timetuple()
ts.tm_year
ts.tm_mon
ts.tm_mday
ts.tm_hour
ts.tm_min
ts.tm_sec
Dirk's method above will absolutely work, but if you're looking for a way to bring in a long string where whitespace/structure is important to preserve (example: a SQL query using RODBC) there is a two step solution.
1) Bring the text string in across multiple lines
long_string <- "this
is
a
long
string
with
whitespace"
2) R will introduce a bunch of \n
characters. Strip those out with strwrap()
, which destroys whitespace, per the documentation:
strwrap(long_string, width=10000, simplify=TRUE)
By telling strwrap to wrap your text to a very, very long row, you get a single character vector with no whitespace/newline characters.
tl;dr: No! Arrow functions and function declarations / expressions are not equivalent and cannot be replaced blindly.
If the function you want to replace does not use this
, arguments
and is not called with new
, then yes.
As so often: it depends. Arrow functions have different behavior than function declarations / expressions, so let's have a look at the differences first:
1. Lexical this
and arguments
Arrow functions don't have their own this
or arguments
binding. Instead, those identifiers are resolved in the lexical scope like any other variable. That means that inside an arrow function, this
and arguments
refer to the values of this
and arguments
in the environment the arrow function is defined in (i.e. "outside" the arrow function):
// Example using a function expression
function createObject() {
console.log('Inside `createObject`:', this.foo);
return {
foo: 42,
bar: function() {
console.log('Inside `bar`:', this.foo);
},
};
}
createObject.call({foo: 21}).bar(); // override `this` inside createObject
_x000D_
// Example using a arrow function
function createObject() {
console.log('Inside `createObject`:', this.foo);
return {
foo: 42,
bar: () => console.log('Inside `bar`:', this.foo),
};
}
createObject.call({foo: 21}).bar(); // override `this` inside createObject
_x000D_
In the function expression case, this
refers to the object that was created inside the createObject
. In the arrow function case, this
refers to this
of createObject
itself.
This makes arrow functions useful if you need to access the this
of the current environment:
// currently common pattern
var that = this;
getData(function(data) {
that.data = data;
});
// better alternative with arrow functions
getData(data => {
this.data = data;
});
Note that this also means that is not possible to set an arrow function's this
with .bind
or .call
.
If you are not very familiar with this
, consider reading
2. Arrow functions cannot be called with new
ES2015 distinguishes between functions that are callable and functions that are constructable. If a function is constructable, it can be called with new
, i.e. new User()
. If a function is callable, it can be called without new
(i.e. normal function call).
Functions created through function declarations / expressions are both constructable and callable.
Arrow functions (and methods) are only callable.
class
constructors are only constructable.
If you are trying to call a non-callable function or to construct a non-constructable function, you will get a runtime error.
Knowing this, we can state the following.
Replaceable:
this
or arguments
..bind(this)
Not replaceable:
this
)arguments
(see below))Lets have a closer look at this using your examples:
Constructor function
This won't work because arrow functions cannot be called with new
. Keep using a function declaration / expression or use class
.
Prototype methods
Most likely not, because prototype methods usually use this
to access the instance. If they don't use this
, then you can replace it. However, if you primarily care for concise syntax, use class
with its concise method syntax:
class User {
constructor(name) {
this.name = name;
}
getName() {
return this.name;
}
}
Object methods
Similarly for methods in an object literal. If the method wants to reference the object itself via this
, keep using function expressions, or use the new method syntax:
const obj = {
getName() {
// ...
},
};
Callbacks
It depends. You should definitely replace it if you are aliasing the outer this
or are using .bind(this)
:
// old
setTimeout(function() {
// ...
}.bind(this), 500);
// new
setTimeout(() => {
// ...
}, 500);
But: If the code which calls the callback explicitly sets this
to a specific value, as is often the case with event handlers, especially with jQuery, and the callback uses this
(or arguments
), you cannot use an arrow function!
Variadic functions
Since arrow functions don't have their own arguments
, you cannot simply replace them with an arrow function. However, ES2015 introduces an alternative to using arguments
: the rest parameter.
// old
function sum() {
let args = [].slice.call(arguments);
// ...
}
// new
const sum = (...args) => {
// ...
};
Related question:
Further resources:
SQL Server 2016 SP2 CU6 and SQL Server 2017 CU12 introduced trace flag 460 in order to return the details of truncation warnings. You can enable it at the query level or at the server level.
Query level
INSERT INTO dbo.TEST (ColumnTest)
VALUES (‘Test truncation warnings’)
OPTION (QUERYTRACEON 460);
GO
Server Level
DBCC TRACEON(460, -1);
GO
From SQL Server 2019 you can enable it at database level:
ALTER DATABASE SCOPED CONFIGURATION
SET VERBOSE_TRUNCATION_WARNINGS = ON;
The old output message is:
Msg 8152, Level 16, State 30, Line 13
String or binary data would be truncated.
The statement has been terminated.
The new output message is:
Msg 2628, Level 16, State 1, Line 30
String or binary data would be truncated in table 'DbTest.dbo.TEST', column 'ColumnTest'. Truncated value: ‘Test truncation warnings‘'.
In a future SQL Server 2019 release, message 2628 will replace message 8152 by default.
DECLARE @dayNumber INT;
SET @dayNumber = DATEPART(DW, GETDATE());
--Sunday = 1, Saturday = 7.
IF(@dayNumber = 1 OR @dayNumber = 7)
PRINT 'Weekend';
ELSE
PRINT 'NOT Weekend';
This may generate wrong results, because the number produced by the weekday datepart depends on the value set by SET DATEFIRST. This sets the first day of the week. So another way is:
DECLARE @dayName VARCHAR(9);
SET @dayName = DATEName(DW, GETDATE());
IF(@dayName = 'Saturday' OR @dayName = 'Sunday')
PRINT 'Weekend';
ELSE
PRINT 'NOT Weekend';
Note that backslashes (
\
) and dollar signs ($
) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string; seeMatcher.replaceAll
. UseMatcher.quoteReplacement(java.lang.String)
to suppress the special meaning of these characters, if desired.
from javadoc.
Here is the code
.showme{ _x000D_
display: none;_x000D_
}_x000D_
.showhim:hover .showme{_x000D_
display : block;_x000D_
}_x000D_
.showhim:hover .ok{_x000D_
display : none;_x000D_
}
_x000D_
<div class="showhim">_x000D_
HOVER ME_x000D_
<div class="showme">hai</div>_x000D_
<div class="ok">ok</div>_x000D_
</div>_x000D_
_x000D_
_x000D_
if setting height to 100% doesn't work, try min-height=100% for div. You still have to set the html tag.
html {
height: 100%;
margin: 0px;
padding: 0px;
position: relative;
}
#fullHeight{
width: 450px;
**min-height: 100%;**
background-color: blue;
}
ls -lart | tail -n +2 #argument means starting with line 2
The HTML5 replaceState is the answer, as already mentioned by Vivart and geo1701. However it is not supported in all browsers/versions. History.js wraps HTML5 state features and provides additional support for HTML4 browsers.
Setting window full height for empty divs
1st solution with absolute positioning - FIDDLE
.div1 {
position: absolute;
top: 0;
bottom: 0;
width: 25%;
}
.div2 {
position: absolute;
top: 0;
left: 25%;
bottom: 0;
width: 75%;
}
2nd solution with static (also can be used a relative) positioning & jQuery - FIDDLE
.div1 {
float: left;
width: 25%;
}
.div2 {
float: left;
width: 75%;
}
$(function(){
$('.div1, .div2').css({ height: $(window).innerHeight() });
$(window).resize(function(){
$('.div1, .div2').css({ height: $(window).innerHeight() });
});
});
This is how graphql-js package detects promises:
function isPromise(value) {
return Boolean(value && typeof value.then === 'function');
}
value
is the returned value of your function. I'm using this code in my project and have no problem so far.
If you want the .wrapper
to be fullscreen, just add the following in the wrapper class:
position: absolute;
width: 100%;
height: 100%;
You can also add top: 0
and left:0
On modern Windows this driver isn't available by default anymore, but you can download as Microsoft Access Database Engine 2010 Redistributable on the MS site. If your app is 32 bits be sure to download and install the 32 bits variant because to my knowledge the 32 and 64 bit variant cannot coexist.
Depending on how your app locates its db driver, that might be all that's needed. However, if you use an UDL file there's one extra step - you need to edit that file. Unfortunately, on a 64bits machine the wizard used to edit UDL files is 64 bits by default, it won't see the JET driver and just slap whatever driver it finds first in the UDL file. There are 2 ways to solve this issue:
C:\Windows\syswow64\rundll32.exe "C:\Program Files (x86)\Common Files\System\Ole DB\oledb32.dll",OpenDSLFile C:\path\to\your.udl
. Note that I could use this technique on a Win7 64 Pro, but it didn't work on a Server 2008R2 (could be my mistake, just mentioning)[oledb]
; Everything after this line is an OLE DB initstring
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Path\To\The\database.mdb;Persist Security Info=False
That should allow your app to start correctly.
data
will return you a string representation of a list, but it is actually still a string. Just check the type of data
with type(data)
. That means if you try using indexing on this string representation of a list as such data['fruits'][0]
, it will return you "[" as it is the first character of data['fruits']
You can do json.loads(data['fruits'])
to convert it back to a Python list so that you can interact with regular list indexing. There are 2 other ways you can convert it back to a Python list suggested here
I think that SYSLOG levels NOTICE and ALERT/EMERGENCY are largely superfluous for application-level logging - while CRITICAL/ALERT/EMERGENCY may be useful alert levels for an operator that may trigger different actions and notifications, to an application admin it's all the same as FATAL. And I just cannot sufficiently distinguish between being given a notice or some information. If the information is not noteworthy, it's not really information :)
I like Jay Cincotta's interpretation best - tracing your code's execution is something very useful in tech support, and putting trace statements into the code liberally should be encouraged - especially in combination with a dynamic filtering mechanism for logging the trace messages from specific application components. However DEBUG level to me indicates that we're still in the process of figuring out what's going on - I see DEBUG level output as a development-only option, not as something that should ever show up in a production log.
There is however a logging level that I like to see in my error logs when wearing the hat of a sysadmin as much as that of tech support, or even developer: OPER, for OPERATIONAL messages. This I use for logging a timestamp, the type of operation invoked, the arguments supplied, possibly a (unique) task identifier, and task completion. It's used when e.g. a standalone task is fired off, something that is a true invocation from within the larger long-running app. It's the sort of thing I want always logged, no matter whether anything goes wrong or not, so I consider the level of OPER to be higher than FATAL, so you can only turn it off by going to totally silent mode. And it's much more than mere INFO log data - a log level often abused for spamming logs with minor operational messages of no historical value whatsoever.
As the case dictates this information may be directed to a separate invocation log, or may be obtained by filtering it out of a large log recording more information. But it's always needed, as historical info, to know what was being done - without descending to the level of AUDIT, another totally separate log level that has nothing to do with malfunctions or system operation, doesn't really fit within the above levels (as it needs its own control switch, not a severity classification) and which definitely needs its own separate log file.
The tab character is \t
. Notice the use of "
instead of '
.
$chunk = "abc\tdef\tghi";
If the string is enclosed in double-quotes ("), PHP will interpret more escape sequences for special characters:
...
\t horizontal tab (HT or 0x09 (9) in ASCII)
Also, let me recommend the fputcsv() function which is for the purpose of writing CSV files.
USING POD
<?php
$username = "root";
$password = "";
$db = "db_name";
$dns = "mysql:host=localhost;dbname=$db;charset=utf8mb4";
$conn = new PDO($dns,$username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "select * from mine where username = ? ";
$stmt1 = $conn->prepare($sql);
$stmt1 -> execute(array($_POST['user']));
$all = $stmt1->fetchAll(); ?>
<div class="controls">
<select data-rel="chosen" name="degree_id" id="selectError">
<?php foreach($all as $nt) { echo "<option value =$nt[id]>$nt[name]</option>";}?>
</select>
</div>
I think what he is trying to say is to use the
getContentPane().setBackground(Color.the_Color_you_want_here)
but if u want to set the color to any other then the JFrame, you use the object.setBackground(Color.the_Color_you_want_here)
Eg:
jPanel.setbackground(Color.BLUE)
SELECT *
FROM table
WHERE some_id = ANY(ARRAY[1, 2])
or ANSI
-compatible:
SELECT *
FROM table
WHERE some_id IN (1, 2)
The ANY
syntax is preferred because the array as a whole can be passed in a bound variable:
SELECT *
FROM table
WHERE some_id = ANY(?::INT[])
You would need to pass a string representation of the array: {1,2}
You are supposed to download the jar files that contain these libraries. Libraries may be used by adding them to the classpath.
For Commons Net you need to download the binary files from Commons Net download page. Then you have to extract the file and add the commons-net-2-2.jar file to some location where you can access it from your application e.g. to /lib.
If you're running your application from the command-line you'll have to define the classpath in the java command: java -cp .;lib/commons-net-2-2.jar myapp
. More info about how to set the classpath can be found from Oracle documentation. You must specify all directories and jar files you'll need in the classpath excluding those implicitely provided by the Java runtime. Notice that there is '.' in the classpath, it is used to include the current directory in case your compiled class is located in the current directory.
For more advanced reading, you might want to read about how to define the classpath for your own jar files, or the directory structure of a war file when you're creating a web application.
If you are using an IDE, such as Eclipse, you have to remember to add the library to your build path before the IDE will recognize it and allow you to use the library.
The ADT plug-in is yet not compatible with 3.6
I have been using Eclipse 3.6 with ADT for the past three months for developing applications on Android. I haven't faced any issues so far. It really good and working fine.
Copy the diff file to the root of your repository, and then do:
git apply yourcoworkers.diff
More information about the apply
command is available on its man page.
By the way: A better way to exchange whole commits by file is the combination of the commands git format-patch
on the sender and then git am
on the receiver, because it also transfers the authorship info and the commit message.
If the patch application fails and if the commits the diff was generated from are actually in your repo, you can use the -3
option of apply
that tries to merge in the changes.
It also works with Unix pipe as follows:
git diff d892531 815a3b5 | git apply
First off: a List
is a Collection
. It is a specialized Collection
, however.
A Collection
is just that: a collection of items. You can add stuff, remove stuff, iterate over stuff and query how much stuff is in there.
A List
adds the information about a defined sequence of stuff to it: You can get the element at position n, you can add an element at position n, you can remove the element at position n.
In a Collection
you can't do that: "the 5th element in this collection" isn't defined, because there is no defined order.
There are other specialized Collections as well, for example a Set
which adds the feature that it will never contain the same element twice.
git reset HEAD~1
if you don't want your changes to be gone(unstaged changes). Change, commit and push again git push -f [origin] [branch]
@ikis, firstly as @Devolus said these are not multiple aruements passed to print()
. Indeed all these arguments passed get
concatenated to form a single String. So print()
does not teakes multiple arguements (a. k. a. var-args). Now the concept that remains to discuss is how print()
prints any type of the arguement passed
to it.
To explain this - toString()
is the secret:
System
is a class, with a static field out
, of type PrintStream
. So you're calling the println(Object x)
method of a
PrintStream
.
It is implemented like this:
public void println(Object x) {
String s = String.valueOf(x);
synchronized (this) {
print(s);
newLine();
}
}
As wee see, it's calling the String.valueOf(Object) method. This is implemented as follows:
public static String valueOf(Object obj) {
return (obj == null) ? "null" : obj.toString();
}
And here you see, that toString()
is called.
So whatever is returned from the toString()
method of that class, same gets printed.
And as we know the toString()
is in Object
class and thus inherits a default iplementation from Object.
ex: Remember when we have a class whose toString()
we override and then we pass that ref variable to print
, what do you see printed? - It's what we return from the toString()
.
I try to get in the habit of using HostingEnvironment
instead of Server
as it works within the context of WCF services too.
HostingEnvironment.MapPath(@"~/App_Data/PriceModels.xml");
The method match() searches a string for a match and returns an Array object.
// Original string
var str = "My cow always gives milk";
// Using index [0] would return<br/>
// "**cow always gives milk**"
str.match(/cow(.*)milk/)**[0]**
// Using index **[1]** would return
// "**always gives**"
str.match(/cow(.*)milk/)[1]
This should do the trick:
image = open("image.png", "wb")
image.write(base64string.decode('base64'))
image.close()
1) You can use standard java utility xjc - ([your java home dir]\bin\xjc.exe). But you need to create .bat (or .sh) script for using it.
e.g. generate.bat:
[your java home dir]\bin\xjc.exe %1 %2 %3
e.g. test-scheme.xsd:
<?xml version="1.0"?>
<xs:schema version="1.0"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
elementFormDefault="qualified"
targetNamespace="http://myprojects.net/xsd/TestScheme"
xmlns="http://myprojects.net/xsd/TestScheme">
<xs:element name="employee" type="PersonInfoType"/>
<xs:complexType name="PersonInfoType">
<xs:sequence>
<xs:element name="firstname" type="xs:string"/>
<xs:element name="lastname" type="xs:string"/>
</xs:sequence>
</xs:complexType>
</xs:schema>
Run .bat file with parameters: generate.bat test-scheme.xsd -d [your src dir]
For more info use this documentation - http://docs.oracle.com/javaee/5/tutorial/doc/bnazg.html
and this - http://docs.oracle.com/javase/6/docs/technotes/tools/share/xjc.html
2) JAXB (xjc utility) is installed together with JDK6 by default.
Try the following command, which I have tested:
$ cp -pv --parents $(git diff --name-only) DESTINATION-DIRECTORY
foreach (DictionaryEntry entry in Hashtable)
{
datagridviewTZ.Rows.Add(entry.Key.ToString(), entry.Value.ToString());
}
The DELIMITER statement changes the standard delimiter which is semicolon ( ;) to another. The delimiter is changed from the semicolon( ;) to double-slashes //.
Why do we have to change the delimiter?
Because we want to pass the stored procedure, custom functions etc. to the server as a whole rather than letting mysql tool to interpret each statement at a time.
It's not officially supported yet.
Edit: It's now supported in modern versions of Android Studio, at least on some platforms.
If you're using an old version of Android Studio which doesn't support the Google Play Store, and you refuse to upgrade, here are two possible workarounds:
Ask your favorite app's maintainers to upload a copy of their app into the Amazon Appstore. Next, install the Appstore onto your Android device. Finally, use the Appstore to install your favorite app.
Or: Do a Web search to find a .apk file for the software you want. For example, if you want to install SleepBot in your Android emulator, you can do a Google Web search for [ SleepBot apk
]. Then use adb install
to install the .apk file.
You can use less code, writing this:
$users = DB::table('really_long_table_name')
->get(array('really_long_table_name.field_very_long_name as short_name'));
And of course if you want to select more fields, just write a "," and add more:
$users = DB::table('really_long_table_name')
->get(array('really_long_table_name.field_very_long_name as short_name', 'really_long_table_name.another_field as other', 'and_another'));
This is very practical when you use a joins complex query
I'm asked this question very frequently, if it's smart to use "Share project..." if a eclipse project has been disconnected from it SVN counterpart in the repository. So, I append my answer to this thread.
The SVN-Team option "Share project ..." is totally fine for projects that exist in SVN and in your Eclipse workspace, even if the Eclipse project is missing the hidden .svn configuration. You can still connect them. Eclipse SVN-implementation (Subclipse/Subversive) will verify if the provided SVN http(s) source is populated. If yes, all existing files will be copied and linked (checked out in SVN terms) to your very personal Eclipse workspace.
Word of caution:
regards, Feder
First, here's some sample data:
set.seed(1)
dat <- data.frame(one = rnorm(15),
two = sample(LETTERS, 15),
three = rnorm(15),
four = runif(15))
dat <- data.frame(lapply(dat, function(x) { x[sample(15, 5)] <- NA; x }))
head(dat)
# one two three four
# 1 NA M 0.80418951 0.8921983
# 2 0.1836433 O -0.05710677 NA
# 3 -0.8356286 L 0.50360797 0.3899895
# 4 NA E NA NA
# 5 0.3295078 S NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595
Here's our replacement:
dat[["four"]][is.na(dat[["four"]])] <- 0
head(dat)
# one two three four
# 1 NA M 0.80418951 0.8921983
# 2 0.1836433 O -0.05710677 0.0000000
# 3 -0.8356286 L 0.50360797 0.3899895
# 4 NA E NA 0.0000000
# 5 0.3295078 S NA 0.9606180
# 6 -0.8204684 <NA> -1.28459935 0.4346595
Alternatively, you can, of course, write dat$four[is.na(dat$four)] <- 0
Posed question
Responding to the question 'what metric should be used for multi-class classification with imbalanced data': Macro-F1-measure. Macro Precision and Macro Recall can be also used, but they are not so easily interpretable as for binary classificaion, they are already incorporated into F-measure, and excess metrics complicate methods comparison, parameters tuning, and so on.
Micro averaging are sensitive to class imbalance: if your method, for example, works good for the most common labels and totally messes others, micro-averaged metrics show good results.
Weighting averaging isn't well suited for imbalanced data, because it weights by counts of labels. Moreover, it is too hardly interpretable and unpopular: for instance, there is no mention of such an averaging in the following very detailed survey I strongly recommend to look through:
Sokolova, Marina, and Guy Lapalme. "A systematic analysis of performance measures for classification tasks." Information Processing & Management 45.4 (2009): 427-437.
Application-specific question
However, returning to your task, I'd research 2 topics:
Commonly used metrics. As I can infer after looking through literature, there are 2 main evaluation metrics:
Yu, April, and Daryl Chang. "Multiclass Sentiment Prediction using Yelp Business."
(link) - note that the authors work with almost the same distribution of ratings, see Figure 5.
Pang, Bo, and Lillian Lee. "Seeing stars: Exploiting class relationships for sentiment categorization with respect to rating scales." Proceedings of the 43rd Annual Meeting on Association for Computational Linguistics. Association for Computational Linguistics, 2005.
(link)
Lee, Moontae, and R. Grafe. "Multiclass sentiment analysis with restaurant reviews." Final Projects from CS N 224 (2010).
(link) - they explore both accuracy and MSE, considering the latter to be better
Pappas, Nikolaos, Rue Marconi, and Andrei Popescu-Belis. "Explaining the Stars: Weighted Multiple-Instance Learning for Aspect-Based Sentiment Analysis." Proceedings of the 2014 Conference on Empirical Methods In Natural Language Processing. No. EPFL-CONF-200899. 2014.
(link) - they utilize scikit-learn for evaluation and baseline approaches and state that their code is available; however, I can't find it, so if you need it, write a letter to the authors, the work is pretty new and seems to be written in Python.
Cost of different errors. If you care more about avoiding gross blunders, e.g. assinging 1-star to 5-star review or something like that, look at MSE; if difference matters, but not so much, try MAE, since it doesn't square diff; otherwise stay with Accuracy.
About approaches, not metrics
Try regression approaches, e.g. SVR, since they generally outperforms Multiclass classifiers like SVC or OVA SVM.
Don't just link to the line numbers! Be sure to use the canonical URL too. Otherwise when that file is updated, you'll have a URL that points to the wrong lines!
How to make a permanent link to the right lines:
Click on the line number you want (like line 18), and the URL in your browser will get a #L18
tacked onto the end. You literally click on the 18
at the left side, not the line of code. Looks like this:
And now your browser's URL looks like this:
https://github.com/git/git/blob/master/README#L18
If you want multiple lines selected, simply hold down the shift key and click a second line number, like line 20. Looks like this:
And now your browser's URL looks like this:
https://github.com/git/git/blob/master/README#L18-L20
Here's the important part:
Now get the canonical url for that particular commit by pressing the y
key. The URL in your browser will change to become something like this:
https://github.com/git/git/blob/5bdb7a78adf2a2656a1915e6fa656aecb45c1fc3/README#L18-L20
That link contains the actual SHA hash for that particular commit, rather than the current version of the file on master
. That means that this link will work forever and not point to lines 18-20 of whatever future version of that file might contain.
Now bask in the glow of your new permanent link. ;-)
update 9/29/2017: As pointed out by @watashiSHUN, github has now made it easier to get the permanent link by providing a ...
menu on the left after you select one or more lines. Please upvote @watashiSHUN's answer too.
update 3/25/2016: Case in point — in the example above, I referred to the "README" file in the URL. Those non-canonical urls actually worked when this answer was written. But now those urls no longer work since README
was moved to README.md
. But the canonical URL with SHA hash still works, just as expected.
Another problem can be that the python version you are using is not yet supported by opencv-python.
E.g. as of right now there is no opencv-python for python 3.8. You would need to downgrade your python to 3.7.5 for now.
It is a string formatting syntax (which it borrows from C).
Please see "PyFormat":
Python supports formatting values into strings. Although this can include very complicated expressions, the most basic usage is to insert values into a string with the
%s
placeholder.
Edit: Here is a really simple example:
#Python2
name = raw_input("who are you? ")
print "hello %s" % (name,)
#Python3+
name = input("who are you? ")
print("hello %s" % (name,))
The %s
token allows me to insert (and potentially format) a string. Notice that the %s
token is replaced by whatever I pass to the string after the %
symbol. Notice also that I am using a tuple here as well (when you only have one string using a tuple is optional) to illustrate that multiple strings can be inserted and formatted in one statement.
try the following example. Image overlay with text on image. demo
<div class="thumbnail">
<img src="https://s3.amazonaws.com/discount_now_staging/uploads/ed964a11-e089-4c61-b927-9623a3fe9dcb/direct_uploader_2F50cc1daf-465f-48f0-8417-b04ac68a999d_2FN_19_jewelry.jpg" alt="..." />
<div class="caption post-content">
</div>
<div class="details">
<h3>Robots!</h3>
<p>Lorem ipsum dolor sit amet</p>
</div>
</div>
css
.post-content {
background: rgba(0, 0, 0, 0.7) none repeat scroll 0 0;
opacity: 0.5;
top:0;
left:0;
min-width: 500px;
min-height: 500px;
position: absolute;
color: #ffffff;
}
.thumbnail{
position:relative;
}
.details {
position: absolute;
z-index: 2;
top: 0;
color: #ffffff;
}
The easiest way to do this would be to put a link on your column headers, pointing to the same page. In the query string, put a variable so that you know what they clicked on, and then use ORDER BY in your SQL query to perform the ordering.
The HTML would look like this:
<th><a href="mypage.php?sort=type">Type:</a></th>
<th><a href="mypage.php?sort=desc">Description:</a></th>
<th><a href="mypage.php?sort=recorded">Recorded Date:</a></th>
<th><a href="mypage.php?sort=added">Added Date:</a></th>
And in the php code, do something like this:
<?php
$sql = "SELECT * FROM MyTable";
if ($_GET['sort'] == 'type')
{
$sql .= " ORDER BY type";
}
elseif ($_GET['sort'] == 'desc')
{
$sql .= " ORDER BY Description";
}
elseif ($_GET['sort'] == 'recorded')
{
$sql .= " ORDER BY DateRecorded";
}
elseif($_GET['sort'] == 'added')
{
$sql .= " ORDER BY DateAdded";
}
$>
Notice that you shouldn't take the $_GET value directly and append it to your query. As some user could got to MyPage.php?sort=; DELETE FROM MyTable;
Consider using a subquery:
from p in context.ParentTable
let cCount =
(
from c in context.ChildTable
where p.ParentId == c.ChildParentId
select c
).Count()
select new { ParentId = p.Key, Count = cCount } ;
If the query types are connected by an association, this simplifies to:
from p in context.ParentTable
let cCount = p.Children.Count()
select new { ParentId = p.Key, Count = cCount } ;
You can get first and last day of previous month (with timestamp) in SQL Server by executing
--select dateadd(dd,-datepart(dd,getdate())+1,dateadd(mm,-1,getdate())) --first day of previous month
--select dateadd(dd,-datepart(dd,getdate()),getdate()) -- last day of previous month**
Since none of the above answers helped me with my problem, here my solution to extract a certain (named) column from each row.
I convert a table into text using the values of some named columns (Yes
, No
, Maybe
) within the named Excel table myTable
on the tab mySheet
using the following (Excel) VBA snippet:
Function Table2text()
Dim NumRows, i As Integer
Dim rngTab As Range
Set rngTab = ThisWorkbook.Worksheets("mySheet").Range("myTable")
' For each row, convert the named columns into an enumeration
For i = 1 To rngTab.Rows.Count
Table2text= Table2text & "- Yes:" & Range("myTable[Yes]")(i).Value & Chr(10)
Table2text= Table2text & "- No: " & Range("myTable[No]")(i).Value & Chr(10)
Table2text= Table2text & "- Maybe: "& Range("myTable[Maybe]")(i).Value & Chr(10) & Chr(10)
Next i
' Finalize return value
Table2text = Table2text & Chr(10)
End Function
We define a range rngTab
over which we loop. The trick is to use Range("myTable[col]")(i)
to extract the entry of column col
in row i
.
var newDate = new Date();
newDate.setTime(unixtime*1000);
dateString = newDate.toUTCString();
Where unixtime
is the time returned by your sql db. Here is a fiddle if it helps.
For example, using it for the current time:
document.write( new Date().toUTCString() );
_x000D_
Same as above, might help some people.
setTimeout(() => {
if (pushToken!=null && deviceId!=null) {
console.log("pushToken & OS ");
this.setState({ pushToken: pushToken});
this.setState({ deviceId: deviceId });
console.log("pushToken & OS "+pushToken+"\n"+deviceId);
}
}, 1000);
Change:
CONVERT(varchar(3), DATEPART(MONTH, S0.OrderDateTime) AS OrderMonth
To:
CONVERT(varchar(3), DATENAME(MONTH, S0.OrderDateTime)) AS OrderMonth
myfun <- function(x, arg1) {
# doing something here with x and arg1
}
x
is a vector or a list and myfun
in lapply(x, myfun)
is called for each element of x
separately.
Option 1
If you'd like to use whole arg1
in each myfun
call (myfun(x[1], arg1)
, myfun(x[2], arg1)
etc.), use lapply(x, myfun, arg1)
(as stated above).
Option 2
If you'd however like to call myfun
to each element of arg1
separately alongside elements of x
(myfun(x[1], arg1[1])
, myfun(x[2], arg1[2])
etc.), it's not possible to use lapply
. Instead, use mapply(myfun, x, arg1)
(as stated above) or apply
:
apply(cbind(x,arg1), 1, myfun)
or
apply(rbind(x,arg1), 2, myfun).
Arrays.copyOf()
method has many options to fix the problem with Array length increasing dynamically.
I just got through fighting with a table that I couldn't make any smaller no matter which element I tried to make smaller the width of the table stayed the same. I searched using firebug but couldn't find the element that was setting the width so high.
Finally I tried changing the size attribute of the input text elements and that fixed it. For some reason the size attribute over-rode the css widths. I was using jQuery to dynamically add rows to a table and it was these rows that contained the inputs. So perhaps when it comes to dynamically adding inputs using the appendTo() function maybe it is better to set the size attribute along with the width.
Here is one solution using java 8:
Stream.of(list1, list2)
.flatMap(Collection::stream)
.distinct()
// .sorted() uncomment if you want sorted list
.collect(Collectors.toList());
I use this mnemonic :
a.compareTo(b) < 0 // a < b
a.compareTo(b) > 0 // a > b
a.compareTo(b) == 0 // a == b
You keep the signs and always compare the result of compareTo()
to 0
Javascript which runs on the client machine can't access the local disk file system due to security restrictions.
If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.
In ST2 there's a package you can install called Default FileType which does just that.
More info here.
console.log is only defined when the console is open. If you want to check for it in your code make sure you check for for it within the window property
if (window.console)
console.log(msg)
this throws an exception in IE9 and will not work correctly. Do not do this
if (console)
console.log(msg)
bool === tool ? bool : tool
if you want the value to hold true if tool
(another boolean) has the same value
As a LinearSegmentedColormaps
is based on a dictionary of red, green and blue, it's necessary to reverse each item:
import matplotlib.pyplot as plt
import matplotlib as mpl
def reverse_colourmap(cmap, name = 'my_cmap_r'):
"""
In:
cmap, name
Out:
my_cmap_r
Explanation:
t[0] goes from 0 to 1
row i: x y0 y1 -> t[0] t[1] t[2]
/
/
row i+1: x y0 y1 -> t[n] t[1] t[2]
so the inverse should do the same:
row i+1: x y1 y0 -> 1-t[0] t[2] t[1]
/
/
row i: x y1 y0 -> 1-t[n] t[2] t[1]
"""
reverse = []
k = []
for key in cmap._segmentdata:
k.append(key)
channel = cmap._segmentdata[key]
data = []
for t in channel:
data.append((1-t[0],t[2],t[1]))
reverse.append(sorted(data))
LinearL = dict(zip(k,reverse))
my_cmap_r = mpl.colors.LinearSegmentedColormap(name, LinearL)
return my_cmap_r
See that it works:
my_cmap
<matplotlib.colors.LinearSegmentedColormap at 0xd5a0518>
my_cmap_r = reverse_colourmap(my_cmap)
fig = plt.figure(figsize=(8, 2))
ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15])
ax2 = fig.add_axes([0.05, 0.475, 0.9, 0.15])
norm = mpl.colors.Normalize(vmin=0, vmax=1)
cb1 = mpl.colorbar.ColorbarBase(ax1, cmap = my_cmap, norm=norm,orientation='horizontal')
cb2 = mpl.colorbar.ColorbarBase(ax2, cmap = my_cmap_r, norm=norm, orientation='horizontal')
EDIT
I don't get the comment of user3445587. It works fine on the rainbow colormap:
cmap = mpl.cm.jet
cmap_r = reverse_colourmap(cmap)
fig = plt.figure(figsize=(8, 2))
ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15])
ax2 = fig.add_axes([0.05, 0.475, 0.9, 0.15])
norm = mpl.colors.Normalize(vmin=0, vmax=1)
cb1 = mpl.colorbar.ColorbarBase(ax1, cmap = cmap, norm=norm,orientation='horizontal')
cb2 = mpl.colorbar.ColorbarBase(ax2, cmap = cmap_r, norm=norm, orientation='horizontal')
But it especially works nice for custom declared colormaps, as there is not a default _r
for custom declared colormaps. Following example taken from http://matplotlib.org/examples/pylab_examples/custom_cmap.html:
cdict1 = {'red': ((0.0, 0.0, 0.0),
(0.5, 0.0, 0.1),
(1.0, 1.0, 1.0)),
'green': ((0.0, 0.0, 0.0),
(1.0, 0.0, 0.0)),
'blue': ((0.0, 0.0, 1.0),
(0.5, 0.1, 0.0),
(1.0, 0.0, 0.0))
}
blue_red1 = mpl.colors.LinearSegmentedColormap('BlueRed1', cdict1)
blue_red1_r = reverse_colourmap(blue_red1)
fig = plt.figure(figsize=(8, 2))
ax1 = fig.add_axes([0.05, 0.80, 0.9, 0.15])
ax2 = fig.add_axes([0.05, 0.475, 0.9, 0.15])
norm = mpl.colors.Normalize(vmin=0, vmax=1)
cb1 = mpl.colorbar.ColorbarBase(ax1, cmap = blue_red1, norm=norm,orientation='horizontal')
cb2 = mpl.colorbar.ColorbarBase(ax2, cmap = blue_red1_r, norm=norm, orientation='horizontal')
Use this:
print '\033[1m' + 'Hello'
And to change back to normal:
print '\033[0m'
This page is a good reference for printing in colors and font-weights. Go to the section that says 'Set graphics mode:'
And note this won't work on all operating systems but you don't need any modules.
Note that you have to be careful if your row contains a factor. Here is an example:
df_1 = data.frame(V1 = factor(11:15),
V2 = 21:25)
df_1[1,] %>% as.numeric() # you expect 11 21 but it returns
[1] 1 21
Here is another example (by default data.frame() converts characters to factors)
df_2 = data.frame(V1 = letters[1:5],
V2 = 1:5)
df_2[3,] %>% as.numeric() # you expect to obtain c 3 but it returns
[1] 3 3
df_2[3,] %>% as.character() # this won't work neither
[1] "3" "3"
To prevent this behavior, you need to take care of the factor, before extracting it:
df_1$V1 = df_1$V1 %>% as.character() %>% as.numeric()
df_2$V1 = df_2$V1 %>% as.character()
df_1[1,] %>% as.numeric()
[1] 11 21
df_2[3,] %>% as.character()
[1] "c" "3"
.currencyinput {_x000D_
border: 1px inset #ccc;_x000D_
padding-bottom: 1px;//FOR IE & Chrome_x000D_
}_x000D_
.currencyinput input {_x000D_
border: 0;_x000D_
}
_x000D_
<span class="currencyinput">$<input type="text" name="currency"></span>
_x000D_
Current Version 1.38.1
I had a problem with intending. The default Command+] is set to 4 and I wanted it to be 2. Installed "Indent 4-to-2" but it changed the entire file and not the selected text.
I changed the tab spacing in settings and it was simple.
Go to Settings
-> Text Editor
-> Tab Size
I faced the same problem when I tried to install Angular.js with bower in my project. I seems bower has lots of javascript files it downloaded automatically which caused my IDE to stuck in validation process for a long time. So, I solved this problem this way,
My IDE currently working without freezing. I took help from there. Tern I guess it can be helpful, where any IDE stuck due to lots of Javascript file.
Had the same issue installing angular material CDK:
npm install --save @angular/material @angular/cdk @angular/animations
Adding -dev
like below worked for me:
npm install --save-dev @angular/material @angular/cdk @angular/animations
You functionally want this:
#include <sys/time.h>
struct timeval tv1, tv2;
gettimeofday(&tv1, NULL);
/* stuff to do! */
gettimeofday(&tv2, NULL);
printf ("Total time = %f seconds\n",
(double) (tv2.tv_usec - tv1.tv_usec) / 1000000 +
(double) (tv2.tv_sec - tv1.tv_sec));
Note that this measures in microseconds, not just seconds.
The only solution I can think of is to install VMWare or any other VT then install OSX on a VM.
It works pretty good for testing.
Here is a simple way to filter any request/response params from the logs using HttpLoggingInterceptor
:
// Request patterns to filter
private static final String[] REQUEST_PATTERNS = {
"Content-Type",
};
// Response patterns to filter
private static final String[] RESPONSE_PATTERNS = {"Server", "server", "X-Powered-By", "Set-Cookie", "Expires", "Cache-Control", "Pragma", "Content-Length", "access-control-allow-origin"};
// Log requests and response
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor(new HttpLoggingInterceptor.Logger() {
@Override
public void log(String message) {
// Blacklist the elements not required
for (String pattern: REQUEST_PATTERNS) {
if (message.startsWith(pattern)) {
return;
}
}
// Any response patterns as well...
for (String pattern: RESPONSE_PATTERNS) {
if (message.startsWith(pattern)) {
return;
}
}
Log.d("RETROFIT", message);
}
});
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
Here is the full gist:
https://gist.github.com/mankum93/179c2d5378f27e95742c3f2434de7168
Just drop the option v
.
-v
is for verbose. If you don't use it then it won't display:
tar -zxf tmp.tar.gz -C ~/tmp1
Or you can just run the following command and you will see all databases of the Redis instance without firing up redis-cli
:
$ redis-cli INFO | grep ^db
db0:keys=1500,expires=2
db1:keys=200000,expires=1
db2:keys=350003,expires=1
That error message usually means that either the password we are using doesn't match what MySQL thinks the password should be for the user we're connecting as, or a matching MySQL user doesn't exist (hasn't been created).
In MySQL, a user is identified by both a username ("test2") and a host ("localhost").
The error message identifies the user ("test2") and the host ("localhost") values...
'test2'@'localhost'
We can check to see if the user exists, using this query from a client we can connect from:
SELECT user, host FROM mysql.user
We're looking for a row that has "test2" for user, and "localhost" for host.
user host
------- -----------
test2 127.0.0.1 cleanup
test2 ::1
test2 localhost
If that row doesn't exist, then the host may be set to wildcard value of %
, to match any other host that isn't a match.
If the row exists, then the password may not match. We can change the password (if we're connected as a user with sufficient privileges, e.g. root
SET PASSWORD FOR 'test2'@'localhost' = PASSWORD('mysecretcleartextpassword')
We can also verify that the user has privileges on objects in the database.
GRANT SELECT ON jobs.* TO 'test2'@'localhost'
EDIT
If we make changes to mysql privilege tables with DML operations (INSERT,UPDATE,DELETE), those changes will not take effect until MySQL re-reads the tables. We can make changes effective by forcing a re-read with a FLUSH PRIVILEGES
statement, executed by a privileged user.
You need to create a C API for exposing the functionality of your C++ code. Basically, you will need to write C++ code that is declared extern "C" and that has a pure C API (not using classes, for example) that wraps the C++ library. Then you use the pure C wrapper library that you've created.
Your C API can optionally follow an object-oriented style, even though C is not object-oriented. Ex:
// *.h file
// ...
#ifdef __cplusplus
#define EXTERNC extern "C"
#else
#define EXTERNC
#endif
typedef void* mylibrary_mytype_t;
EXTERNC mylibrary_mytype_t mylibrary_mytype_init();
EXTERNC void mylibrary_mytype_destroy(mylibrary_mytype_t mytype);
EXTERNC void mylibrary_mytype_doit(mylibrary_mytype_t self, int param);
#undef EXTERNC
// ...
// *.cpp file
mylibrary_mytype_t mylibrary_mytype_init() {
return new MyType;
}
void mylibrary_mytype_destroy(mylibrary_mytype_t untyped_ptr) {
MyType* typed_ptr = static_cast<MyType*>(untyped_ptr);
delete typed_ptr;
}
void mylibrary_mytype_doit(mylibrary_mytype_t untyped_self, int param) {
MyType* typed_self = static_cast<MyType*>(untyped_self);
typed_self->doIt(param);
}
If you don't want to use a function constructor like in Brian's answer you can use Object.create() instead:-
var myVar = {
count: 0
}
myVar.init = function(n) {
this.count = n
this.newDiv()
}
myVar.newDiv = function() {
var newDiv = document.createElement("div")
var contents = document.createTextNode("Click me!")
var func = myVar.func(this)
newDiv.addEventListener ?
newDiv.addEventListener('click', func, false) :
newDiv.attachEvent('onclick', func)
newDiv.appendChild(contents)
document.getElementsByTagName("body")[0].appendChild(newDiv)
}
myVar.func = function (thys) {
return function() {
thys.clickme()
}
}
myVar.clickme = function () {
this.count += 1
alert(this.count)
}
myVar.init(2)
var myVar1 = Object.create(myVar)
myVar1.init(55)
var myVar2 = Object.create(myVar)
myVar2.init(150)
// etc
Strangely, I couldn't get the above to work using newDiv.onClick, but it works with newDiv.addEventListener / newDiv.attachEvent.
Since Object.create is newish, include the following code from Douglas Crockford for older browsers, including IE8.
if (typeof Object.create !== 'function') {
Object.create = function (o) {
function F() {}
F.prototype = o
return new F()
}
}
In my case the reason was fairly trivial.
I had known that the SSL verification had worked until a few days earlier, and was infact working on a different machine.
My next step was to compare the certificate contents and size between the machine on which verification was working, and the one on which it was not.
This quickly led to me determining that the Certificate on the 'incorrectly' working machine was not good, and once I replaced it with the 'good' cert, everything was fine.
Use JodaTime for this. It is much better than the standard Java DateTime Apis. Here is the code in JodaTime for calculating difference in days:
private static void dateDiff() {
System.out.println("Calculate difference between two dates");
System.out.println("=================================================================");
DateTime startDate = new DateTime(2000, 1, 19, 0, 0, 0, 0);
DateTime endDate = new DateTime();
Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
System.out.println(" Difference between " + endDate);
System.out.println(" and " + startDate + " is " + days + " days.");
}
This one worked for me, in startup.bat
the following line needs to be added if it doesn't exist set JAVA_OPTS
with the value -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256
. The full line:
set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256
I did something similar with this construct
$('li').each(function(){
if(this.id){
this.id = this.id+"something";
}
});
The only way is to modify the file src/http/ngx_http_header_filter_module.c . I changed nginx on line 48 to a different string.
What you can do in the nginx config file is to set server_tokens to off. This will prevent nginx from printing the version number.
To check things out, try curl -I http://vurbu.com/ | grep Server
It should return
Server: Hai
git --work-tree=/tmp/files_without_dot_git clone --depth=1 \
https://git.yourgit.your.com/myawesomerepo.git \
/tmp/deleteme_contents_of_dot_git
Both the directories in /tmp are created on the fly. No need to pre-create these.
Simply go to the directory where the troubling file is, type touch *
without quotes in the console, and you should be good.
Since you are probably running Windows (from looking at your tags), this would be the easiest way to open and show an image file from the console without installing extra stuff like PIL.
import os
os.system('start pic.png')
I think this does a good job of explaining.
The following is a UNION query that uses an ORDER BY clause:
select supplier_id, supplier_name
from suppliers
where supplier_id > 2000
UNION
select company_id, company_name
from companies
where company_id > 1000
ORDER BY 2;
Since the column names are different between the two "select" statements, it is more advantageous to reference the columns in the ORDER BY clause by their position in the result set.
In this example, we've sorted the results by supplier_name
/ company_name
in ascending order, as denoted by the "ORDER BY 2".
The supplier_name
/ company_name
fields are in position #2 in the
result set.
Taken from here: http://www.techonthenet.com/sql/union.php
The modern approach uses the java.time classes.
YearMonth.from(
ZonedDateTime.parse(
"Mon Mar 14 16:02:37 GMT 2011" ,
DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" )
)
).toString()
2011-03
The modern way is with java.time classes. The old date-time classes such as Calendar
have proven to be poorly-designed, confusing, and troublesome.
Define a custom formatter to match your string input.
String input = "Mon Mar 14 16:02:37 GMT 2011";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" );
Parse as a ZonedDateTime
.
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
You are interested in the year and month. The java.time classes include YearMonth
class for that purpose.
YearMonth ym = YearMonth.from( zdt );
You can interrogate for the year and month numbers if needed.
int year = ym.getYear();
int month = ym.getMonthValue();
But the toString
method generates a string in standard ISO 8601 format.
String output = ym.toString();
Put this all together.
String input = "Mon Mar 14 16:02:37 GMT 2011";
DateTimeFormatter f = DateTimeFormatter.ofPattern( "E MMM d HH:mm:ss z uuuu" );
ZonedDateTime zdt = ZonedDateTime.parse( input , f );
YearMonth ym = YearMonth.from( zdt );
int year = ym.getYear();
int month = ym.getMonthValue();
Dump to console.
System.out.println( "input: " + input );
System.out.println( "zdt: " + zdt );
System.out.println( "ym: " + ym );
input: Mon Mar 14 16:02:37 GMT 2011
zdt: 2011-03-14T16:02:37Z[GMT]
ym: 2011-03
See this code running in IdeOne.com.
If you must have a Calendar
object, you can convert to a GregorianCalendar
using new methods added to the old classes.
GregorianCalendar gc = GregorianCalendar.from( zdt );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
Rule of handling check and unchecked exceptions on overridden methods
-When parent-class method declares no exception, then child-class overriding- method can declare,
1. No exception or
2. Any number of unchecked exception
3. but strictly no checked exception
-When parent-class method declares unchecked exception, then child-class overriding-method can declare,
1. No exception or
2. Any number of unchecked exception
3. but strictly no checked exception
-When parent-class method declares checked exception, then child-class overriding-method can declare,
1. No exception or
2. Same checked exception or
3. Sub-type of checked exception or
4. any number of unchecked exception
All above conclusion hold true, even if combination of both checked & unchecked exception is declared in parent-class’ method
When we try to add an object to the arraylist,
Java checks to ensure that there is enough capacity in the existing array to hold the new object. If not, a new array of a greater size is created, the old array is copied to new array using Arrays.copyOf and the new array is assigned to the existing array.
Look at the code below (taken from Java ArrayList Code at GrepCode.com).
Edit:
public ArrayList() Constructs an empty list with an initial capacity of ten.
public ArrayList(int initialCapacity) we can specify initial capacity.
public ArrayList(Collection c) Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator.
Now when we use ArrayList() constructore we get a ArrayList with Size=10 On adding 11th element in the list new Arraylist is created inside ensureCapacity() method.
Using following formula:
int newCapacity= (oldCapacity * 3)/2 +1;
This happened to me when I created a CSV file with OpenOffice Calc. It didn't happen when I created the CSV file in my text editor, even if I later edited it with Calc.
I solved my problem by copy-pasting in my text editor the data from my Calc-created file to a new editor-created file.
In order to remotely access a PostgreSQL database, you must set the two main PostgreSQL configuration files:
postgresql.conf
pg_hba.conf
Here is a brief description about how you can set them (note that the following description is purely indicative: To configure a machine safely, you must be familiar with all the parameters and their meanings)
First of all configure PostgreSQL service to listen on port 5432 on all network interfaces in Windows 7 machine:
open the file postgresql.conf
(usually located in C:\Program Files\PostgreSQL\9.2\data) and sets the parameter
listen_addresses = '*'
Check the network address of WindowsXP virtual machine, and sets parameters in pg_hba.conf file (located in the same directory of postgresql.conf) so that postgresql can accept connections from virtual machine hosts.
For example, if the machine with Windows XP have 192.168.56.2 IP address, add in the pg_hba.conf
file:
host all all 192.168.56.1/24 md5
this way, PostgreSQL will accept connections from all hosts on the network 192.168.1.XXX.
Restart the PostgreSQL service in Windows 7 (Services-> PosgreSQL 9.2: right click and restart sevice). Install pgAdmin on windows XP machine and try to connect to PostgreSQL.
maxRequestLength (length in KB) Here as ex. I took 1024 (1MB) maxAllowedContentLength (length in Bytes) should be same as your maxRequestLength (1048576 bytes = 1MB).
<system.web>
<httpRuntime maxRequestLength="1024" executionTimeout="3600" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1048576"/>
</requestFiltering>
</security>
</system.webServer>
Here is another one, I think. Just for reference. Let's set a variable to be an instantance of class StringVar
If you program Tk using the Tcl language, you can ask the system to let you know when a variable is changed. The Tk toolkit can use this feature, called tracing, to update certain widgets when an associated variable is modified.
There’s no way to track changes to Python variables, but Tkinter allows you to create variable wrappers that can be used wherever Tk can use a traced Tcl variable.
text = StringVar()
self.depositLabel = Label(self.__mainWindow, text = self.labelText, textvariable = text)
^^^^^^^^^^^^^^^^^
def depositCallBack(self,event):
text.set('change the value')
Intent myIntent = new Intent(MainActivity.this, Katra_home.class);
startActivity(myIntent);
This Should the perfect one :)
Basically, a webservice is a method of communication between two machines while an API is an exposed layer allowing you to program against something.
You could very well have an API and the main method of interacting with that API is via a webservice.
The technical definitions (courtesy of Wikipedia) are:
An application programming interface (API) is a set of routines, data structures, object classes and/or protocols provided by libraries and/or operating system services in order to support the building of applications.
A Web service (also Web Service) is defined by the W3C as "a software system designed to support interoperable machine-to-machine interaction over a network"
Use rowspan
if you want to extend cells down and colspan
to extend across.
For the Windows OS, I used Fiddler to work around the issue.
Run gem:
$ gem install --http-proxy http://localhost:8888 $gem_name
In order to trap repeated clicks on the same cell, you need to move the focus to a different cell, so that each time you click, you are in fact moving the selection.
The code below will select the top left cell visible on the screen, when you click on any cell. Obviously, it has the flaw that it won't trap a click on the top left cell, but that can be managed (eg by selecting the top right cell if the activecell is the top left).
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'put your code here to process the selection, then..
ActiveWindow.VisibleRange.Cells(1, 1).Select
End Sub
That's probably a requireJS module definition
Check here for more details
RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node. Using a modular script loader like RequireJS will improve the speed and quality of your code.
This seems to work with closed file: add a pivot table (rows, tabular layout, no subtotals, no grand totals) of the source to the current workbook, then reference all you want from that pivot table, INDIRECT, LOOKUPs,...
Just use:
Focus.of(context).unfocus();
All about Focus in Flutter here -> enter link description here
I wanted to write this as a comment but I do not have 50 reputation.
All of the answers in this thread are essentially to use Invoke-Item or to use explorer.exe directly; however, this isn't completely synonymous with "open containing folder", so in terms of opening an Explorer window as the question states, if we wanted to apply the answer to a particular file the question still hasn't really been answered.
e.g.,
Invoke-Item C:\Users\Foo\bar.txt
explorer.exe C:\Users\Foo\bar.html
^ those two commands would result in Notepad.exe or Firefox.exe being invoked on the two files respectively, not an explorer.exe window on C:\Users\Foo\ (the containing directory).
Whereas if one was issuing this command from powershell, this would be no big deal (less typing anyway), if one is scripting and needs to "open containing folder" on a variable, it becomes a matter of string matching to extract the directory from the full path to the file.
Is there no simple command "Open-Containing-Folder" such that a variable could be substituted?
e.g.,
$foo = "C:\Users\Foo\foo.txt"
[some code] $fooPath
# opens C:\Users\Foo\ and not the default program for .txt file extension
You may also try the Copy method:
File.Copy(@"c:\work\foo.txt", @"c:\data\bar.txt")
Segmentation fault is a specific kind of error caused by accessing memory that “does not belong to you.” It’s a helper mechanism that keeps you from corrupting the memory and introducing hard-to-debug memory bugs. Whenever you get a segfault you know you are doing something wrong with memory – accessing a variable that has already been freed, writing to a read-only portion of the memory, etc. Segmentation fault is essentially the same in most languages that let you mess with memory management, there is no principal difference between segfaults in C and C++.
There are many ways to get a segfault, at least in the lower-level languages such as C(++). A common way to get a segfault is to dereference a null pointer:
int *p = NULL;
*p = 1;
Another segfault happens when you try to write to a portion of memory that was marked as read-only:
char *str = "Foo"; // Compiler marks the constant string as read-only
*str = 'b'; // Which means this is illegal and results in a segfault
Dangling pointer points to a thing that does not exist anymore, like here:
char *p = NULL;
{
char c;
p = &c;
}
// Now p is dangling
The pointer p
dangles because it points to the character variable c
that ceased to exist after the block ended. And when you try to dereference dangling pointer (like *p='A'
), you would probably get a segfault.
Simon Howard's answer is great. But /\%81v.\+/
fails to highlight tabs that exceed column 81 . So I did a little tweak, based on the stuff I found on VIM wiki and HS's choice of colors above:
highlight OverLength ctermbg=darkred ctermfg=white guibg=#FFD9D9
match OverLength /\%>80v.\+/
And now VIM will highlight anything that exceeds column 80.
I'm a PHP developer and to be able to work on my development environment with a certificate, I was able to do the same by finding the real SSL HTTPS/HTTP Certificate and deleting it.
The steps are :
You can find more information at : http://classically.me/blogs/how-clear-hsts-settings-major-browsers
Although this solution is not the best, Chrome currently does not have any good solution for the moment. I have escalated this situation with their support team to help improve user experience.
Edit : you have to repeat the steps every time you will go on the production site.
You can override the IIS default document setting using the web.config
<system.webServer>
<defaultDocument>
<files>
<clear />
<add value="DefaultPageToBeSet.aspx" />
</files>
</defaultDocument>
</system.webServer>
Or using the IIS, refer the link for reference http://www.iis.net/configreference/system.webserver/defaultdocument
If you have multiple references to a particular variable i.e. User or IdentityFile, the first entry in the ssh config file always takes precedence, if you want something specific then put it in first, anything generic put it at the bottom.
You can put it in a different class and then call a function. This works when ajax refresh
$(document).on("change", ".inputQty", function(e) {
//Call a function(input,input);
});
Adapted from CodeReview, here is a variant which works with num=1
!
from itertools import product
import operator
def prod(ls):
return reduce(operator.mul, ls, 1)
def powered(factors, powers):
return prod(f**p for (f,p) in zip(factors, powers))
def divisors(num) :
pf = dict(prime_factors(num))
primes = pf.keys()
#For each prime, possible exponents
exponents = [range(i+1) for i in pf.values()]
return (powered(primes,es) for es in product(*exponents))
You can concatenate an array of values together using PowerShell's `-join' operator. Here is an example:
$FilePath = '{0}\temp\scripts\pshell\dump.txt' -f $env:SystemDrive;
$Computer = 'pc1';
$Speed = 9001;
$RegCheck = $true;
$Computer,$Speed,$RegCheck -join ',' | Out-File -FilePath $FilePath -Append -Width 200;
Output
pc1,9001,True
Couldn't you just have another sub that acts as a caller using module level variable(s) for the arguments you want to pass. For example...
Option Explicit
Public strMsg As String
Sub Scheduler()
strMsg = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
Application.OnTime Now + TimeValue("00:00:01"), "'Caller'"
End Sub
Sub Caller()
Call aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa("It Works! " & strMsg)
End Sub
Sub aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa(strMessage As String)
MsgBox strMessage
End Sub
Like nearly everyone else said, go to file -> Import Settings.
But if you don't see the "Import Settings" option under the file menu, you need to disable 2 plugins : IDE Settings Sync and Settings Repository
This works for me:
convert original.png -fuzz 10% -transparent white transparent.png
where the smaller the fuzz %, the closer to true white or conversely, the larger the %, the more variation from white is allowed to become transparent
If you have an Eloquent Relationship between your models you can do something like that:
@foreach ($ships as $ship)
<select name="data[]" class="form-control" multiple>
@foreach ($goods_containers as $container)
<option value="{{ $container->id }}"
@if ($ship->containers->contains('container_id',$container->id ) ))
selected="selected"
@endif
>{{ $container->number}}</option>
@endforeach
</select>
@endforeach
Try this, I hope it helps you.
if (lstCustumers.Any(cus => cus.Firstname == "John"))
{
//TODO CODE
}
If you want to edit the decoded JSON, try getting it as an associative array instead of an array of objects.
$data = json_decode($json, TRUE);
From other post:
find /c "string" file >NUL
if %errorlevel% equ 1 goto notfound
echo found
goto done
:notfound
echo notfound
goto done
:done
Use the /i switch when you want case insensitive checking:
find /i /c "string" file >NUL
Or something like: if not found write to file.
find /c "%%P" file.txt || ( echo %%P >> newfile.txt )
Or something like: if found write to file.
find /c "%%P" file.txt && ( echo %%P >> newfile.txt )
Or something like:
find /c "%%P" file.txt && ( echo found ) || ( echo not found )
Remove the quotes here:
is:
ORDER BY = 'post_datetime DESC' AND LIMIT = '3'
Should be:
ORDER BY post_datetime DESC LIMIT 3
For your case, you may use regex:
boolean checkFormat;
if (input.matches("([0-9]{2})/([0-9]{2})/([0-9]{4})"))
checkFormat=true;
else
checkFormat=false;
For a larger scope or if you want a flexible solution, refer to MadProgrammer's answer.
Almost 5 years after posting this answer, I realize that this is a stupid way to validate a date format. But i'll just leave this here to tell people that using regex to validate a date is unacceptable
<content>(?:[^\n]*(\n+))+</content>
You can rename a file using git
's mv
command:
$ git mv file_from file_to
Example:
$ git mv helo.txt hello.txt
$ git status
# On branch master
# Changes to be committed:
# (use "git reset HEAD <file>..." to unstage)
#
# renamed: helo.txt -> hello.txt
#
$ git commit -m "renamed helo.txt to hello.txt"
[master 14c8c4f] renamed helo.txt to hello.txt
1 files changed, 0 insertions(+), 0 deletions(-)
rename helo.txt => hello.txt (100%)
Here is another option
$array = [1=>'one', 2=>'two', 3=>'there'];
$array = array_flip($array);
echo $array['one'];
Queue
is an interface in java, you could not do that.
try:
Queue<Integer> Q = new LinkedList<Integer>();
pep8 was recently added to PyPi.
It is now super easy to check your code against pep8.
If you want to edit that file (or any file in generally), you can't edit it simply writing its name in terminal. You must to use a command to a text editor to do this. For example:
nano ~/.bashrc
or
gedit ~/.bashrc
And in general, for any type of file:
xdg-open ~/.bashrc
Writing only ~/.bashrc
in terminal, this will try to execute that file, but .bashrc
file is not meant to be an executable file. If you want to execute the code inside of it, you can source it like follow:
source ~/.bashrc
or simple:
. ~/.bashrc
Maybe I'm a bit of late to answer this question, but I'm working on this subject at my job :)
I wanted to write column 'a_code' = c1,c2,c3,c4...
Firstly I opened a column with the name ref_id
and the type serial
.
Then I solved my problem with this command:
update myschema.mytable set a_code=cast('c'||"ref_id" as text)
I think you're talking about the logical meaning of both operators, here you have a table-resume:
boolean a, b;
Operation Meaning Note
--------- ------- ----
a && b logical AND short-circuiting
a || b logical OR short-circuiting
a & b boolean logical AND not short-circuiting
a | b boolean logical OR not short-circuiting
a ^ b boolean logical exclusive OR
!a logical NOT
short-circuiting (x != 0) && (1/x > 1) SAFE
not short-circuiting (x != 0) & (1/x > 1) NOT SAFE
Short-circuit evaluation, minimal evaluation, or McCarthy evaluation (after John McCarthy) is the semantics of some Boolean operators in some programming languages in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression: when the first argument of the AND function evaluates to false, the overall value must be false; and when the first argument of the OR function evaluates to true, the overall value must be true.
Not Safe means the operator always examines every condition in the clause, so in the examples above, 1/x may be evaluated when the x is, in fact, a 0 value, raising an exception.
How about using the same for technique for "fooling" the validator with Javascript by sticking a target attribute in XHTML <a onclick="this.target='_blank'">
?
<iframe onload = " this.frameborder='0' " src="menu.html" id="menu"> </iframe>
Or getElementsByTagName]("iframe")
1 adding this attribute for all iframes on the page?
Haven't tested this because I've done something which means that nothing is working in IE less than 9! :) So while I'm sorting that out ... :)
How do I change Android Studio editor's background color?
Changing Editor's Background
Open Preference > Editor (In IDE Settings Section) > Colors & Fonts > Darcula or Any item available there
IDE will display a dialog like this, Press 'No'
Darcula color scheme has been set for editors. Would you like to set Darcula as default Look and Feel?
Changing IDE's Theme
Open Preference > Appearance (In IDE Settings Section) > Theme > Darcula or Any item available there
Press OK. Android Studio will ask you to restart the IDE.
Have a look at <openssl/pem.h>
. It gives possible BEGIN markers.
Copying the content from the above link for quick reference:
#define PEM_STRING_X509_OLD "X509 CERTIFICATE"
#define PEM_STRING_X509 "CERTIFICATE"
#define PEM_STRING_X509_PAIR "CERTIFICATE PAIR"
#define PEM_STRING_X509_TRUSTED "TRUSTED CERTIFICATE"
#define PEM_STRING_X509_REQ_OLD "NEW CERTIFICATE REQUEST"
#define PEM_STRING_X509_REQ "CERTIFICATE REQUEST"
#define PEM_STRING_X509_CRL "X509 CRL"
#define PEM_STRING_EVP_PKEY "ANY PRIVATE KEY"
#define PEM_STRING_PUBLIC "PUBLIC KEY"
#define PEM_STRING_RSA "RSA PRIVATE KEY"
#define PEM_STRING_RSA_PUBLIC "RSA PUBLIC KEY"
#define PEM_STRING_DSA "DSA PRIVATE KEY"
#define PEM_STRING_DSA_PUBLIC "DSA PUBLIC KEY"
#define PEM_STRING_PKCS7 "PKCS7"
#define PEM_STRING_PKCS7_SIGNED "PKCS #7 SIGNED DATA"
#define PEM_STRING_PKCS8 "ENCRYPTED PRIVATE KEY"
#define PEM_STRING_PKCS8INF "PRIVATE KEY"
#define PEM_STRING_DHPARAMS "DH PARAMETERS"
#define PEM_STRING_DHXPARAMS "X9.42 DH PARAMETERS"
#define PEM_STRING_SSL_SESSION "SSL SESSION PARAMETERS"
#define PEM_STRING_DSAPARAMS "DSA PARAMETERS"
#define PEM_STRING_ECDSA_PUBLIC "ECDSA PUBLIC KEY"
#define PEM_STRING_ECPARAMETERS "EC PARAMETERS"
#define PEM_STRING_ECPRIVATEKEY "EC PRIVATE KEY"
#define PEM_STRING_PARAMETERS "PARAMETERS"
#define PEM_STRING_CMS "CMS"
function CheckValidAmount() {
var amounttext = document.getElementById('txtRemittanceNumber').value;
if (!(/^[-+]?\d*\.?\d*$/.test(amounttext))){
alert('Please enter only numbers into amount textbox.')
document.getElementById('txtRemittanceNumber').value = "10.00";
}
}
This is the function which will take decimal number with any number of decimal places and without any decimal places.
Thanks ... :)
I know this is old but this seems to work well for me in 2020...
Using the border-image CSS property I was able to quickly manipulate the borders for this fading purpose.
Note: I don't think border-image
works well with border-radius
... I seen someone saying that somewhere but for this purpose it works well.
1 Liner:
CSS
.bbdr_rfade_1 { border: 4px solid; border-image: linear-gradient(90deg, rgba(60,74,83,0.90), rgba(60,74,83,.00)) 1; border-left:none; border-top:none; border-right:none; }
HTML
<div class = 'bbdr_rfade_1'>Oh I am so going to not up-vote this guy...</div>
extension UIApplication {
/// The top most view controller
static var topMostViewController: UIViewController? {
return UIApplication.shared.keyWindow?.rootViewController?.visibleViewController
}
}
extension UIViewController {
/// The visible view controller from a given view controller
var visibleViewController: UIViewController? {
if let navigationController = self as? UINavigationController {
return navigationController.topViewController?.visibleViewController
} else if let tabBarController = self as? UITabBarController {
return tabBarController.selectedViewController?.visibleViewController
} else if let presentedViewController = presentedViewController {
return presentedViewController.visibleViewController
} else {
return self
}
}
}
With this you can easily get the top post view controller like so
let viewController = UIApplication.topMostViewController
One thing to note is that if there's a UIAlertController currently being displayed, UIApplication.topMostViewController
will return a UIAlertController
.
The fastest, easiest way to do this is to use the --exec argument of git rebase:
git rebase -i -p --exec 'git commit --amend --reset-author --no-edit'
This will create a todo-list that looks like this:
pick ef11092 Blah blah blah
exec git commit --amend --reset-author --no-edit
pick 52d6391 Blah bloh bloo
exec git commit --amend --reset-author --no-edit
pick 30ebbfe Blah bluh bleh
exec git commit --amend --reset-author --no-edit
...
and this will work all automatically, which works when you have hundreds of commits.
This should work:
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"
I know this is late to the party, however I thought I would share the solution I use for DLL's.
I am more of the K.I.S.S. school of thinking, so when I have a .NET DLL that wants to store external data points that control how it works or where it goes, etc. I simply create a "config" class that has only public properties that store all the data points it needs and that I would like to be able to have controlled external to the DLL to prevent recompiling it to make the changes. Then I use .Net's XML Serializing to save and load the object representation of the class to a file.
There are a lot of ways then to handle reading it and accessing it, from a Singleton, a static utility class, to extension methods, etc. This depends on how your DLL is structured and what method will fit your DLL best.
This should do it:
[entry for tag in tags for entry in entries if tag in entry]
Separate with commas:
http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505
or:
http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505
Either way, your method signature needs to be:
@RequestMapping(value = "/GetJson", method = RequestMethod.GET)
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
//code to get results from db for those params.
}
Seriously try some of these, you can choose fixed width or more fluid layouts, the choice is yours! Really easy to implement too.
Microsoft has their own Command Line Standard specification:
This document is focused at developers of command line utilities. Collectively, our goal is to present a consistent, composable command line user experience. Achieving that allows a user to learn a core set of concepts (syntax, naming, behaviors, etc) and then be able to translate that knowledge into working with a large set of commands. Those commands should be able to output standardized streams of data in a standardized format to allow easy composition without the burden of parsing streams of output text. This document is written to be independent of any specific implementation of a shell, set of utilities or command creation technologies; however, Appendix J - Using Windows Powershell to implement the Microsoft Command Line Standard shows how using Windows PowerShell will provide implementation of many of these guidelines for free.
how about this?
fun <- function(x, ...){
y=NULL
parms=list(...)
for (name in names(parms) ) {
assign(name, parms[[name]])
}
print(is.null(y))
}
Then try:
> fun(1,y=4)
[1] FALSE
> fun(1)
[1] TRUE
Stumbled upon this question while checking for correct code for duplicate record.
Pardon my ignorance but I don't understand why everyone is ignoring the code "300" which clearly says "multiple choice" or "Ambiguous"
In my opinion this would be the perfect code for building a non standard or a particular system for your own use. I could be wrong as well!
Hash tables are O(1)
average and amortized case complexity, however it suffers from O(n)
worst case time complexity. [And I think this is where your confusion is]
Hash tables suffer from O(n)
worst time complexity due to two reasons:
O(n)
time.However, it is said to be O(1)
average and amortized case because:
O(n)
, can at most happen after n/2
ops, which are all assumed O(1)
: Thus when you sum the average time per op, you get : (n*O(1) + O(n)) / n) = O(1)
Note because of the rehashing issue - a realtime applications and applications that need low latency - should not use a hash table as their data structure.
EDIT: Annother issue with hash tables: cache
Another issue where you might see a performance loss in large hash tables is due to cache performance. Hash Tables suffer from bad cache performance, and thus for large collection - the access time might take longer, since you need to reload the relevant part of the table from the memory back into the cache.
Assure you have used method="post" in the form you are sending data from.
you can detect offline cross-browser way easily like below
var randomValue = Math.floor((1 + Math.random()) * 0x10000)
$.ajax({
type: "HEAD",
url: "http://yoururl.com?rand=" + randomValue,
contentType: "application/json",
error: function(response) { return response.status == 0; },
success: function() { return true; }
});
you can replace yoururl.com by document.location.pathname
.
The crux of the solution is, try to connect to your domain name, if you are not able to connect - you are offline. works cross browser.
Could they make it any harder? Here's what I did: open system properties, click on advanced, add the environment variable, shut down visual studio and start it up again.
Your HTML and the way you call the function from the button look correct.
The problem appears to be in the CapacityCount
function. I'm getting this error in my console on Firefox 3.5: "document.all is undefined" on line 759 of bendelcorp.js.
Edit:
Looks like document.all
is an IE-only thing and is a nonstandard way of accessing the DOM. If you use document.getElementById()
, it should probably work. Example: document.getElementById("RUnits").value
instead of document.all.Capacity.RUnits.value
So the base idea is that you are running a UI operation on a fragment that is getting in the onDetach lifecycle.
When this is happening the fragment is getting off the stack and losing the context of the Activity.
So when you call UI related functions for example calling the progress spinner and you want to leave the fragment check if the Fragment is added to the stack, like this:
if(isAdded){ progressBar.visibility=View.VISIBLE }
var fileInput = $('#uploadCaptureInputFile');
fileInput.replaceWith(fileInput.val('').clone(true));