try this:
$(window).unbind('scroll');
it works in my project
Run this command to show ip4 and ip6:
ifconfig eth0 | grep inet | awk '{print $2}' | cut -d/ -f1
I came up with this solution.
Click to view image of blurry effect
It is kind of a trick which uses an absolutely positioned child div
, sets its background image same as the parent div
and then uses the background-attachment:fixed
CSS property together with the same background
properties set on the parent element.
Then you apply filter:blur(10px)
(or any value) on the child div.
*{
margin:0;
padding:0;
box-sizing: border-box;
}
.background{
position: relative;
width:100%;
height:100vh;
background-image:url('https://images.unsplash.com/photo-1547937414-009abc449011?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80');
background-size:cover;
background-position: center;
background-repeat:no-repeat;
}
.blur{
position: absolute;
top:0;
left:0;
width:50%;
height:100%;
background-image:url('https://images.unsplash.com/photo-1547937414-009abc449011?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1350&q=80');
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed;
background-size:cover;
filter:blur(10px);
transition:filter .5s ease;
backface-visibility: hidden;
}
.background:hover .blur{
filter:blur(0);
}
.text{
display: inline-block;
font-family: sans-serif;
color:white;
font-weight: 600;
text-align: center;
position: relative;
left:25%;
top:50%;
transform:translate(-50%,-50%);
}
_x000D_
<head>
<title>Blurry Effect</title>
</head>
<body>
<div class="background">
<div class="blur"></div>
<h1 class="text">This is the <br>blurry side</h1>
</div>
</body>
_x000D_
The following list contains links to the the enhancements pages in the Java SE 7.
Swing
IO and New IO
Networking
Security
Concurrency Utilities
Rich Internet Applications (RIA)/Deployment
Requesting and Customizing Applet Decoration in Dragg able Applets
Embedding JNLP File in Applet Tag
Deploying without Codebase
Handling Applet Initialization Status with Event Handlers
Java 2D
Java XML – JAXP, JAXB, and JAX-WS
Internationalization
java.lang Package
Multithreaded Custom Class Loaders in Java SE 7
Java Programming Language
Binary Literals
Strings in switch Statements
The try-with-resources Statement
Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking
Underscores in Numeric Literals
Type Inference for Generic Instance Creation
Improved Compiler Warnings and Errors When Using Non-Reifiable Formal Parameters with Varargs Methods
Java Virtual Machine (JVM)
Java Virtual Machine Support for Non-Java Languages
Garbage-First Collector
Java HotSpot Virtual Machine Performance Enhancements
JDBC
Not quite, although generally you can usually use some workaround on one of the forms
[^abc]
, which is character by character not a
or b
or c
, a(?!b)
, which is a
not followed by b
(?<!a)b
, which is b
not preceeded by a
You can use this..
var asciiVal = "32343630".match(/.{1,2}/g).map(function(v){_x000D_
return String.fromCharCode(parseInt(v, 16));_x000D_
}).join('');_x000D_
_x000D_
document.write(asciiVal);
_x000D_
s=input("Enter any character:")
if s.isalnum():
print("Alpha Numeric Character")
if s.isalpha():
print("Alphabet character")
if s.islower():
print("Lower case alphabet character")
else:
print("Upper case alphabet character")
else:
print("it is a digit")
elif s.isspace():
print("It is space character")
else:
print("Non Space Special Character")
Edit: With the introduction of Hooks
it is possible to implement a lifecycle kind of behavior as well as the state in the functional Components. Currently
Hooks are a new feature proposal that lets you use state and other React features without writing a class. They are released in React as a part of v16.8.0
useEffect
hook can be used to replicate lifecycle behavior, and useState
can be used to store state in a function component.
Basic syntax:
useEffect(callbackFunction, [dependentProps]) => cleanupFunction
You can implement your use case in hooks like
const grid = (props) => {
console.log(props);
let {skuRules} = props;
useEffect(() => {
if(!props.fetched) {
props.fetchRules();
}
console.log('mount it!');
}, []); // passing an empty array as second argument triggers the callback in useEffect only after the initial render thus replicating `componentDidMount` lifecycle behaviour
return(
<Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
<Box title="Sku Promotion">
<ActionButtons buttons={actionButtons} />
<SkuRuleGrid
data={skuRules.payload}
fetch={props.fetchSkuRules}
/>
</Box>
</Content>
)
}
useEffect
can also return a function that will be run when the component is unmounted. This can be used to unsubscribe to listeners, replicating the behavior of componentWillUnmount
:
Eg: componentWillUnmount
useEffect(() => {
window.addEventListener('unhandledRejection', handler);
return () => {
window.removeEventListener('unhandledRejection', handler);
}
}, [])
To make useEffect
conditional on specific events, you may provide it with an array of values to check for changes:
Eg: componentDidUpdate
componentDidUpdate(prevProps, prevState) {
const { counter } = this.props;
if (this.props.counter !== prevState.counter) {
// some action here
}
}
Hooks Equivalent
useEffect(() => {
// action here
}, [props.counter]); // checks for changes in the values in this array
If you include this array, make sure to include all values from the component scope that change over time (props, state), or you may end up referencing values from previous renders.
There are some subtleties to using useEffect
; check out the API Here
.
Before v16.7.0
The property of function components is that they don't have access to Reacts lifecycle functions or the this
keyword. You need to extend the React.Component
class if you want to use the lifecycle function.
class Grid extends React.Component {
constructor(props) {
super(props)
}
componentDidMount () {
if(!this.props.fetched) {
this.props.fetchRules();
}
console.log('mount it!');
}
render() {
return(
<Content title="Promotions" breadcrumbs={breadcrumbs} fetched={skuRules.fetched}>
<Box title="Sku Promotion">
<ActionButtons buttons={actionButtons} />
<SkuRuleGrid
data={skuRules.payload}
fetch={props.fetchSkuRules}
/>
</Box>
</Content>
)
}
}
Function components are useful when you only want to render your Component without the need of extra logic.
I'm not so thrilled about the InetAddress.getLocalHost().getHostName()
solution that you can find so many places on the Internet and indeed also here. That method will get you the hostname as seen from a network perspective. I can see two problems with this:
What if the host has multiple network interfaces ? The host may be known on the network by multiple names. The one returned by said method is indeterminate afaik.
What if the host is not connected to any network and has no network interfaces ?
All OS'es that I know of have the concept of naming a node/host irrespective of network. Sad that Java cannot return this in an easy way. This would be the environment variable COMPUTERNAME
on all versions of Windows and the environment variable HOSTNAME
on Unix/Linux/MacOS (or alternatively the output from host command hostname
if the HOSTNAME
environment variable is not available as is the case in old shells like Bourne and Korn).
I would write a method that would retrieve (depending on OS) those OS vars and only as a last resort use the InetAddress.getLocalHost().getHostName()
method. But that's just me.
As others have pointed out the HOSTNAME
environment variable is typically not available to a Java application on Unix/Linux as it is not exported by default. Hence not a reliable method unless you are in control of the clients. This really sucks. Why isn't there a standard property with this information?
Alas, as far as I can see the only reliable way on Unix/Linux would be to make a JNI call to gethostname() or to use Runtime.exec()
to capture the output from the hostname
command. I don't particularly like any of these ideas but if anyone has a better idea I'm all ears. (update: I recently came across gethostname4j which seems to be the answer to my prayers).
I've created a long explanation in another answer on another post. In particular you may want to read it because it attempts to establish some terminology, gives concrete examples of when the InetAddress.getLocalHost().getHostName()
solution will fail, and points to the only safe solution that I know of currently, namely gethostname4j.
It's sad that Java doesn't provide a method for obtaining the computername. Vote for JDK-8169296 if you are able to.
To find the home directory for user FOO on a UNIX-ish system, use ~FOO
. For the current user, use ~
.
If you don't care too much about performance and want to use the straightforward way, you can use either DIV
or IDIV
.
DIV
or IDIV
takes only one operand where it divides
a certain register with this operand, the operand can
be register or memory location only.
When operand is a byte: AL = AL / operand, AH = remainder (modulus).
Ex:
MOV AL,31h ; Al = 31h
DIV BL ; Al (quotient)= 08h, Ah(remainder)= 01h
when operand is a word: AX = (AX) / operand, DX = remainder (modulus).
Ex:
MOV AX,9031h ; Ax = 9031h
DIV BX ; Ax=1808h & Dx(remainder)= 01h
Well here is a complete example of an AutoStart Application
AndroidManifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pack.saltriver" android:versionCode="1" android:versionName="1.0">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<receiver android:name=".autostart">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<activity android:name=".hello"></activity>
<service android:enabled="true" android:name=".service" />
</application>
</manifest>
autostart.java
public class autostart extends BroadcastReceiver
{
public void onReceive(Context context, Intent arg1)
{
Intent intent = new Intent(context,service.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
context.startForegroundService(intent);
} else {
context.startService(intent);
}
Log.i("Autostart", "started");
}
}
service.java
public class service extends Service
{
private static final String TAG = "MyService";
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
@Override
public void onStart(Intent intent, int startid)
{
Intent intents = new Intent(getBaseContext(),hello.class);
intents.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intents);
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
}
}
hello.java - This will pop-up everytime you start the device after executing the Applicaton once.
public class hello extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Toast.makeText(getBaseContext(), "Hello........", Toast.LENGTH_LONG).show();
}
}
You could also try bitpocket: https://github.com/sickill/bitpocket
You can run build
for a specific service by running docker-compose up --build <service name>
where the service name must match how did you call it in your docker-compose file.
Example
Let's assume that your docker-compose file contains many services (.net app - database - let's encrypt... etc) and you want to update only the .net app which named as application
in docker-compose file.
You can then simply run docker-compose up --build application
Extra parameters
In case you want to add extra parameters to your command such as -d
for running in the background, the parameter must be before the service name:
docker-compose up --build -d application
SELECT host_name
FROM v$instance
This is a sample simplelogger.properties
which you can place on the classpath (uncomment the properties you wish to use):
# SLF4J's SimpleLogger configuration file
# Simple implementation of Logger that sends all enabled log messages, for all defined loggers, to System.err.
# Default logging detail level for all instances of SimpleLogger.
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, defaults to "info".
#org.slf4j.simpleLogger.defaultLogLevel=info
# Logging detail level for a SimpleLogger instance named "xxxxx".
# Must be one of ("trace", "debug", "info", "warn", or "error").
# If not specified, the default logging detail level is used.
#org.slf4j.simpleLogger.log.xxxxx=
# Set to true if you want the current date and time to be included in output messages.
# Default is false, and will output the number of milliseconds elapsed since startup.
#org.slf4j.simpleLogger.showDateTime=false
# The date and time format to be used in the output messages.
# The pattern describing the date and time format is the same that is used in java.text.SimpleDateFormat.
# If the format is not specified or is invalid, the default format is used.
# The default format is yyyy-MM-dd HH:mm:ss:SSS Z.
#org.slf4j.simpleLogger.dateTimeFormat=yyyy-MM-dd HH:mm:ss:SSS Z
# Set to true if you want to output the current thread name.
# Defaults to true.
#org.slf4j.simpleLogger.showThreadName=true
# Set to true if you want the Logger instance name to be included in output messages.
# Defaults to true.
#org.slf4j.simpleLogger.showLogName=true
# Set to true if you want the last component of the name to be included in output messages.
# Defaults to false.
#org.slf4j.simpleLogger.showShortLogName=false
A little verbose, but self documenting...
Dim strEmpty() As String = Enumerable.Empty(Of String).ToArray
How about this... http://jsfiddle.net/gSaPb/
Check out my example on jsFiddle: http://jsfiddle.net/QzPGu. Code snippet:
td {
text-align: center;
/* center checkbox horizontally */
vertical-align: middle;
/* center checkbox vertically */
}
table {
border: 1px solid;
width: 200px;
}
tr {
height: 80px;
}
_x000D_
<table>
<tr>
<td>
<input type="checkbox" name="myTextEditBox" value="checked" /> checkbox
</td>
</tr>
</table>
_x000D_
Just a little fix for the Shlome answer in Swift 4 and Xcode 9.
extension UILabel {
func underline() {
if let textString = self.text {
let attributedString = NSMutableAttributedString(string: textString)
attributedString.addAttribute(NSAttributedStringKey.underlineStyle,
value: NSUnderlineStyle.styleSingle.rawValue,
range: NSRange(location: 0, length: attributedString.length - 1))
attributedText = attributedString
}
}
}
extension UIButton {
func underline() {
let attributedString = NSMutableAttributedString(string: (self.titleLabel?.text!)!)
attributedString.addAttribute(NSAttributedStringKey.underlineStyle,
value: NSUnderlineStyle.styleSingle.rawValue,
range: NSRange(location: 0, length: (self.titleLabel?.text!.count)!))
self.setAttributedTitle(attributedString, for: .normal)
}
}
Could you please have a look at: http://jsfiddle.net/4Zw3M/1/.
Basically, the data is stored in an Array and the options are added accordingly. I think the code says more than a thousand words.
var data = [ // The data
['ten', [
'eleven','twelve'
]],
['twenty', [
'twentyone', 'twentytwo'
]]
];
$a = $('#a'); // The dropdowns
$b = $('#b');
for(var i = 0; i < data.length; i++) {
var first = data[i][0];
$a.append($("<option>"). // Add options
attr("value",first).
data("sel", i).
text(first));
}
$a.change(function() {
var index = $(this).children('option:selected').data('sel');
var second = data[index][1]; // The second-choice data
$b.html(''); // Clear existing options in second dropdown
for(var j = 0; j < second.length; j++) {
$b.append($("<option>"). // Add options
attr("value",second[j]).
data("sel", j).
text(second[j]));
}
}).change(); // Trigger once to add options at load of first choice
You need to make an HTTP call to your games.json
to retrieve it.
Something like:
this.http.get(./app/resources/games.json).map
You can use a simply bind on click and close, like this: (click)="drawer.close()
<a class="nav-link" [routerLink]="navItem.link" routerLinkActive="selected" (click)="drawer.close()">
Use del
.
Example:
>>> text = 'lipsum'
>>> l = list(text)
>>> del l[3:]
>>> ''.join(l)
'sum'
React + TypeScript inline util method:
const navigateToExternalUrl = (url: string, shouldOpenNewTab: boolean = true) =>
shouldOpenNewTab ? window.open(url, "_blank") : window.location.href = url;
This can be done by using the different div class for the text Hi There...
<div class="myDiv">
<div class="bg">
<p> Hi there</p>
</div>
</div>
Now you can apply the styles to the
tag. otherwise for bg class. I am sure it works fine
try this one:
var http = require('http');
var fs = require('fs');
var PORT = 8080;
http.createServer((req, res) => {
fs.readFile('./' + req.url, (err, data) => {
if (!err) {
var dotoffset = req.url.lastIndexOf('.');
var mimetype = dotoffset == -1 ? 'text/plaint' : {
'.html': 'text/html',
'.css': 'text/css',
'.js': 'text/javascript',
'.jpg': 'image/jpeg',
'.png': 'image/png',
'.ico': 'image/x-icon',
'.gif': 'image/gif'
}[ req.url.substr(dotoffset) ];
res.setHeader('Content-Type', mimetype);
res.end(data);
console.log(req.url, mimetype);
} else {
console.log('File not fount: ' + req.url);
res.writeHead(404, "Not Found");
res.end();
}
});
}).listen(PORT);
With this, you can include js, css source-codes when linking them and you can load icons, imgs, gifs. And if you want, you can add more if you need.
One more thing that might be the problem in a case similar to described - X is not forwarded and $DISPLAY is not set when 'xauth' program is not installed on the remote side. You can see it searches for it when you run "ssh -Xv ip_address", and, if not found, fails, which's not seen unless you turn on verbose mode (a fail IMO). You can usually find 'xauth' in a package with the same name.
If you're able to make a stored procedure, it could take an array of values, and you could just call that.
Extension of the question answered here How do you tell if a string contains another string in POSIX sh?:
This solution works with special characters:
# contains(string, substring)
#
# Returns 0 if the specified string contains the specified substring,
# otherwise returns 1.
contains() {
string="$1"
substring="$2"
if echo "$string" | $(type -p ggrep grep | head -1) -F -- "$substring" >/dev/null; then
return 0 # $substring is in $string
else
return 1 # $substring is not in $string
fi
}
contains "abcd" "e" || echo "abcd does not contain e"
contains "abcd" "ab" && echo "abcd contains ab"
contains "abcd" "bc" && echo "abcd contains bc"
contains "abcd" "cd" && echo "abcd contains cd"
contains "abcd" "abcd" && echo "abcd contains abcd"
contains "" "" && echo "empty string contains empty string"
contains "a" "" && echo "a contains empty string"
contains "" "a" || echo "empty string does not contain a"
contains "abcd efgh" "cd ef" && echo "abcd efgh contains cd ef"
contains "abcd efgh" " " && echo "abcd efgh contains a space"
contains "abcd [efg] hij" "[efg]" && echo "abcd [efg] hij contains [efg]"
contains "abcd [efg] hij" "[effg]" || echo "abcd [efg] hij does not contain [effg]"
contains "abcd *efg* hij" "*efg*" && echo "abcd *efg* hij contains *efg*"
contains "abcd *efg* hij" "d *efg* h" && echo "abcd *efg* hij contains d *efg* h"
contains "abcd *efg* hij" "*effg*" || echo "abcd *efg* hij does not contain *effg*"
Without really knowing the complexity of the setup, I like the sudo route. First, you must configure sudo to permit your webserver to sudo run the given command as root. Then, you need to have the script that the webserver shell_exec's(testscript) run the command with sudo.
For A Debian box with Apache and sudo:
Configure sudo:
As root, run the following to edit a new/dedicated configuration file for sudo:
visudo -f /etc/sudoers.d/Webserver
(or whatever you want to call your file in /etc/sudoers.d/
)
Add the following to the file:
www-data ALL = (root) NOPASSWD: <executable_file_path>
where <executable_file_path>
is the command that you need to be able to run as root with the full path in its name(say /bin/chown
for the chown executable). If the executable will be run with the same arguments every time, you can add its arguments right after the executable file's name to further restrict its use.
For example, say we always want to copy the same file in the /root/ directory, we would write the following:
www-data ALL = (root) NOPASSWD: /bin/cp /root/test1 /root/test2
Modify the script(testscript):
Edit your script such that sudo
appears before the command that requires root privileges(say sudo /bin/chown ...
or sudo /bin/cp /root/test1 /root/test2
). Make sure that the arguments specified in the sudo configuration file exactly match the arguments used with the executable in this file.
So, for our example above, we would have the following in the script:
sudo /bin/cp /root/test1 /root/test2
If you are still getting permission denied, the script file and it's parent directories' permissions may not allow the webserver to execute the script itself. Thus, you need to move the script to a more appropriate directory and/or change the script and parent directory's permissions to allow execution by www-data(user or group), which is beyond the scope of this tutorial.
Keep in mind:
When configuring sudo, the objective is to permit the command in it's most restricted form. For example, instead of permitting the general use of the cp command, you only allow the cp command if the arguments are, say, /root/test1 /root/test2. This means that cp's arguments(and cp's functionality cannot be altered).
For MySQL, use
SELECT column_name
FROM information_schema.columns
WHERE
table_schema = 'Schema' AND table_name = 'Table_Name'
private void Button1_Click(object sender, EventArgs e)
{
NewForm newForm = new NewForm(); //Create the New Form Object
this.Hide(); //Hide the Old Form
newForm.ShowDialog(); //Show the New Form
this.Close(); //Close the Old Form
}
Automatically fill all form fields from an array
http://jsfiddle.net/brynner/wf0rk7tz/2/
JS
function fill(a){
for(var k in a){
$('[name="'+k+'"]').val(a[k]);
}
}
array_example = {"God":"Jesus","Holy":"Spirit"};
fill(array_example);
HTML
<form>
<input name="God">
<input name="Holy">
</form>
Many answers provided for this question. Just wanted to add one more which uses bashism-
#! /bin/bash
while read -r || [[ -n "$REPLY" ]]; do
[[ "$REPLY" =~ ^(-rwx|drwx).*[[:digit:]]+$ ]] && echo "Got one -> $REPLY"
done <"$1"
@kurumi answer for bash, which uses case is also correct but it will not read last line of file if there is no newline sequence at the end(Just save the file without pressing 'Enter/Return' at the last line).
Running PHP as a CGI means that you basically tell your web server the location of the PHP executable file, and the server runs that executable
whereas
PHP FastCGI Process Manager (PHP-FPM) is an alternative FastCGI daemon for PHP that allows a website to handle strenuous loads. PHP-FPM maintains pools (workers that can respond to PHP requests) to accomplish this. PHP-FPM is faster than traditional CGI-based methods, such as SUPHP, for multi-user PHP environments
However, there are pros and cons to both and one should choose as per their specific use case.
I found info on this link for fastcgi vs fpm quite helpful in choosing which handler to use in my scenario.
You can try with this code
var result = (from item in List
select new
{
EmpLoc = item.empLoc,
EmpPL= item.empPL,
EmpShift= item.empShift
})
.ToList()
.Distinct();
The problem may lie in selected null values ??in combination with a CLOB-type column.
select valueVarchar c1 ,
valueClob c2 ,
valueVarchar c3 ,
valueVvarchar c4
of Table_1
union
select valueVarchar c1 ,
valueClob c2 ,
valueVarchar c3 ,
null c4
of table_2
I reworked the cursor. The first cursor is composed of four non-null columns. The second cursor selects three non-null columns. The null values ??were injected into the cursorForLoop .
The error TypeError: 'numpy.ndarray' object is not callable
means that you tried to call a numpy array as a function. We can reproduce the error like so in the repl:
In [16]: import numpy as np
In [17]: np.array([1,2,3])()
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-17-1abf8f3c8162> in <module>()
----> 1 np.array([1,2,3])()
TypeError: 'numpy.ndarray' object is not callable
If we are to assume that the error is indeed coming from the snippet of code that you posted (something that you should check,) then you must have reassigned either pd.rolling_mean
or pd.rolling_std
to a numpy array earlier in your code.
What I mean is something like this:
In [1]: import numpy as np
In [2]: import pandas as pd
In [3]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Works
Out[3]: array([ nan, nan, nan])
In [4]: pd.rolling_mean = np.array([1,2,3])
In [5]: pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/user/<ipython-input-5-f528129299b9> in <module>()
----> 1 pd.rolling_mean(np.array([1,2,3]), 20, min_periods=5) # Doesn't work anymore...
TypeError: 'numpy.ndarray' object is not callable
So, basically you need to search the rest of your codebase for pd.rolling_mean = ...
and/or pd.rolling_std = ...
to see where you may have overwritten them.
reload(pd)
just before your snippet, which should make it run by restoring the value of pd
to what you originally imported it as, but I still highly recommend that you try to find where you may have reassigned the given functions.
**Return the comman longest substring**
def longestSubString(str1, str2):
longestString = ""
maxLength = 0
for i in range(0, len(str1)):
if str1[i] in str2:
for j in range(i + 1, len(str1)):
if str1[i:j] in str2:
if(len(str1[i:j]) > maxLength):
maxLength = len(str1[i:j])
longestString = str1[i:j]
return longestString
If you're using Radiant CMS, simply add
require 'thread'
to the top of config/boot.rb
.
(Kudos to Aaron's and nathanvda's responses.)
You can use the PHP printf
or sprintf
functions:
Example with sprintf
:
$num = 2.12;
echo sprintf("%.3f", $num);
You can run the same without echo
as well. Example: sprintf("%.3f", $num);
Output:
2.120
Alternatively, with printf
:
echo printf("%.2f", $num);
Output:
2.124
Here is a pretty short version
function getCookie(n) {
let a = `; ${document.cookie}`.match(`;\\s*${n}=([^;]+)`);
return a ? a[1] : '';
}
Note that I made use of ES6's template strings to compose the regex expression.
You can use string.punctuation with built-in NLTK stopwords list:
from nltk.tokenize import word_tokenize, sent_tokenize
from nltk.corpus import stopwords
from string import punctuation
words = tokenize(text)
wordsWOStopwords = removeStopWords(words)
def tokenize(text):
sents = sent_tokenize(text)
return [word_tokenize(sent) for sent in sents]
def removeStopWords(words):
customStopWords = set(stopwords.words('english')+list(punctuation))
return [word for word in words if word not in customStopWords]
NLTK stopwords complete list
To see the full code(query) written in stored procedure/ functions, Use below Command:
sp_helptext procedure/function_name
for function name and procedure name don't add prefix 'dbo.' or 'sys.'.
don't add brackets at the end of procedure or function name and also don't pass the parameters.
use sp_helptext keyword and then just pass the procedure/ function name.
use below command to see full code written for Procedure:
sp_helptext ProcedureName
use below command to see full code written for function:
sp_helptext FunctionName
You can use this. react hooks
<input
type="number"
name="price"
placeholder="Enter price"
step="any"
required
/>
_x000D_
right click on the project create a file with name .ignore, then you can see that file opened.
at the right top of the file you can see install plugins or else you can install using plugins(plugin name - .ignore).
Now when ever you give a right click on the file or project you can see the option call add to .ignore
A lambda for calculating it inside a function, with help from @Nate's answer
converter = lambda amount, currency: "%s%s%s" %(
"-" if amount < 0 else "",
currency,
('{:%d,.2f}'%(len(str(amount))+3)).format(abs(amount)).lstrip())
and then,
>>> converter(123132132.13, "$")
'$123,132,132.13'
>>> converter(-123132132.13, "$")
'-$123,132,132.13'
I don't think any of the current answers really do what you said you want. (Correction: I now see that @Gareth Latty / @Lattyware has incorporated my answer into his own as an "Edit" near the end.)
Anyway, here's my take:
Say these are the tab-separated values in your input file:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
then this:
with open("tab-separated-values.txt") as inp:
print( list(zip(*(line.strip().split('\t') for line in inp))) )
would produce the following:
[('1', '6', '11', '16'),
('2', '7', '12', '17'),
('3', '8', '13', '18'),
('4', '9', '14', '19'),
('5', '10', '15', '20')]
As you can see, it put the k-th element of each row into the k-th array.
I found the following removed the indent and the margin from both the left AND right sides, but allowed the bullets to remain left-justified below the text above it. Add this to your css file:
ul.noindent {
margin-left: 5px;
margin-right: 0px;
padding-left: 10px;
padding-right: 0px;
}
To use it in your html file add class="noindent" to the UL tag. I've tested w/FF 14 and IE 9.
I have no idea why browsers default to the indents, but I haven't really had a reason for changing them that often.
I've been using the Intel(86) CPU/ABI. I created another emulator using the ARM(armeabi-v7a) and i found quite an improvement with the speed. I'm using platform 4.1.2 API level 16
You also need to add /usr/include/libxml2
to your include path.
On windows 10 (client) you can also script this using
Enable-WindowsOptionalFeature -Online -NoRestart -FeatureName WCF-HTTP-Activation45 -All
Note that this is a different command from the server skus
You just need to set :
/usr/bin/php path_to_your_php_file
in your crontab.
Button click event only.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$("#btnext").click(function () {
window.open("HTMLPage.htm", "PopupWindow", "width=600,height=600,scrollbars=yes,resizable=no");
});
});
</script>
My case was that I did not have direct access to EF context from my MVC app.
So if you are using some kind of repository for entity persistence it could be appropiate to simply detach explicitly loaded entity and then set binded EntityState to Modified.
Sample (abstract) code:
MVC
public ActionResult(A a)
{
A aa = repo.Find(...);
// some logic
repo.Detach(aa);
repo.Update(a);
}
Repository
void Update(A a)
{
context.Entry(a).EntityState = EntityState.Modified;
context.SaveChanges();
}
void Detach(A a)
{
context.Entry(a).EntityState = EntityState.Detached;
}
select * from emp where sal=(select max(sal) from emp where sal<(select max(sal) from emp))
so in our emp table(default provided by oracle) here is the output
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7698 BLAKE MANAGER 7839 01-MAY-81 3000 30
7788 SCOTT ANALYST 7566 19-APR-87 3000 20
7902 FORD ANALYST 7566 03-DEC-81 3000 20
or just you want 2nd maximum salary to be displayed
select max(sal) from emp where sal<(select max(sal) from emp)
3000
:unchecked
is not defined in the Selectors or CSS UI level 3 specs, nor has it appeared in level 4 of Selectors.
In fact, the quote from W3C is taken from the Selectors 4 spec. Since Selectors 4 recommends using :not(:checked)
, it's safe to assume that there is no corresponding :unchecked
pseudo. Browser support for :not()
and :checked
is identical, so that shouldn't be a problem.
This may seem inconsistent with the :enabled
and :disabled
states, especially since an element can be neither enabled nor disabled (i.e. the semantics completely do not apply), however there does not appear to be any explanation for this inconsistency.
(:indeterminate
does not count, because an element can similarly be neither unchecked, checked nor indeterminate because the semantics don't apply.)
There is no CREATE TABLE IF NOT EXISTS... but you can write a simple procedure for that, something like:
CREATE OR REPLACE FUNCTION execute(TEXT) RETURNS VOID AS $$
BEGIN
EXECUTE $1;
END; $$ LANGUAGE plpgsql;
SELECT
execute($$
CREATE TABLE sch.foo
(
i integer
)
$$)
WHERE
NOT exists
(
SELECT *
FROM information_schema.tables
WHERE table_name = 'foo'
AND table_schema = 'sch'
);
Use brackets. So to look for 75%
WHERE MyCol LIKE '%75[%]%'
This is simpler than ESCAPE and common to most RDBMSes.
I had this problem with Blend for Visual Studio 2015. The Toolbox would just not appear anymore. This turns out to be because Blend is not Visual Studio!
(You can edit your code in Blend and build and run it... It certainly seems like Visual Studio, but it isn't. I'm not sure what the purpose of Blend is...)
You can tell you are in Blend if the task bar icon has big "B" in it. To switch from Blend to Visual Studio, go to View
-> Edit in Visual Studio...
. It will open up another application that looks just like Blend, except the Solution Explorer is on the right instead of the left, and now you have a toolbox...
You can achieve 2 way data-binding in Nuxt/Vue like this:
Child.vue
<template>
<input
v-model="content"
<!-- How you choose to emit the event is up to you could be @keydown or even inside a watch prop -->
@keyup="$emit('update:dataFromParent', content)"
/>
</template>
<script>
export default {
props: ["dataFromParent"],
mounted() {
this.content = this.dataFromParent;
},
data: () => ({
content: "",
}),
};
</script>
Parent.vue
<tenplate>
<Child :dataFromParent.sync="text" />
</template>
<script>
import Child from "~/components/Child";
export default {
components: {
Child,
},
data: () => ({
text: "Hello World!" ,
}),
};
</script>
I was facing the same problem. I just changed my port number from 8000 to 6000. as you have 3000 you try 5000,4000,7000,8000 etc.
Essentially console.log("Put a message here.")
if the browser has a supporting console.
Another typical debugging method is using alerts, alert("Put a message here.")
RE: Update II
This seems to make sense, you are trying to automate QUnit tests, from what I have read on QUnit this is an in-browser unit testing suite/library. QUnit expects to run in a browser and therefore expects the browser to recognize all of the JavaScript functions you are calling.
Based on your Maven configuration it appears you are using Rhino to execute your Javascript at the command line/terminal. This is not going to work for testing browser specifics, you would likely need to look into Selenium for this. If you do not care about testing your JavaScript in a browser but are only testing JavaScript at a command line level (for reason I would not be familiar with) it appears that Rhino recognizes a print()
method for evaluating expressions and printing them out. Checkout this documentation.
These links might be of interest to you.
To center the table in the middle of the email use
<table width="100%" align="center" border="0" cellspacing="0" cellpadding="0">
<tr>
<td>
Your Content
</td>
</tr>
</table>
To align the content in the middle use:
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td align="center">
Your Content
</td>
</tr>
</table>
The zmbq solution is good, but cannot be used in all situations, such as inside a block of code like a FOR DO(...) loop.
An alternative is to use an indicator variable. Initialize it to be undefined, and then define it only if any one of the OR conditions is true. Then use IF DEFINED as a final test - no need to use delayed expansion.
FOR ..... DO (
set "TRUE="
IF cond1 set TRUE=1
IF cond2 set TRUE=1
IF defined TRUE (
...
) else (
...
)
)
You could add the ELSE IF logic that arasmussen uses on the grounds that it might perform a wee bit faster if the 1st condition is true, but I never bother.
Addendum - This is a duplicate question with nearly identical answers to Using an OR in an IF statement WinXP Batch Script
Final addendum - I almost forgot my favorite technique to test if a variable is any one of a list of case insensitive values. Initialize a test variable containing a delimitted list of acceptable values, and then use search and replace to test if your variable is within the list. This is very fast and uses minimal code for an arbitrarily long list. It does require delayed expansion (or else the CALL %%VAR%% trick). Also the test is CASE INSENSITIVE.
set "TEST=;val1;val2;val3;val4;val5;"
if "!TEST:;%VAR%;=!" neq "!TEST!" (echo true) else (echo false)
The above can fail if VAR contains =
, so the test is not fool-proof.
If doing the test within a block where delayed expansion is needed to access current value of VAR then
for ... do (
set "TEST=;val1;val2;val3;val4;val5;"
for /f %%A in (";!VAR!;") do if "!TEST:%%A=!" neq "!TEST!" (echo true) else (echo false)
)
FOR options like "delims=" might be needed depending on expected values within VAR
The above strategy can be made reliable even with =
in VAR by adding a bit more code.
set "TEST=;val1;val2;val3;val4;val5;"
if "!TEST:;%VAR%;=!" neq "!TEST!" if "!TEST:;%VAR%;=;%VAR%;"=="!TEST!" echo true
But now we have lost the ability of providing an ELSE clause unless we add an indicator variable. The code has begun to look a bit "ugly", but I think it is the best performing reliable method for testing if VAR is any one of an arbitrary number of case-insensitive options.
Finally there is a simpler version that I think is slightly slower because it must perform one IF for each value. Aacini provided this solution in a comment to the accepted answer in the before mentioned link
for %%A in ("val1" "val2" "val3" "val4" "val5") do if "%VAR%"==%%A echo true
The list of values cannot include the * or ? characters, and the values and %VAR%
should not contain quotes. Quotes lead to problems if the %VAR%
also contains spaces or special characters like ^
, &
etc. One other limitation with this solution is it does not provide the option for an ELSE clause unless you add an indicator variable. Advantages are it can be case sensitive or insensitive depending on presence or absence of IF /I
option.
From here:
-Xmn : the size of the heap for the young generation
Young generation represents all the objects which have a short life of time. Young generation objects are in a specific location into the heap, where the garbage collector will pass often. All new objects are created into the young generation region (called "eden"). When an object survive is still "alive" after more than 2-3 gc cleaning, then it will be swap has an "old generation" : they are "survivor".
And a more "official" source from IBM:
-Xmn
Sets the initial and maximum size of the new (nursery) heap to the specified value when using -Xgcpolicy:gencon. Equivalent to setting both -Xmns and -Xmnx. If you set either -Xmns or -Xmnx, you cannot set -Xmn. If you attempt to set -Xmn with either -Xmns or -Xmnx, the VM will not start, returning an error. By default, -Xmn is selected internally according to your system's capability. You can use the -verbose:sizes option to find out the values that the VM is currently using.
We don't need to plt.ioff()
or plt.show()
(if we use %matplotlib inline
). You can test above code without plt.ioff()
. plt.close()
has the essential role. Try this one:
%matplotlib inline
import pylab as plt
# It doesn't matter you add line below. You can even replace it by 'plt.ion()', but you will see no changes.
## plt.ioff()
# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('test0.png')
plt.close(fig)
# Create a new figure, plot into it, then don't close it so it does get displayed
fig2 = plt.figure()
plt.plot([1,3,2])
plt.savefig('test1.png')
If you run this code in iPython, it will display a second plot, and if you add plt.close(fig2)
to the end of it, you will see nothing.
In conclusion, if you close figure by plt.close(fig)
, it won't be displayed.
If you just want to change the legend title, you can do the following:
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
g = sns.lmplot(
x="total_bill",
y="tip",
hue="smoker",
data=tips,
legend=True
)
g._legend.set_title("New Title")
Try:
SELECT * FROM information_schema.statistics
WHERE table_schema = [DATABASE NAME]
AND table_name = [TABLE NAME] AND column_name = [COLUMN NAME]
It will tell you if there is an index of any kind on a certain column without the need to know the name given to the index. It will also work in a stored procedure (as opposed to show index)
Just check first the session is not already created and if not create one. Here i am setting it for 1 minute only.
<?php
if(!isset($_SESSION["timeout"])){
$_SESSION['timeout'] = time();
};
$st = $_SESSION['timeout'] + 60; //session time is 1 minute
?>
<?php
if(time() < $st){
echo 'Session will last 1 minute';
}
?>
You can also install R from this page:
https://cran.r-project.org/bin/macosx/
It works out of the box
Sql Server does not (on my knowledge) have in-build Split function. Split function in general on all platforms would have comma-separated string value to be split into individual strings. In sql server, the main objective or necessary of the Split function is to convert a comma-separated string value (‘abc,cde,fgh’) into a temp table with each string as rows.
The below Split function is Table-valued function which would help us splitting comma-separated (or any other delimiter value) string to individual string.
CREATE FUNCTION dbo.Split(@String varchar(8000), @Delimiter char(1))
returns @temptable TABLE (items varchar(8000))
as
begin
declare @idx int
declare @slice varchar(8000)
select @idx = 1
if len(@String)<1 or @String is null return
while @idx!= 0
begin
set @idx = charindex(@Delimiter,@String)
if @idx!=0
set @slice = left(@String,@idx - 1)
else
set @slice = @String
if(len(@slice)>0)
insert into @temptable(Items) values(@slice)
set @String = right(@String,len(@String) - @idx)
if len(@String) = 0 break
end
return
end
select top 10 * from dbo.split('Chennai,Bangalore,Mumbai',',')
the complete can be found at follownig link http://www.logiclabz.com/sql-server/split-function-in-sql-server-to-break-comma-separated-strings-into-table.aspx
I only had one model i wanted to use, so i ended up with the following code:
var JsonImageModel = Newtonsoft.Json.JsonConvert.SerializeObject(Images, new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore });
You can use something like this:
List<Object[]> list = em.createQuery("SELECT p.field1, p.field2 FROM Entity p").getResultList();
then you can iterate over it:
for (Object[] obj : list){
System.out.println(obj[0]);
System.out.println(obj[1]);
}
BUT if you have only one field in query, you get a list of the type not from Object[]
Use the ListView.HitTest
method
private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
{
var senderList = (ListView) sender;
var clickedItem = senderList.HitTest(e.Location).Item;
if (clickedItem != null)
{
//do something
}
}
Or the old way
private void listView_MouseDoubleClick(object sender, MouseEventArgs e)
{
var senderList = (ListView) sender;
if (senderList.SelectedItems.Count == 1 && IsInBound(e.Location, senderList.SelectedItems[0].Bounds))
{
//Do something
}
}
public bool IsInBound(Point location, Rectangle bound)
{
return (bound.Y <= location.Y &&
bound.Y + bound.Height >= location.Y &&
bound.X <= location.X &&
bound.X + bound.Width >= location.X);
}
This isn't too difficult with a little CSS, and is much better than using an image for the bullet since you can scale it and colour it and it will keep sharp at all resolutions.
Find the character code of the glyphicon by opening the Bootstrap docs and inspecting the character you want to use.
Use that character code in the following CSS
li {
display: block;
}
li:before {
/*Using a Bootstrap glyphicon as the bullet point*/
content: "\e080";
font-family: 'Glyphicons Halflings';
font-size: 9px;
float: left;
margin-top: 4px;
margin-left: -17px;
color: #CCCCCC;
}
You may like to tweak the colour and margins to suit your font size and taste.
I use this
<staticContent>
<clientCache cacheControlCustom="public" cacheControlMode="UseMaxAge" cacheControlMaxAge="500.00:00:00" />
</staticContent>
to cache static content for 500 days with public cache-control header.
—In addition to using "this" for handlebars, and the nested variable within variable block for mustache, you can also use the nested dot in a block for mustache:
{{#variable}}<span class="text">{{.}}</span>{{/variable}}
final Date currentTime = new Date();
final SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("UTC time: " + sdf.format(currentTime));
if your application uses threads directly or indirectly (i.e. behind the scene like in a 3rd-party library) it is absolutely common to have threads terminate after they are done... which is basically what you describe... the debugger shows this message... you can configure the debugger to not display this message if you don't want it...
If the above does not help then please provide more details since I am not sure what exactly the problem is you face...
I finally solved this myself. If anyone else is having this problem, here is my solution:
I created a new method:
public function curl_del($path)
{
$url = $this->__url.$path;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
$result = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
return $result;
}
Update 2
Since this seems to help some people, here is my final curl DELETE method, which returns the HTTP response in JSON decoded object:
/**
* @desc Do a DELETE request with cURL
*
* @param string $path path that goes after the URL fx. "/user/login"
* @param array $json If you need to send some json with your request.
* For me delete requests are always blank
* @return Obj $result HTTP response from REST interface in JSON decoded.
*/
public function curl_del($path, $json = '')
{
$url = $this->__url.$path;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
$result = json_decode($result);
curl_close($ch);
return $result;
}
Per the comments to the original post, merges / joins are well-suited for this problem. In particular, an inner join will return only values that are present in both dataframes, making thesetdiff
statement unnecessary.
Using the data from Dinre's example:
In base R:
cleanedA <- merge(data_A, data_B[, "index"], by = 1, sort = FALSE)
cleanedB <- merge(data_B, data_A[, "index"], by = 1, sort = FALSE)
Using the dplyr package:
library(dplyr)
cleanedA <- inner_join(data_A, data_B %>% select(index))
cleanedB <- inner_join(data_B, data_A %>% select(index))
To keep the data as two separate tables, each containing only its own variables, this subsets the unwanted table to only its index variable before joining. Then no new variables are added to the resulting table.
I believe you can create a new Vector using your ArrayList and pass that to the JCombobox Constructor.
JComboBox<String> combobox = new JComboBox<String>(new Vector<String>(myArrayList));
my example is only strings though.
I'm suspicious of the ActiveFileName
property. According to the log4j javadoc, there isn't such a property on the TimeBasedRollingPolicy
class. (No setActiveFileName
or getActiveFileName
methods.)
I don't know what specifying an unknown property would do, but it is possible that it will cause the containing object to be abandoned, and that could lead to the warnings that you saw.
Try leaving it out and seeing what happens.
.NetCore is a fine release from Microsoft and Visual Studio's latest version is also available for mac but there is still some limitation. Like for creating GUI based application on .net core you have to write code manually for everything. Like in older version of VS we just drag and drop the things and magic happens. But in VS latest version for mac every code has to be written manually. However you can make web application and console application easily on VS for mac.
it works: call this function after ajax success and send your form id as it's paramete. something like this:
This function clear all input fields value including button, submit, reset, hidden fields
function resetForm(formid) {
$('#' + formid + ' :input').each(function(){
$(this).val('').attr('checked',false).attr('selected',false);
});
}
* This function clears all input fields value except button, submit, reset, hidden fields * */
function resetForm(formid) {
$(':input','#'+formid) .not(':button, :submit, :reset, :hidden') .val('')
.removeAttr('checked') .removeAttr('selected');
}
example:
<script>
(function($){
function processForm( e ){
$.ajax({
url: 'insert.php',
dataType: 'text',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
data: $(this).serialize(),
success: function( data, textStatus, jQxhr ){
$('#alertt').fadeIn(2000);
$('#alertt').html( data );
$('#alertt').fadeOut(3000);
resetForm('userInf');
},
error: function( jqXhr, textStatus, errorThrown ){
console.log( errorThrown );
}
});
e.preventDefault();
}
$('#userInf').submit( processForm );
})(jQuery);
function resetForm(formid) {
$(':input','#'+formid) .not(':button, :submit, :reset, :hidden') .val('')
.removeAttr('checked') .removeAttr('selected');
}
</script>
Abstract Class : Use it when there is strong is-a relation between super class and sub class and all subclass share some common behavior .
Interface : It define just protocol which all subclass need to follow.
Even though you define android:onClick = "DoIt" in XML, you need to make sure your activity (or view context) has public method defined with exact same name and View as parameter. Android wires your definitions with this implementation in activity. At the end, implementation will have same code which you wrote in anonymous inner class. So, in simple words instead of having inner class and listener attachement in activity, you will simply have a public method with implementation code.
I can confirm that my original code seems to work. I was casually sticking to an image with a wrong path.
Here's a test : http://paragraphe.org/slidetoggletest/test.html
<script>
var pic = new Image();
var pic2 = new Image();
var pic3 = new Image();
pic.src="images/inputs/input1.png";
pic2.src="images/inputs/input2.png";
pic3.src="images/inputs/input3.png";
</script>
Most of the solutions here count the amount of commits you'd like to go back. I think this is an error prone methodology. Counting would require recounting.
You can simply pass the commit hash of the commit you want to be at HEAD or in other words, the commit you'd like to be the last commit via:
(Notice see commit hash)
To avoid this:
1) git checkout master
2) git branch <feature branch> master
3) git reset --hard <commit hash>
4) git push -f origin master
Javascript doesn't handle Strings over multiple lines.
You will need to concatenate those:
var obj = '{'
+'"name" : "Raj",'
+'"age" : 32,'
+'"married" : false'
+'}';
You can also use template literals in ES6 and above: (See here for the documentation)
var obj = `{
"name" : "Raj",
"age" : 32,
"married" : false,
}`;
I found this to work best
var data = [
{ label: "Choice 1", value: "choice_1" },
{ label: "Choice 2", value: "choice_2" },
{ label: "Choice 3", value: "choice_3" }
];
$("#example")
.autocomplete({
source: data,
minLength: 0
})
.focus(function() {
$(this).autocomplete('search', $(this).val())
});
It searches the labels and places the value into the element $(#example)
I'm way late, but check out Quandl. They have an API for stock prices and fundamentals.
Here's an example call, using Quandl-api download in csv
example:
https://www.quandl.com/api/v1/datasets/WIKI/AAPL.csv?column=4&sort_order=asc&collapse=quarterly&trim_start=2012-01-01&trim_end=2013-12-31
They support these languages. Their source data comes from Yahoo Finance, Google Finance, NSE, BSE, FSE, HKEX, LSE, SSE, TSE and more (see here).
If your sed
allows in place editing via the -i
parameter:
sed -e 's/$/string after each line/' -i filename
If not, you have to make a temporary file:
typeset TMP_FILE=$( mktemp )
touch "${TMP_FILE}"
cp -p filename "${TMP_FILE}"
sed -e 's/$/string after each line/' "${TMP_FILE}" > filename
Reinstalling the nuget solved it for me
PM> Install-Package Microsoft.AspNet.Razor -Version 3.2.3
I use this little PowerShell snippet:
function Get-SystemUptime {
$operatingSystem = Get-WmiObject Win32_OperatingSystem
"$((Get-Date) - ([Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.LastBootUpTime)))"
}
which then yields something like the following:
PS> Get-SystemUptime
6.20:40:40.2625526
I've had a few instances where I've needed inner shadows on text, and the following has worked out well for me:
.inner {
color: rgba(252, 195, 67, 0.8);
font-size: 48px;
text-shadow: 1px 2px 3px #fff, 0 0 0 #000;
}
This sets the opacity of the text to 80%, and then creates two shadows:
Caveats
urllib.request should work. Just set it up in a while(not done) loop, check if a localfile already exists, if it does send a GET with a RANGE header, specifying how far you got in downloading the localfile. Be sure to use read() to append to the localfile until an error occurs.
This is also potentially a duplicate of Python urllib2 resume download doesn't work when network reconnects
One can use these simple javascript within the input tag.
<input type="text" name="your_name" value="your_value"
onfocus="this.setSelectionRange(this.value.length, this.value.length);"
autofocus />
I had to sort on several criterion (date, and, if same date; other things...). What was working on Eclipse with an older version of Java, did not worked any more on Android : comparison method violates contract ...
After reading on StackOverflow, I wrote a separate function that I called from compare() if the dates are the same. This function calculates the priority, according to the criteria, and returns -1, 0, or 1 to compare(). It seems to work now.
In MySQL, the word 'type' is a Reserved Word.
import re
if re.search('(?i)Mandy Pande:', line):
...
I ended up at this question on a similar search. In my case I was looking to extract a file from another branch into current working directory that was different from the file's original location. Answer:
git show TREEISH:path/to/file > path/to/local/file
use a cursor
ADDENDUM: [MS SQL cursor example]
declare @field1 int
declare @field2 int
declare cur CURSOR LOCAL for
select field1, field2 from sometable where someotherfield is null
open cur
fetch next from cur into @field1, @field2
while @@FETCH_STATUS = 0 BEGIN
--execute your sproc on each row
exec uspYourSproc @field1, @field2
fetch next from cur into @field1, @field2
END
close cur
deallocate cur
in MS SQL, here's an example article
note that cursors are slower than set-based operations, but faster than manual while-loops; more details in this SO question
ADDENDUM 2: if you will be processing more than just a few records, pull them into a temp table first and run the cursor over the temp table; this will prevent SQL from escalating into table-locks and speed up operation
ADDENDUM 3: and of course, if you can inline whatever your stored procedure is doing to each user ID and run the whole thing as a single SQL update statement, that would be optimal
To accept both @PathVariable
and @RequestParam
in the same /user
endpoint:
@GetMapping(path = {"/user", "/user/{data}"})
public void user(@PathVariable(required=false,name="data") String data,
@RequestParam(required=false) Map<String,String> qparams) {
qparams.forEach((a,b) -> {
System.out.println(String.format("%s -> %s",a,b));
}
if (data != null) {
System.out.println(data);
}
}
Testing with curl:
Insert a column, for instance a new A column. Then use this function;
="k"&B1
and copy it down.
Then you can hide the new column A if you need too.
You create the frame with button enable, do some test to see if btn1Cliked is true, and that's all.
Then you have the actionPerformed method that does nothing with your button. So, if you don't have any action related, your button status will never be evaluated again.
I've tried all the methods and the best way for me is to use the built-in bootstrap classes .fade
and .in
Example:
<div class="alert alert-danger fade <?php echo ($show) ? 'in' : '' ?>" role="alert">...</div>
Note: In jQuery, addClass('in') to show the alert, removeClass('in') to hide it.
Fun fact: This works for all elements. Not just alerts.
I used Palash's answer given above but it was somewhat incomplete, I had to provide permission like this
Intent intent = new Intent(Intent.ACTION_VIEW);
Uri uri;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
uri = FileProvider.getUriForFile(this, getPackageName() + ".provider", new File(path));
List<ResolveInfo> resInfoList = getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
for (ResolveInfo resolveInfo : resInfoList) {
String packageName = resolveInfo.activityInfo.packageName;
grantUriPermission(packageName, uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION | Intent.FLAG_GRANT_READ_URI_PERMISSION);
}
}else {
uri = Uri.fromFile(new File(path));
}
intent.setDataAndType(uri, "application/vnd.android.package-archive");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
You can use java.util.regex.Pattern with the CASE_INSENSITIVE flag for case insensitive matching:
Pattern.compile(Pattern.quote(strptrn), Pattern.CASE_INSENSITIVE).matcher(str1).find();
Instantiate the class Date and call upon its getFullYear method to get the current year in yyyy format. Something like this:
let currentYear = new Date().getFullYear;
The currentYear variable will hold the value you are looking out for.
change
print item
to
print "\033[K", item, "\r",
sys.stdout.flush()
private String temp = "mahesh.hiren.darshan";
String s_temp[] = temp.split("[.]");
Log.e("1", ""+s_temp[0]);
Use the android.support.v7.widget.Toolbar
and just do:
toolbar.inflateMenu(R.menu.my_menu)
toolbar.setOnMenuItemClickListener {
onOptionsItemSelected(it)
}
Most of the suggested solutions like setHasOptionsMenu(true)
are only working when the parent Activity has the Toolbar in its layout and declares it via setSupportActionBar()
. Then the Fragments can participate in the menu population of this exact ActionBar:
Fragment.onCreateOptionsMenu(): Initialize the contents of the Fragment host's standard options menu.
If you want a standalone toolbar and menu for one specific Fragment you can to do the following:
menu_custom_fragment.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/menu_save"
android:title="SAVE" />
</menu>
custom_fragment.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
...
CustomFragment.kt
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = inflater.inflate(layout.custom_fragment, container, false)
val toolbar = view.findViewById<Toolbar>(R.id.toolbar)
toolbar.inflateMenu(R.menu.menu_custom_fragment)
toolbar.setOnMenuItemClickListener {
onOptionsItemSelected(it)
}
return view
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
return when (item.itemId) {
R.id.menu_save -> {
// TODO: User clicked the save button
true
}
else -> super.onOptionsItemSelected(item)
}
}
Yes, it's that easy. You don't even need to override onCreate()
or onCreateOptionsMenu()
.
PS: This is only working with android.support.v4.app.Fragment
and android.support.v7.widget.Toolbar
(also be sure to use AppCompatActivity
and an AppCompat
theme in your styles.xml
).
The solution I came up with was to use the publishing feature.
File > Publish to the web...
Then in the URL you can just replace the .../edit
path with .../pub
This solves the problem described in the question of breaking up a table with footnotes.
Need to support old browser and have a object hierarchy
body.head.eyes[0] //body, head, eyes may be null
may use this,
(((body||{}) .head||{}) .eyes||[])[0] ||'left eye'
Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.
In the case the first arg is '-v', then do your conditional ps -ef
, else in all other cases throw the usage.
#!/bin/sh
case $1 in
'-v') if [ "$1" = -v ]; then
echo "`ps -ef | grep -v '\['`"
else
echo "`ps -ef | grep '\[' | grep root`"
fi;;
*) echo "usage: $0 [-v]"
exit 1;; #It is good practice to throw a code, hence allowing $? check
esac
If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.
#!/bin/sh
usage ()
{
echo "usage: $0 [-v]"
exit 1
}
unset arg_match
for arg in $*
do
case $arg in
'-v') if [ "$arg" = -v ]; then
echo "`ps -ef | grep -v '\['`"
else
echo "`ps -ef | grep '\[' | grep root`"
fi
arg_match=1;; # this is set, but could increment.
*) ;;
esac
done
if [ ! $arg_match ]
then
usage
fi
But, allow multiple occurrences of an argument is convenient to use in situations such as:
$ adduser -u:sam -s -f -u:bob -trace -verbose
We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:
$ adduser -u sam -s -f -u bob -trace -verbose
Changing php.ini
for a web application requires restarting Apache.
You should verify that the change took place by running a PHP script that executes the function phpinfo()
. The output of that function will tell you a lot of PHP parameters, including the timeout value.
You might also have changed a copy of php.ini
that is not the same file used by Apache.
You can also use exists
, since sometimes it's faster than left join
. You'd have to benchmark them to figure out which one you want to use.
select
id
from
tableA a
where
not exists
(select 1 from tableB b where b.id = a.id)
To show that exists
can be more efficient than a left join
, here's the execution plans of these queries in SQL Server 2008:
left join
- total subtree cost: 1.09724:
exists
- total subtree cost: 1.07421:
While the OP doesn't want to use an 'in' statement, in reply to Ankur Gupta, this was the easiest way I found to delete the records in one table which didn't exist in another table, in a one to many relationship:
DELETE
FROM Table1 as t1
WHERE ID_Number NOT IN
(SELECT ID_Number FROM Table2 as t2)
Worked like a charm in Access 2016, for me.
I have tried changing the tnsnames.ora file putting the IP of the server instead of localhost or loopback address, it did not work. The firewall was blocking the requests. Please configure your firewall or turn it off(not recommended), it would work.
I had the same problem and then figured out the cause. I was trying to type in a span tag instead of an input tag. My XPath was written with a span tag, which was a wrong thing to do. I reviewed the Html for the element and found the problem. All I then did was to find the input tag which happens to be a child element. You can only type in an input field if your XPath is created with an input tagname
variable declares and call like this in a class
class X {
var x: Int = 3
}
var y = X()
print("value of x is: ", y.x)
//value of x is: 3
now you want to program to make the default value of x more than or equal to 3. Now take the hypothetical case if x is less than 3, your program will fail. so, you want people to either put 3 or more than 3. Swift got it easy for you and it is important to understand this bit-advance way of dating the variable value because they will extensively use in iOS development. Now let's see how get and set will be used here.
class X {
var _x: Int = 3
var x: Int {
get {
return _x
}
set(newVal) { //set always take 1 argument
if newVal >= 3 {
_x = newVal //updating _x with the input value by the user
print("new value is: ", _x)
}
else {
print("error must be greater than 3")
}
}
}
}
let y = X()
y.x = 1
print(y.x) //error must be greater than 3
y.x = 8 // //new value is: 8
if you still have doubts, just remember, the use of get and set is to update any variable the way we want it to be updated. get and set will give you better control to rule your logic. Powerful tool hence not easily understandable.
Swift 2.0
Here is a sample:
let newsString: NSMutableAttributedString = NSMutableAttributedString(string: "Tap here to read the latest Football News.")
newsString.addAttributes([NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleDouble.rawValue], range: NSMakeRange(4, 4))
sampleLabel.attributedText = newsString.copy() as? NSAttributedString
Swift 5.x
let newsString: NSMutableAttributedString = NSMutableAttributedString(string: "Tap here to read the latest Football News.")
newsString.addAttributes([NSAttributedString.Key.underlineStyle: NSUnderlineStyle.double.rawValue], range: NSMakeRange(4, 4))
sampleLabel.attributedText = newsString.copy() as? NSAttributedString
OR
let stringAttributes = [
NSFontAttributeName : UIFont(name: "Helvetica Neue", size: 17.0)!,
NSUnderlineStyleAttributeName : 1,
NSForegroundColorAttributeName : UIColor.orangeColor(),
NSTextEffectAttributeName : NSTextEffectLetterpressStyle,
NSStrokeWidthAttributeName : 2.0]
let atrributedString = NSAttributedString(string: "Sample String: Attributed", attributes: stringAttributes)
sampleLabel.attributedText = atrributedString
According to this blog post, you need to set -moz-appearance:textfield;
on the input
.
input[type=number]::-webkit-outer-spin-button,_x000D_
input[type=number]::-webkit-inner-spin-button {_x000D_
-webkit-appearance: none;_x000D_
margin: 0;_x000D_
}_x000D_
_x000D_
input[type=number] {_x000D_
-moz-appearance:textfield;_x000D_
}
_x000D_
<input type="number" step="0.01"/>
_x000D_
I ran into the same problem every time it finds a special character marks it as ??. to solve this, I tried using the encoding: ISO-8859-1
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream("txtPath"),"ISO-8859-1"));
while ((line = br.readLine()) != null) {
}
I hope this can help anyone who sees this post.
HTML are markup languages, basically they are set of tags like <html>
, <body>
, which is used to present a website using css, and javascript as a whole. All these, happen in the clients system or the user you will be browsing the website.
Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.
So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like php, jsp, asp.net etc.
Now, lets see a snippet of connection using MYSQLi Extension of PHP
$db = mysqli_connect('hostname','username','password','databasename');
This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:
<?php
$db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
<body>
<?php
$query = "SELECT * FROM `mytable`;";
$result = mysqli_query($db, $query);
while($row = mysqli_fetch_assoc($result)) {
// Display your datas on the page
}
?>
</body>
</html>
In order to insert new data into the database, you can use phpMyAdmin
or write a INSERT
query and execute them.
import operator
tuple(map(operator.add, a, b))
Instead of create the new Container class you can use a dataTable.
DataTable dt = new DataTable();
dt.Columns.Add("My first column Name");
dt.Rows.Add(new object[] { "Item 1" });
dt.Rows.Add(new object[] { "Item number 2" });
dt.Rows.Add(new object[] { "Item number three" });
myDataGridView.DataSource = dt;
More about this problem you can find here: http://psworld.pl/Programming/BindingListOfString
Chart.JS API has changed since this was posted and older examples did not seem to be working for me. here is an updated fiddle that works on the newer versions
HTML:
<body>
<canvas id="canvas" height="450" width="600"></canvas>
<img id="url" />
</body>
JS:
function done(){
alert("haha");
var url=myLine.toBase64Image();
document.getElementById("url").src=url;
}
var options = {
bezierCurve : false,
animation: {
onComplete: done
}
};
var myLine = new
Chart(document.getElementById("canvas").getContext("2d"),
{
data:lineChartData,
type:"line",
options:options
}
);
this was available in php 5.6 in php 7+ you should declare the array first
$users = array(); // not $users = ";
$users[] = "762";
I had the same problem:
tr:hover { background: #000 !important; }
allone did not work, but adding
tr:hover td { background: transparent; }
to the next line of my css did the job for me!! My problem was that some of the TDs already had a background-color assigned and I did not know that I have to set that to TRANSPARENT to make the tr:hover work.
Actually, I used it with a classnames:
.trclass:hover { background: #000 !important; }
.trclass:hover td { background: transparent; }
Thanks for these answers, they made my day!! :)
Mac Solution:
Added local ssh id_rsa key to vagrant private key
vi /Users//.vagrant/machines/default/virtualbox/private_key
/Users//.ssh/id_rsa
copied public key /Users//.ssh/id_rsa.pub on vagrant box authorized_keys
ssh vagrant@localhost -p 2222
(password: vagrant)
ls -la
cd .ssh
chmod 0600 ~/.ssh/authorized_keys
vagrant reload
Problem resolved.
Thanks to
http://plnkr.co/edit/A2IG03FLYnEYMpZ5RxEm?p=preview
Here is a case sensitive search that also separates your search into words to search in each model as well. Only when it finds a space will it try to split the query into an array and then search each word.
It returns true if every word is at least in one of the models.
$scope.songSearch = function (row) {
var query = angular.lowercase($scope.query);
if (query.indexOf(" ") > 0) {
query_array = query.split(" ");
search_result = false;
for (x in query_array) {
query = query_array[x];
if (angular.lowercase(row.model1).indexOf(query || '') !== -1 || angular.lowercase(row.model2).indexOf(query || '') !== -1 || angular.lowercase(row.model3).indexOf(query || '') !== -1){
search_result = true;
} else {
search_result = false;
break;
}
}
return search_result;
} else {
return (angular.lowercase(row.model1).indexOf(query || '') !== -1 || angular.lowercase(row.model2).indexOf(query || '') !== -1 || angular.lowercase(row.model3).indexOf(query || '') !== -1);
}
};
I had the same problem and I solved the problem in another way, without import ReactiveFormsModule. You may be but this block in
ngOnInt(){
userForm = new FormGroup({
name: new FormControl(),
email: new FormControl(),
adresse: new FormGroup({
rue: new FormControl(),
ville: new FormControl(),
cp: new FormControl(),
})
});
)
When you killed the session, the session hangs around for a while in "KILLED" status while Oracle cleans up after it.
If you absolutely must, you can kill the OS process as well (look up v$process.spid
), which would release any locks it was holding on to.
See this for more detailed info.
I took the above lattice example and made a nifty function. There is probably a better way to do this with reshape via melt/cast. (Comment or edit if you see an improvement.)
multi.density.plot=function(data,main=paste(names(data),collapse = ' vs '),...){
##combines multiple density plots together when given a list
df=data.frame();
for(n in names(data)){
idf=data.frame(x=data[[n]],label=rep(n,length(data[[n]])))
df=rbind(df,idf)
}
densityplot(~x,data=df,groups = label,plot.points = F, ref = T, auto.key = list(space = "right"),main=main,...)
}
Example usage:
multi.density.plot(list(BN1=bn1$V1,BN2=bn2$V1),main='BN1 vs BN2')
multi.density.plot(list(BN1=bn1$V1,BN2=bn2$V1))
You can try this:
select * FROM table where (concat(first_name, ' ', last_name)) = $search_term;
You have to write a specific media query for this, from your question, below 768px, the navbar will collapse, so apply it above 768px and below 1000px, just like that:
@media (min-width: 768px) and (max-width: 1000px) {
.collapse {
display: none !important;
}
}
This will hide the navbar collapse until the default occurrence of the bootstrap unit. As the collapse class flips the inner assets inside navbar collapse will be automatically hidden, like wise you have to set your css as you desired design.
When you get the error: implicit declaration of function
it should also list the offending function. Often this error happens because of a forgotten or missing header file, so at the shell prompt you can type man 2 functionname
and look at the SYNOPSIS
section at the top, as this section will list any header files that need to be included. Or try http://linux.die.net/man/ This is the online man pages they are hyperlinked and easy to search.
Functions are often defined in the header files, including any required header files is often the answer. Like cnicutar said,
You are using a function for which the compiler has not seen a declaration ("prototype") yet.
HAVING
operates on aggregates. Since COUNT
is an aggregate function, you can't use it in a WHERE
clause.
Here's some reading from MSDN on aggregate functions.
You can use strip() or split() to control the spaces values as in the following:
words = " first second "
# Remove end spaces
def remove_end_spaces(string):
return "".join(string.rstrip())
# Remove the first and end spaces
def remove_first_end_spaces(string):
return "".join(string.rstrip().lstrip())
# Remove all spaces
def remove_all_spaces(string):
return "".join(string.split())
# Show results
print(words)
print(remove_end_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))
To get the cell value, you need to read it directly from DataGridView1
using e.RowIndex
and e.ColumnIndex
properties.
Eg:
Private Sub DataGridView1_CellContentClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim value As Object = DataGridView1.Rows(e.RowIndex).Cells(e.ColumnIndex).Value
If IsDBNull(value) Then
TextBox1.Text = "" ' blank if dbnull values
Else
TextBox1.Text = CType(value, String)
End If
End Sub
This is default by iOS7 design. try to do the below:
[tableView setSeparatorInset:UIEdgeInsetsMake(0, 0, 0, 0)];
You can set the 'Separator Inset' from the storyboard:
An addition informative point that goes well with the answer by StompChicken above.
The fundamental difference between discriminative models and generative models is:
Discriminative models learn the (hard or soft) boundary between classes
Generative models model the distribution of individual classes
Edit:
A Generative model is the one that can generate data. It models both the features and the class (i.e. the complete data).
If we model P(x,y)
: I can use this probability distribution to generate data points - and hence all algorithms modeling P(x,y)
are generative.
Eg. of generative models
Naive Bayes models P(c)
and P(d|c)
- where c
is the class and d
is the feature vector.
Also, P(c,d) = P(c) * P(d|c)
Hence, Naive Bayes in some form models, P(c,d)
Bayes Net
Markov Nets
A discriminative model is the one that can only be used to discriminate/classify the data points.
You only require to model P(y|x)
in such cases, (i.e. probability of class given the feature vector).
Eg. of discriminative models:
logistic regression
Neural Networks
Conditional random fields
In general, generative models need to model much more than the discriminative models and hence are sometimes not as effective. As a matter of fact, most (not sure if all) unsupervised learning algorithms like clustering etc can be called generative, since they model P(d)
(and there are no classes:P)
PS: Part of the answer is taken from source
try with this
$ cat /tmp/topfs.txt
/dev/sda2 xfs 32G 10G 22G 32% /
awk print last column
$ cat /tmp/topfs.txt | awk '{print $NF}'
awk print before last column
$ cat /tmp/topfs.txt | awk '{print $(NF-1)}'
32%
awk - print last two columns
$ cat /tmp/topfs.txt | awk '{print $(NF-1), $NF}'
32% /
Right click-> generate getters and setters does the job well but if you want to create a keyboard shortcut in eclipse in windows, you can follow the following steps:
Hope this helps!
To display the all details for each news post title ie. "news.id" which is the primary key, you need to use GROUP BY clause for "news.id"
SELECT news.id, users.username, news.title, news.date,
news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id
I assume you are using gcc
, to simply link object files do:
$ gcc -o output file1.o file2.o
To get the object-files simply compile using
$ gcc -c file1.c
this yields file1.o and so on.
If you want to link your files to an executable do
$ gcc -o output file1.c file2.c
You can use a background image to accomplish this;
From MDN - Background Size: Contain:
This keyword specifies that the background image should be scaled to be as large as possible while ensuring both its dimensions are less than or equal to the corresponding dimensions of the background positioning area.
CSS:
#im {
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-image: url("path/to/img");
background-repeat: no-repeat;
background-size: contain;
}
HTML:
<div id="wrapper">
<div id="im">
</div>
</div>
The answer is in the documentation:
Real partial mocks (Since 1.8.0)
Finally, after many internal debates & discussions on the mailing list, partial mock support was added to Mockito. Previously we considered partial mocks as code smells. However, we found a legitimate use case for partial mocks.
Before release 1.8 spy() was not producing real partial mocks and it was confusing for some users. Read more about spying: here or in javadoc for spy(Object) method.
callRealMethod()
was introduced after spy()
, but spy() was left there of course, to ensure backward compatibility.
Otherwise, you're right: all the methods of a spy are real unless stubbed. All the methods of a mock are stubbed unless callRealMethod()
is called. In general, I would prefer using callRealMethod()
, because it doesn't force me to use the doXxx().when()
idiom instead of the traditional when().thenXxx()
Simplified version
final EditText taskEditText = new EditText(this);
AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle("Add a new task")
.setMessage("What do you want to do next?")
.setView(taskEditText)
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String task = String.valueOf(taskEditText.getText());
SQLiteDatabase db = mHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(TaskContract.TaskEntry.COL_TASK_TITLE, task);
db.insertWithOnConflict(TaskContract.TaskEntry.TABLE,
null,
values,
SQLiteDatabase.CONFLICT_REPLACE);
db.close();
updateUI();
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
return true;
Here is an elegant solution.
There is hidden property for each input element on the form that you can use to determine whether or not the value was changed. Each type of input has it's own property name. For example
text/textarea
it's defaultValueselect
it's defaultSelectcheckbox/radio
it's defaultCheckedHere is the example.
function bindFormChange($form) {
function touchButtons() {
var
changed_objects = [],
$observable_buttons = $form.find('input[type="submit"], button[type="submit"], button[data-object="reset-form"]');
changed_objects = $('input:text, input:checkbox, input:radio, textarea, select', $form).map(function () {
var
$input = $(this),
changed = false;
if ($input.is('input:text') || $input.is('textarea') ) {
changed = (($input).prop('defaultValue') != $input.val());
}
if (!changed && $input.is('select') ) {
changed = !$('option:selected', $input).prop('defaultSelected');
}
if (!changed && $input.is('input:checkbox') || $input.is('input:radio') ) {
changed = (($input).prop('defaultChecked') != $input.is(':checked'));
}
if (changed) {
return $input.attr('id');
}
}).toArray();
if (changed_objects.length) {
$observable_buttons.removeAttr('disabled')
} else {
$observable_buttons.attr('disabled', 'disabled');
}
};
touchButtons();
$('input, textarea, select', $form).each(function () {
var $input = $(this);
$input.on('keyup change', function () {
touchButtons();
});
});
};
Now just loop thru the forms on the page and you should see submit buttons disabled by default and they will be activated ONLY if you indeed will change some input value on the form.
$('form').each(function () {
bindFormChange($(this));
});
Implementation as a jQuery
plugin is here https://github.com/kulbida/jmodifiable
For bold and italic whatever you are doing is correct for underscore use following code
HelloAndroid.java
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.style.UnderlineSpan;
import android.widget.TextView;
public class HelloAndroid extends Activity {
TextView textview;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
textview = (TextView)findViewById(R.id.textview);
SpannableString content = new SpannableString(getText(R.string.hello));
content.setSpan(new UnderlineSpan(), 0, content.length(), 0);
textview.setText(content);
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/textview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="@string/hello"
android:textStyle="bold|italic"/>
string.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello World, HelloAndroid!</string>
<string name="app_name">Hello, Android</string>
</resources>
Try this:
def name_the_key(dict, key):
return key, dict[key]
mydict = {'key1':1, 'key2':2, 'key3':3}
key_name, value = name_the_key(mydict, 'key2')
print 'KEY NAME: %s' % key_name
print 'KEY VALUE: %s' % value
Define your target to
1) take an argument q
2) replace any statements return foo
with q.put(foo); return
so a function
def func(a):
ans = a * a
return ans
would become
def func(a, q):
ans = a * a
q.put(ans)
return
and then you would proceed as such
from Queue import Queue
from threading import Thread
ans_q = Queue()
arg_tups = [(i, ans_q) for i in xrange(10)]
threads = [Thread(target=func, args=arg_tup) for arg_tup in arg_tups]
_ = [t.start() for t in threads]
_ = [t.join() for t in threads]
results = [q.get() for _ in xrange(len(threads))]
And you can use function decorators/wrappers to make it so you can use your existing functions as target
without modifying them, but follow this basic scheme.
Here is my version in Swift 3 for a UIView
let corners:UIRectCorner = [.bottomLeft, .topRight]
let path = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let mask = CAShapeLayer()
mask.path = path.cgPath
mask.fillColor = UIColor.white.cgColor
let shadowLayer = CAShapeLayer()
shadowLayer.shadowColor = UIColor.black.cgColor
shadowLayer.shadowOffset = CGSize(width: 0.0, height: 4.0)
shadowLayer.shadowRadius = 6.0
shadowLayer.shadowOpacity = 0.25
shadowLayer.shadowPath = mask.path
self.layer.insertSublayer(shadowLayer, at: 0)
self.layer.insertSublayer(mask, at: 1)
There is no solution to prevent browser/proxy caching since you cannot have the control on it.
The other way to force fresh content to your users it to rename the HTML file! Exactly like https://www.npmjs.com/package/grunt-filerev does for assets.
If you are pulling your queries using java code, there is a great class that can be used, ResultSetMetaData, that can retrieve column names and the properties of the columns (type and length).
Example
ResultSet rs = null;
rs = sql.executeQuery();
if (rs != null) {
if (rs.next()) {
ResultSetMetaData rsmd = rs.getMetaData();
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
System.out.println("column name: "
+ rsmd.getColumnName(i));
System.out.println("column size: "
+ rsmd.getColumnDisplaySize(i));
}
}
AddEventListener take a simple string that represents event.type. So You need to write a custom function to iterate over multiple events.
This is being handled in jQuery by using .split(" ") and then iterating over the list to set the eventListeners for each types
.
// Add elem as a property of the handle function
// This is to prevent a memory leak with non-native events in IE.
eventHandle.elem = elem;
// Handle multiple events separated by a space
// jQuery(...).bind("mouseover mouseout", fn);
types = types.split(" ");
var type, i = 0, namespaces;
while ( (type = types[ i++ ]) ) { <-- iterates thru 1 by 1
you should add this line above your page
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
In the past, I have found it quite difficult to try to upgrade in-place.
Note: my use-case for Anaconda is as an all-in-one Python environment. I don't bother with separate virtual environments. If you're using conda
to create environments, this may be destructive because conda
creates environments with hard-links inside your Anaconda/envs
directory.
So if you use environments, you may first want to export your environments. After activating your environment, do something like:
conda env export > environment.yml
After backing up your environments (if necessary), you may remove your old Anaconda (it's very simple to uninstall Anaconda):
$ rm -rf ~/anaconda3/
and replace it by downloading the new Anaconda, e.g. Linux, 64 bit:
$ cd ~/Downloads
$ wget https://repo.continuum.io/archive/Anaconda3-4.3.0-Linux-x86_64.sh
(see here for a more recent one),
and then executing it:
$ bash Anaconda3-4.3.0-Linux-x86_64.sh
By default you will get a core file. Check to see that the current directory of the process is writable, or no core file will be created.
I have python 2.7.3 and this solved my problem:
pip install pysqlite
Not sure what you call FIFO these days since Queue is FILO, but when I was a student we used the Stack<E>
with the simple push, pop, and a peek... It is really that simple, no need for complicating further with Queue and whatever the accepted answer suggests.
Q:Can't bind to 'pSelectableRow' since it isn't a known property of 'tr'.
A:you need to configure the primeng tabulemodule in ngmodule
If you are using modalInstance and have the object you can use "then" to do actions after opening the modal. If you are not using the modalInstance, and hard coded to open the modal you can use the event. The $timeout is not a good solution.
You can do (Bootstrap3):
$("#" + modalId).on("shown.bs.modal", function() {
angular.element("[name='name']").focus();
});
At modalInstance you can look at library to how execute the code after open modal.
Don't use $timeout like this, the $timeout can be 0, 1, 10, 30, 50, 200 or more this will depend on client computer, and the process to open modal.
Don't use $timeout let the method tell you when you can focus ;)
I hope that this help! :)
NB: Should you want the year to be based on some reference date, the code below calculates the dates for the between
statement:
declare @referenceTime datetime = getutcdate()
select *
from myTable
where SomeDate
between dateadd(year, year(@referenceTime) - 1900, '01-01-1900') --1st Jan this year (midnight)
and dateadd(millisecond, -3, dateadd(year, year(@referenceTime) - 1900, '01-01-1901')) --31st Dec end of this year (just before midnight of the new year)
Similarly, if you're using a year value, swapping year(@referenceDate)
for your reference year's value will work
declare @referenceYear int = 2010
select *
from myTable
where SomeDate
between dateadd(year,@referenceYear - 1900, '01-01-1900') --1st Jan this year (midnight)
and dateadd(millisecond, -3, dateadd(year,@referenceYear - 1900, '01-01-1901')) --31st Dec end of this year (just before midnight of the new year)
The NULL
part is calculated AFTER the actual join, so that is why it needs to be in the where clause.
This problem usually occurs when some process such as loading huge data to memory stream and your system memory is not capable of storing so much of data. Try clearing temp folder by giving the command
start -> run -> %temp%
So you want the next multiple of 6, is that it?
You can divide your number by 6, then ceil
it, and multiply it again:
$answer = ceil($foo / 6) * 6;
wget -S -O - http://google.com
works as expected for me, but with a caveat: the headers are considered debugging information and as such they are sent to the standard error rather than the standard output. If you are redirecting the standard output to a file or another process, you will only get the document contents.
You can try redirecting the standard error to the standard output as a possible solution. For example, in bash
:
$ wget -q -S -O - 2>&1 | grep ...
or
$ wget -q -S -O - 1>wget.txt 2>&1
The -q
option suppresses the progress bar and some other annoyingly chatty parts of the wget
output.
While exporting your source into a jar, make sure you select runnable jar option from the options. Then select if you want to package all the dependency jars or just include them directly in the jar file. It depends on the project that you are working on.
You then run the jar directly by java -jar example.jar.
The order of initialization doesn’t matter. All fields are initialized in the order of their definition in their class/struct. But if the order in initialization list is different gcc/g++ generate this warning. Only change the initialization order to avoid this warning. But you can't define field using in initialization before its construct. It will be a runtime error. So you change the order of definition. Be careful and keep attention!
a = ["item 1", "item 2", "item 3", "item 4"]
h = Hash[*a] # => { "item 1" => "item 2", "item 3" => "item 4" }
That's it. The *
is called the splat operator.
One caveat per @Mike Lewis (in the comments): "Be very careful with this. Ruby expands splats on the stack. If you do this with a large dataset, expect to blow out your stack."
So, for most general use cases this method is great, but use a different method if you want to do the conversion on lots of data. For example, @Lukasz Niemier (also in the comments) offers this method for large data sets:
h = Hash[a.each_slice(2).to_a]
Here's a simple way
for (i in 1:10) {
skip_to_next <- FALSE
# Note that print(b) fails since b doesn't exist
tryCatch(print(b), error = function(e) { skip_to_next <<- TRUE})
if(skip_to_next) { next }
}
Note that the loop completes all 10 iterations, despite errors. You can obviously replace print(b)
with any code you want. You can also wrap many lines of code in {
and }
if you have more than one line of code inside the tryCatch
Xcode provides CFNetwork Diagnostic Logging. Apple doc
To enable it, add CFNETWORK_DIAGNOSTICS=3
in the Environment Variable section:
This will show requests from the App with its headers & body. Note that OS_ACTIVITY_MODE
must be set to enable
as shown. Otherwise no output will be shown on the Console.
This snippet invokes when a link of class 'menu_link' is clicked, and shows the text and url of the link. The return false prevents the link from being followed.
<a rel='1' class="menu_link" href="option1.html">Option 1</a>
<a rel='2' class="menu_link" href="option2.html">Option 2</a>
$('.menu_link').live('click', function() {
var thelink = $(this);
alert ( thelink.html() );
alert ( thelink.attr('href') );
alert ( thelink.attr('rel') );
return false;
});
my case seems to be invalid JRE version.
1.7+ required while I launched with 1.6
plus: I filtered some plugin jars which might be required. so changed to select all
Actually quite easy to roll your own tester, by abusing Java's method overload ability. Though I'm still curious if there is an official method in the sdk.
Example:
class Typetester {
void printType(byte x) {
System.out.println(x + " is an byte");
}
void printType(int x) {
System.out.println(x + " is an int");
}
void printType(float x) {
System.out.println(x + " is an float");
}
void printType(double x) {
System.out.println(x + " is an double");
}
void printType(char x) {
System.out.println(x + " is an char");
}
}
then:
Typetester t = new Typetester();
t.printType( yourVariable );
I think simpler (though without a script) assuming the Status
column is ColumnS.
Select ColumnS and clear formatting from it. Select entire range to be formatted and Format, Conditional formatting..., Format cells if... Custom formula is
and:
=and($S1<>"",search("Complete",$S1)>0)
with fill of choice and Done.
This is not case sensitive (change search
to find
for that) and will highlight a row where ColumnS contains the likes of Now complete
(though also Not yet complete
).
Below is my solution to get date from miliseconds to date format. You have to use Joda Library to get this code run.
import java.util.GregorianCalendar;
import java.util.TimeZone;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
public class time {
public static void main(String args[]){
String str = "1431601084000";
long geTime= Long.parseLong(str);
GregorianCalendar calendar = new GregorianCalendar(TimeZone.getTimeZone("US/Central"));
calendar.setTimeInMillis(geTime);
DateTime jodaTime = new DateTime(geTime,
DateTimeZone.forTimeZone(TimeZone.getTimeZone("US/Central")));
DateTimeFormatter parser1 = DateTimeFormat.forPattern("yyyy-MM-dd");
System.out.println("Get Time : "+parser1.print(jodaTime));
}
}
With Java 8+ you can use the ints
method of Random
to get an IntStream
of random values then distinct
and limit
to reduce the stream to a number of unique random values.
ThreadLocalRandom.current().ints(0, 100).distinct().limit(5).forEach(System.out::println);
Random
also has methods which create LongStream
s and DoubleStream
s if you need those instead.
If you want all (or a large amount) of the numbers in a range in a random order it might be more efficient to add all of the numbers to a list, shuffle it, and take the first n because the above example is currently implemented by generating random numbers in the range requested and passing them through a set (similarly to Rob Kielty's answer), which may require generating many more than the amount passed to limit because the probability of a generating a new unique number decreases with each one found. Here's an example of the other way:
List<Integer> range = IntStream.range(0, 100).boxed()
.collect(Collectors.toCollection(ArrayList::new));
Collections.shuffle(range);
range.subList(0, 99).forEach(System.out::println);
JSON in any HTML tag except <script>
tag would be a mere text. Thus it's like you add a story to your HTML page.
However, about formatting, that's another matter. I guess you should change the title of your question.
Just try this in razor
@{
var selectList = new SelectList(
new List<SelectListItem>
{
new SelectListItem {Text = "Google", Value = "Google"},
new SelectListItem {Text = "Other", Value = "Other"},
}, "Value", "Text");
}
and then
@Html.DropDownListFor(m => m.YourFieldName, selectList, "Default label", new { @class = "css-class" })
or
@Html.DropDownList("ddlDropDownList", selectList, "Default label", new { @class = "css-class" })
Have you considered mmap()? You can read from the file directly as if it were already in memory.
You need to write a document.write object:
document.write('<script type="text/javascript" src="file.js" ></script>');
and place it in your main javascript file
Using this object --> TinyDB--Android-Shared-Preferences-Turbo its very simple. you can save most of the commonly used objects with it like arrays, integer, strings lists etc
Or you could use:
exec bash
This does the same thing, and is easier to remember (at least for me).
The exec
command completely replaces the shell process by running the specified command-line. In our example, it replaces whatever the current shell is with a fresh instance of bash
(with the updated configuration files).
Try with,
<uses-permission android:name="android.permission.INTERNET"/>
instead of,
<permission android:name="android.permission.INTERNET"></permission>
You can also use sed's change line to accomplish this:
sed -i "/aaa=/c\aaa=xxx" your_file_here
This will go through and find any lines that pass the aaa=
test, which means that the line contains the letters aaa=
. Then it replaces the entire line with aaa=xxx. You can add a ^
at the beginning of the test to make sure you only get the lines that start with aaa=
but that's up to you.
Here Response.Write():to display only string and you can not display any other data type values like int,date,etc.Conversion(from one data type to another) is not allowed. whereas Response .Output .Write(): you can display any type of data like int, date ,string etc.,by giving index values.
Here is example:
protected void Button1_Click(object sender, EventArgs e)
{
Response.Write ("hi good morning!"+"is it right?");//only strings are allowed
Response.Write("Scott is {0} at {1:d}", "cool", DateTime.Now);//this will give error(conversion is not allowed)
Response.Output.Write("\nhi goood morning!");//works fine
Response.Output.Write("Jai is {0} on {1:d}", "cool", DateTime.Now);//here the current date will be converted into string and displayed
}
I should add: You should not be putting your dll's into \system32\ anyway! Modify your code, modify your installer... find a home for your bits that is NOT anywhere under c:\windows\
For example, your installer puts your dlls into:
\program files\<your app dir>\
or
\program files\common files\<your app name>\
(Note: The way you actually do this is to use the environment var: %ProgramFiles% or %ProgramFiles(x86)% to find where Program Files is.... you do not assume it is c:\program files\ ....)
and then sets a registry tag :
HKLM\software\<your app name>
-- dllLocation
The code that uses your dlls reads the registry, then dynamically links to the dlls in that location.
The above is the smart way to go.
You do not ever install your dlls, or third party dlls into \system32\ or \syswow64. If you have to statically load, you put your dlls in your exe dir (where they will be found). If you cannot predict the exe dir (e.g. some other exe is going to call your dll), you may have to put your dll dir into the search path (avoid this if at all poss!)
system32 and syswow64 are for Windows provided files... not for anyone elses files. The only reason folks got into the bad habit of putting stuff there is because it is always in the search path, and many apps/modules use static linking. (So, if you really get down to it, the real sin is static linking -- this is a sin in native code and managed code -- always always always dynamically link!)
Here's a compact way to do something different in all four cases:
if(empty($youtube)) {
if(empty($link)) {
# both empty
} else {
# only $youtube not empty
}
} else {
if(empty($link)) {
# only $link empty
} else {
# both not empty
}
}
If you want to use an expression instead, you can use ?:
instead:
echo empty($youtube) ? ( empty($link) ? 'both empty' : 'only $youtube not empty' )
: ( empty($link) ? 'only $link empty' : 'both not empty' );
JavaScript
If you want to make it case insensitive just add i
at the end of regex:
'Test'.match(/[A-Z]/gi)
//Returns ["T", "e", "s", "t"]
Without i
'Test'.match(/[A-Z]/g)
//Returns ["T"]
Adding to the above answers: To find the package name of installed apps on any android device: Go to Storage/Android/data/< package-name >
I'd like to make some changes: In C, you can use the built in qsort command:
int compare( const void* a, const void* b)
{
int int_a = * ( (int*) a );
int int_b = * ( (int*) b );
// an easy expression for comparing
return (int_a > int_b) - (int_a < int_b);
}
qsort( a, 6, sizeof(int), compare )