If you are using Java 9 or above you may need to require the junit dependency in your module-info.java
module myModule {
requires junit;
}
Play around with this jsFiddle example:
HTML:
<p id="foo" name="bar">Hello, world!</p>
jQuery:
$(function() {
var name = $('#foo').attr('name');
alert(name);
console.log(name);
});
This uses jQuery's .attr() method to get value for the first element in the matched set.
While not specifically jQuery, the result is shown as an alert prompt and written to the browser's console.
The error means that docker build
is either using a PATH | URL
that are incorrectly input or that the Dockerfile
cannot be found in the current directory. Also, make sure that when running the command from an integrated terminal (e.g. bash
inside your IDE or text editor) you have the admin permissions to do so.
Best if you can check the PATH
from your terminal with pwd
(in bash shell
or dir
if using a simple cli
on windows) and copy the exact path where you want the image to be build.
docker build C:\windows\your_amazing_directory
docker build --help
will also show you available options to use in case of malformed or illegal commands.
use HTML instead of javascript
<html>_x000D_
<head><style> * { margin: 0; padding: 0; } </style></head>_x000D_
<body>_x000D_
<h1>svg foreignObject to embed html</h1>_x000D_
_x000D_
<svg_x000D_
xmlns="http://www.w3.org/2000/svg"_x000D_
viewBox="0 0 300 300"_x000D_
x="0" y="0" height="300" width="300"_x000D_
>_x000D_
_x000D_
<circle_x000D_
r="142" cx="150" cy="150"_x000D_
fill="none" stroke="#000000" stroke-width="2"_x000D_
/>_x000D_
_x000D_
<foreignObject_x000D_
x="50" y="50" width="200" height="200"_x000D_
>_x000D_
<div_x000D_
xmlns="http://www.w3.org/1999/xhtml"_x000D_
style="_x000D_
width: 196px; height: 196px;_x000D_
border: solid 2px #000000;_x000D_
font-size: 32px;_x000D_
overflow: auto; /* scroll */_x000D_
"_x000D_
>_x000D_
<p>this is html in svg 1</p>_x000D_
<p>this is html in svg 2</p>_x000D_
<p>this is html in svg 3</p>_x000D_
<p>this is html in svg 4</p>_x000D_
</div>_x000D_
</foreignObject>_x000D_
_x000D_
</svg>_x000D_
_x000D_
</body></html>
_x000D_
create sequence serial start 1;
select * from comments c
join (select unnest(ARRAY[1,3,2,4]) as id, nextval('serial') as id_sorter) x
on x.id = c.id
order by x.id_sorter;
drop sequence serial;
[EDIT]
unnest is not yet built-in in 8.3, but you can create one yourself(the beauty of any*):
create function unnest(anyarray) returns setof anyelement
language sql as
$$
select $1[i] from generate_series(array_lower($1,1),array_upper($1,1)) i;
$$;
that function can work in any type:
select unnest(array['John','Paul','George','Ringo']) as beatle
select unnest(array[1,3,2,4]) as id
myHash.each{|item|..}
is returning you array object for item
iterative variable like the following :--
[:company_name, "MyCompany"]
[:street, "Mainstreet"]
[:postcode, "1234"]
[:city, "MyCity"]
[:free_seats, "3"]
You should do this:--
def format
output = Hash.new
myHash.each do |k, v|
output[k] = cleanup(v)
end
output
end
For those coming from Ionic or Cordova, you can try the following:
Disconnect your ios devices from the computer before ios cordova build ios --release
(seems to change the targeted device for xcode signing).
public static String readFileToString(String filePath) {
InputStream in = Test.class.getResourceAsStream(filePath);//filePath="/com/myproject/Sample.xml"
try {
return IOUtils.toString(in, StandardCharsets.UTF_8);
} catch (IOException e) {
logger.error("Failed to read the xml : ", e);
}
return null;
}
If you have different pool per user make sure user and group are set correctly in configuration file. You can find nginx user in /etc/nginx/nginx.conf file. nginx group is same as nginx user.
user = [pool-user]
group = [pool-group]
listen.owner = [nginx-user]
listen.group = [nginx-group]
I found this to work really well if you want to count rows without counting the th and any rows from tables inside of tables:
var rowCount = $("#tableData > tbody").children().length;
Just combine them. I think this should work but it's untested:
p <- ggplot(visual1, aes(ISSUE_DATE,COUNTED)) + geom_point() +
geom_smooth(fill="blue", colour="darkblue", size=1)
p <- p + geom_point(data=visual2, aes(ISSUE_DATE,COUNTED)) +
geom_smooth(data=visual2, fill="red", colour="red", size=1)
print(p)
Here's my two cents: Considering a CSV file is just lines of text I've streamed the data (strings) to avoid this problem.
Easiest solution for me that worked in my usecase.
It can be used with graceful fs or standard fs. Just note that there won't be headers in the file when creating.
// import graceful-fs or normal fs
const fs = require("graceful-fs"); // or use: const fs = require("fs")
// Create output file and set it up to receive streamed data
// Flag is to say "append" so that data can be recursively added to the same file
let fakeCSV = fs.createWriteStream("./output/document.csv", {
flags: "a",
});
and the data that needs to be streamed to the file i've done like this
// create custom streamer that can be invoked when needed
const customStreamer = (dataToWrite) => {
fakeCSV.write(dataToWrite + "\n");
};
Note that the dataToWrite is simply a string with a custom seperator like ";" or ",". i.e.
const dataToWrite = "batman" + ";" + "superman"
customStreamer(dataToWrite);
This writes "batman;superman" to the file.
If you're using some plugin which takes string and use construct Regex to create Regex Object i:e new RegExp()
Than Below string will work
'^\\S*$'
It's same regex @Bergi mentioned just the string version for new RegExp constructor
Netcat sends one packet per newline. So you're fine. If you do anything more complex then you might need something else.
I was fooling around with Wireshark when I realized this. Don't know if it helps.
I am using MVC4, I used following approach to redirect a custom html screen upon authorization breach.
Extend AuthorizeAttribute
say CutomAuthorizer
override the OnAuthorization
and HandleUnauthorizedRequest
Register the CustomAuthorizer
in the RegisterGlobalFilters
.
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new CustomAuthorizer());
}
upon identifying the unAuthorized
access call HandleUnauthorizedRequest
and redirect to the concerned controller action as shown below.
public class CustomAuthorizer : AuthorizeAttribute
{
public override void OnAuthorization(AuthorizationContext filterContext)
{
bool isAuthorized = IsAuthorized(filterContext); // check authorization
base.OnAuthorization(filterContext);
if (!isAuthorized && !filterContext.ActionDescriptor.ActionName.Equals("Unauthorized", StringComparison.InvariantCultureIgnoreCase)
&& !filterContext.ActionDescriptor.ControllerDescriptor.ControllerName.Equals("LogOn", StringComparison.InvariantCultureIgnoreCase))
{
HandleUnauthorizedRequest(filterContext);
}
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result =
new RedirectToRouteResult(
new RouteValueDictionary{{ "controller", "LogOn" },
{ "action", "Unauthorized" }
});
}
}
I believe you have libx264
installed and configured with ffmpeg
to convert video to h264
... Then you can try with -vcodec libx264
... The -format
option is for showing available formats, this is not a conversion option I think...
java: Java application executor which is associated with a console to display output/errors
javaw: (Java windowed) application executor not associated with console. So no display of output/errors. It can be used to silently push the output/errors to text files. It is mostly used to launch GUI-based applications.
javaws: (Java web start) to download and run the distributed web applications. Again, no console is associated.
All are part of JRE and use the same JVM.
As mentioned before you can use --extra-vars (-e) , but instead of specifying the pwd on the commandline so it doesn't end up in the history files you can save it to an environment variable. This way it also goes away when you close the session.
read -s PASS
ansible windows -i hosts -m win_ping -e "ansible_password=$PASS"
There is a trick, Arithmetic exceptions only happen when you are playing around with integers and only during / or % operation.
If there is any floating point number in an arithmetic operation, internally all integers will get converted into floating point. This may help you to remember things easily.
You need both getText() - which returns an Editable and toString() - to convert that to a String for matching.
So instead of: passw1.toString().equalsIgnoreCase("1234")
you need passw1.getText().toString().equalsIgnoreCase("1234")
.
<a href="javascript:history.back(1)">Back</a>
this one (by Eiko) is perfect, use css to make a button of <a>
...
eg you can use this css class in <a>
as `
<a class=".back_button" href="javascript:history.back(1)">Back</a>`
.back_button {
display:block;
width:100px;
height:30px;
text-align:center;
background-color:yellow;
border:1px solid #000000;
}
Ok, Im assuming you want to put the .left inside the container so I suggest you edit your html. The key is the position:absolute
and right:0
#right {
background-color: red;
height: 300px;
width: 300px;
z-index: 999999;
margin-top: 0px;
position: absolute;
right:0;
}
here is the full code: http://jsfiddle.net/T9FJL/
I appreciate the OP is new to Java, so methods might be considered "advanced", however I think it's worth using this problem to show how you can attack a problem by breaking it into pieces.
Let's think about writing a method to print a single line, telling the method which number line it is:
public void printTriangleLine(int rowNumber) {
// we have to work out what to put here
}
We have to print some number of spaces, then some number of stars.
Looking at the example, I can see that (if the first row is 0) it's (5-rowNumber) spaces and (2*rowNumber + 1) stars.
Let's invent a method that prints the rows of characters for us, and use it:
public void printTriangleLine(int rowNumber) {
printSequence(" ", 5 - rowNumber);
printSequence("*", 2 * rowNumber + 1);
System.out.println();
}
That won't compile until we actually write printSequence(), so let's do that:
public void printSequence(String s, int repeats) {
for(int i=0; i<repeats; i++) {
System.out.print(s);
}
}
Now you can test printSequence on its own, and you can test printTriangleLine on its own. For now you can just try it out by calling those methods directly in main()
public static void main(String [] args) {
printSequence("a",3);
System.out.println();
printTriangleLine(2);
}
... run it and verify (with your eyes) that it outputs:
aaa
*****
When you get further into programming, you'll want to use a unit testing framework like jUnit. Instead of printing, you'd more likely write things like printTriangleLine to return a String (which you'd print from higher up in your program), and you would automate your testing with commands like:
assertEquals(" *****", TriangleDrawer.triangleLine(2));
assertEquals(" *", TriangleDrawer.triangleLine(0))
Now we have the pieces we need to draw a triangle.
public void drawTriangle() {
for(int i=0; i<5; i++) {
printTriangleLine(i);
}
}
The code we have written is a bit longer than the answers other people have given. But we have been able to test each step, and we have methods that we can use again in other problems. In real life, we have to find the right balance between breaking a problem into too many methods, or too few. I tend to prefer lots of really short methods.
For extra credit:
System.out.print(drawTriangle())
drawTriangle(3)
or drawTriangle(5)
Here is a more comprehensive method that can also accept full month names
def month_string_to_number(string):
m = {
'jan': 1,
'feb': 2,
'mar': 3,
'apr':4,
'may':5,
'jun':6,
'jul':7,
'aug':8,
'sep':9,
'oct':10,
'nov':11,
'dec':12
}
s = string.strip()[:3].lower()
try:
out = m[s]
return out
except:
raise ValueError('Not a month')
example:
>>> month_string_to_number("October")
10
>>> month_string_to_number("oct")
10
Python 3.6 will add literal string interpolation similar to Ruby's string interpolation. Starting with that version of Python (which is scheduled to be released by the end of 2016), you will be able to include expressions in "f-strings", e.g.
name = "Spongebob Squarepants"
print(f"Who lives in a Pineapple under the sea? {name}.")
Prior to 3.6, the closest you can get to this is
name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? %(name)s." % locals())
The %
operator can be used for string interpolation in Python. The first operand is the string to be interpolated, the second can have different types including a "mapping", mapping field names to the values to be interpolated. Here I used the dictionary of local variables locals()
to map the field name name
to its value as a local variable.
The same code using the .format()
method of recent Python versions would look like this:
name = "Spongebob Squarepants"
print("Who lives in a Pineapple under the sea? {name!s}.".format(**locals()))
There is also the string.Template
class:
tmpl = string.Template("Who lives in a Pineapple under the sea? $name.")
print(tmpl.substitute(name="Spongebob Squarepants"))
Using docker links, you can link the upstream container to the nginx container. An added feature is that docker manages the host file, which means you'll be able to refer to the linked container using a name rather than the potentially random ip.
You should use Linking
.
Example from the docs:
class OpenURLButton extends React.Component {
static propTypes = { url: React.PropTypes.string };
handleClick = () => {
Linking.canOpenURL(this.props.url).then(supported => {
if (supported) {
Linking.openURL(this.props.url);
} else {
console.log("Don't know how to open URI: " + this.props.url);
}
});
};
render() {
return (
<TouchableOpacity onPress={this.handleClick}>
{" "}
<View style={styles.button}>
{" "}<Text style={styles.text}>Open {this.props.url}</Text>{" "}
</View>
{" "}
</TouchableOpacity>
);
}
}
Here's an example you can try on Expo Snack:
import React, { Component } from 'react';
import { View, StyleSheet, Button, Linking } from 'react-native';
import { Constants } from 'expo';
export default class App extends Component {
render() {
return (
<View style={styles.container}>
<Button title="Click me" onPress={ ()=>{ Linking.openURL('https://google.com')}} />
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingTop: Constants.statusBarHeight,
backgroundColor: '#ecf0f1',
},
});
Now that Chrome 18 was released last week with the required APIs, I published my chrome extension in the Chrome web store. The extension automatically saves changes in CSS or JS in Developer tools into the local disk. Go check it out.
iContribute: It's never too late for a right answer.
var form = $("form#myForm");
if($('form#myForm > :input[required]:visible').val() != ""){
form.submit();
}else{
console.log("Required field missing.");
}
This way the basic HTML5 validation for 'required' fields takes place without interfering with the standard submit using the form's 'name' values.
for Z score, we can stick to documentation instead of using 'apply' function
from scipy.stats import zscore
df_zscore = zscore(cols as array, axis=1)
Go to SDK Manager and see if there are any updates on the emulator & build tools that need to be updated.
A simple switch statement should do the trick:
function abc() {
var elem=document.getElementById('test'),color;
switch(elem.style.color) {
case('red'):
color='black';
break;
case('black'):
default:
color='red';
}
elem.style.color=color;
}
Based on Bootstrap 4
Disabled elements Elements with the disabled attribute aren’t interactive, meaning users cannot focus, hover, or click them to trigger a tooltip (or popover). As a workaround, you’ll want to trigger the tooltip from a wrapper or , ideally made keyboard-focusable using tabindex="0", and override the pointer-events on the disabled element.
<span class="d-inline-block" tabindex="0" data-toggle="tooltip" title="Disabled tooltip">
<button class="btn btn-primary" style="pointer-events: none;" type="button" disabled>Disabled button</button>
</span>
All the details here: Bootstrap 4 doc
In response to mrCoders answer using jsperf why not just use the dom node ?
var $foo = $('#foo');
var count = $foo[0].childElementCount
You can try the test here: http://jsperf.com/jquery-child-ele-size/7
This method gets 46,095 op/s while the other methods at best 2000 op/s
You can use the following code to open a file location from vba.
Dim Foldername As String
Foldername = "\\server\Instructions\"
Shell "C:\WINDOWS\explorer.exe """ & Foldername & "", vbNormalFocus
You can use this code for both windows shares and local drives.
VbNormalFocus can be swapper for VbMaximizedFocus if you want a maximized view.
Rather give names of the column on which you want to merge:
exporttab <- merge(x=dwd_nogap, y=dwd_gap, by.x='x1', by.y='x2', fill=-9999)
Open report in Report designer
Go to View menu -> Report data
Use:
str.search(regex)
See the documentation here.
It works much easier with that:
document.querySelector('input[type=password]').setAttribute('type', 'text');
and in order to turn it back to password field again,(assuming the password field is the 2nd input tag with text type):
document.querySelectorAll('input[type=text]')[1].setAttribute('type', 'password')
Httponly cookies' purpose is being inaccessible by script, so you CAN NOT.
write() only takes a single string argument, so you could do this:
outf.write(str(num))
or
outf.write('{}'.format(num)) # more "modern"
outf.write('%d' % num) # deprecated mostly
Also note that write
will not append a newline to your output so if you need it you'll have to supply it yourself.
Aside:
Using string formatting would give you more control over your output, so for instance you could write (both of these are equivalent):
num = 7
outf.write('{:03d}\n'.format(num))
num = 12
outf.write('%03d\n' % num)
to get three spaces, with leading zeros for your integer value followed by a newline:
007
012
format() will be around for a long while, so it's worth learning/knowing.
It depends on how you want the text to display. If you want it all to be left-aligned then either format it as in the first snippet or iterate through the lines left-trimming all the space.
Might be better to use a choice, don't have to type (or possibly mistype) your expressions more than once, and allows you to follow additional different behaviors.
I very often use count(/html/body) = 0
, as the specific number of nodes is more interesting than the set. For example... when there is unexpectedly more than 1 node that matches your expression.
<xsl:choose>
<xsl:when test="/html/body">
<!-- Found the node(s) -->
</xsl:when>
<!-- more xsl:when here, if needed -->
<xsl:otherwise>
<!-- No node exists -->
</xsl:otherwise>
</xsl:choose>
If by array of String you mean array of char:
public class Test
{
public static void main(String[] args)
{
String test = "aabbab ";
char[] t = test.toCharArray();
for(char c : t)
System.out.println(c);
System.out.println("The end!");
}
}
If not, the String.split()
function could transform a String into an array of String
See those String.split
examples
/* String to split. */
String str = "one-two-three";
String[] temp;
/* delimiter */
String delimiter = "-";
/* given string will be split by the argument delimiter provided. */
temp = str.split(delimiter);
/* print substrings */
for(int i =0; i < temp.length ; i++)
System.out.println(temp[i]);
The input.split("(?!^)")
proposed by Joachim in his answer is based on:
?!
' zero-width negative lookahead (see Lookaround)^
' as an Anchor to match the start of the string the regex pattern is applied toAny character which is not the first will be split. An empty string will not be split but return an empty array.
Originally, I created a database and then restored the backup file to my new empty database:
Right click on Databases > Restore Database > General : Device: [the path of back up file] ? OK
This was wrong. I shouldn't have first created the database.
Now, instead, I do this:
Right click on Databases > Restore Database > General : Device: [the path of back up file] ? OK
With Angular CLI 6 you need to use builders as ng eject is deprecated and will soon be removed in 8.0. That's what it says when I try to do an ng eject
You can use angular-builders package (https://github.com/meltedspark/angular-builders) to provide your custom webpack config.
I have tried to summarize all in a single blog post on my blog - How to customize build configuration with custom webpack config in Angular CLI 6
but essentially you add following dependencies -
"devDependencies": {
"@angular-builders/custom-webpack": "^7.0.0",
"@angular-builders/dev-server": "^7.0.0",
"@angular-devkit/build-angular": "~0.11.0",
In angular.json make following changes -
"architect": {
"build": {
"builder": "@angular-builders/custom-webpack:browser",
"options": {
"customWebpackConfig": {"path": "./custom-webpack.config.js"},
Notice change in builder and new option customWebpackConfig. Also change
"serve": {
"builder": "@angular-builders/dev-server:generic",
Notice the change in builder again for serve target. Post these changes you can create a file called custom-webpack.config.js in your same root directory and add your webpack config there.
However, unlike ng eject configuration provided here will be merged with default config so just add stuff you want to edit/add.
In case this helps someone, I deployed my app to google play, when I uninstalled it and tried to run a debug on my device (new version) I was getting this failed update message.
I couldn't see the app in my device (it was already uninstalled) so I:
Installed the first version again from google play
Opened Settings/App/App name
Cleared the Data
Cleared the Cache
Uninstalled the app
Now you can deploy the debug version again to the device :)
I figured out how to do this. I was building an application very similar to the example/tutorial you discussed in your original question.
Here's a snippet of the code that worked for me:
int pageSize = 4;
int pageNumber = (page ?? 1);
//Used the following two formulas so that it doesn't round down on the returned integer
decimal totalPages = ((decimal)(viewModel.Teachers.Count() /(decimal) pageSize));
ViewBag.TotalPages = Math.Ceiling(totalPages);
//These next two functions could maybe be reduced to one function....would require some testing and building
viewModel.Teachers = viewModel.Teachers.ToPagedList(pageNumber, pageSize);
ViewBag.OnePageofTeachers = viewModel.Teachers;
ViewBag.PageNumber = pageNumber;
return View(viewModel);
I added
using.PagedList;
to my controller as the tutorial states.
Now in my view my using statements etc at the top, NOTE i didnt change my using model statement.
@model CSHM.ViewModels.TeacherIndexData
@using PagedList;
@using PagedList.Mvc;
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
and then at the bottom to build my paged list I used the following and it seems to work. I haven't yet built in the functionality for current sort, showing related data, filters, etc but i dont think it will be that difficult.
Page @ViewBag.PageNumber of @ViewBag.TotalPages
@Html.PagedListPager((IPagedList)ViewBag.OnePageofTeachers, page => Url.Action("Index", new { page }))
Hope that works for you. Let me know if it works!!
Client closed the connection doesn't mean it's a browser issue!? Not at all!
You can find 499 errors in a log file if you have a LB (load balancer) in front of your webserver (nginx) either AWS or haproxy (custom). That said the LB will act as a client to nginx.
If you run haproxy default values for:
timeout client 60000
timeout server 60000
That would mean that LB will time out after 60000ms if there is no respond from nginx. Time outs might happen for busy websites or scripts that need more time for execution. You'll need to find timeout that will work for you. For example extend it to:
timeout client 180s
timeout server 180s
And you will be probably set.
Depending on your setup you might see a 504 gateway timeout error in your browser which indicates that something is wrong with php-fpm but that will not be the case with 499 errors in your log files.
Based on the date of this question the original poster wouldn't have been using Windows Subsystem for Linux. But if you are, and you get the same error, the following alternative works:
clip.exe < ~/.ssh/id_rsa.pub
Thanks to this page for pointing out Windows' clip.exe (and you have to type the ".exe") can be run from the bash shell.
click() is a reserved word and already a function, change the name from click() to runclick() it works fine
The following imports an external CSS file in a React component and outputs the CSS rules in the <head />
of the website.
npm install --save-dev style-loader
npm install --save-dev css-loader
module.exports = {
module: {
rules: [
{
test: /\.css$/,
use: [ 'style-loader', 'css-loader' ]
}
]
}
}
import './path/to/file.css';
include script manager
code behind function
ScriptManager.RegisterStartupScript(this, this.GetType(), "HideConfirmBox", "javascript:HideAAConfirmBox(); ", true);
According to Google Developers article, you can:
<script src="..." async>
or element.appendChild()
,font-family:'Open Sans' , sans-serif;
For light:
font-weight : 100;
Or
font-weight : lighter;
For normal:
font-weight : 500;
Or
font-weight : normal;
For bold:
font-weight : 700;
Or
font-weight : bold;
For more bolder:
font-weight : 900;
Or
font-weight : bolder;
HTTP_CLIENT_IP is the most reliable way of getting the user's IP address. Next is HTTP_X_FORWARDED_FOR, followed by REMOTE_ADDR. Check all three, in that order, assuming that the first one that is set (isset($_SERVER['HTTP_CLIENT_IP'])
returns true if that variable is set) is correct. You can independently check if the user is using a proxy using various methods. Check this out.
It's not a solution but a hint for those using Spring:
I tried to use org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean
with setting persistenceXmlLocation
but with this I had to provide the <class>
elements (even if the persistenceXmlLocation
just pointed to META-INF/persistence.xml
).
When not using persistenceXmlLocation
I could omit these <class>
elements.
Because the number can be up to 15 digits, you'll need to cast to an 64 bit (8-byte) integer. Try this:
SELECT * FROM table
WHERE myint = mytext::int8
The ::
cast operator is historical but convenient. Postgres also conforms to the SQL standard syntax
myint = cast ( mytext as int8)
If you have literal text you want to compare with an int
, cast the int
to text:
SELECT * FROM table
WHERE myint::varchar(255) = mytext
Use this code for IE9 and above:
window.frames["printf"].focus();
window.frames["printf"].print();
For IE8:
window.frames[0].focus();
window.frames[0].print();
If I understand the question correctly, you don't even need jQuery for this. Shrinking the image proportionally on the client can be done with CSS alone: just set its max-width
and max-height
to 100%
.
<div style="height: 100px">
<img src="http://www.getdigital.de/images/produkte/t4/t4_css_sucks2.jpg"
style="max-height: 100%; max-width: 100%">
</div>?
Here's the fiddle: http://jsfiddle.net/9EQ5c/
"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.
Check that you don't send ANY content before calling session_start
. Better yet, just make session_start
the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).
bool vExist = false;
int vSelectValue = 1;
List<int> vList = new List<int>();
vList.Add(1);
vList.Add(2);
IEnumerable vRes = (from n in vListwhere n == vSelectValue);
if (vRes.Count > 0) {
vExist = true;
}
First, the extensions and libraries that we're going to use:
{-# LANGUAGE RankNTypes, TypeOperators #-}
import Control.Monad (join)
Of these, RankNTypes
is the only one that's absolutely essential to the below. I once wrote an explanation of RankNTypes
that some people seem to have found useful, so I'll refer to that.
Quoting Tom Crockett's excellent answer, we have:
A monad is...
- An endofunctor, T : X -> X
- A natural transformation, µ : T × T -> T, where × means functor composition
- A natural transformation, ? : I -> T, where I is the identity endofunctor on X
...satisfying these laws:
- µ(µ(T × T) × T)) = µ(T × µ(T × T))
- µ(?(T)) = T = µ(T(?))
How do we translate this to Haskell code? Well, let's start with the notion of a natural transformation:
-- | A natural transformations between two 'Functor' instances. Law:
--
-- > fmap f . eta g == eta g . fmap f
--
-- Neat fact: the type system actually guarantees this law.
--
newtype f :-> g =
Natural { eta :: forall x. f x -> g x }
A type of the form f :-> g
is analogous to a function type, but instead of thinking of it as a function between two types (of kind *
), think of it as a morphism between two functors (each of kind * -> *
). Examples:
listToMaybe :: [] :-> Maybe
listToMaybe = Natural go
where go [] = Nothing
go (x:_) = Just x
maybeToList :: Maybe :-> []
maybeToList = Natural go
where go Nothing = []
go (Just x) = [x]
reverse' :: [] :-> []
reverse' = Natural reverse
Basically, in Haskell, natural transformations are functions from some type f x
to another type g x
such that the x
type variable is "inaccessible" to the caller. So for example, sort :: Ord a => [a] -> [a]
cannot be made into a natural transformation, because it's "picky" about which types we may instantiate for a
. One intuitive way I often use to think of this is the following:
Now, with that out of the way, let's tackle the clauses of the definition.
The first clause is "an endofunctor, T : X -> X." Well, every Functor
in Haskell is an endofunctor in what people call "the Hask category," whose objects are Haskell types (of kind *
) and whose morphisms are Haskell functions. This sounds like a complicated statement, but it's actually a very trivial one. All it means is that that a Functor f :: * -> *
gives you the means of constructing a type f a :: *
for any a :: *
and a function fmap f :: f a -> f b
out of any f :: a -> b
, and that these obey the functor laws.
Second clause: the Identity
functor in Haskell (which comes with the Platform, so you can just import it) is defined this way:
newtype Identity a = Identity { runIdentity :: a }
instance Functor Identity where
fmap f (Identity a) = Identity (f a)
So the natural transformation ? : I -> T from Tom Crockett's definition can be written this way for any Monad
instance t
:
return' :: Monad t => Identity :-> t
return' = Natural (return . runIdentity)
Third clause: The composition of two functors in Haskell can be defined this way (which also comes with the Platform):
newtype Compose f g a = Compose { getCompose :: f (g a) }
-- | The composition of two 'Functor's is also a 'Functor'.
instance (Functor f, Functor g) => Functor (Compose f g) where
fmap f (Compose fga) = Compose (fmap (fmap f) fga)
So the natural transformation µ : T × T -> T from Tom Crockett's definition can be written like this:
join' :: Monad t => Compose t t :-> t
join' = Natural (join . getCompose)
The statement that this is a monoid in the category of endofunctors then means that Compose
(partially applied to just its first two parameters) is associative, and that Identity
is its identity element. I.e., that the following isomorphisms hold:
Compose f (Compose g h) ~= Compose (Compose f g) h
Compose f Identity ~= f
Compose Identity g ~= g
These are very easy to prove because Compose
and Identity
are both defined as newtype
, and the Haskell Reports define the semantics of newtype
as an isomorphism between the type being defined and the type of the argument to the newtype
's data constructor. So for example, let's prove Compose f Identity ~= f
:
Compose f Identity a
~= f (Identity a) -- newtype Compose f g a = Compose (f (g a))
~= f a -- newtype Identity a = Identity a
Q.E.D.
I use JSONP.
Basically, you add
<script src="http://..../someData.js?callback=some_func"/>
on your page.
some_func() should get called so that you are notified that the data is in.
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
var formObj = document.getElementById("pageID");
formObj.response_order_id.value = getParameterByName("name");
Below the code will print 0 if it is Palindrome else it will print -1
Optimized Code
word = "nepalapen"
is_palindrome = word.find(word[::-1])
print is_palindrome
Output: 0
word = "nepalapend"
is_palindrome = word.find(word[::-1])
print is_palindrome
Output: -1
when searching the string the value that is returned is the value of the location that the string starts at.
So when you do word.find(word[::-1])
it finds nepalapen
at location 0
and [::-1]
reverses nepalapen
and it still is nepalapen
at location 0
so 0
is returned.
Now when we search for nepalapend
and then reverse nepalapend
to dnepalapen
it renders a FALSE
statement nepalapend
was reversed to dnepalapen
causing the search to fail to find nepalapend
resulting in a value of -1
which indicates string not found.
Another method print true if palindrome else print false
word = "nepalapen"
print(word[::-1]==word[::1])
output: TRUE
The list of supported tags is:
If you use a string resource, you can add some simple styling, such as bold or italic using HTML notation. The currently supported tags are:
B
(bold),I
(italic),U
(underline),TT
(monospace),BIG
,SMALL
,SUP
(superscript),SUB
(subscript), andSTRIKE
(strikethrough). So, for example, inres/values/strings.xml
you could declare this:<resource> <string id="@+id/styled_welcome_message">We are <b><i>so</i></b> glad to see you.</string> </resources>
(From http://developer.android.com/guide/faq/commontasks.html#selectingtext — Web Archive link, <resource>
typo is in original!)
It also shows that Html.fromHtml
isn't really needed in simple cases.
You probably mean the difference between Http Only cookies and their counter part?
Http Only cookies cannot be accessed (read from or written to) in client side JavaScript, only server side. If the Http Only flag is not set, or the cookie is created in (client side) JavaScript, the cookie can be read from and written to in (client side) JavaScript as well as server side.
First off, it is perfectly feasible to use R successfully for years and not need to know the answer to this question. R handles the differences between the (usual) numerics and integers for you in the background.
> is.numeric(1)
[1] TRUE
> is.integer(1)
[1] FALSE
> is.numeric(1L)
[1] TRUE
> is.integer(1L)
[1] TRUE
(Putting capital 'L' after an integer forces it to be stored as an integer.)
As you can see "integer" is a subset of "numeric".
> .Machine$integer.max
[1] 2147483647
> .Machine$double.xmax
[1] 1.797693e+308
Integers only go to a little more than 2 billion, while the other numerics can be much bigger. They can be bigger because they are stored as double precision floating point numbers. This means that the number is stored in two pieces: the exponent (like 308 above, except in base 2 rather than base 10), and the "significand" (like 1.797693 above).
Note that 'is.integer' is not a test of whether you have a whole number, but a test of how the data are stored.
One thing to watch out for is that the colon operator, :
, will return integers if the start and end points are whole numbers. For example, 1:5
creates an integer
vector of numbers from 1 to 5. You don't need to append the letter L
.
> class(1:5)
[1] "integer"
Reference: https://www.quora.com/What-is-the-difference-between-numeric-and-integer-in-R
Commenting with some updated information from 2018.
Executable Binaries for Platform tools are made available for mac by Android here: https://developer.android.com/studio/releases/platform-tools.html
Download these to your mac. Place them in a directory e.g. I placed in ~/Software/platform-tools
If you have root access, the easiest way I have found on a mac is to add your directories to the list in /etc/paths
. I like this way because after a few additions the $PATH
starts to look too messy and hard to read, the /etc/paths
has everything in separate line, clean and organized. The downside is that you require root access.
$ cat /etc/paths # check contents of the file
$ sudo nano /etc/paths
Paste the full path of your platform-tools directory (something like /Users/GodZilla/Software/platform-tools/adb
) at the end of this list and save. Quit and Open terminal again and check if it sees your platform-tools directory.
$ which adb
/Users/GodZilla/Software/platform-tools/adb
$ which fastboot
/Users/GodZilla/Software/platform-tools/fastboot
If you don't have root access, just add the platform-tools directory to $PATH
in your .bash_profile (or .zshenv if you use zsh) as other users have suggested.
You have one choice hide your back button and make it with your self. Then set its color.
I did that:
self.navigationItem.setHidesBackButton(true, animated: true)
let backbtn = UIBarButtonItem(title: "Back", style:UIBarButtonItemStyle.Plain, target: self, action: "backTapped:")
self.navigationItem.leftBarButtonItem = backbtn
self.navigationItem.leftBarButtonItem?.tintColor = UIColor.grayColor()
There is a lot of options to store your data and Android offers you to chose anyone Your data storage options are the following:
Shared Preferences Store private primitive data in key-value pairs. Internal Storage Store private data on the device memory. External Storage Store public data on the shared external storage. SQLite Databases Store structured data in a private database. Network Connection Store data on the web with your own network server
Check here for examples and tuto
If you're interested, there's a well-established package out there that you can add to your Codeigniter project that will handle this:
https://bitbucket.org/wiredesignz/codeigniter-modular-extensions-hmvc/
Modular Extensions makes the CodeIgniter PHP framework modular. Modules are groups of independent components, typically model, controller and view, arranged in an application modules sub-directory, that can be dropped into other CodeIgniter applications.
OK, so the big change is that now you'd be using a modular structure - but to me this is desirable. I have used CI for about 3 years now, and can't imagine life without Modular Extensions.
Now, here's the part that deals with directly calling controllers for rendering view partials:
// Using a Module as a view partial from within a view is as easy as writing:
<?php echo modules::run('module/controller/method', $param1, $params2); ?>
That's all there is to it. I typically use this for loading little "widgets" like:
Typically I build a "widget" controller for each module and use it only for this purpose.
Your question was also one of my first questions when I started with Codeigniter. I hope this helps you out, even though it may be a bit more than you were looking for. I've been using MX ever since and haven't looked back.
Make sure to read the docs and check out the multitude of information regarding this package on the Codeigniter forums. Enjoy!
You need to assign $first and $second
$first = $_POST['first'];
$second= $_POST['second'];
Also, As Travesty3 said, you need to do your arithmetic outside of the quotes:
echo $first + $second;
How easy :)
date("F j, Y", strtotime( '-1 days' ) );
Example:
echo date("Y-m-j H:i:s", strtotime( '-1 days' ) ); // 2018-07-18 07:02:43
Output:
2018-07-17 07:02:43
If you use make generators like cmake, JUCE, etc. try to set a correct VS version target (2013, 2015, 2017) and regenerate the solution again.
A New Laravel Blade Error Directive comes to Laravel 5.8.13
// Before
@if ($errors->has('email'))
<span>{{ $errors->first('email') }}</span>
@endif
// After:
@error('email')
<span>{{ $message }}</span>
@enderror
You can pass vector by reference just like this:
void do_something(int el, std::vector<int> &arr){
arr.push_back(el);
}
However, note that this function would always add a new element at the back of the vector, whereas your array function actually modifies the first element (or initializes it value).
In order to achieve exactly the same result you should write:
void do_something(int el, std::vector<int> &arr){
if (arr.size() == 0) { // can't modify value of non-existent element
arr.push_back(el);
} else {
arr[0] = el;
}
}
In this way you either add the first element (if the vector is empty) or modify its value (if there first element already exists).
I got the same error when I had Authentication disabled/chose "No Authentication'. I re-made my project and chose "Individual User Accounts" and I didn't get the error anymore.
What gives? It works. Just ignore it:
@SuppressWarnings("unchecked")
No, you cannot parameterize it. I'd however rather use a List<Map<K, V>>
instead.
List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();
To learn more about collections and maps, have a look at this tutorial.
input.Replace("\r\n", "\n").Replace("\r", "\n").Replace("\n", "\r\n")
This will work if the input contains only one type of line breaks - either CR, or LF, or CR+LF.
An old thread, sure, but a popular one apparently. It's 2020 now and none of these answers have addressed the issue of unreadable code. @pimvdb's answer takes up less lines, but it's also pretty complicated to follow. For easier debugging and better readability, I should suggest refactoring the OP's code to something like this, and adopting an early return pattern, as this is likely the main reason you were unsure of why the were getting undefined:
function validatePassword() {
const password = document.getElementById("password");
const confirm_password = document.getElementById("password_confirm");
if (password.value.length === 0) {
return false;
}
if (password.value !== confirm_password.value) {
return false;
}
return true;
}
There actually is a way to do this that is allowed by C#. This gets back to C++, and rather violates the nice Object-Oriented structure of C#.
USE THIS METHOD WITH CAUTION!
Here's the way you declare and write your function with an optional parameter:
unsafe public void OptionalOutParameter(int* pOutParam = null)
{
int lInteger = 5;
// If the parameter is NULL, the caller doesn't care about this value.
if (pOutParam != null)
{
// If it isn't null, the caller has provided the address of an integer.
*pOutParam = lInteger; // Dereference the pointer and assign the return value.
}
}
Then call the function like this:
unsafe { OptionalOutParameter(); } // does nothing
int MyInteger = 0;
unsafe { OptionalOutParameter(&MyInteger); } // pass in the address of MyInteger.
In order to get this to compile, you will need to enable unsafe code in the project options. This is a really hacky solution that usually shouldn't be used, but if you for some strange, arcane, mysterious, management-inspired decision, REALLY need an optional out parameter in C#, then this will allow you to do just that.
That is a problem of security protocol. I am using TLSv1 but the host accept only TLSv1.1 and TLSv1.2 then I changed the protocol in Java with the instruction below:
System.setProperty("https.protocols", "TLSv1.1")
;
<script src="http://crypto-js.googlecode.com/svn/tags/3.0.2/build/rollups/md5.js"></script>
<script>
var passhash = CryptoJS.MD5(password).toString();
$.post(
'includes/login.php',
{ user: username, pass: passhash },
onLogin,
'json' );
</script>
let clickTimes = 0;
let timer = null;
roundBox.click = function (e) {
clearTimeout(timer);
timer = setTimeout(() => { // ????
console.log("single click");
}, 600);
clickTimes++;
if (clickTimes == 2) { // ??
clearTimeout(timer);
clickTimes = 0;
console.log("double click");
toggleExpanded(id);
}
}
If you use UPPER(text)
, the like '%lah%'
will always return zero results. Use '%LAH%'
.
I used to use the #define because they make code easier to read, and there should be no performances degradation compared to using numbers (0,1) coz' the preprocessor converts the #define into numbers before compilation. Once the application is run preprocessor does not come into the way again because the code is already compiled.
BTW it should be:
#define FALSE 0
#define TRUE 1
and remember that -1, -2, ... 2, 3, etc. all evaluates to true.
The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.
When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.
Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:
http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database
Update Collation of all fields in database on the fly
http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx
If you need to have different collation on two objects or can't change collations - you can still JOIN
between them using COLLATE
command, and choosing the collation you want for join.
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS
or using default database collation:
SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT
You can also deny access to a folder using RedirectMatch
Add the following line to htaccess
RedirectMatch 403 ^/folder/?$
This will return a 403 forbidden
error for the folder ie : http://example.com/folder/
but it doest block access to files and folders inside that folder, if you want to block everything inside the folder then just change the regex pattern to ^/folder/.*$
.
Another option is mod-rewrite
If url-rewrting-module
is enabled you can use something like the following in root/.htaccss
:
RewriteEngine on
RewriteRule ^folder/?$ - [F,L]
This will internally map a request for the folder
to forbidden
error page.
You need to use the __getitem__
method.
class MyClass:
def __getitem__(self, key):
return key * 2
myobj = MyClass()
myobj[3] #Output: 6
And if you're going to be setting values you'll need to implement the __setitem__
method too, otherwise this will happen:
>>> myobj[5] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__setitem__'
melt()
from the reshape2 package gets you close ...
library(reshape2)
(res <- melt(as.data.frame(mat), id="time"))
# time variable value
# 1 0.0 C_0 0.1
# 2 0.5 C_0 0.2
# 3 1.0 C_0 0.3
# 4 0.0 C_1 0.3
# 5 0.5 C_1 0.4
# 6 1.0 C_1 0.5
... although you may want to post-process its results to get your preferred column names and ordering.
setNames(res[c("variable", "time", "value")], c("name", "time", "val"))
# name time val
# 1 C_0 0.0 0.1
# 2 C_0 0.5 0.2
# 3 C_0 1.0 0.3
# 4 C_1 0.0 0.3
# 5 C_1 0.5 0.4
# 6 C_1 1.0 0.5
-z string
True if the string is null (an empty string)
Are you sure you cloned it using the ssh url?
The url for origin says url = https://[email protected]/Nicolas_Raoul/therepo.git
so if it is using https it will ask for password irrespective of your ssh keys.
So what you want to do is the following:
open your config file in your current repo ..
vim .git/config
and change the line with the url from
[remote "origin"]
fetch = +refs/heads/*:refs/remotes/origin/*
url = https://[email protected]/Nicolas_Raoul/therepo.git
to
[remote "origin"]
fetch = +refs/heads/*:refs/remotes/origin/*
url = [email protected]:Nicolas_Raoul/therepo.git
You need to include jQueryUI for the extended easing options.
I think there may be an option to only include the easing in the download, or at least just the base library plus easing.
for (int i = 0; i < clbIncludes.Items.Count; i++)
if (clbIncludes.GetItemChecked(i))
// Do selected stuff
else
// Do unselected stuff
If the the check is in indeterminate state, this will still return true. You may want to replace
if (clbIncludes.GetItemChecked(i))
with
if (clbIncludes.GetItemCheckState(i) == CheckState.Checked)
if you want to only include actually checked items.
You should use double instead of float for precise calculations, and float instead of double when using less accurate calculations. Float contains only decimal numbers, but double contains an IEEE754 double-precision floating point number, making it easier to contain and computate numbers more accurately. Hope this helps.
Swift 3.0 version of Tommy's answer
let imageToDisplay = UIImage.init(cgImage: originalImage.cgImage!, scale: originalImage.scale, orientation: UIImageOrientation.up)
Public Function connectDB() As OleDbConnection
Dim Con As New OleDbConnection
'Con.ConnectionString = "Provider=SQLOLEDB.1;Persist Security Info=False;User ID=sa;Initial Catalog=" & DBNAME & ";Data Source=" & DBSERVER & ";Pwd=" & DBPWD & ""
Con.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=DBNAME;Data Source=DBSERVER-TOSH;User ID=Sa;Pwd= & DBPWD"
Try
Con.Open()
Catch ex As Exception
showMessage(ex)
End Try
Return Con
End Function
I'd like to promote factory methods for creating helpers for functional APIs:
Optional<R> result = things.stream()
.flatMap(streamopt(this::resolve))
.findFirst();
The factory method:
<T, R> Function<T, Stream<R>> streamopt(Function<T, Optional<R>> f) {
return f.andThen(Optional::stream); // or the J8 alternative:
// return t -> f.apply(t).map(Stream::of).orElseGet(Stream::empty);
}
Reasoning:
As with method references in general, compared to lambda expressions, you can't accidentaly capture a variable from the accessible scope, like:
t -> streamopt(resolve(o))
It's composable, you can e.g. call Function::andThen
on the factory method result:
streamopt(this::resolve).andThen(...)
Whereas in the case of a lambda, you'd need to cast it first:
((Function<T, Stream<R>>) t -> streamopt(resolve(t))).andThen(...)
I think CAST(ROUND(yourColumn,2) as varchar)
should do the job.
But why do you want to do this presentational formatting in T-SQL?
By default, div
elements are displayed as block elements, so they have 100% width, making centering them meaningless. As suggested by Arief, you must specify a width
and you can then use auto
when specifying margin
in order to center a div
.
Alternatively, you could also force display: inline
, but then you'd have something that pretty much behaves like a span
instead of a div
, so that doesn't make a lot of sense.
public static void Main()
{
int a,b=0;
int []arr={1, 2, 2, 3, 3, 4, 5, 6, 5, 7, 7, 7, 100, 8, 1};
for(int i=arr.Length-1 ; i>-1 ; i--)
{
a = arr[i];
if(a > b)
{
b=a;
}
}
Console.WriteLine(b);
}
I have just discovered an apparent bug in the whole Saved Import/XML setup in Access. Also frustrated by the rigidity of the Saved Import system, I created forms and wrote code to pick apart the XML in which the Saved Import specs are stored, to the point that I could use this tool to actually create a Saved Import from scratch via coded examination of a source Excel workbook.
What I've found out is that, while Access correctly imports a worksheet per modifications of default settings by the user (for example, it likes to take any column with a header name ending with "ID" and make it an indexed field in the resulting table, but you can cancel this during the import process), and while it also correctly creates XML in accordance to the user changes, if you then drop the table and use the Saved Import to re-import the worksheet, it ignores the XML import spec and reverts back to using its own invented defaults, at least in the case of the "ID" columns.
You can try this on your own: import an worksheet Excel with at least one column header name ending with "ID" ("OrderID", "User ID", or just plain "ID"). During the process, be sure to set "Indexed" to No for those columns. Execute the import and check "Save import steps" in the final dialog window. If you inspect the resulting table design, you will see there is no index on the field(s) in question. Then delete the table, find the saved import and execute it again. This time, those fields will be set as Indexed in the table design, even though the XML still says no index.
I was pulling my hair out until I discovered what was going on, comparing the XML I built from scratch with examples created through the Access tool.
On Windows :
1-Open Run Window by Winkey + R
2-Type services.msc
3-Search Postgres service based on version installed.
4-Click stop, start or restart the service option.
On Linux :
sudo systemctl restart postgresql
also instead of "restart" you can replace : status, stop or status.
For string comparisons in Perl, use eq
or ne
:
if ($str eq "")
{
// ...
}
The ==
and !=
operators are numeric comparison operators. They will attempt to convert both operands to integers before comparing them.
See the perlop man page for more information.
I know this question was asked 2 years ago, but I run into the same issue and the answer for the problem is since ES2017, that you can simply await
the functions return value (as of now, only works in async
functions), like:
let AuthUser = function(data) {
return google.login(data.username, data.password).then(token => { return token } )
}
let userToken = await AuthUser(data)
console.log(userToken) // your data
You can always use Request.QueryString
collection like Web forms, but you can also make MVC handle them and pass them as parameters. This is the suggested way as it's easier and it will validate input data type automatically.
safe: replace every sequence of NOT "a-zA-Z0-9_-" to a dash; add an extension yourself.
$name = preg_replace('/[^a-zA-Z0-9_-]+/', '-', strtolower($name)).'.'.$extension;
PyLibTiff worked better for me than PIL, which as of December 2020 still doesn't support color images with more than 8 bits per color.
from libtiff import TIFF
tif = TIFF.open('filename.tif') # open tiff file in read mode
# read an image in the currect TIFF directory as a numpy array
image = tif.read_image()
# read all images in a TIFF file:
for image in tif.iter_images():
pass
tif = TIFF.open('filename.tif', mode='w')
tif.write_image(image)
You can install PyLibTiff with
pip3 install numpy libtiff
The readme of PyLibTiff also mentions the tifffile
library but I haven't tried it.
Not sure if that's exactly what are you looking for, but I did single/double taps without gesture recognizers. I'm using it in a UITableView, so I used that code in the didSelectRowAtIndexPath method
tapCount++;
switch (tapCount)
{
case 1: //single tap
[self performSelector:@selector(singleTap:) withObject: indexPath afterDelay: 0.2];
break;
case 2: //double tap
[NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(singleTap:) object:indexPath];
[self performSelector:@selector(doubleTap:) withObject: indexPath];
break;
default:
break;
}
if (tapCount>2) tapCount=0;
Methods singleTap and doubleTap are just void with NSIndexPath as a parameter:
- (void)singleTap:(NSIndexPath *)indexPath {
//do your stuff for a single tap
}
- (void)doubleTap:(NSIndexPath *)indexPath {
//do your stuff for a double tap
}
Hope it helps
Edit: This is a very old answer and is here for prosperity just to show that it was supported once back in the 2000's but dropped because browsers strategy in the 2010's was to respect W3C specifications even if some features were removed: Scrollable table with fixed header/footer was clumsily specified before HTML5.
Unfortunately there is no elegant way to handle scrollable table with fixed thead
/tfoot
because HTML/CSS specifications are not very clear about that feature.
Although HTML 4.01 Specification says thead
/tfoot
/tbody
are used (introduced?) to scroll table body:
Table rows may be grouped [...] using the THEAD, TFOOT and TBODY elements [...]. This division enables user agents to support scrolling of table bodies independently of the table head and foot.
But the working scrollable table feature on FF 3.6 has been removed in FF 3.7 because considered as a bug because not compliant with HTML/CSS specifications. See this and that comments on FF bugs.
Below is a simplified version of the MDN useful tips for scrollable table
see this archived page or the current French version
<style type="text/css">
table {
border-spacing: 0; /* workaround */
}
tbody {
height: 4em; /* define the height */
overflow-x: hidden; /* esthetics */
overflow-y: auto; /* allow scrolling cells */
}
td {
border-left: 1px solid blue; /* workaround */
border-bottom: 1px solid blue; /* workaround */
}
</style>
<table>
<thead><tr><th>Header
<tfoot><tr><th>Footer
<tbody>
<tr><td>Cell 1 <tr><td>Cell 2
<tr><td>Cell 3 <tr><td>Cell 4
<tr><td>Cell 5 <tr><td>Cell 6
<tr><td>Cell 7 <tr><td>Cell 8
<tr><td>Cell 9 <tr><td>Cell 10
<tr><td>Cell 11 <tr><td>Cell 12
<tr><td>Cell 13 <tr><td>Cell 14
</tbody>
</table>
However MDN also says this does not work any more on FF :-(
I have also tested on IE8 => table is not scrollable either :-((
The standard formula to extract the values of attribute using XPath is
elementXPath/@attributeName
So here is the xpath to fetch the lang value of first attribute-
//title[text()='Harry Potter']/@lang
PS: indexes are never suggested to use in XPath as they can change if one more title tag comes in.
Dynamically:
editText.setFilters(new InputFilter[] { new InputFilter.LengthFilter(MAX_NUM) });
Via xml:
<EditText
android:maxLength="@integer/max_edittext_length"
It is better to use DataView for this task.
Example of the using it you can find in this post: How to filter data in dataview
A quick summary of the concepts:
Example:
Say you've got a button like this:
[ Click Me ]
and you've pinned the edges to a larger superview with priority 500.
Then, if Hugging priority > 500 it'll look like this:
[Click Me]
If Hugging priority < 500 it'll look like this:
[ Click Me ]
If the superview now shrinks then, if the Compression Resistance priority > 500, it'll look like this
[Click Me]
Else if Compression Resistance priority < 500, it could look like this:
[Cli..]
If it doesn't work like this then you've probably got some other constraints going on that are messing up your good work!
E.g. you could have it pinned to the superview with priority 1000. Or you could have a width priority. If so, this can be helpful:
Editor > Size to Fit Content
The easiest way to understand the difference is to think of the different possibilities. There are two objects to consider, the pointer and the object pointed to (in this case 'a' is the name of the pointer, the object pointed to is unnamed, of type char). The possibilities are:
These different possibilities can be expressed in C as follows:
I hope this illustrates the possible differences
You can check it easily using Java.lang.Class.getSimpleName()
Method Only if variable has non-primitive type. It doesnt work with primitive types int ,long etc.
reference - Here is the Oracle docs link
It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories.
It's abbreviated because C compilers at the dawn of time didn't support more than 8 characters in symbols.
This might help
lsof -n -i4TCP:8080
The PID is the second field in the output.
Or try:
lsof -i -P
Add a reference to System.Web
using System.Web;
Get the host or any other component of the url you want
string host = HttpContext.Current.Request.Url.Host;
I currently use this function in my project after a series of googling to download excel file from sql statement
// $sql = sql query e.g "select * from mytablename"
// $filename = name of the file to download
function queryToExcel($sql, $fileName = 'name.xlsx') {
// initialise excel column name
// currently limited to queries with less than 27 columns
$columnArray = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
// Execute the database query
$result = mysql_query($sql) or die(mysql_error());
// Instantiate a new PHPExcel object
$objPHPExcel = new PHPExcel();
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0);
// Initialise the Excel row number
$rowCount = 1;
// fetch result set column information
$finfo = mysqli_fetch_fields($result);
// initialise columnlenght counter
$columnlenght = 0;
foreach ($finfo as $val) {
// set column header values
$objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$columnlenght++] . $rowCount, $val->name);
}
// make the column headers bold
$objPHPExcel->getActiveSheet()->getStyle($columnArray[0]."1:".$columnArray[$columnlenght]."1")->getFont()->setBold(true);
$rowCount++;
// Iterate through each result from the SQL query in turn
// We fetch each database result row into $row in turn
while ($row = mysqli_fetch_array($result, MYSQL_NUM)) {
for ($i = 0; $i < $columnLenght; $i++) {
$objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$i] . $rowCount, $row[$i]);
}
$rowCount++;
}
// set header information to force download
header('Content-type: application/vnd.ms-excel');
header('Content-Disposition: attachment; filename="' . $fileName . '"');
// Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file
// Write the Excel file to filename some_excel_file.xlsx in the current directory
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel);
// Write the Excel file to filename some_excel_file.xlsx in the current directory
$objWriter->save('php://output');
}
Google gives a breakdown of these fields in the Evaluating network performance section of their DevTools documentation.
Stalled/Blocking
Time the request spent waiting before it could be sent. This time is inclusive of any time spent in proxy negotiation. Additionally, this time will include when the browser is waiting for an already established connection to become available for re-use, obeying Chrome's maximum six TCP connection per origin rule.
(If you forget, Chrome has an "Explanation" link in the hover tooltip and under the "Timing" panel.)
Basically, the primary reason you will see this is because Chrome will only download 6 files per-server at a time and other requests will be stalled until a connection slot becomes available.
This isn't necessarily something that needs fixing, but one way to avoid the stalled state would be to distribute the files across multiple domain names and/or servers, keeping CORS in mind if applicable to your needs, however HTTP2 is probably a better option going forward. Resource bundling (like JS and CSS concatenation) can also help to reduce amount of stalled connections.
I too was searching for this topic and I put together a way to iterate through a DataFrame and update it with lookup values from a second DataFrame. Here is my code.
src_df = pd.read_sql_query(src_sql,src_connection)
for index1, row1 in src_df.iterrows():
for index, row in vertical_df.iterrows():
src_df.set_value(index=index1,col=u'etl_load_key',value=etl_load_key)
if (row1[u'src_id'] == row['SRC_ID']) is True:
src_df.set_value(index=index1,col=u'vertical',value=row['VERTICAL'])
You can use it to transform some aggregate functions into analytic:
SELECT MAX(date)
FROM mytable
will return 1
row with a single maximum,
SELECT MAX(date) OVER (ORDER BY id)
FROM mytable
will return all rows with a running maximum.
you don't need to destroy the object CKeditor, you need remove() :
Change this :
CKEDITOR.instances['textarea_name'].destroy();
for that :
CKEDITOR.remove(CKEDITOR.instances['textarea_name']);
The PropertiesPlaceholderConfigurer
bean has an alternative property called "propertiesArray". Use this instead of the "properties" property, and configure it with an <array>
of property references.
I'm glad that worked out, so I guess you had to explicitly set 'auto' on IE6 in order for it to mimic other browsers!
I actually recently found another technique for scaling images, again designed for backgrounds. This technique has some interesting features:
The markup relies on a wrapper element:
<div id="wrap"><img src="test.png" /></div>
Given the above markup you then use these rules:
#wrap {
height: 100px;
width: 100px;
}
#wrap img {
min-height: 100%;
min-width: 100%;
}
If you then control the size of wrapper you get the interesting scale effects that I list above.
To be explicit, consider the following base state: A container that is 100x100 and an image that is 10x10. The result is a scaled image of 100x100.
So, in other words, the image is always at least as big as the container, but will scale beyond it to maintain it's aspect ratio.
This probably isn't useful for your site, and it doesn't work in IE6. But, it is useful to get a scaled background for your view port or container.
Although maven exec does the trick here, I found it pretty poor for a real test. While waiting for maven shell, and hoping this could help others, I finally came out to this repo mvnexec
Clone it, and symlink the script somewhere in your path. I use ~/bin/mvnexec
, as I have ~/bin
in my path. I think mvnexec is a good name for the script, but is up to you to change the symlink...
Launch it from the root of your project, where you can see src and target dirs.
The script search for classes with main method, offering a select to choose one (Example with mavenized JMeld project)
$ mvnexec
1) org.jmeld.ui.JMeldComponent
2) org.jmeld.ui.text.FileDocument
3) org.jmeld.JMeld
4) org.jmeld.util.UIDefaultsPrint
5) org.jmeld.util.PrintProperties
6) org.jmeld.util.file.DirectoryDiff
7) org.jmeld.util.file.VersionControlDiff
8) org.jmeld.vc.svn.InfoCmd
9) org.jmeld.vc.svn.DiffCmd
10) org.jmeld.vc.svn.BlameCmd
11) org.jmeld.vc.svn.LogCmd
12) org.jmeld.vc.svn.CatCmd
13) org.jmeld.vc.svn.StatusCmd
14) org.jmeld.vc.git.StatusCmd
15) org.jmeld.vc.hg.StatusCmd
16) org.jmeld.vc.bzr.StatusCmd
17) org.jmeld.Main
18) org.apache.commons.jrcs.tools.JDiff
#?
If one is selected (typing number), you are prompt for arguments (you can avoid with mvnexec -P
)
By default it compiles project every run. but you can avoid that using mvnexec -B
It allows to search only in test classes -M
or --no-main
, or only in main classes -T
or --no-test
. also has a filter by name option -f <whatever>
Hope this could save you some time, for me it does.
In a .git directory in the root of the project. Unlike some other version control systems, notably CVS, there are no additional directories in any of the subdirectories.
If you really like one-liners and there is a use for underscore.js in your project (which is a great library) you can do write-only things like:
_.range(9).map(function(n) {
return _.range(9).map(function(n) {
return null;
});
});
But I would go with standard for-cycle version mentioned above.
You don't need root to pull the apk files from /data/app
. Sure, you might not have permissions to list the contents of that directory, but you can find the file locations of APKs with:
adb shell pm list packages -f
Then you can use adb pull
:
adb pull <APK path from previous command>
and then aapt
to get the information you want:
aapt dump badging <pulledfile.apk>
Google thrives on scraping websites of the world...so if it was "so illegal" then even Google won't survive ..of course other answers mention ways of mitigating IP blocks by Google. One more way to explore avoiding captcha could be scraping at random times (dint try) ..Moreover, I have a feeling, that if we provide novelty or some significant processing of data then it sounds fine at least to me...if we are simply copying a website.. or hampering its business/brand in some way...then it is bad and should be avoided..on top of it all...if you are a startup then no one will fight you as there is no benefit.. but if your entire premise is on scraping even when you are funded then you should think of more sophisticated ways...alternative APIs..eventually..Also Google keeps releasing (or depricating) fields for its API so what you want to scrap now may be in roadmap of new Google API releases..
If you are using a Form Control
, you can get the same property as ActiveX
by using OLEFormat.Object
property of the Shape Object
. Better yet assign it in a variable declared as OptionButton to get the Intellisense kick in.
Dim opt As OptionButton
With Sheets("Sheet1") ' Try to be always explicit
Set opt = .Shapes("Option Button 1").OLEFormat.Object ' Form Control
Debug.Pring opt.Value ' returns 1 (true) or -4146 (false)
End With
But then again, you really don't need to know the value.
If you use Form Control
, you associate a Macro
or sub routine with it which is executed when it is selected. So you just need to set up a sub routine that identifies which button is clicked and then execute a corresponding action for it.
For example you have 2 Form Control
Option Buttons.
Sub CheckOptions()
Select Case Application.Caller
Case "Option Button 1"
' Action for option button 1
Case "Option Button 2"
' Action for option button 2
End Select
End Sub
In above code, you have only one sub routine assigned to both option buttons.
Then you test which called the sub routine by checking Application.Caller
.
This way, no need to check whether the option button value is true or false.
You can do that by storing cookies on client side.
In general, you're looking for the "Except" extension.
var rejectStatus = GenerateRejectStatuses();
var fullList = GenerateFullList();
var rejectList = fullList.Where(i => rejectStatus.Contains(i.Status));
var filteredList = fullList.Except(rejectList);
In this example, GenerateRegectStatuses() should be the list of statuses you wish to reject (or in more concrete terms based on your example, a List<int>
of IDs)
Try this:
scanf("%[^\n]s",name);
\n
just sets the delimiter for the scanned string.
See here - http://my.opera.com/community/forums/topic.dml?id=1319992&t=1331393279&page=1#comment11751402
Essentially:
history.pushState('data', '', 'http://your-domain/path');
You can manipulate the history object to make this work.
It only works on the same domain, but since you're satisfied with using the hash tag approach, that shouldn't matter.
Obviously would need to be cross-browser tested, but since that was posted on the Opera forum I'm safe to assume it would work in Opera, and I just tested it in Chrome and it worked fine.
You can use Application Settings for this, using database is not the best option considering the time consumed to read and write the settings(specially if you use web services).
Here are few links which explains how to achieve this and use them in WPF -
Quick WPF Tip: How to bind to WPF application resources and settings?
foreach ($tmpArray as $innerArray) {
// Check type
if (is_array($innerArray)){
// Scan through inner loop
foreach ($innerArray as $value) {
echo $value;
}
}else{
// one, two, three
echo $innerArray;
}
}
You can redirect by this method also:
return Yii::$app->response->redirect(['user/index', 'id' => 10]);
If you want to send the Header information immediately use with send().This method adds a Location header to the current response.
return Yii::$app->response->redirect(['user/index', 'id' => 10])->send();
If you want the complete URL then use like Url::to(['user/index', 'id' => 302])
with the header of use yii\helpers\Url;
.
For more information check Here. Hope this will help someone.
I used this and works for me.
<div class="col-sm-3">
<img src="xxx.png" style="width: auto; height: 195px;">
</div>
On Windows 2003, to call another script without waiting, I used this:
$commandString = "start /b c:\\php\\php.EXE C:\\Inetpub\\wwwroot\\mysite.com\\phpforktest.php --passmsg=$testmsg";
pclose(popen($commandString, 'r'));
This only works AFTER giving changing permissions on cmd.exe
- add Read and Execute for IUSR_YOURMACHINE
(I also set write to Deny).
First, disable the php5
module:
a2dismod php5
then, enable the php7
module:
a2enmod php7.0
Next, reload/restart the Apache service:
service apache2 restart
wrt the comment, you need to specify exact installed php-7.x version.
I have used following function to parse csv string to associative array
public function csvToArray($file) {
$rows = array();
$headers = array();
if (file_exists($file) && is_readable($file)) {
$handle = fopen($file, 'r');
while (!feof($handle)) {
$row = fgetcsv($handle, 10240, ',', '"');
if (empty($headers))
$headers = $row;
else if (is_array($row)) {
array_splice($row, count($headers));
$rows[] = array_combine($headers, $row);
}
}
fclose($handle);
} else {
throw new Exception($file . ' doesn`t exist or is not readable.');
}
return $rows;
}
if your csv file name is mycsv.csv then you call this function as:
$dataArray = csvToArray(mycsv.csv);
you can get this script also in http://www.scriptville.in/parse-csv-data-to-array/
As everyone noticed: you can't. But you can create a obj and assign every var you declare to that obj. That way you can easily check out your vars:
var v = {}; //put everything here
var f = function(a, b){//do something
}; v.f = f; //make's easy to debug
var a = [1,2,3];
v.a = a;
var x = 'x';
v.x = x; //so on...
console.log(v); //it's all there
You need an scp client. Putty is not one. You can use WinSCP or PSCP. Both are free software.
One trick you can use to increase the number of concurrent connections is to host your images from a different sub domain. These will be treated as separate requests, each domain is what will be limited to the concurrent maximum.
IE6, IE7 - have a limit of two. IE8 is 6 if you have a broadband - 2 (if it's a dial up).
There is only one way from what I am aware.
Have 2 images, first a jpeg with first frame(or whatever you want) of the gif and the actual gif.
Load the page with the jpeg in place and on mouse over replace the jpeg with the gif. You can preload the gifs if you want or if they are of big size show a loading while the gif is loading and then replace the jpeg with it.
If you whant it to bi linear as in have the gif play on mouse over, stop it on mouse out and then resume play from the frame you stopped, then this cannot be done with javascript+gif combo.
This solution will allow you to load a local script using jQuery.getScript(). This is a global setting but you can also set the crossDomain option on a per-request basis.
$.ajaxPrefilter( "json script", function( options ) {
options.crossDomain = true;
});
string.replace(/^\s+|\s+$/g, "");
$time = 00:06:00;
$timeInSeconds = strtotime($time) - strtotime('TODAY');
You can also use synchronized
keyword for addFinisher
method like this
//Implement the one method in the RaceListener interface
public synchronized void addFinisher(RaceCar finisher) {
finishingOrder.add(finisher);
}
So you can use ArrayList add method thread-safe with this way.
The first value is the precision and the second is the scale, so 18,0
is essentially 18 digits with 0 digits after the decimal place. If you had 18,2
for example, you would have 18 digits, two of which would come after the decimal...
example of 18,2: 1234567890123456.12
There is no functional difference between numeric
and decimal
, other that the name and I think I recall that numeric came first, as in an earlier version.
And to answer, "can I add (-10) in that column?" - Yes, you can.
TextView has an android:drawablePadding property which should do the trick:
android:drawablePadding
The padding between the drawables and the text.
Must be a dimension value, which is a floating point number appended with a unit such as "14.5sp". Available units are: px (pixels), dp (density-independent pixels), sp (scaled pixels based on preferred font size), in (inches), mm (millimeters).
This may also be a reference to a resource (in the form "@[package:]type:name") or theme attribute (in the form "?[package:][type:]name") containing a value of this type.
This corresponds to the global attribute resource symbol drawablePadding.
You can use PyObjC on the iPhone as well, due to the excellent work by Jay Freeman (saurik). See iPhone Applications in Python.
Note that this requires a jailbroken iPhone at the moment.
server {
server_name .mydomain.com;
return 301 http://www.adifferentdomain.com$request_uri;
}
http://wiki.nginx.org/HttpRewriteModule#return
and
The answers to your two questions are related. I'll start with the second:
Once you have staged a file (often with git add
, though some other commands implicitly stage the changes as well, like git rm
) you can back out that change with git reset -- <file>
.
In your case you must have used git rm
to remove the file, which is equivalent to simply removing it with rm
and then staging that change. If you first unstage it with git reset -- <file>
you can then recover it with git checkout -- <file>
.
try...
String.format("%016d\n", Integer.parseInt(Integer.toBinaryString(256)));
I dont think this is the "correct" way to doing this... but it works :)
There was a Python enhancement proposal PEP 299 which aimed to replace if __name__ == '__main__':
idiom with def __main__:
, but it was rejected. It's still a good read to know what to keep in mind when using if __name__ = '__main__':
.
After you correct the possible dmp file problem, this is a way to ensure that the schema is remapped and imported appropriately. This will also ensure that the tablespace will change also, if needed:
impdp system/<password> SCHEMAS=user1 remap_schema=user1:user2 \
remap_tablespace=user1:user2 directory=EXPORTDIR \
dumpfile=user1.dmp logfile=E:\Data\user1.log
EXPORTDIR must be defined in oracle as a directory as the system user
create or replace directory EXPORTDIR as 'E:\Data';
grant read, write on directory EXPORTDIR to user2;
<select id="ddlvalue" name="ddlvaluename">
<option value='0' disabled selected>Select Value</option>
<option value='1' >Value 1</option>
<option value='2' >Value 2</option>
</select>
<input type="submit" id="btn_submit" value="click me"/>
<script>
$('#btn_submit').on('click',function(){
$('#ddlvalue').val(0);
});
</script>
I also faced the same problem but I resolved the issue by starting the TNS listener in control panel -> administrative tools -> services ->oracle TNS listener start.I am using windows Xp and Toad to connect to Oracle.
As in the opencv-doc you can get video feed from a camera which is connected to your computer by following code.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
You can change cap = cv2.VideoCapture(0)
index from 0
to 1
to access the 2nd camera.
Tested in opencv-3.2.0
Hibernate is not going to make it easy for you to do what you are trying to do. From the Hibernate documentation:
Note that when using referencedColumnName to a non primary key column, the associated class has to be Serializable. Also note that the referencedColumnName to a non primary key column has to be mapped to a property having a single column (other cases might not work). (emphasis added)
So if you are unwilling to make AnEmbeddableObject
the Identifier for Bar then Hibernate is not going to lazily, automatically retrieve Bar for you. You can, of course, still use HQL to write queries that join on AnEmbeddableObject
, but you lose automatic fetching and life cycle maintenance if you insist on using a multi-column non-primary key for Bar.
with Kotlin I execute this code:
requireContext().startActivity<YourTargetActivity>()
In Bash 5 there's a new variable:
echo $EPOCHSECONDS
Or if you want higher precision (in microseconds):
echo $EPOCHREALTIME
Set a local value with the observer
...also, don't forget to initialize the value with dummy data to avoid uninitialized
errors.
export class ModelService {
constructor() {
this.mode = new Model();
this._http.get('/api/v1/cats')
.map(res => res.json())
.subscribe(
json => {
this.model = new Model(json);
},
error => console.log(error);
);
}
}
This assumes Model, is a data model representing the structure of your data.
Model with no parameters should create a new instance with all values initialized (but empty). That way, if the template renders before the data is received it won't throw an error.
Ideally, if you want to persist the data to avoid unnecessary http requests you should put this in an object that has its own observer that you can subscribe to.
If the logic parsing this knows that {"key": "slide0001.html", "value": "Looking Ahead"}
is a key/value pair, then you could transform it in an array and hold a few constants specifying which index maps to which key.
For example:
var data = ["slide0001.html", "Looking Ahead"];
var C_KEY = 0;
var C_VALUE = 1;
var value = data[C_VALUE];
So, now, your data can be:
[
["slide0001.html", "Looking Ahead"],
["slide0008.html", "Forecast"],
["slide0021.html", "Summary"]
]
If your parsing logic doesn't know ahead of time about the structure of the data, you can add some metadata to describe it. For example:
{ meta: { keys: [ "key", "value" ] },
data: [
["slide0001.html", "Looking Ahead"],
["slide0008.html", "Forecast"],
["slide0021.html", "Summary"]
]
}
... which would then be handled by the parser.
Two main steps involved are
1- Creating a C++ dll
In visual studio
New->Project->Class Library in c++ template. Name of project here is first_dll in
visual studio 2010. Now declare your function as public in first_dll.h file and
write the code in first_dll.cpp file as shown below.
Header File code
// first_dll.h
using namespace System;
namespace first_dll
{
public ref class Class1
{
public:
static double sum(int ,int );
// TODO: Add your methods for this class here.
};
}
Cpp File
//first_dll.cpp
#include "stdafx.h"
#include "first_dll.h"
namespace first_dll
{
double Class1:: sum(int x,int y)
{
return x+y;
}
}
Check This
**Project-> Properties -> Configuration/General -> Configuration Type**
this option should be Dynamic Library(.dll) and build the solution/project now.
first_dll.dll file is created in Debug folder
2- Linking it in C# project
Open C# project
Rightclick on project name in solution explorer -> Add -> References -> Browse to path
where first_dll.dll is created and add the file.
Add this line at top in C# project
Using first_dll;
Now function from dll can be accessed using below statement in some function
double var = Class1.sum(4,5);
I created dll in c++ project in VS2010 and used it in VS2013 C# project.It works well.
If you are looking for an answer in java code,
LinearLayout linearLayout = new LinearLayout(context);
linearLayout.setGravity(Gravity.CENTER);
// add children
Instead of implementing a "constants interface", in Java 1.5+, you can use static imports to import the constants/static methods from another class/interface:
import static com.kittens.kittenpolisher.KittenConstants.*;
This avoids the ugliness of making your classes implement interfaces that have no functionality.
As for the practice of having a class just to store constants, I think it's sometimes necessary. There are certain constants that just don't have a natural place in a class, so it's better to have them in a "neutral" place.
But instead of using an interface, use a final class with a private constructor. (Making it impossible to instantiate or subclass the class, sending a strong message that it doesn't contain non-static functionality/data.)
Eg:
/** Set of constants needed for Kitten Polisher. */
public final class KittenConstants
{
private KittenConstants() {}
public static final String KITTEN_SOUND = "meow";
public static final double KITTEN_CUTENESS_FACTOR = 1;
}
Try this code.
public void send (String fileName) {
String SFTPHOST = "host:IP";
int SFTPPORT = 22;
String SFTPUSER = "username";
String SFTPPASS = "password";
String SFTPWORKINGDIR = "file/to/transfer";
Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;
System.out.println("preparing the host information for sftp.");
try {
JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER, SFTPHOST, SFTPPORT);
session.setPassword(SFTPPASS);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();
System.out.println("Host connected.");
channel = session.openChannel("sftp");
channel.connect();
System.out.println("sftp channel opened and connected.");
channelSftp = (ChannelSftp) channel;
channelSftp.cd(SFTPWORKINGDIR);
File f = new File(fileName);
channelSftp.put(new FileInputStream(f), f.getName());
log.info("File transfered successfully to host.");
} catch (Exception ex) {
System.out.println("Exception found while tranfer the response.");
} finally {
channelSftp.exit();
System.out.println("sftp Channel exited.");
channel.disconnect();
System.out.println("Channel disconnected.");
session.disconnect();
System.out.println("Host Session disconnected.");
}
}
This is not the exact answer, but this might be helpful for the people looking to solve some problem with the approach of ordering row before group by in mysql.
I came to this thread, when I wanted to find the latest row(which is order by date desc
but get the only one result for a particular column type, which is group by column name
).
One other approach to solve such problem is to make use of aggregation.
So, we can let the query run as usual, which sorted asc and introduce new field as max(doc) as latest_doc
, which will give the latest date, with grouped by the same column.
Suppose, you want to find the data of a particular column now and max aggregation cannot be done.
In general, to finding the data of a particular column, you can make use of GROUP_CONCAT aggregator
, with some unique separator which can't be present in that column, like GROUP_CONCAT(string SEPARATOR ' ') as new_column
, and while you're accessing it, you can split/explode the new_column field.
Again, this might not sound to everyone. I did it, and liked it as well because I had written few functions and I couldn't run subqueries. I am working on codeigniter framework for php.
Not sure of the complexity as well, may be someone can put some light on that.
Regards :)
'use lib' can also take a single string value...
#!/usr/bin/perl
use lib '<relative-path>';
use <your lib>;
navigate to the folder where you have installed your kibana if you have used yum to install kibana it will be placed in following location by default
/usr/share/kibana
then use the following command
bin/kibana --version
Swift 5 - This works for me:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedCell:UITableViewCell = tableView.cellForRow(at: indexPath as IndexPath)!
selectedCell.contentView.backgroundColor = .red
}
func tableView(_ tableView: UITableView, didDeselectRowAt indexPath: IndexPath) {
let cellToDeSelect:UITableViewCell = tableView.cellForRow(at: indexPath as IndexPath)!
cellToDeSelect.contentView.backgroundColor = .clear
}
You are producing a filtered list by using a list comprehension. i
is still being bound to each and every element of that list, and the last element is still 'three'
, even if it was subsequently filtered out from the list being produced.
You should not use a list comprehension to pick out one element. Just use a for
loop, and break
to end it:
for elem in my_list:
if elem == 'two':
break
If you must have a one-liner (which would be counter to Python's philosophy, where readability matters), use the next()
function and a generator expression:
i = next((elem for elem in my_list if elem == 'two'), None)
which will set i
to None
if there is no such matching element.
The above is not that useful a filter; your are essentially testing if the value 'two'
is in the list. You can use in
for that:
elem = 'two' if 'two' in my_list else None
"The
==
operator checks to see if twoObjects
are exactly the sameObject
."
http://leepoint.net/notes-java/data/strings/12stringcomparison.html
String
is an Object
in java, so it falls into that category of comparison rules.
SQLAlchemy introduced that in version 1.0.0
:
Bulk operations - SQLAlchemy docs
With these operations, you can now do bulk inserts or updates!
For instance (if you want the lowest overhead for simple table INSERTs), you can use Session.bulk_insert_mappings()
:
loadme = [(1, 'a'),
(2, 'b'),
(3, 'c')]
dicts = [dict(bar=t[0], fly=t[1]) for t in loadme]
s = Session()
s.bulk_insert_mappings(Foo, dicts)
s.commit()
Or, if you want, skip the loadme
tuples and write the dictionaries directly into dicts
(but I find it easier to leave all the wordiness out of the data and load up a list of dictionaries in a loop).
The problem is due to the input element box model. I just recently found a nice solution to the issue when trying to keep my input at 100% for mobile devices.
Wrap your input with another element, a div for example. Then apply the styling you want for your input to that the wrapper div. For example:
<div class="input-wrapper">
<input type="text" />
</div>
.input-wrapper {
border-raius:5px;
padding:10px;
}
.input-wrapper input[type=text] {
width:100%;
font-size:16px;
}
Give .input-wrapper rounded corner padding etc, whatever you want for your input, then give the input width 100%. You have your input padded nicely with a border etc but without the annoying overflow!
When dealing with the HTML DOM (ie. this
), the array selector [0]
must be used to retrieve the jQuery element from the Javascript array.
$(this)[0].getAttribute('src');
You can check for port numbers with these command examples on wireshark:-
tcp.port==80
tcp.port==14220
Also, comments have to be on their own line. They can't be put after an entry. So this won't work:
/node_modules # DON'T COMMENT HERE (since nullifies entire line)
But this will work:
# fine to comment here
/node_modules
rmdir /s /q folder
powershell -Command "Remove-Item -LiteralPath 'folder' -Force -Recurse"
Note that in more cases del
and rmdir
wil leave you with leftover files, where Powershell manages to delete the files.
To elaborate on the answer @xhh provided, you can append the red, green, and blue to format your string as "rgb(0,0,0)" before returning it.
/**
*
* @param colorStr e.g. "#FFFFFF"
* @return String - formatted "rgb(0,0,0)"
*/
public static String hex2Rgb(String colorStr) {
Color c = new Color(
Integer.valueOf(hexString.substring(1, 3), 16),
Integer.valueOf(hexString.substring(3, 5), 16),
Integer.valueOf(hexString.substring(5, 7), 16));
StringBuffer sb = new StringBuffer();
sb.append("rgb(");
sb.append(c.getRed());
sb.append(",");
sb.append(c.getGreen());
sb.append(",");
sb.append(c.getBlue());
sb.append(")");
return sb.toString();
}
In modern-day JS, you can get your JSON data by calling ES6's fetch()
on your URL and then using ES7's async/await
to "unpack" the Response object from the fetch to get the JSON data like so:
const getJSON = async url => {
try {
const response = await fetch(url);
if(!response.ok) // check if response worked (no 404 errors etc...)
throw new Error(response.statusText);
const data = await response.json(); // get JSON from the response
return data; // returns a promise, which resolves to this data value
} catch(error) {
return error;
}
}
console.log("Fetching data...");
getJSON("https://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=json").then(data => {
console.log(data);
}).catch(error => {
console.error(error);
});
_x000D_
The above method can be simplified down to a few lines if you ignore the exception/error handling (usually not recommended as this can lead to unwanted errors):
const getJSON = async url => {
const response = await fetch(url);
return response.json(); // get JSON from the response
}
console.log("Fetching data...");
getJSON("https://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=json")
.then(data => console.log(data));
_x000D_
I am not 100% sure where all of the other suggestions are trying to go, but the issue is basically related to the extension that you have on the file. If you save the file as a Excel 97/2003 workbook it will not allow you to see all million rows. Create a new sheet and save it as a workbook and you will see all million. Note: the extension will be .xlsx
I hope it will be useful.
// Get the canvas element
var canvas = document.getElementById('canvas');
var isInFullScreen = (document.fullscreenElement && document.fullscreenElement !== null) ||
(document.webkitFullscreenElement && document.webkitFullscreenElement !== null) ||
(document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
(document.msFullscreenElement && document.msFullscreenElement !== null);
// Enter fullscreen
function fullscreen(){
if(canvas.RequestFullScreen){
canvas.RequestFullScreen();
}else if(canvas.webkitRequestFullScreen){
canvas.webkitRequestFullScreen();
}else if(canvas.mozRequestFullScreen){
canvas.mozRequestFullScreen();
}else if(canvas.msRequestFullscreen){
canvas.msRequestFullscreen();
}else{
alert("This browser doesn't supporter fullscreen");
}
}
// Exit fullscreen
function exitfullscreen(){
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}else{
alert("Exit fullscreen doesn't work");
}
}
Honestly, I'd recommend using phpseclib, a pure PHP SSH2 implementation. Example:
<?php
include('Net/SSH2.php');
$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
exit('Login Failed');
}
echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
?>
It's a ton more portable, easier to use and more feature packed too.
Thanks @BIJAY_JHA and @Manaus. I used the Kotlin version to call my signIn() method that lives in the Activity and that I'm calling from a Fragment. I'm using Navigation Architecture in Android so the Listener interface pattern isn't in the Fragment:
(activity as MainActivity).signIn()
This can be caused by SELinux. If you don't want to disable SELinux completely, you need to set the db directory fcontext to httpd_sys_rw_content_t.
semanage fcontext -a -t httpd_sys_rw_content_t "/var/www/railsapp/db(/.*)?"
restorecon -v /var/www/railsapp/db