This will do the same as many of the other answers, but will make sides flush with the window, so there is no scroll bars.
<div class="container-fluid">
<div class="row">
<div class="col" style="padding: 0;">
<img src="example.jpg" class="img-responsive" alt="Example">
</div>
</div>
</div>
Or... in shell...
service mysql restart
Yeah, I know, I'm lazy, but it can be handy too.
Save yourself of a MAJOR headache... Your problem might be that you are missing the quotes around the password. At least that was my case that detoured me for 3 hours.
[client]
user = myusername
password = "mypassword" # <----------------------- VERY IMPORTANT (quotes)
host = localhost
http://dev.mysql.com/doc/refman/5.7/en/option-files.html
Search for "Here is a typical user option file:" and see the example they state in there. Good luck, and I hope to save someone else some time.
In the App domain section, you are writing your app domain but you also need to add your login domain i.e. the name of html page where you ask user to login. In my case, I was testing it on localhost and the login route was localhost/login, If I only put http://localhost.com in App domain section, I get this error. But after adding http://localhost/login.com, the error was fixed. and also the App settings has changed in newer version of SDK, in which there is no option for OAuth redirect route. You've to assign the redirect route directly from server side, after successfully getting OAuth token.
using SimpleDateFormat or DateFormat class through
for e.g.
try{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy"); // here set the pattern as you date in string was containing like date/month/year
Date d = sdf.parse("20/12/2011");
}catch(ParseException ex){
// handle parsing exception if date string was different from the pattern applying into the SimpleDateFormat contructor
}
Text files in Windows don't have a format. There's an unofficial convention that if the file starts with the BOM codepoint in UTF-8 format that it's UTF-8, but that convention isn't universally supported. That would be the 3 byte sequence "\xef\xbf\xbe"
, i.e. ￾
in the Latin-1 character set.
Enabled
property to false
or
this.dataGridView1.DefaultCellStyle.SelectionBackColor = this.dataGridView1.DefaultCellStyle.BackColor;
this.dataGridView1.DefaultCellStyle.SelectionForeColor = this.dataGridView1.DefaultCellStyle.ForeColor;
The inherit
value, when used, means that the value of the property is set to the value of the same property of the parent element. For the root element (in HTML documents, for the html
element) there is no parent element; by definition, the value used is the initial value of the property. The initial value is defined for each property in CSS specifications.
The font-family
property is special in the sense that the initial value is not fixed in the specification but defined to be browser-dependent. This means that the browser’s default font family is used. This value can be set by the user.
If there is a continuous chain of elements (in the sense of parent-child relationships) from the root element to the current element, all with font-family
set to inherit
or not set at all in any style sheet (which also causes inheritance), then the font is the browser default.
This is rather uninteresting, though. If you don’t set fonts at all, browsers defaults will be used. Your real problem might be different – you seem to be looking at the part of style sheets that constitute a browser style sheet. There are probably other, more interesting style sheets that affect the situation.
In Python 2:
data = raw_input('Enter something: ')
print data
In Python 3:
data = input('Enter something: ')
print(data)
Two ways comes to mind:
int i = 3;
String someNum = "123";
// Way 1:
char[] zeroes1 = new char[i];
Arrays.fill(zeroes1, '0');
String newNum1 = someNum + new String(zeroes1);
System.out.println(newNum1); // 123000
// Way 2:
String zeroes2 = String.format("%0" + i + "d", 0);
String newNum2 = someNum + zeroes2;
System.out.println(newNum2); // 123000
Way 2 can be shortened to:
someNum += String.format("%0" + i + "d", 0);
System.out.println(someNum); // 123000
More about String#format()
is available in its API doc and the one of java.util.Formatter
.
As all the other answers say; it can be almost anything but is usually "JQuery".
However, in ES6 it is a string interpolation operator in a template "literal" eg.
var s = "new" ; // you can put whatever you think appropriate here.
var s2 = `There are so many ${s} ideas these days !!` ; //back-ticks not quotes
console.log(s2) ;
result:
There are so many new ideas these days !!
I'm sure that the above answers work perfectly. However, I had the difficulty of adding the double quotes as my bash lines where closer to 100. So, the following way helped me. (In a nutshell, no double quotes around each line of the shell)
Also, when I had "bash '''#!/bin/bash" within steps, I got the following error java.lang.NoSuchMethodError: No such DSL method '**bash**' found among steps
pipeline {
agent none
stages {
stage ('Hello') {
agent any
steps {
echo 'Hello, '
sh '''#!/bin/bash
echo "Hello from bash"
echo "Who I'm $SHELL"
'''
}
}
}
}
The result of the above execution is
If you also want to preserve the original file name, try with:
wget --content-disposition --trust-server-names -i list_of_urls.txt
Chrome makes this very simple these days:
function saveContent(fileContents, fileName)
{
var link = document.createElement('a');
link.download = fileName;
link.href = 'data:,' + fileContents;
link.click();
}
Lots of potential solutions, but let's add just one more. Use Jackson (JSON processing lib) to do "json-less" conversion, like:
ObjectMapper m = new ObjectMapper();
Map<String,Object> props = m.convertValue(myBean, Map.class);
MyBean anotherBean = m.convertValue(props, MyBean.class);
(this blog entry has some more examples)
You can basically convert any compatible types: compatible meaning that if you did convert from type to JSON, and from that JSON to result type, entries would match (if configured properly can also just ignore unrecognized ones).
Works well for cases one would expect, including Maps, Lists, arrays, primitives, bean-like POJOs.
What you've written actually almost works (it would work if all the variables were numbers), but it's not an idiomatic way at all.
(…)
parentheses indicate a subshell. What's inside them isn't an expression like in many other languages. It's a list of commands (just like outside parentheses). These commands are executed in a separate subprocess, so any redirection, assignment, etc. performed inside the parentheses has no effect outside the parentheses.
$(…)
is a command substitution: there is a command inside the parentheses, and the output from the command is used as part of the command line (after extra expansions unless the substitution is between double quotes, but that's another story).{ … }
braces are like parentheses in that they group commands, but they only influence parsing, not grouping. The program x=2; { x=4; }; echo $x
prints 4, whereas x=2; (x=4); echo $x
prints 2. (Also braces require spaces around them and a semicolon before closing, whereas parentheses don't. That's just a syntax quirk.)
${VAR}
is a parameter expansion, expanding to the value of a variable, with possible extra transformations.((…))
double parentheses surround an arithmetic instruction, that is, a computation on integers, with a syntax resembling other programming languages. This syntax is mostly used for assignments and in conditionals.
$((…))
, which expand to the integer value of the expression.[[ … ]]
double brackets surround conditional expressions. Conditional expressions are mostly built on operators such as -n $variable
to test if a variable is empty and -e $file
to test if a file exists. There are also string equality operators: "$string1" == "$string2"
(beware that the right-hand side is a pattern, e.g. [[ $foo == a* ]]
tests if $foo
starts with a
while [[ $foo == "a*" ]]
tests if $foo
is exactly a*
), and the familiar !
, &&
and ||
operators for negation, conjunction and disjunction as well as parentheses for grouping. Note that you need a space around each operator (e.g. [[ "$x" == "$y" ]]
, not [[ "$x"=="$y" ]]
;
both inside and outside the brackets (e.g. [[ -n $foo ]]
, not [[-n $foo]]
[ … ]
single brackets are an alternate form of conditional expressions with more quirks (but older and more portable). Don't write any for now; start worrying about them when you find scripts that contain them.This is the idiomatic way to write your test in bash:
if [[ $varA == 1 && ($varB == "t1" || $varC == "t2") ]]; then
If you need portability to other shells, this would be the way (note the additional quoting and the separate sets of brackets around each individual test, and the use of the traditional =
operator rather than the ksh/bash/zsh ==
variant):
if [ "$varA" = 1 ] && { [ "$varB" = "t1" ] || [ "$varC" = "t2" ]; }; then
Take a look at my jquery videoBG plugin
http://syddev.com/jquery.videoBG/
Make any HTML5 video a site background... has an image fallback for browsers that don't support html5
Really easy to use
Let me know if you need any help.
For what it's worth, my groovy spike seems to work with both UTF-8 and ISO-8859-1 character encodings. Not sure what will happen when a non zxing decoder tries to decode the UTF-8 encoded image though... probably varies depending on the device.
// ------------------------------------------------------------------------------------
// Requires: groovy-1.7.6, jdk1.6.0_03, ./lib with zxing core-1.7.jar, javase-1.7.jar
// Javadocs: http://zxing.org/w/docs/javadoc/overview-summary.html
// Run with: groovy -cp "./lib/*" zxing.groovy
// ------------------------------------------------------------------------------------
import com.google.zxing.*
import com.google.zxing.common.*
import com.google.zxing.client.j2se.*
import java.awt.image.BufferedImage
import javax.imageio.ImageIO
def class zxing {
def static main(def args) {
def filename = "./qrcode.png"
def data = "This is a test to see if I can encode and decode this data..."
def charset = "UTF-8" //"ISO-8859-1"
def hints = new Hashtable<EncodeHintType, String>([(EncodeHintType.CHARACTER_SET): charset])
writeQrCode(filename, data, charset, hints, 100, 100)
assert data == readQrCode(filename, charset, hints)
}
def static writeQrCode(def filename, def data, def charset, def hints, def width, def height) {
BitMatrix matrix = new MultiFormatWriter().encode(new String(data.getBytes(charset), charset), BarcodeFormat.QR_CODE, width, height, hints)
MatrixToImageWriter.writeToFile(matrix, filename.substring(filename.lastIndexOf('.')+1), new File(filename))
}
def static readQrCode(def filename, def charset, def hints) {
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(ImageIO.read(new FileInputStream(filename)))))
Result result = new MultiFormatReader().decode(binaryBitmap, hints)
result.getText()
}
}
Coming at this almost a year later, there's a different manner in which I solved my particular problem. Since I wanted the link to be handled by my own app, there is a solution that is a bit simpler.
Besides the default intent filter, I simply let my target activity listen to ACTION_VIEW
intents, and specifically, those with the scheme com.package.name
<intent-filter>
<category android:name="android.intent.category.DEFAULT" />
<action android:name="android.intent.action.VIEW" />
<data android:scheme="com.package.name" />
</intent-filter>
This means that links starting with com.package.name://
will be handled by my activity.
So all I have to do is construct a URL that contains the information I want to convey:
com.package.name://action-to-perform/id-that-might-be-needed/
In my target activity, I can retrieve this address:
Uri data = getIntent().getData();
In my example, I could simply check data
for null values, because when ever it isn't null, I'll know it was invoked by means of such a link. From there, I extract the instructions I need from the url to be able to display the appropriate data.
Try this:
UPDATE test
SET
field = 1
WHERE id = 123 and condition
So, you may download it from:
https://go.microsoft.com/fwlink/?LinkId=708984
And I got this from: http://blogs.bukutamudigital.com/2016/06/28/visual-studio-2015-update-3-offline-installer/
It's around 6GB
There's lots of subtleties in setting up an efficient and high quality matrix class. Thankfully there's several good implementations floating about.
Think hard about whether you want a fixed size matrix class or a variable sized one. i.e. can you do this:
// These tend to be fast and allocated on the stack.
matrix<3,3> M;
or do you need to be able to do this
// These are slower but more flexible and partially allocated on the heap
matrix M(3,3);
There's good libraries that support either style, and some that support both. They have different allocation patterns and different performances.
If you want to code it yourself, then the template version requires some knowledge of templates (duh). And the dynamic one needs some hacks to get around lots of small allocations if used inside tight loops.
The only surefire option to find the current session.save_path
value is always to check with phpinfo()
in exactly the environment where you want to find out the session storage directory.
Reason: there can be all sorts of things that change session.save_path
, either by overriding the php.ini
value or by setting it at runtime with ini_set('session.save_path','/path/to/folder');
. For example, web server management panels like ISPConfig, Plesk etc. often adapt this to give each website its own directory with session files.
You could do this
<div style="text-align:center;">
<div style="border:1px solid #000; display:inline-block;">Div 1</div>
<div style="border:1px solid red; display:inline-block;">Div 2</div>
</div>
http://jsfiddle.net/jasongennaro/MZrym/
div
with text-align:center;
div
s a display:inline-block;
instead of a float
Best also to put that css in a stylesheet.
try to do this in the behind code
public diagboxclass()
{
List<object> list = new List<object>();
list = GetObjectList();
Imported.ItemsSource = null;
Imported.ItemsSource = list;
}
Also be sure your list is effectively populated and as mentioned by Blindmeis, never use words that already are given a function in c#.
Disable package-lock.json globally
type the following in your terminal:
npm config set package-lock false
this really work for me like magic
The solution above does not work in all InputBox-Cancel cases. Most notably, it does not work if you have to InputBox a Range.
For example, try the following InputBox for defining a custom range ('sRange', type:=8, requires Set + Application.InputBox) and you will get an error upon pressing Cancel:
Sub Cancel_Handler_WRONG()
Set sRange = Application.InputBox("Input custom range", _
"Cancel-press test", Selection.Address, Type:=8)
If StrPtr(sRange) = 0 Then 'I also tried with sRange.address and vbNullString
MsgBox ("Cancel pressed!")
Exit Sub
End If
MsgBox ("Your custom range is " & sRange.Address)
End Sub
The only thing that works, in this case, is an "On Error GoTo ErrorHandler" statement before the InputBox + ErrorHandler at the end:
Sub Cancel_Handler_OK()
On Error GoTo ErrorHandler
Set sRange = Application.InputBox("Input custom range", _
"Cancel-press test", Selection.Address, Type:=8)
MsgBox ("Your custom range is " & sRange.Address)
Exit Sub
ErrorHandler:
MsgBox ("Cancel pressed")
End Sub
So, the question is how to detect either an error or StrPtr()=0 with an If statement?
I find std::getline()
is often the simplest. The optional delimiter parameter means it's not just for reading "lines":
#include <sstream>
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<string> strings;
istringstream f("denmark;sweden;india;us");
string s;
while (getline(f, s, ';')) {
cout << s << endl;
strings.push_back(s);
}
}
As for the testing, you should use from Spring 4.1 which will overwrite the properties defined in other places:
@TestPropertySource("classpath:application-test.properties")
Test property sources have higher precedence than those loaded from the operating system's environment or Java system properties as well as property sources added by the application like @PropertySource
You probably updated your Ubuntu installation and one of the updates included the upgrade of Apache to version 2.4.x
In Apache 2.4.x the vhost configuration files, located in the /etc/apache2/sites-available directory, must have the .conf extension.
Using terminal (mv command), rename all your existing configuration files and add the .conf extension to all of them.
mv /etc/apache2/sites-available/cmsplus.dev /etc/apache2/sites-available/cmsplus.dev.conf
If you get a "Permission denied" error, then add "sudo " in front of your terminal commands.
You do not need to make any other changes to the configuration files.
Enable the vhost(s):
a2ensite cmsplus.dev.conf
And then reload Apache:
service apache2 reload
Your sites should be up and running now.
UPDATE: As mentioned here, a Linux distribution that you installed changed the configuration to Include *.conf only. Therefore it has nothing to do with Apache 2.2 or 2.4
typedef struct{
char name[30];
char surname[30];
int age;
} data;
defines that data
should be a block of memory that fits 60 chars plus 4 for the int (see note)
[----------------------------,------------------------------,----]
^ this is name ^ this is surname ^ this is age
This allocates the memory on the stack.
data s1;
Assignments just copies numbers, sometimes pointers.
This fails
s1.name = "Paulo";
because the compiler knows that s1.name
is the start of a struct 64 bytes long, and "Paulo"
is a char[] 6 bytes long (6 because of the trailing \0 in C strings)
Thus, trying to assign a pointer to a string into a string.
To copy "Paulo" into the struct at the point name
and "Rossi" into the struct at point surname
.
memcpy(s1.name, "Paulo", 6);
memcpy(s1.surname, "Rossi", 6);
s1.age = 1;
You end up with
[Paulo0----------------------,Rossi0-------------------------,0001]
strcpy
does the same thing but it knows about \0
termination so does not need the length hardcoded.
Alternatively you can define a struct which points to char arrays of any length.
typedef struct {
char *name;
char *surname;
int age;
} data;
This will create
[----,----,----]
This will now work because you are filling the struct with pointers.
s1.name = "Paulo";
s1.surname = "Rossi";
s1.age = 1;
Something like this
[---4,--10,---1]
Where 4 and 10 are pointers.
Note: the ints and pointers can be different sizes, the sizes 4 above are 32bit as an example.
In PowerShell you can use the command Set-Service:
Set-Service -Name Winmgmt -StartupType Manual
I haven't found a PowerShell command to view the startup type though. One would assume that the command Get-Service would provide that, but it doesn't seem to.
You can use the position:fixed;
, but without set left
and top
. Then you will push it to the right using margin-left
, to position it in the right position you wish.
Check a demo here: http://jsbin.com/icili5
This will enable appending to file using StreamWriter
using (StreamWriter stream = new StreamWriter("YourFilePath", true)) {...}
This is default mode, not append to file and create a new file.
using (StreamWriter stream = new StreamWriter("YourFilePath", false)){...}
or
using (StreamWriter stream = new StreamWriter("YourFilePath")){...}
Anyhow if you want to check if the file exists and then do other things,you can use
using (StreamWriter sw = (File.Exists(path)) ? File.AppendText(path) : File.CreateText(path))
{...}
SELECT column FROM
( SELECT column, dbms_random.value FROM table ORDER BY 2 )
where rownum <= 20;
Yes, LINQ to Objects supports this with Enumerable.Concat
:
var together = first.Concat(second);
NB: Should first
or second
be null you would receive a ArgumentNullException
. To avoid this & treat nulls as you would an empty set, use the null coalescing operator like so:
var together = (first ?? Enumerable.Empty<string>()).Concat(second ?? Enumerable.Empty<string>()); //amending `<string>` to the appropriate type
Yes, you can use Linq to check the AllKeys
property:
using System.Linq;
...
collection.AllKeys.Contains(key);
However a Dictionary<string, string[]>
would be far more suited to this purpose, perhaps created via an extension method:
public static void Dictionary<string, string[]> ToDictionary(this NameValueCollection collection)
{
return collection.Cast<string>().ToDictionary(key => key, key => collection.GetValues(key));
}
var dictionary = collection.ToDictionary();
if (dictionary.ContainsKey(key))
{
...
}
This also works when $_SERVER['HTTPS']
is undefined
if( (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off') || $_SERVER['SERVER_PORT'] == 443 ){
//enable secure connection
}
Batch files have really very limited logic powers so the best you can hope to come up with is a good workaround that indirectly achieves what you want. That's not to say that you should feel they are inferior to a real language - they still demand the same attention to detail and manual debugging as a real application. It's just that you'll need to work a lot harder to make them do what you want in a robust manner.
For the OP's question it sounds like you require two specific files to exist. Just use a tally:
IF EXIST somefile.txt (
set /a file1_status=1
)
IF EXIST someotehrfile.txt (
set /a file2_status=1
)
set /a file_status_result=file1_status + file2_status
if %file_status_result% equ 2 (
goto somefileexists
)
goto exit
:somefileexists
IF EXIST someotherfile.txt SET var=...
:exit
My example uses 3 variables, but you could just add 1 to file_result_status if the file exists. But if you want more granular control later in your batch file you can record the result for each file as I have done so you don't have to keep checking if a file exists later on.
Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english
You can always refer to resources in your application directly by their JNDI name as configured in the container, but if you do so, essentially you are wiring the container-specific name into your code. This has some disadvantages, for example, if you'll ever want to change the name later for some reason, you'll need to update all the references in all your applications, and then rebuild and redeploy them.
<resource-ref>
introduces another layer of indirection: you specify the name you want to use in the web.xml, and, depending on the container, provide a binding in a container-specific configuration file.
So here's what happens: let's say you want to lookup the java:comp/env/jdbc/primaryDB
name. The container finds that web.xml has a <resource-ref>
element for jdbc/primaryDB
, so it will look into the container-specific configuration, that contains something similar to the following:
<resource-ref>
<res-ref-name>jdbc/primaryDB</res-ref-name>
<jndi-name>jdbc/PrimaryDBInTheContainer</jndi-name>
</resource-ref>
Finally, it returns the object registered under the name of jdbc/PrimaryDBInTheContainer
.
The idea is that specifying resources in the web.xml has the advantage of separating the developer role from the deployer role. In other words, as a developer, you don't have to know what your required resources are actually called in production, and as the guy deploying the application, you will have a nice list of names to map to real resources.
I was having a problem getting my ASP.NET 5.0/MVC 6 app to serve static binary file types or browse virtual directories. It looks like this is now done in Configure() at startup. See http://docs.asp.net/en/latest/fundamentals/static-files.html for a quick primer.
It's called designated initializer which is introduced in C99. It's used to initialize struct
or arrays, in this example, struct
.
Given
struct point {
int x, y;
};
the following initialization
struct point p = { .y = 2, .x = 1 };
is equivalent to the C89-style
struct point p = { 1, 2 };
You have to write your own compareTo() method that has the Java code needed to perform the comparison.
If we wanted for example to compare two public fields, campus, then faculty, we might do something like:
int compareTo(GraduationCeremony gc)
{
int c = this.campus.compareTo(gc.campus);
if( c != 0 )
{
//sort by campus if we can
return c;
}
else
{
//campus equal, so sort by faculty
return this.faculty.compareTo(gc.faculty);
}
}
This is simplified but hopefully gives you an idea. Consult the Comparable and Comparator docs for more info.
If you are using PyCharm IDE, then you can run that individual test or all tests using Run toolbar. The Run tool window displays output generated by your application and you can see all the print statements in there as part of test output.
C strings are enclosed in double quotes:
const char *options[2][100];
options[0][0] = "test1";
options[1][0] = "test2";
Re-reading your question and comments though I'm guessing that what you really want to do is this:
const char *options[2] = { "test1", "test2" };
In my case, it was caused by an unseen trailing space at the end of the column name. Just check if you really use "y" or "y " instead.
You are missing the std namespace reference in the cc file. You should also call nom.c_str()
because there is no implicit conversion from std::string
to const char *
expected by ifstream
's constructor.
Polygone::Polygone(std::string nom) {
std::ifstream fichier (nom.c_str(), std::ifstream::in);
// ...
}
Your problem is basically that you never specified the right path to the file.
Try instead, from your main script:
from folder.file import Klasa
Or, with from folder import file
:
from folder import file
k = file.Klasa()
Or again:
import folder.file as myModule
k = myModule.Klasa()
I know this is like years old post but since there is no selected answer I hope this answer may give you what you are expecting...
if(document.getElementsByTagName){
var table = document.getElementById('table className');
for (var i = 0, row; row = table.rows[i]; i++) {
//rows would be accessed using the "row" variable assigned in the for loop
for (var j = 0, col; col = row.cells[j]; j++) {
//columns would be accessed using the "col" variable assigned in the for loop
alert('col html>>'+col.innerHTML); //Will give you the html content of the td
alert('col>>'+col.innerText); //Will give you the td value
}
}
}
}
In pandas 0.16.1+ you can drop columns only if they exist per the solution posted by @eiTanLaVi. Prior to that version, you can achieve the same result via a conditional list comprehension:
df.drop([col for col in ['col_name_1','col_name_2',...,'col_name_N'] if col in df],
axis=1, inplace=True)
The following solution combines other answers and handles some special cases:
?
character\b
ensures another parameter ending with paramName won't be matchedSolution:
function replaceUrlParam(url, paramName, paramValue)
{
if (paramValue == null) {
paramValue = '';
}
var pattern = new RegExp('\\b('+paramName+'=).*?(&|#|$)');
if (url.search(pattern)>=0) {
return url.replace(pattern,'$1' + paramValue + '$2');
}
url = url.replace(/[?#]$/,'');
return url + (url.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue;
}
Known limitations:
@Daniel's suggestion worked perfectly for me. To install
make, open Xcode, go to Preferences -> Downloads -> Components -> Command Line Tools.You can then test with
gcc -v
The ...
(spread operator) is used in react to:
provide a neat way to pass props from parent to child components. e.g given these props in a parent component,
this.props = {
username: "danM",
email: "[email protected]"
}
they could be passed in the following manner to the child,
<ChildComponent {...this.props} />
which is similar to this
<ChildComponent username={this.props.username} email={this.props.email} />
but way cleaner.
Here's what to do:
Create a new Project in Objective-C
Create a new .swift
file
Click on your Xcode Project file
Click on Build Settings
Find the Search bar and search for Defines Module.
Change value to Yes.
Search Product Module Name.
Change the value to the name of your project.
In App delegate, add the following : #import "YourProjectName-Swift.h"
Note: Whenever you want to use your Swift file you must be import following line :
#import "YourProjectName-Swift.h"
const args = process.argv;
console.log(args);
This returns:
$ node server.js one two=three four
['node', '/home/server.js', 'one', 'two=three', 'four']
Minimist: For minimal argument parsing.
Commander.js: Most adopted module for argument parsing.
Meow: Lighter alternative to Commander.js
Yargs: More sophisticated argument parsing (heavy).
Vorpal.js: Mature / interactive command-line applications with argument parsing.
Choose which DI to inject stuff into Jersey:
Spring 4:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring4</artifactId>
</dependency>
Spring 3:
<dependency>
<groupId>org.glassfish.jersey.ext</groupId>
<artifactId>jersey-spring3</artifactId>
</dependency>
HK2:
<dependency>
<groupId>org.glassfish.jersey.inject</groupId>
<artifactId>jersey-hk2</artifactId>
</dependency>
Just add
model.addAttribute("login", new Login());
to your method ..
it will work..
While technically correct, the other answers would benefit from an explanation of Angular's URL-to-route matching. I don't think you can fully (pardon the pun) understand what pathMatch: full
does if you don't know how the router works in the first place.
Let's first define a few basic things. We'll use this URL as an example: /users/james/articles?from=134#section
.
It may be obvious but let's first point out that query parameters (?from=134
) and fragments (#section
) do not play any role in path matching. Only the base url (/users/james/articles
) matters.
Angular splits URLs into segments. The segments of /users/james/articles
are, of course, users
, james
and articles
.
The router configuration is a tree structure with a single root node. Each Route
object is a node, which may have children
nodes, which may in turn have other children
or be leaf nodes.
The goal of the router is to find a router configuration branch, starting at the root node, which would match exactly all (!!!) segments of the URL. This is crucial! If Angular does not find a route configuration branch which could match the whole URL - no more and no less - it will not render anything.
E.g. if your target URL is /a/b/c
but the router is only able to match either /a/b
or /a/b/c/d
, then there is no match and the application will not render anything.
Finally, routes with redirectTo
behave slightly differently than regular routes, and it seems to me that they would be the only place where anyone would really ever want to use pathMatch: full
. But we will get to this later.
prefix
) path matchingThe reasoning behind the name prefix
is that such a route configuration will check if the configured path
is a prefix of the remaining URL segments. However, the router is only able to match full segments, which makes this naming slightly confusing.
Anyway, let's say this is our root-level router configuration:
const routes: Routes = [
{
path: 'products',
children: [
{
path: ':productID',
component: ProductComponent,
},
],
},
{
path: ':other',
children: [
{
path: 'tricks',
component: TricksComponent,
},
],
},
{
path: 'user',
component: UsersonComponent,
},
{
path: 'users',
children: [
{
path: 'permissions',
component: UsersPermissionsComponent,
},
{
path: ':userID',
children: [
{
path: 'comments',
component: UserCommentsComponent,
},
{
path: 'articles',
component: UserArticlesComponent,
},
],
},
],
},
];
Note that every single Route
object here uses the default matching strategy, which is prefix
. This strategy means that the router iterates over the whole configuration tree and tries to match it against the target URL segment by segment until the URL is fully matched. Here's how it would be done for this example:
users
.'products' !== 'users'
, so skip that branch. Note that we are using an equality check rather than a .startsWith()
or .includes()
- only full segment matches count!:other
matches any value, so it's a match. However, the target URL is not yet fully matched (we still need to match james
and articles
), thus the router looks for children.:other
is tricks
, which is !== 'james'
, hence not a match.'user' !== 'users
, skip branch.'users' === 'users
- the segment matches. However, this is not a full match yet, thus we need to look for children (same as in step 3).'permissions' !== 'james'
, skip it.:userID
matches anything, thus we have a match for the james
segment. However this is still not a full match, thus we need to look for a child which would match articles
.
:userID
has a child route articles
, which gives us a full match! Thus the application renders UserArticlesComponent
.full
) matchingImagine now that the users
route configuration object looked like this:
{
path: 'users',
component: UsersComponent,
pathMatch: 'full',
children: [
{
path: 'permissions',
component: UsersPermissionsComponent,
},
{
path: ':userID',
component: UserComponent,
children: [
{
path: 'comments',
component: UserCommentsComponent,
},
{
path: 'articles',
component: UserArticlesComponent,
},
],
},
],
}
Note the usage of pathMatch: full
. If this were the case, steps 1-5 would be the same, however step 6 would be different:
'users' !== 'users/james/articles
- the segment does not match because the path configuration users
with pathMatch: full
does not match the full URL, which is users/james/articles
.What if we had this instead:
{
path: 'users/:userID',
component: UsersComponent,
pathMatch: 'full',
children: [
{
path: 'comments',
component: UserCommentsComponent,
},
{
path: 'articles',
component: UserArticlesComponent,
},
],
}
users/:userID
with pathMatch: full
matches only users/james
thus it's a no-match once again, and the application renders nothing.
Let's consider this:
{
path: 'users',
children: [
{
path: 'permissions',
component: UsersPermissionsComponent,
},
{
path: ':userID',
component: UserComponent,
pathMatch: 'full',
children: [
{
path: 'comments',
component: UserCommentsComponent,
},
{
path: 'articles',
component: UserArticlesComponent,
},
],
},
],
}
In this case:
'users' === 'users
- the segment matches, but james/articles
still remains unmatched. Let's look for children.'permissions' !== 'james'
- skip.:userID'
can only match a single segment, which would be james
. However, it's a pathMatch: full
route, and it must match james/articles
(the whole remaining URL). It's not able to do that and thus it's not a match (so we skip this branch)!As you may have noticed, a pathMatch: full
configuration is basically saying this:
Ignore my children and only match me. If I am not able to match all of the remaining URL segments myself, then move on.
Any Route
which has defined a redirectTo
will be matched against the target URL according to the same principles. The only difference here is that the redirect is applied as soon as a segment matches. This means that if a redirecting route is using the default prefix
strategy, a partial match is enough to cause a redirect. Here's a good example:
const routes: Routes = [
{
path: 'not-found',
component: NotFoundComponent,
},
{
path: 'users',
redirectTo: 'not-found',
},
{
path: 'users/:userID',
children: [
{
path: 'comments',
component: UserCommentsComponent,
},
{
path: 'articles',
component: UserArticlesComponent,
},
],
},
];
For our initial URL (/users/james/articles
), here's what would happen:
'not-found' !== 'users'
- skip it.'users' === 'users'
- we have a match.redirectTo: 'not-found'
, which is applied immediately.not-found
.not-found
right away. The application renders NotFoundComponent
.Now consider what would happen if the users
route also had pathMatch: full
:
const routes: Routes = [
{
path: 'not-found',
component: NotFoundComponent,
},
{
path: 'users',
pathMatch: 'full',
redirectTo: 'not-found',
},
{
path: 'users/:userID',
children: [
{
path: 'comments',
component: UserCommentsComponent,
},
{
path: 'articles',
component: UserArticlesComponent,
},
],
},
];
'not-found' !== 'users'
- skip it.users
would match the first segment of the URL, but the route configuration requires a full
match, thus skip it.'users/:userID'
matches users/james
. articles
is still not matched but this route has children.articles
in the children. The whole URL is now matched and the application renders UserArticlesComponent
.path: ''
)The empty path is a bit of a special case because it can match any segment without "consuming" it (so it's children would have to match that segment again). Consider this example:
const routes: Routes = [
{
path: '',
children: [
{
path: 'users',
component: BadUsersComponent,
}
]
},
{
path: 'users',
component: GoodUsersComponent,
},
];
Let's say we are trying to access /users
:
path: ''
will always match, thus the route matches. However, the whole URL has not been matched - we still need to match users
!users
, which matches the remaining (and only!) segment and we have a full match. The application renders BadUsersComponent
.The OP used this router configuration:
const routes: Routes = [
{
path: 'welcome',
component: WelcomeComponent,
},
{
path: '',
redirectTo: 'welcome',
pathMatch: 'full',
},
{
path: '**',
redirectTo: 'welcome',
pathMatch: 'full',
},
];
If we are navigating to the root URL (/
), here's how the router would resolve that:
welcome
does not match an empty segment, so skip it.path: ''
matches the empty segment. It has a pathMatch: 'full'
, which is also satisfied as we have matched the whole URL (it had a single empty segment).welcome
happens and the application renders WelcomeComponent
.pathMatch: 'full'
?Actually, one would expect the whole thing to behave exactly the same. However, Angular explicitly prevents such a configuration ({ path: '', redirectTo: 'welcome' }
) because if you put this Route
above welcome
, it would theoretically create an endless loop of redirects. So Angular just throws an error, which is why the application would not work at all! (https://angular.io/api/router/Route#pathMatch)
Actually, this does not make too much sense to me because Angular also has implemented a protection against such endless redirects - it only runs a single redirect per routing level! This would stop all further redirects (as you'll see in the example below).
path: '**'
?path: '**'
will match absolutely anything (af/frewf/321532152/fsa
is a match) with or without a pathMatch: 'full'
.
Also, since it matches everything, the root path is also included, which makes { path: '', redirectTo: 'welcome' }
completely redundant in this setup.
Funnily enough, it is perfectly fine to have this configuration:
const routes: Routes = [
{
path: '**',
redirectTo: 'welcome'
},
{
path: 'welcome',
component: WelcomeComponent,
},
];
If we navigate to /welcome
, path: '**'
will be a match and a redirect to welcome will happen. Theoretically this should kick off an endless loop of redirects but Angular stops that immediately (because of the protection I mentioned earlier) and the whole thing works just fine.
You can easily draw simple svg
s onto a canvas by:
Note: The only drawback of the method is that it cannot draw images embedded in the svg
. (see demo)
(Note that the embedded image is only visible in the svg
)
var svg = document.querySelector('svg');_x000D_
var img = document.querySelector('img');_x000D_
var canvas = document.querySelector('canvas');_x000D_
_x000D_
// get svg data_x000D_
var xml = new XMLSerializer().serializeToString(svg);_x000D_
_x000D_
// make it base64_x000D_
var svg64 = btoa(xml);_x000D_
var b64Start = 'data:image/svg+xml;base64,';_x000D_
_x000D_
// prepend a "header"_x000D_
var image64 = b64Start + svg64;_x000D_
_x000D_
// set it as the source of the img element_x000D_
img.src = image64;_x000D_
_x000D_
// draw the image onto the canvas_x000D_
canvas.getContext('2d').drawImage(img, 0, 0);
_x000D_
svg, img, canvas {_x000D_
display: block;_x000D_
}
_x000D_
SVG_x000D_
_x000D_
<svg height="40">_x000D_
<rect width="40" height="40" style="fill:rgb(255,0,255);" />_x000D_
<image xlink:href="https://en.gravatar.com/userimage/16084558/1a38852cf33713b48da096c8dc72c338.png?size=20" height="20px" width="20px" x="10" y="10"></image>_x000D_
</svg>_x000D_
<hr/><br/>_x000D_
_x000D_
IMAGE_x000D_
<img/>_x000D_
<hr/><br/>_x000D_
_x000D_
CANVAS_x000D_
<canvas></canvas>_x000D_
<hr/><br/>
_x000D_
Initialize tSize to
tSize = ""
before your if block to be safe. Also in your else case, put tSize in quotes so it is a string not an int. Also also you are comparing strings to ints.
A method I use in my login servlet to verify reCaptcha responses. Uses classes from the java.json package. Returns the API response in a JsonObject.
Check the success field for true or false
private JsonObject validateCaptcha(String secret, String response, String remoteip)
{
JsonObject jsonObject = null;
URLConnection connection = null;
InputStream is = null;
String charset = java.nio.charset.StandardCharsets.UTF_8.name();
String url = "https://www.google.com/recaptcha/api/siteverify";
try {
String query = String.format("secret=%s&response=%s&remoteip=%s",
URLEncoder.encode(secret, charset),
URLEncoder.encode(response, charset),
URLEncoder.encode(remoteip, charset));
connection = new URL(url + "?" + query).openConnection();
is = connection.getInputStream();
JsonReader rdr = Json.createReader(is);
jsonObject = rdr.readObject();
} catch (IOException ex) {
Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
}
finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
return jsonObject;
}
You can still use the textmode and force the linefeed-newline with the keyword argument newline
f = open("./foo",'w',newline='\n')
Tested with Python 3.4.2.
Edit: This does not work in Python 2.7.
If you are using mobile,
Turn on your developer options.
Turn on USB debugging option
I was having a similar issue and used $stateParams
instead of routeParam
Use chown
to change ownership and chmod
to change rights.
use the -R
option to apply the rights for all files inside of a directory too.
Note that both these commands just work for directories too. The -R
option makes them also change the permissions for all files and directories inside of the directory.
For example
sudo chown -R username:group directory
will change ownership (both user and group) of all files and directories inside of directory and directory itself.
sudo chown username:group directory
will only change the permission of the folder directory but will leave the files and folders inside the directory alone.
you need to use sudo to change the ownership from root to yourself.
Edit:
Note that if you use chown user: file
(Note the left-out group), it will use the default group for that user.
Also You can change the group ownership of a file or directory with the command:
chgrp group_name file/directory_name
You must be a member of the group to which you are changing ownership to.
You can find group of file as follows
# ls -l file
-rw-r--r-- 1 root family 0 2012-05-22 20:03 file
# chown sujit:friends file
User 500 is just a normal user. Typically user 500 was the first user on the system, recent changes (to /etc/login.defs) has altered the minimum user id to 1000 in many distributions, so typically 1000 is now the first (non root) user.
What you may be seeing is a system which has been upgraded from the old state to the new state and still has some processes knocking about on uid 500. You can likely change it by first checking if your distro should indeed now use 1000, and if so alter the login.defs file yourself, the renumber the user account in /etc/passwd and chown/chgrp all their files, usually in /home/, then reboot.
But in answer to your question, no, you should not really be worried about this in all likelihood. It'll be showing as "500" instead of a username because o user in /etc/passwd has a uid set of 500, that's all.
Also you can show your current numbers using id i'm willing to bet it comes back as 1000 for you.
It appears that tkFileDialog.askdirectory
should work. documentation
Use this line of code in your css
border: 1px solid #000 !important;
or if you want border only in left and right side of container then use:
border-right: 1px solid #000 !important;
border-left: 1px solid #000 !important;
The inefficiency here is not really due to Python, but to the nature of how files are read. The only way to find the last line is to read the file in and find the line endings. However, the seek operation may be used to skip to any byte offset in the file. You can, therefore begin very close to the end of the file, and grab larger and larger chunks as needed until the last line ending is found:
from os import SEEK_END
def get_last_line(file):
CHUNK_SIZE = 1024 # Would be good to make this the chunk size of the filesystem
last_line = ""
while True:
# We grab chunks from the end of the file towards the beginning until we
# get a new line
file.seek(-len(last_line) - CHUNK_SIZE, SEEK_END)
chunk = file.read(CHUNK_SIZE)
if not chunk:
# The whole file is one big line
return last_line
if not last_line and chunk.endswith('\n'):
# Ignore the trailing newline at the end of the file (but include it
# in the output).
last_line = '\n'
chunk = chunk[:-1]
nl_pos = chunk.rfind('\n')
# What's being searched for will have to be modified if you are searching
# files with non-unix line endings.
last_line = chunk[nl_pos + 1:] + last_line
if nl_pos == -1:
# The whole chunk is part of the last line.
continue
return last_line
A great resource is iosfonts.com, which says that the name for that font is HelveticaNeue-UltraLight
. So you'd use this code:
label.font = UIFont(name: "HelveticaNeue-UltraLight", size: 30)
If the system can't find the font, it defaults to a 'normal' font - I think it's something like 11-point Helvetica. This can be quite confusing, always check your font names.
I insert this code in my tag and it works correctly:
ng-show="!Contract.BuyerName.trim()" >
With the Material Components Library you can use the MaterialButtonToggleGroup
:
<com.google.android.material.button.MaterialButtonToggleGroup
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:checkedButton="@id/b1"
app:selectionRequired="true"
app:singleSelection="true">
<Button
style="?attr/materialButtonOutlinedStyle"
android:id="@+id/b1"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="OPT1" />
<Button
style="?attr/materialButtonOutlinedStyle"
android:id="@+id/b2"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="OPT2" />
</com.google.android.material.button.MaterialButtonToggleGroup>
Try the solution from Reportlab.
Download it and install it as usual with python setup.py install
You will also need to install the following modules: xhtml2pdf, html5lib, pypdf with easy_install.
Here is an usage example:
First define this function:
import cStringIO as StringIO
from xhtml2pdf import pisa
from django.template.loader import get_template
from django.template import Context
from django.http import HttpResponse
from cgi import escape
def render_to_pdf(template_src, context_dict):
template = get_template(template_src)
context = Context(context_dict)
html = template.render(context)
result = StringIO.StringIO()
pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
if not pdf.err:
return HttpResponse(result.getvalue(), content_type='application/pdf')
return HttpResponse('We had some errors<pre>%s</pre>' % escape(html))
Then you can use it like this:
def myview(request):
#Retrieve data or whatever you need
return render_to_pdf(
'mytemplate.html',
{
'pagesize':'A4',
'mylist': results,
}
)
The template:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>My Title</title>
<style type="text/css">
@page {
size: {{ pagesize }};
margin: 1cm;
@frame footer {
-pdf-frame-content: footerContent;
bottom: 0cm;
margin-left: 9cm;
margin-right: 9cm;
height: 1cm;
}
}
</style>
</head>
<body>
<div>
{% for item in mylist %}
RENDER MY CONTENT
{% endfor %}
</div>
<div id="footerContent">
{%block page_foot%}
Page <pdf:pagenumber>
{%endblock%}
</div>
</body>
</html>
Hope it helps.
Approach with React Native and Hooks:
You can wrap the TextInput into a new one that watches if the value changed and trigger the onChange function if it does.
import React, { useState, useEffect } from 'react';
import { View, TextInput as RNTextInput, Button } from 'react-native';
// New TextInput that triggers onChange when value changes.
// You can add more TextInput methods as props to it.
const TextInput = ({ onChange, value, placeholder }) => {
// When value changes, you can do whatever you want or just to trigger the onChange function
useEffect(() => {
onChange(value);
}, [value]);
return (
<RNTextInput
onChange={onChange}
value={value}
placeholder={placeholder}
/>
);
};
const Main = () => {
const [myValue, setMyValue] = useState('');
const handleChange = (value) => {
setMyValue(value);
console.log("Handling value");
};
const randomLetters = [...Array(15)].map(() => Math.random().toString(36)[2]).join('');
return (
<View>
<TextInput
placeholder="Write something here"
onChange={handleChange}
value={myValue}
/>
<Button
title='Change value with state'
onPress={() => setMyValue(randomLetters)}
/>
</View>
);
};
export default Main;
I had the exact same problem when using Spring Security 3.1.0. and Oracle 11G. I was using the following query and getting the invalid column index error:
<security:jdbc-user-service data-source-ref="dataSource"
users-by-username-query="SELECT A.user_name AS username, A.password AS password FROM MB_REG_USER A where A.user_name=lower(?)"
It turns out that I needed to add: "1 as enabled" to the query:
<security:jdbc-user-service data-source-ref="dataSource" users-by-username query="SELECT A.user_name AS username, A.password AS password, 1 as enabled FROM MB_REG_USER A where A.user_name=lower(?)"
Everything worked after that. I believe this could be a bug in the Spring JDBC core package...
You can use alert(arrayObj.toSource());
The print
statement in Python converts its arguments to strings, and outputs those strings to stdout. To save the string to a variable instead, only convert it to a string:
a = str(tag.getArtist())
Use the toLocaleString() method in any number. So for the number 6, as seen below, you can get the desired results.
(6).toLocaleString('en-US', {minimumIntegerDigits: 2, useGrouping:false})
Will generate the string '06'.
It looks like your Spring component scan Base is missing UserServiceImpl
<context:component-scan base-package="org.assessme.com.controller." />
For reference, a non-CSS solution:
Below is some JS that re-sizes a font depending on the text length within a container.
Codepen with slightly modified code, but same idea as below:
function scaleFontSize(element) {
var container = document.getElementById(element);
// Reset font-size to 100% to begin
container.style.fontSize = "100%";
// Check if the text is wider than its container,
// if so then reduce font-size
if (container.scrollWidth > container.clientWidth) {
container.style.fontSize = "70%";
}
}
For me, I call this function when a user makes a selection in a drop-down, and then a div in my menu gets populated (this is where I have dynamic text occurring).
scaleFontSize("my_container_div");
In addition, I also use CSS ellipses ("...") to truncate yet even longer text too, like so:
#my_container_div {
width: 200px; /* width required for text-overflow to work */
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
So, ultimately:
Short text: e.g. "APPLES"
Fully rendered, nice big letters.
Long text: e.g. "APPLES & ORANGES"
Gets scaled down 70%, via the above JS scaling function.
Super long text: e.g. "APPLES & ORANGES & BANAN..."
Gets scaled down 70% AND gets truncated with a "..." ellipses, via the above JS scaling function together with the CSS rule.
You could also explore playing with CSS letter-spacing to make text narrower while keeping the same font size.
Immutable lists are best represented through two-tuples, with None representing NIL. To allow simple formulation of such lists, you can use this function:
def mklist(*args):
result = None
for element in reversed(args):
result = (element, result)
return result
To work with such lists, I'd rather provide the whole collection of LISP functions (i.e. first, second, nth, etc), than introducing methods.
Try the easy and usable way: just call StripHTML(WebBrowserControl_name);
public string StripHTML(WebBrowser webp)
{
try
{
doc.execCommand("SelectAll", true, null);
IHTMLSelectionObject currentSelection = doc.selection;
if (currentSelection != null)
{
IHTMLTxtRange range = currentSelection.createRange() as IHTMLTxtRange;
if (range != null)
{
currentSelection.empty();
return range.text;
}
}
}
catch (Exception ep)
{
//MessageBox.Show(ep.Message);
}
return "";
}
I faced with same issue. For python3.6.8 and ubuntu 16.04 none of above did not help me.
sudo apt-get install python3.6-dev
This solved my problem.
you should replace @RequestBody with @RequestParam, and do not accept parameters with a java entity.
Then you controller is probably like this:
@RequestMapping(value = "/patientdetails", method = RequestMethod.POST,
consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
public @ResponseBody List<PatientProfileDto> getPatientDetails(
@RequestParam Map<String, String> name) {
List<PatientProfileDto> list = new ArrayList<PatientProfileDto>();
...
PatientProfileDto patientProfileDto = mapToPatientProfileDto(mame);
...
list = service.getPatient(patientProfileDto);
return list;
}
Here's a simple way to get date without time if you are using Java 8+: Use java.time.LocalDate type instead of Date.
LocalDate now = LocalDate.now();
System.out.println(now.toString());
The output:
2019-05-30
https://docs.oracle.com/javase/8/docs/api/java/time/LocalDate.html
I came up with this [untested]
import sys
class Tee(object):
def __init__(self, *files):
self.files = files
def write(self, obj):
for f in self.files:
f.write(obj)
f.flush() # If you want the output to be visible immediately
def flush(self) :
for f in self.files:
f.flush()
f = open('out.txt', 'w')
original = sys.stdout
sys.stdout = Tee(sys.stdout, f)
print "test" # This will go to stdout and the file out.txt
#use the original
sys.stdout = original
print "This won't appear on file" # Only on stdout
f.close()
print>>xyz
in python will expect a write()
function in xyz
. You could use your own custom object which has this. Or else, you could also have sys.stdout refer to your object, in which case it will be tee-ed even without >>xyz
.
Java IO using stream oriented APIs is performed using a buffer as temporary storage of data within user space. Data read from disk by DMA is first copied to buffers in kernel space, which is then transfer to buffer in user space. Hence there is overhead. Avoiding it can achieve considerable gain in performance.
We could skip this temporary buffer in user space, if there was a way directly to access the buffer in kernel space. Java NIO provides a way to do so.
ByteBuffer
is among several buffers provided by Java NIO. Its just a container or holding tank to read data from or write data to. Above behavior is achieved by allocating a direct buffer using allocateDirect()
API on Buffer.
I got this error, hope this will help someone:
const firstName = 'Joe';
const lastName = 'Blogs';
const wholeName = firstName + ' ' lastName + '.';
The problem was that I was missing a plus (+) between the empty space and lastName. This is a super simplified example: I was concatenating about 9 different parts so it was hard to spot the error.
Summa summarum: if you get "SyntaxError: missing ; before statement", don't look at what is wrong with the the semicolon (;) symbols in your code, look for an error in syntax on that line.
Today (2.5 years after this answer) you can safely use Array.forEach
. As @ricosrealm suggests, decodeURIComponent
was used in this function.
function getJsonFromUrl(url) {
if(!url) url = location.search;
var query = url.substr(1);
var result = {};
query.split("&").forEach(function(part) {
var item = part.split("=");
result[item[0]] = decodeURIComponent(item[1]);
});
return result;
}
actually it's not that simple, see the peer-review in the comments, especially:
=
(@AndrewF)+
(added by me)For further details, see MDN article and RFC 3986.
Maybe this should go to codereview SE, but here is safer and regexp-free code:
function getJsonFromUrl(url) {
if(!url) url = location.href;
var question = url.indexOf("?");
var hash = url.indexOf("#");
if(hash==-1 && question==-1) return {};
if(hash==-1) hash = url.length;
var query = question==-1 || hash==question+1 ? url.substring(hash) :
url.substring(question+1,hash);
var result = {};
query.split("&").forEach(function(part) {
if(!part) return;
part = part.split("+").join(" "); // replace every + with space, regexp-free version
var eq = part.indexOf("=");
var key = eq>-1 ? part.substr(0,eq) : part;
var val = eq>-1 ? decodeURIComponent(part.substr(eq+1)) : "";
var from = key.indexOf("[");
if(from==-1) result[decodeURIComponent(key)] = val;
else {
var to = key.indexOf("]",from);
var index = decodeURIComponent(key.substring(from+1,to));
key = decodeURIComponent(key.substring(0,from));
if(!result[key]) result[key] = [];
if(!index) result[key].push(val);
else result[key][index] = val;
}
});
return result;
}
This function can parse even URLs like
var url = "?foo%20e[]=a%20a&foo+e[%5Bx%5D]=b&foo e[]=c";
// {"foo e": ["a a", "c", "[x]":"b"]}
var obj = getJsonFromUrl(url)["foo e"];
for(var key in obj) { // Array.forEach would skip string keys here
console.log(key,":",obj[key]);
}
/*
0 : a a
1 : c
[x] : b
*/
Using the credentials helper command-line option:
git -c credential.helper='!f() { echo "password=mysecretpassword"; }; f' fetch origin
tl;dr;
mylist.clear() # Added in Python 3.3
del mylist[:]
are probably the best ways to do this. The rest of this answer tries to explain why some of your other efforts didn't work.
cpython at least works on reference counting to determine when objects will be deleted. Here you have multiple references to the same objects. a
refers to the same object that c[0]
references. When you loop over c
(for i in c:
), at some point i
also refers to that same object. the del
keyword removes a single reference, so:
for i in c:
del i
creates a reference to an object in c
and then deletes that reference -- but the object still has other references (one stored in c
for example) so it will persist.
In the same way:
def kill(self):
del self
only deletes a reference to the object in that method. One way to remove all the references from a list is to use slice assignment:
mylist = list(range(10000))
mylist[:] = []
print(mylist)
Apparently you can also delete the slice to remove objects in place:
del mylist[:] #This will implicitly call the `__delslice__` or `__delitem__` method.
This will remove all the references from mylist
and also remove the references from anything that refers to mylist
. Compared that to simply deleting the list -- e.g.
mylist = list(range(10000))
b = mylist
del mylist
#here we didn't get all the references to the objects we created ...
print(b) #[0, 1, 2, 3, 4, ...]
Finally, more recent python revisions have added a clear
method which does the same thing that del mylist[:]
does.
mylist = [1, 2, 3]
mylist.clear()
print(mylist)
your xpath should work . i have tested your xpath and mine in both MarkLogic and Zorba Xquery/ Xpath implementation.
Both should work.
/node/child::text()[1] - should return Text1
/node/child::text()[2] - should return text2
/node/text()[1] - should return Text1
/node/text()[2] - should return text2
A predicate is a function that returns true
or false
. A predicate delegate is a reference to a predicate.
So basically a predicate delegate is a reference to a function that returns true
or false
. Predicates are very useful for filtering a list of values - here is an example.
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> list = new List<int> { 1, 2, 3 };
Predicate<int> predicate = new Predicate<int>(greaterThanTwo);
List<int> newList = list.FindAll(predicate);
}
static bool greaterThanTwo(int arg)
{
return arg > 2;
}
}
Now if you are using C# 3 you can use a lambda to represent the predicate in a cleaner fashion:
using System;
using System.Collections.Generic;
class Program
{
static void Main()
{
List<int> list = new List<int> { 1, 2, 3 };
List<int> newList = list.FindAll(i => i > 2);
}
}
Your $_POST array contains the invite array, so reading it out as
<?php
if(isset($_POST['invite'])){
$invite = $_POST['invite'];
echo $invite;
}
?>
won't work since it's an array. You have to loop through the array to get all of the values.
<?php
if(isset($_POST['invite'])){
if (is_array($_POST['invite'])) {
foreach($_POST['invite'] as $value){
echo $value;
}
} else {
$value = $_POST['invite'];
echo $value;
}
}
?>
None of the answers solved exactly my problem (the solution file I was running was trying to find xcopy to copy a dll after generation).
What solved it for me was going into menu "Project -> Properties"
Then in the window that opens choosing on the left pane: "Configuration Properties -> VC++ Directories
On the right pane under "General" choosing "Executable Directories "
And then adding:
$(SystemRoot)\system32;$(SystemRoot);$(SystemRoot)\System32\Wbem;$(SystemRoot)\System32\WindowsPowerShell\v1.0\;$(ExecutablePath)
ConfigurationManager.AppSettings
is actually a property, so you need to use square brackets.
Overall, here's what you need to do:
SqlConnection con= new SqlConnection(ConfigurationManager.AppSettings["ConnectionString"]);
The problem is that you tried to set con to a string, which is not correct. You have to either pass it to the constructor or set con.ConnectionString property.
Added: I found something that should do the trick right away, but the rest of the code below also offers an alternative.
Use the subplots_adjust()
function to move the bottom of the subplot up:
fig.subplots_adjust(bottom=0.2) # <-- Change the 0.02 to work for your plot.
Then play with the offset in the legend bbox_to_anchor
part of the legend command, to get the legend box where you want it. Some combination of setting the figsize
and using the subplots_adjust(bottom=...)
should produce a quality plot for you.
Alternative: I simply changed the line:
fig = plt.figure(1)
to:
fig = plt.figure(num=1, figsize=(13, 13), dpi=80, facecolor='w', edgecolor='k')
and changed
lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,0))
to
lgd = ax.legend(loc=9, bbox_to_anchor=(0.5,-0.02))
and it shows up fine on my screen (a 24-inch CRT monitor).
Here figsize=(M,N)
sets the figure window to be M inches by N inches. Just play with this until it looks right for you. Convert it to a more scalable image format and use GIMP to edit if necessary, or just crop with the LaTeX viewport
option when including graphics.
When creating subdirectories hanging off from a non-existing parent directory(s) you must pass the -p
flag to mkdir
... Please update your Dockerfile with
RUN mkdir -p ...
I tested this and it's correct.
Try to use ftp.nlst(dir)
.
However, note that if the folder is empty, it might throw an error:
files = []
try:
files = ftp.nlst()
except ftplib.error_perm, resp:
if str(resp) == "550 No files found":
print "No files in this directory"
else:
raise
for f in files:
print f
That selects the row number per country code, account, and currency. So, the rows with country code "US", account "XYZ" and currency "$USD" will each get a row number assigned from 1-n; the same goes for every other combination of those columns in the result set.
This query is kind of funny, because the order by clause does absolutely nothing. All the rows in each partition have the same country code, account, and currency, so there's no point ordering by those columns. The ultimate row numbers assigned in this particular query will therefore be unpredictable.
Hope that helps...
In this case, the most proper way to exit the application in to override onExit() method in App.xaml.cs:
protected override void OnExit(ExitEventArgs e) {
base.OnExit(e);
}
You can do something like this to read your nodes.
Also you can find some explanation in this page http://www.compoc.com/tuts/
<script type="text/javascript">
var markers = null;
$(document).ready(function () {
$.get("File.xml", {}, function (xml){
$('marker',xml).each(function(i){
markers = $(this);
});
});
});
</script>
Method 1 : Using jQuery Ajax Get call (partial page update).
Suitable for when you need to retrieve jSon data from database.
Controller's Action Method
[HttpGet]
public ActionResult Foo(string id)
{
var person = Something.GetPersonByID(id);
return Json(person, JsonRequestBehavior.AllowGet);
}
Jquery GET
function getPerson(id) {
$.ajax({
url: '@Url.Action("Foo", "SomeController")',
type: 'GET',
dataType: 'json',
// we set cache: false because GET requests are often cached by browsers
// IE is particularly aggressive in that respect
cache: false,
data: { id: id },
success: function(person) {
$('#FirstName').val(person.FirstName);
$('#LastName').val(person.LastName);
}
});
}
Person class
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
Method 2 : Using jQuery Ajax Post call (partial page update).
Suitable for when you need to do partial page post data into database.
Post method is also same like above just replace [HttpPost]
on Action method and type as post
for jquery method.
For more information check Posting JSON Data to MVC Controllers Here
Method 3 : As a Form post scenario (full page update).
Suitable for when you need to save or update data into database.
View
@using (Html.BeginForm("SaveData","ControllerName", FormMethod.Post))
{
@Html.TextBoxFor(model => m.Text)
<input type="submit" value="Save" />
}
Action Method
[HttpPost]
public ActionResult SaveData(FormCollection form)
{
// Get movie to update
return View();
}
Method 4 : As a Form Get scenario (full page update).
Suitable for when you need to Get data from database
Get method also same like above just replace [HttpGet]
on Action method and FormMethod.Get
for View's form method.
I hope this will help to you.
Yes, this is possible by using worksheet events:
In the Visual Basic Editor open the worksheet you're interested in (i.e. "BigBoard") by double clicking on the name of the worksheet in the tree at the top left. Place the following code in the module:
Private Sub Worksheet_Change(ByVal Target As Range)
If Intersect(Target, Me.Range("D2")) Is Nothing Then Exit Sub
Application.EnableEvents = False 'to prevent endless loop
On Error Goto Finalize 'to re-enable the events
MsgBox "You changed THE CELL!"
End If
Finalize:
Application.EnableEvents = True
End Sub
Simple read loop use this code
var resx = ResourcesName.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, false, false);
foreach (DictionaryEntry dictionaryEntry in resx)
{
Console.WriteLine("Key: " + dictionaryEntry.Key);
Console.WriteLine("Val: " + dictionaryEntry.Value);
}
You may use
values, counts = np.unique(a, return_counts=True)
ind = np.argmax(counts)
print(values[ind]) # prints the most frequent element
ind = np.argpartition(-counts, kth=10)[:10]
print(values[ind]) # prints the 10 most frequent elements
If some element is as frequent as another one, this code will return only the first element.
This takes advantage of DOMContentLoaded - which fires before onload - but allows you to stick in all your unobtrusiveness...
window.onload - Dean Edwards - The blog post talks more about it - and here is the complete code copied from the comments of that same blog.
// Dean Edwards/Matthias Miller/John Resig
function init() {
// quit if this function has already been called
if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
// kill the timer
if (_timer) clearInterval(_timer);
// do stuff
};
/* for Mozilla/Opera9 */
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}
/* for Internet Explorer */
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
init(); // call the onload handler
}
};
/*@end @*/
/* for Safari */
if (/WebKit/i.test(navigator.userAgent)) { // sniff
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
init(); // call the onload handler
}
}, 10);
}
/* for other browsers */
window.onload = init;
You can also do it without modulus. Just reset your counter when it matches.
if($counter == 2) { // matches every 3 iterations
echo 'image-file';
$counter = 0;
}
I needed to see the results of this script and was able to do so by incorporating the below:
var i=0;
function increase()
{
i++;
document.getElementById('boldstuff').innerHTML= +i;
}
<p>var = <b id="boldstuff">0</b></p>
<input type="button" onclick="increase();">
add the "script" tag above all and a closing script tag below the function end curly brace. Returning false caused firefox to hang when I tried it. All other solutions didn't show the result of the increment, in my experience.
Here is a more complete example:
import csv
import numpy as np
with open('filename','rb') as csvfile:
cdl = list( csv.reader(csvfile,delimiter='\t'))
print "Number of records = " + str(len(cdl))
#then later
npcdl = np.array(cdl)
Hope this helps!!
You need to do something like this:
// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");
// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");
// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
// grab the "id" attribute
XmlAttribute idAttribute = aNode.Attributes["id"];
// check if that attribute even exists...
if (idAttribute != null)
{
// if yes - read its current value
string currentValue = idAttribute.Value;
// here, you can now decide what to do - for demo purposes,
// I just set the ID value to a fixed value if it was empty before
if (string.IsNullOrEmpty(currentValue))
{
idAttribute.Value = "515";
}
}
}
// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");
Shortest way: Click lock icon in address bar. Then click Site settings, then click Reset permissions
My understanding is that there are duplicate references to the same API (Likely different version numbers). It should be reasonably easy to debug when building from the command line.
Try ./gradlew yourBuildVariantName --debug
from the command line.
The offending item will be the first failure. An example might look like:
14:32:29.171 [INFO] [org.gradle.api.Task] INPUT: /Users/mydir/Documents/androidApp/BaseApp/build/intermediates/exploded-aar/theOffendingAAR/libs/google-play-services.jar
14:32:29.171 [DEBUG] [org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter] Finished executing task ':BaseApp:packageAllyourBuildVariantNameClassesForMultiDex'
14:32:29.172 [LIFECYCLE] [class org.gradle.TaskExecutionLogger] :BaseApp:packageAllyourBuildVariantNameClassesForMultiDex FAILED'
In the case above, the aar file that I'd included in my libs directory (theOffendingAAR) included the Google Play Services jar (yes the whole thing. yes I know.) file whilst my BaseApp build file utilised location services:
compile 'com.google.android.gms:play-services-location:6.5.87'
You can safely remove the offending item from your build file(s), clean and rebuild (repeat if necessary).
1 - If you have spaces and want tabs.
First, you need to decide how many spaces will have a single tab. That said, suppose you have lines with leading 4 spaces, or 8... Than you realize you probably want a tab to be 4 spaces. Now with that info, you do:
:set ts=4
:set noet
:%retab!
There is a problem here! This sequence of commands will look for all your text, not only spaces in the begin of the line. That mean a string like: "Hey,?this????is?4?spaces"
will become "Hey,?this?is?4?spaces"
, but its not! its a tab!.
To settle this little problem I recomend a search
, instead of retab
.
:%s/^\(^I*\)????/\1^I/g
This search will look in the whole file for any lines starting with whatever number of tabs, followed by 4 spaces, and substitute it for whatever number of tabs it found plus one.
This, unfortunately, will not run at once!
At first, the file will have lines starting with spaces. The search will then convert only the first 4 spaces to a tab, and let the following...
You need to repeat the command. How many times? Until you get a pattern not found
. I cannot think of a way to automatize the process yet. But if you do:
`10@:`
You are probably done. This command repeats the last search/replace for 10 times. Its not likely your program will have so many indents. If it has, just repeat again @@
.
Now, just to complete the answer. I know you asked for the opposite, but you never know when you need to undo things.
2 - You have tabs and want spaces.
First, decide how many spaces you want your tabs to be converted to. Lets say you want each tab to be 2 spaces. You then do:
:set ts=2
:set et
:%retab!
This would have the same problem with strings. But as its better programming style to not use hard tabs inside strings, you actually are doing a good thing here. If you really need a tab inside a string, use \t
.
Here's technique I figured out after a bit of trial and error that allows you to preserve your XML styles and avoid the issues of using a <merge/>
(i.e. inflate() requires a merge to attach to root, and returns the root node). No runtime new TableRow()
s or new TextView()
s required.
Code
Note: Here CheckBalanceActivity
is some sample Activity
class
TableLayout table = (TableLayout)CheckBalanceActivity.this.findViewById(R.id.attrib_table);
for(ResourceBalance b : xmlDoc.balance_info)
{
// Inflate your row "template" and fill out the fields.
TableRow row = (TableRow)LayoutInflater.from(CheckBalanceActivity.this).inflate(R.layout.attrib_row, null);
((TextView)row.findViewById(R.id.attrib_name)).setText(b.NAME);
((TextView)row.findViewById(R.id.attrib_value)).setText(b.VALUE);
table.addView(row);
}
table.requestLayout(); // Not sure if this is needed.
attrib_row.xml
<?xml version="1.0" encoding="utf-8"?>
<TableRow style="@style/PlanAttribute" xmlns:android="http://schemas.android.com/apk/res/android">
<TextView
style="@style/PlanAttributeText"
android:id="@+id/attrib_name"
android:textStyle="bold"/>
<TextView
style="@style/PlanAttributeText"
android:id="@+id/attrib_value"
android:gravity="right"
android:textStyle="normal"/>
</TableRow>
Make sure, that all of your class methods (updateVelocity
, updatePosition
, ...) take at least one positional argument, which is canonically named self
and refers to the current instance of the class.
When you call particle.updateVelocity()
, the called method implicitly gets an argument: the instance, here particle
as first parameter.
clearInterval is one option:
var interval = setInterval(doStuff, 2000); // 2000 ms = start after 2sec
function doStuff() {
alert('this is a 2 second warning');
clearInterval(interval);
}
Try this it works for me:
/^(http[s]?:\/\/){0,1}(w{3,3}\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/;
There are tons of sample code online as to how to do this.
Here is just one example of how to do this: http://geekswithblogs.net/dotNETvinz/archive/2009/04/30/creating-a-simple-registration-form-in-asp.net.aspx
you define the text boxes between the following tag:
<form id="form1" runat="server">
you create your textboxes and define them to runat="server" like so:
<asp:TextBox ID="TxtName" runat="server"></asp:TextBox>
define a button to process your logic like so (notice the onclick):
<asp:Button ID="Button1" runat="server" Text="Save" onclick="Button1_Click" />
in the code behind, you define what you want the server to do if the user clicks on the button by defining a method named
protected void Button1_Click(object sender, EventArgs e)
or you could just double click the button in the design view.
Here is a very quick sample of code to insert into a table in the button click event (codebehind)
protected void Button1_Click(object sender, EventArgs e)
{
string name = TxtName.Text; // Scrub user data
string connString = ConfigurationManager.ConnectionStrings["yourconnstringInWebConfig"].ConnectionString;
SqlConnection conn = null;
try
{
conn = new SqlConnection(connString);
conn.Open();
using(SqlCommand cmd = new SqlCommand())
{
cmd.Conn = conn;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO dummyTable(name) Values (@var)";
cmd.Parameters.AddWithValue("@var", name);
int rowsAffected = cmd.ExecuteNonQuery();
if(rowsAffected ==1)
{
//Success notification
}
else
{
//Error notification
}
}
}
catch(Exception ex)
{
//log error
//display friendly error to user
}
finally
{
if(conn!=null)
{
//cleanup connection i.e close
}
}
}
SELECT COALESCE(IF(myColumn = 1,COUNT(DISTINCT NumberColumn),NULL),0) column1,
COALESCE(CASE WHEN myColumn = 1 THEN COUNT(DISTINCT NumberColumn) ELSE NULL END,0) AS column2
FROM AD_CurrentView
My use case is that I'm on a metered account. Data transfer is limited on weekdays, Mon - Fri, from 6am - 6pm. I am using bandwidth limiting, but somehow, data still slips through, about 1GB per day!
I strongly suspected it's sickrage or sickbeard, doing a high amount of searches. My download machine is called "download." The following was my solution, using the above,for starting, and stopping the download VM, using KVM:
# Stop download Mon-Fri, 6am
0 6 * * 1,2,3,4,5 root virsh shutdown download
# Start download Mon-Fri, 6pm
0 18 * * 1,2,3,4,5 root virsh start download
I think this is correct, and hope it helps someone else too.
This works too:
SELECT DATEADD(DAY,(DATEPART(DAY,@mydate)-1)*(-1),@mydate) AS FirstOfMonth
Styling checkboxes (and many other input elements for that mater) is not really possible with pure css if you want to drastically change the visual appearance.
Your best bet is to implement something like jqTransform does which actually replaces you inputs with images and applies javascript behaviour to it to mimic a checkbox (or other element for that matter)
The substitute of fcntl
on windows are win32api
calls. The usage is completely different. It is not some switch you can just flip.
In other words, porting a fcntl
-heavy-user module to windows is not trivial. It requires you to analyze what exactly each fcntl
call does and then find the equivalent win32api
code, if any.
There's also the possibility that some code using fcntl
has no windows equivalent, which would require you to change the module api and maybe the structure/paradigm of the program using the module you're porting.
If you provide more details about the fcntl
calls people can find windows equivalents.
Visit https://www.tutorialspoint.com/python/string_join.htm
s=" "
seq=["ab", "cd", "ef"]
print(s.join(seq))
ab cd ef
s="."
print(s.join(seq))
ab.cd.ef
i fixed my problem by this code on linux file system
if (!file.exists())
Files.createFile(file.toPath());
I managed to find a relatively clean straightforward way to do this. To see it working click on my webpage: http://developersfound.com/yde-portfolio.html and hover over the 'Youtube Demos' link.
Below are two snippets to show how this can be done quite easily:
I achieved this with an iFrame. Assuming this DOM is 'yde-home.html' Which is the source of your iFrame.
<!DOCTYPE html>
<html>
<head>
<title>iFrame Container</title>
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<style type="text/css">.OBJ-1 { border:none; }</style>
<script>
$(document).ready(function() {
$('#myHiddenButton').trigger('click');
});
</script>
</head>
<body>
<section style="visibility: hidden;">
<button id="myHiddenButton" onclick="$(location).attr('href', '"http://www.youtube.com/embed/wtwOZMXCe-c?version=3&start=0&rel=0&fs=1&wmode=transparent;");">View Full Screen</button>
</section>
<section class="main-area-inner" style="background:transparent;margin-left:auto;margin-right:auto;position:relative;width:1080px;height:720px;">
<iframe src="http://www.youtube.com/embed/wtwOZMXCe-c?version=3&start=0&rel=0&fs=1&wmode=transparent;"
class="OBJ-1" style="position:absolute;left:79px;top:145px;width:1080px;height:720px;">
</iframe>
</section>
</body>
</html>
Assume this is the DOM that loads the iFrame.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<title>Full Screen Youtube</title>
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function() {});
</script>
</head>
<body>
<iframe name="iframe-container" id="iframe-container" src="yde-home.html" style="width: 100%; height: 100%;">
<p>Your browser does not support iFrames</p>
</iframe>
</body>
</html>
I've also checked this against the W3c Validator and it validates a HTML5 with no errors.
It is also important to note that: Youtube embed URLs sometimes check to see if the request is coming from a server so it may be necessary to set up your test environment to listen on your external IP. So you may need to set up port forwarding on your router for this solution to work. Once you've set up port forwarding just test from the external IP instead of LocalHost. Remember that some routers need port forwarding from LocalHost/loopback but most use the same IP that you used to log into the router. For example if your router login page is 192.168.0.1, then the port forward would have to use 192.168.0.? where ? could be any unused number (you may need to experiment). From this address you would add the ports that your test environment listen from (normally 80, 81, 8080 or 8088).
Here is a resource you can edit and use Download Source Code or see live demo here http://purpledesign.in/blog/pop-out-a-form-using-jquery-and-javascript/
Add a Button or link to your page like this
<p><a href="#inline">click to open</a></p>
“#inline” here should be the “id” of the that will contain the form.
<div id="inline">
<h2>Send us a Message</h2>
<form id="contact" name="contact" action="#" method="post">
<label for="email">Your E-mail</label>
<input type="email" id="email" name="email" class="txt">
<br>
<label for="msg">Enter a Message</label>
<textarea id="msg" name="msg" class="txtarea"></textarea>
<button id="send">Send E-mail</button>
</form>
</div>
Include these script to listen of the event of click. If you have an action defined in your form you can use “preventDefault()” method
<script type="text/javascript">
$(document).ready(function() {
$(".modalbox").fancybox();
$("#contact").submit(function() { return false; });
$("#send").on("click", function(){
var emailval = $("#email").val();
var msgval = $("#msg").val();
var msglen = msgval.length;
var mailvalid = validateEmail(emailval);
if(mailvalid == false) {
$("#email").addClass("error");
}
else if(mailvalid == true){
$("#email").removeClass("error");
}
if(msglen < 4) {
$("#msg").addClass("error");
}
else if(msglen >= 4){
$("#msg").removeClass("error");
}
if(mailvalid == true && msglen >= 4) {
// if both validate we attempt to send the e-mail
// first we hide the submit btn so the user doesnt click twice
$("#send").replaceWith("<em>sending...</em>");
//This will post it to the php page
$.ajax({
type: 'POST',
url: 'sendmessage.php',
data: $("#contact").serialize(),
success: function(data) {
if(data == "true") {
$("#contact").fadeOut("fast", function(){
//Display a message on successful posting for 1 sec
$(this).before("<p><strong>Success! Your feedback has been sent, thanks :)</strong></p>");
setTimeout("$.fancybox.close()", 1000);
});
}
}
});
}
});
});
</script>
You can add anything you want to do in your PHP file.
Strings can have for loops to:
for a in string:
print a
var stringArray = ["String1", "String2", "String3"];
return (stringArray.indexOf(searchStr) > -1)
I had the same problem - for me it was the SQL Server running out of memory. Freeing up some memory solved the issue
pull vs fetch:
The way I understand this, is that git pull
is simply a git fetch
followed by git merge
. I.e. you fetch the changes from a remote branch and then merge it into the current branch.
merge vs rebase:
A merge will do as the command says; merge the differences between current branch and the specified branch (into the current branch). I.e. the command git merge another_branch
will the merge another_branch
into the current branch.
A rebase works a bit differently and is kind of cool. Let's say you perform the command git rebase another_branch
. Git will first find the latest common version between the current branch and another_branch
. I.e. the point before the branches diverged. Then git will move this divergent point to the head of the another_branch
. Finally, all the commits in the current branch since the original divergent point are replayed from the new divergent point. This creates a very clean history, with fewer branches and merges.
However, it is not without pitfalls! Since the version history is "rewritten", you should only do this if the commits only exists in your local git repo. That is: Never do this if you have pushed the commits to a remote repo.
The explanation on rebasing given in this online book is quite good, with easy-to-understand illustrations.
pull with rebasing instead of merge
I'm actually using rebase quite a lot, but usually it is in combination with pull:
git pull --rebase
will fetch remote changes and then rebase instead of merge. I.e. it will replay all your local commits from the last time you performed a pull. I find this much cleaner than doing a normal pull with merging, which will create an extra commit with the merges.
if you're happy using it as a background image and CSS3 then background-size: cover;
would do the trick
The dat file has some lines of extra information before the actual data. Skip them with the skip
argument:
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)
An easy way to check this if you are unfamiliar with the dataset is to first use readLines
to check a few lines, as below:
readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
n=10)
# [1] "Ozone data from CZ03 2009" "Local time: GMT + 0"
# [3] "" "Date Hour Value"
# [5] "01.01.2009 00:00 34.3" "01.01.2009 01:00 31.9"
# [7] "01.01.2009 02:00 29.9" "01.01.2009 03:00 28.5"
# [9] "01.01.2009 04:00 32.9" "01.01.2009 05:00 20.5"
Here, we can see that the actual data starts at [4]
, so we know to skip the first three lines.
If you really only wanted the Value
column, you could do that by:
as.vector(
read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
header=TRUE, skip=3)$Value)
Again, readLines
is useful for helping us figure out the actual name of the columns we will be importing.
But I don't see much advantage to doing that over reading the whole dataset in and extracting later.
It seems Yahoo server does some heuristic based on User-Agent
in a case Accept
header is set to */*
.
Accept: text/html
did the trick for me.
e.g.
wget --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" http://yahoo.com
Note: if you don't declare Accept
header then wget
automatically adds Accept:*/*
which means give me anything you have.
Some basics:
RTSP server can be used for dead source as well as for live source. RTSP protocols provides you commands (Like your VCR Remote), and functionality depends upon your implementation.
RTP is real time protocol used for transporting audio and video in real time. Transport used can be unicast, multicast or broadcast, depending upon transport address and port. Besides transporting RTP does lots of things for you like packetization, reordering, jitter control, QoS, support for Lip sync.....
In your case if you want broadcasting streaming server then you need both RTSP (for control) as well as RTP (broadcasting audio and video)
To start with you can go through sample code provided by live555
It is a static function on the MessageBox class, the simple way to do this is using
MessageBox.Show("my message");
in the System.Windows.Forms class. You can find more on the msdn page for this here . Among other things you can control the message box text, title, default button, and icons. Since you didn't specify, if you are trying to do this in a webpage you should look at triggering the javascript alert("my message"); or confirm("my question"); functions.
Using aws s3 cp
from the AWS Command-Line Interface (CLI) will require the --recursive
parameter to copy multiple files.
aws s3 cp s3://myBucket/dir localdir --recursive
The aws s3 sync
command will, by default, copy a whole directory. It will only copy new/modified files.
aws s3 sync s3://mybucket/dir localdir
Just experiment to get the result you want.
Documentation:
In Android Studio version 3.0 or more I have used bellow like :
Project
view in upper left cornerIn build.gradle add these lines
// Add this line if was not added before.
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation files('libs/com.ibm.icu_3.4.4.1.jar')
The "directory where postgresql will keep all databases" (and configuration) is called "data directory" and corresponds to what PostgreSQL calls (a little confusingly) a "database cluster", which is not related to distributed computing, it just means a group of databases and related objects managed by a PostgreSQL server.
The location of the data directory depends on the distribution. If you install from source, the default is /usr/local/pgsql/data
:
In file system terms, a database cluster will be a single directory under which all data will be stored. We call this the data directory or data area. It is completely up to you where you choose to store your data. There is no default, although locations such as /usr/local/pgsql/data or /var/lib/pgsql/data are popular. (ref)
Besides, an instance of a running PostgreSQL server is associated to one cluster; the location of its data directory can be passed to the server daemon ("postmaster" or "postgres") in the -D
command line option, or by the PGDATA
environment variable (usually in the scope of the running user, typically postgres
). You can usually see the running server with something like this:
[root@server1 ~]# ps auxw | grep postgres | grep -- -D
postgres 1535 0.0 0.1 39768 1584 ? S May17 0:23 /usr/local/pgsql/bin/postgres -D /usr/local/pgsql/data
Note that it is possible, though not very frequent, to run two instances of the same PostgreSQL server (same binaries, different processes) that serve different "clusters" (data directories). Of course, each instance would listen on its own TCP/IP port.
This is more pythonic
my_list = [0, 1, 2, 3, 4, 5] # some list
my_list_copy = list(my_list) # my_list_copy and my_list does not share reference now.
NOTE: This is not safe with a list of referenced objects
I'm using Eclipse 4.3.2 (Kepler) with M2E 1.4.x and felt over this problem several times!
In my case the "mvn eclipse:eclipse" command also generates Checkstyle, PMD and Findbugs configuration so "mvn eclipse:clean" does not help me because it drops all those config files again.
The best solution for me was to delete all ".classpath" files:
find . -name ".classpath" -delete
and import the project into eclipse afterwards.
The original order is in fact backwards. Certs should be followed by the issuing cert until the last cert is issued by a known root per IETF's RFC 5246 Section 7.4.2
This is a sequence (chain) of certificates. The sender's certificate MUST come first in the list. Each following certificate MUST directly certify the one preceding it.
See also SSL: error:0B080074:x509 certificate routines:X509_check_private_key:key values mismatch for troubleshooting techniques.
But I still don't know why they wrote the spec so that the order matters.
I think your problem is that the :after psuedo-element requires the content: property set inside it. You need to tell it to insert something. You could even just have it insert the image directly:
ul li:after {
content: url('../images/small_triangle.png');
}
If we want to add numbers of an Array and find the average of them follow this easy way! .....
public class Array {
public static void main(String[] args) {
int[]array = {1,3,5,7,9,6,3};
int i=0;
int sum=0;
double average=0;
for( i=0;i<array.length;i++){
System.out.println(array[i]);
sum=sum+array[i];
}
System.out.println("sum is:"+sum);
System.out.println("average is: "+(double)sum/vargu.length);
}
}
I know it's old news but to add my two cents. By default I use the commands LIKE[cd]
rather than just [c]
. The [d]
compares letters with accent symbols. This works especially well in my Warcraft App where people spell their name "Vòódòó" making it nearly impossible to search for their name in a tableview. The [d]
strips their accent symbols during the predicate. So a predicate of @"name LIKE[CD] %@", object.name
where object.name == @"voodoo"
will return the object containing the name Vòódòó.
From the Apple documentation: like[cd] means “case- and diacritic-insensitive like.”) For a complete description of the string syntax and a list of all the operators available, see Predicate Format String Syntax.
function myFunction(value1,value2,value3)
{
return {val2: value2, val3: value3};
}
This is a few months late, but I have created PR#6251 with matplotlib to add a new PercentFormatter
class. With this class you just need one line to reformat your axis (two if you count the import of matplotlib.ticker
):
import ...
import matplotlib.ticker as mtick
ax = df['myvar'].plot(kind='bar')
ax.yaxis.set_major_formatter(mtick.PercentFormatter())
PercentFormatter()
accepts three arguments, xmax
, decimals
, symbol
. xmax
allows you to set the value that corresponds to 100% on the axis. This is nice if you have data from 0.0 to 1.0 and you want to display it from 0% to 100%. Just do PercentFormatter(1.0)
.
The other two parameters allow you to set the number of digits after the decimal point and the symbol. They default to None
and '%'
, respectively. decimals=None
will automatically set the number of decimal points based on how much of the axes you are showing.
Update
PercentFormatter
was introduced into Matplotlib proper in version 2.1.0.
The standard approach is to use sprintf(buffer, "%lu", value);
to write a string rep of value
to buffer
. However, overflow is a potential problem, as sprintf
will happily (and unknowingly) write over the end of your buffer.
This is actually a big weakness of sprintf, partially fixed in C++ by using streams rather than buffers. The usual "answer" is to allocate a very generous buffer unlikely to overflow, let sprintf output to that, and then use strlen to determine the actual string length produced, calloc a buffer of (that size + 1) and copy the string to that.
This site discusses this and related problems at some length.
Some libraries offer snprintf
as an alternative which lets you specify a maximum buffer size.
Date startTime = new Date();
//...
//... lengthy jobs
//...
Date endTime = new Date();
long diff = endTime.getTime() - startTime.getTime();
String hrDateText = DurationFormatUtils.formatDuration(diff, "d 'day(s)' H 'hour(s)' m 'minute(s)' s 'second(s)' ");
System.out.println("Duration : " + hrDateText);
You can use Apache Commons Duration Format Utils. It formats like SimpleDateFormatter
Output:
0 days(s) 0 hour(s) 0 minute(s) 1 second(s)
The correct answer is:
Blah.find({}).sort({date: -1}).execFind(function(err,docs){
});
Maybe this is what you mean to do:
import random
x = 0
z = input('Please Enter an integer: ')
z = int(z) # you need to capture the result of the expressioin: int(z) and assign it backk to z
def main():
for i in range(x,z):
n1 = random.randrange(1,3)
n2 = random.randrange(1,3)
t1 = n1+n2
print('{0}+{1}={2}'.format(n1,n2,t1))
main()
Here's a link on the range() function: http://docs.python.org/release/1.5.1p1/tut/range.html
I was trying to select a table row, so that it can be easily copied to the clipboard and then pasted in Excel. Below is a small adaptation of your solution.
References:
Where I took the window.prompt line from (Jarek Milewski):
The user is presented with the prompt box, where the text to be copied is already selected...
For selecting a complete table (Tim Down). Very interesting, but I was not able to adapt for a <tr>
element.
<!DOCTYPE html>
<html>
<body>
<div>
<table id="tableId" border=1>
<tbody>
<tr><td>Item <b>A1</b></td><td>Item <b>B1</b></td></tr>
<tr><td>Item <b>A2</b></td><td>Item <b>B2</b></td></tr>
<tr><td>Item <b>A3</b></td><td>Item <b>B3</b></td></tr>
</tbody>
</table>
</div>
<script>
function addRowHandlers() {
var table = document.getElementById("tableId");
var rows = table.getElementsByTagName("tr");
for (i = 0; i < rows.length; i++) {
var currentRow = table.rows[i];
var createClickHandler =
function(row)
{
return function() {
var cell = row.getElementsByTagName("td")[0];
var id = cell.innerHTML;
var cell1 = row.getElementsByTagName("td")[1];
var id2 = cell1.innerHTML;
// alert(id + " - " + id2);
window.prompt("Copy to clipboard: Ctrl+C, Enter", "<table><tr><td>" + id + "</td><td>" + id2 + "</td></tr></table>")
};
};
currentRow.onclick = createClickHandler(currentRow);
}
}
window.onload = addRowHandlers();
</script>
</body>
</html>
If you are using WL 10 use the following:
org.hibernate.dialect.Oracle10gDialect
I once had this kind of problem installing MinGW to work in Windows, even after I added the right System PATH in my Environment Variables.
After days of misery, I finally stumbled on a thread that recommended uninstalling the original MinGW compiler and deleting the C:\MinGW
folder and installing TDM-GCC MinGW compiler which can be found here.
You have options of choosing a 64/32-bit installer from the download page, and it creates the environment path variables for you too.
SOAP currently has the advantage of better tools where they will generate a lot of the boilerplate code for both the service layer as well as generating clients from any given WSDL.
REST is simpler, can be easier to maintain as a result, lies at the heart of Web architecture, allows for better protocol visibility, and has been proven to scale at the size of the WWW itself. Some frameworks out there help you build REST services, like Ruby on Rails, and some even help you with writing clients, like ADO.NET Data Services. But for the most part, tool support is lacking.
You need to get the mouse position relative to the canvas
To do that you need to know the X/Y position of the canvas on the page.
This is called the canvas’s “offset”, and here’s how to get the offset. (I’m using jQuery in order to simplify cross-browser compatibility, but if you want to use raw javascript a quick Google will get that too).
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
Then in your mouse handler, you can get the mouse X/Y like this:
function handleMouseDown(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
}
Here is an illustrating code and fiddle that shows how to successfully track mouse events on the canvas:
http://jsfiddle.net/m1erickson/WB7Zu/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
function handleMouseDown(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
$("#downlog").html("Down: "+ mouseX + " / " + mouseY);
// Put your mousedown stuff here
}
function handleMouseUp(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
$("#uplog").html("Up: "+ mouseX + " / " + mouseY);
// Put your mouseup stuff here
}
function handleMouseOut(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
$("#outlog").html("Out: "+ mouseX + " / " + mouseY);
// Put your mouseOut stuff here
}
function handleMouseMove(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
$("#movelog").html("Move: "+ mouseX + " / " + mouseY);
// Put your mousemove stuff here
}
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseOut(e);});
}); // end $(function(){});
</script>
</head>
<body>
<p>Move, press and release the mouse</p>
<p id="downlog">Down</p>
<p id="movelog">Move</p>
<p id="uplog">Up</p>
<p id="outlog">Out</p>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
document.getElementById('mybox').style.display = "block";
Use:
enter code var moment = require('moment')
var startDate = moment('2013-5-11 8:73:18', 'YYYY-M-DD HH:mm:ss')
Moment.js works very well. You can read more about it here.
Well, local storage speed greatly depends on the browser the client is using, as well as the operating system. Chrome or Safari on a mac could be much faster than Firefox on a PC, especially with newer APIs. As always though, testing is your friend (I could not find any benchmarks).
I really don't see a huge difference in cookie vs local storage. Also, you should be more worried about compatibility issues: not all browsers have even begun to support the new HTML5 APIs, so cookies would be your best bet for speed and compatibility.
This is a late addition but I was looking for information on the scale function myself and though it might help somebody else as well.
To modify the response from Ricardo Saporta a little bit.
Scaling is not done using standard deviation, at least not in version 3.6.1 of R, I base this on "Becker, R. (2018). The new S language. CRC Press." and my own experimentation.
X.man.scaled <- X/sqrt(sum(X^2)/(length(X)-1))
X.aut.scaled <- scale(X, center = F)
The result of these rows are exactly the same, I show it without centering because of simplicity.
I would respond in a comment but did not have enough reputation.
First uninstall python and again install the latest version during installation use custom install and mark all user checkbox and set the installation path C:\Python 3.9 and make PYTHON_HOME value C:\Python 3.9 in the Environmental variable it works for me
Here is what I am using...
$day = date('w');
$week_start = date('m-d-Y', strtotime('-'.$day.' days'));
$week_end = date('m-d-Y', strtotime('+'.(6-$day).' days'));
$day contains a number from 0 to 6 representing the day of the week (Sunday = 0, Monday = 1, etc.).
$week_start contains the date for Sunday of the current week as mm-dd-yyyy.
$week_end contains the date for the Saturday of the current week as mm-dd-yyyy.
System.Threading.Timer
is a plain timer. It calls you back on a thread pool thread (from the worker pool).
System.Timers.Timer
is a System.ComponentModel.Component
that wraps a System.Threading.Timer
, and provides some additional features used for dispatching on a particular thread.
System.Windows.Forms.Timer
instead wraps a native message-only-HWND and uses Window Timers to raise events in that HWNDs message loop.
If your app has no UI, and you want the most light-weight and general-purpose .Net timer possible, (because you are happy figuring out your own threading/dispatching) then System.Threading.Timer
is as good as it gets in the framework.
I'm not fully clear what the supposed 'not thread safe' issues with System.Threading.Timer
are. Perhaps it is just same as asked in this question: Thread-safety of System.Timers.Timer vs System.Threading.Timer, or perhaps everyone just means that:
it's easy to write race conditions when you're using timers. E.g. see this question: Timer (System.Threading) thread safety
re-entrancy of timer notifications, where your timer event can trigger and call you back a second time before you finish processing the first event. E.g. see this question: Thread-safe execution using System.Threading.Timer and Monitor
It's possible to decide which reactor projects to build by specifying the -pl
command line argument:
$ mvn --help
[...]
-pl,--projects <arg> Build specified reactor projects
instead of all projects
[...]
It accepts a comma separated list of parameters in one of the following forms:
[groupId]:artifactId
Thus, given the following structure:
project-root [com.mycorp:parent]
|
+ --- server [com.mycorp:server]
| |
| + --- orm [com.mycorp.server:orm]
|
+ --- client [com.mycorp:client]
You can specify the following command line:
mvn -pl .,server,:client,com.mycorp.server:orm clean install
to build everything. Remove elements in the list to build only the modules you please.
EDIT: as blackbuild pointed out, as of Maven 3.2.1 you have a new -el
flag that excludes projects from the reactor, similarly to what -pl
does:
You can use the Source property of the image. Try this code...
ImageSource imageSource = new BitmapImage(new Uri("C:\\FileName.gif"));
image1.Source = imageSource;
You should put the button inside a div, and in the div you should be able to use the classes:
text-left, text-center and text-right.
for example:
<div class="row">
<div class="col text-center">
<button class="button button-small button-light">Search</button>
</div>
</div>
And about the "textarea" position:
<div class="list">
<label class="item item-input">
<span class="input-label">Date</span>
<input type="text" placeholder="Text Area">
</label>
Demo using your code:
http://codepen.io/douglask/pen/zxXvYY
If you right-click on your "Computer" (or "My Computer") icon and select "Manage" from the pop-up menu, that'll take you to the Computer Management console.
In there, under System Tools\Shared Folders, you'll find "Open Files". This is probably close to what you want, but if the file is on a network share then you'd need to do the same thing on the server on which the file lives.
select *
from emp
where rownum <= &upperlimit
minus
select *
from emp
where rownum <= &lower limit ;
A helpful blog post on the subject, linked to from within the Modernizr source for detecting touch events. Conclusion: it's not possible to reliably detect touchscreen devices from Javascript.
Solution:
^(?!.*STRING1|.*STRING2|.*STRING3).*$
xxxxxx OK
xxxSTRING1xxx KO (is whether it is desired)
xxxSTRING2xxx KO (is whether it is desired)
xxxSTRING3xxx KO (is whether it is desired)
$num = 5;
$location = 'tree';
$format = 'There are %d monkeys in the %s';
echo sprintf($format, $num, $location);
Once you click the item add some data attribute like data-selected-item='true' and get it again.
Try adding data-selected-item='true' for li element that you clicked, then
$('ul.dropdown-menu li[data-selected-item] a').text();
Before adding this attribute you simply remove existing data-selected-item in the list. Hope this would help you
For information about data attribute usage in jQuery, refer jQuery data
Don't want to create a drawable resource?
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@android:color/black"
android:minHeight="128dp">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="1dp"
android:background="@android:color/white">
<TextView ... />
</FrameLayout>
</FrameLayout>
The fs-extra
module allows you to do this with it's move()
method. I already implemented it and it works well if you want to completely move a file from one directory to another - ie. removing the file from the source directory. Should work for most basic cases.
var fs = require('fs-extra')
fs.move('/tmp/somefile', '/tmp/does/not/exist/yet/somefile', function (err) {
if (err) return console.error(err)
console.log("success!")
})
What maven does is, it downloads all your project's dependencies into your local repo (.m2 folder). Because of the internet causing issues with your local repo, you project is facing problems. I am not sure if this will surely help you or not but you can try deleting all the files within the repository folder inside the .m2 folder. Since there would be nothing in the local repo, maven would be forced to download the dependencies again, thus forcing an update. Generally, the .m2 folder is located at c:users:[username]:.m2
ArrayIndexOutOfBoundsException in simple words is -> you have 10 students in your class (int array size 10) and you want to view the value of the 11th student (a student who does not exist)
if you make this int i[3] then i takes values i[0] i[1] i[2]
for your problem try this code structure
double[] array = new double[50];
for (int i = 0; i < 24; i++) {
}
for (int j = 25; j < 50; j++) {
}
You can use this code to see the last modified date of a file.
DateTime dt = File.GetLastWriteTime(path);
And this code to see the creation time.
DateTime fileCreatedDate = File.GetCreationTime(@"C:\Example\MyTest.txt");
You can choose a delimiter, in this case I chose a colon and printed the column number one, sorting by alphabetical order:
awk -F\: '{print $1|"sort -u"}' /etc/passwd
Place this in the ~/.m2/settings.xml
or custom file to be run with $ mvn -s custom-settings.xml install
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
https://maven.apache.org/xsd/settings-1.0.0.xsd">
<localRepository>${user.home}/.m2/repository</localRepository>
<interactiveMode/>
<offline/>
<pluginGroups/>
<profiles>
<profile>
<repositories>
<repository>
<id>mvnrepository</id>
<name>mvnrepository</name>
<url>http://www.mvnrepository.com</url>
</repository>
</repositories>
</profile>
</profiles>
<activeProfiles>
<activeProfile>mvnrepository</activeProfile>
</activeProfiles>
</settings>
There are a few things you can look at:
Pre-loading your images
Setting a cache time in an .htaccess file
File size of images and base64 encoding them.
Preloading: http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/
Caching: http://www.askapache.com/htaccess/speed-up-sites-with-htaccess-caching.html
There are a couple different thoughts for base64 encoding, some say that the http requests bog down bandwidth, while others say that the "perceived" loading is better. I'll leave this up in the air.
Method 1:
df = df.withColumnRenamed("new_column_name", "old_column_name")
Method 2: If you want to do some computation and rename the new values
df = df.withColumn("old_column_name", F.when(F.col("old_column_name") > 1, F.lit(1)).otherwise(F.col("old_column_name"))
df = df.drop("new_column_name", "old_column_name")
If you just need something simple and more of a verification.
public String getKey(String key)
{
if(map.containsKey(key)
{
return key;
}
return null;
}
Then you can search for any key.
System.out.println( "Does this key exist? : " + getKey("United") );
As of Visual Studio Code Release 1.22 this comes free without the need of an extension.
Shift+Alt+O will take care of you.
Add
[config]="{backdrop: 'static'}"
to the model code.
This was the only reasonable thing I found to fade a background image.
<div id="foo">
<!-- some content here -->
</div>
Your CSS; now enhanced with CSS3 transition.
#foo {
background-image: url(a.jpg);
transition: background 1s linear;
}
Now swap out the background
document.getElementById("foo").style.backgroundImage = "url(b.jpg)";
Voilà, it fades!
Obvious disclaimer: if your browser doesn't support the CSS3 transition
property, this won't work. In which case, the image will change without a transition. Given <1%
of your users' browser don't support CSS3, that's probably fine. Don't kid yourself, it's fine.
EDIT:
Ok I found why the int.ToString() in LINQtoEF fails, please read this post: Problem with converting int to string in Linq to entities
This works on my side :
List<string> materialTypes = (from u in result.Users
select u.LastName)
.Union(from u in result.Users
select SqlFunctions.StringConvert((double) u.UserId)).ToList();
On yours it should be like this:
IList<String> materialTypes = ((from tom in context.MaterialTypes
where tom.IsActive == true
select tom.Name)
.Union(from tom in context.MaterialTypes
where tom.IsActive == true
select SqlFunctions.StringConvert((double)tom.ID))).ToList();
Thanks, i've learnt something today :)
You can use a container for your background, placed as absolute and negative z-index : http://jsfiddle.net/2YW7g/
HTML
<div class="main">
<div class="bg">
</div>
Hello World!!!!
</div>
CSS
.main{
width:400px;
height:400px;
position:relative;
color:red;
background-color:transparent;
font-size:18px;
}
.main .bg{
position:absolute;
width:400px;
height:400px;
background-image:url("http://fc02.deviantart.net/fs71/i/2011/274/6/f/ocean__sky__stars__and_you_by_muddymelly-d4bg1ub.png");
z-index:-1;
}
.main:hover .bg{
opacity:0.5;
}
In the Html
<div id="AssignUniqueId" runat="server">.....BLAH......<div/>
In the code
public void Page_Load(object source, Event Args e)
{
if(Session["Something"] == "ShowDiv")
AssignUniqueId.Visible = true;
else
AssignUniqueID.Visible = false;
}
The debug compilation is different from the release one, so:
Consider your Project file structure like that [this case if for a Debug assemble]:
src
|
debug
|
assets
|
index.html
You should call index.html into your WebView like:
web.loadUrl("file:///android_asset/index.html");
So forth, for the Release assemble, it should be like:
src
|
release
|
assets
|
index.html
The bellow structure also works, for both compilations [debug and release]:
src
|
main
|
assets
|
index.html
create .bowerrc file in you home directory and adding this to the file worked for me
{
"directory": "bower_components",
"proxy": "http://youProxy:yourPort",
"https-proxy":"http://yourProxy:yourPort"
}
Inline elements:
Block elements:
Inline-block elements:
From W3Schools:
An inline element has no line break before or after it, and it tolerates HTML elements next to it.
A block element has some whitespace above and below it and does not tolerate any HTML elements next to it.
An inline-block element is placed as an inline element (on the same line as adjacent content), but it behaves as a block element.
When you visualize this, it looks like this:
The image is taken from this page, which also talks some more about this subject.
I was looking for a way to play VMDK files without the vmx file in VMware Player 5 and didn't find any explicit tutorial to do it. So after some time messing around with VMware PLayer 5, it turned out to be pretty simple, but not so intuitive. Here it is:
Create a new virtual machine from VMware Player 5; There's no need to install an OS, since you already have the VMDK (Virtual Machine Disk); Set the Virtual Machine to the OS you'll be playing (the one from the VMDK); After creating the VM with the remaining creation wizard options, go to your VM settings; There you can remove the existing hard drive and add a new one; Upon addition of the new hard drive, point it to your existing VMDK file.
And that's it.
If you have problems starting the VM because VMware Player can't lock the VMDK file, rename/delete the dir/files with extension *.lck from the directory where the *.vmdk file is located.
Hope this is helpful.
Change Copy Pods Resources for the target from:
"${SRCROOT}/Pods/Target Support Files/Pods-Wishlist/Pods-Wishlist-resources.sh"
to:
"${SRCROOT}/Pods/Target Support Files/Pods-Wishlist/Pods-Wishlist-frameworks.sh"
If you're looking for a file to use in httpd-ssl.conf as a value for SSLCertificateKeyFile, a PEM file should work just fine.
See this SO question/answer for more details on the SSL options in that file.
My solution was:
UPDATE: Added a more detailed description of the formset errors.
Form.errors combines all field and non_field_errors. Therefore you can simplify the html to this:
template
{% load form_tags %}
{% if form.errors %}
<div class="alert alert-danger alert-dismissible col-12 mx-1" role="alert">
<div id="form_errors">
{% for key, value in form.errors.items %}
<span class="fieldWrapper">
{{ key }}:{{ value }}
</span>
{% endfor %}
</div>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% endif %}
If you want to generalise it you can create a list_errors.html which you include in every form template. It handles form and formset errors:
{% if form.errors %}
<div class="alert alert-danger alert-dismissible col-12 mx-1" role="alert">
<div id="form_errors">
{% for key, value in form.errors.items %}
<span class="fieldWrapper">
{{ key }}:{{ value }}
</span>
{% endfor %}
</div>
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
{% elif formset.total_error_count %}
<div class="alert alert-danger alert-dismissible col-12 mx-1" role="alert">
<div id="form_errors">
{% if formset.non_form_errors %}
{{ formset.non_form_errors }}
{% endif %}
{% for form in formset.forms %}
{% if form.errors %}
Form number {{ forloop.counter }}:
<ul class="errorlist">
{% for key, error in form.errors.items %}
<li>{{form.fields|get_label:key}}
<ul class="errorlist">
<li>{{error}}</li>
</ul>
</li>
{% endfor %}
</ul>
{% endif %}
{% endfor %}
</div>
</div>
{% endif %}
form_tags.py
from django import template
register = template.Library()
def get_label(a_dict, key):
return getattr(a_dict.get(key), 'label', 'No label')
register.filter("get_label", get_label)
One caveat: In contrast to forms Formset.errors does not include non_field_errors.
Starting with AspNetCore 2.0, it's recommended to use ContentResult
instead of the Produce
attribute in this case. See: https://github.com/aspnet/Mvc/issues/6657#issuecomment-322586885
This doesn't rely on serialization nor on content negotiation.
[HttpGet]
public ContentResult Index() {
return new ContentResult {
ContentType = "text/html",
StatusCode = (int)HttpStatusCode.OK,
Content = "<html><body>Hello World</body></html>"
};
}