I found that even though under project properties build & debug tab are set to Debug and all the other setting are correct I still get the message, however after digging some more under the Build menu select Configurations Manager... and make sure Debug is selected in two places there as well. go figure...how many different places do they need to set debug?????? even though you set Project - Configuration to Debug then under Build - Manager it is not changed so you have change the same setting there as well Project Configuration - seems like a microsoft issue again.......
Make sure all your dependent projects are using the same .Net Framework version. I had the same issue caused by a dependent project using 4.5.1, while all others were using 4.5. Changing the project from 4.5.1 to 4.5 and rebuilding my solution fixed this issue for me.
GitHub
git config --global url.ssh://[email protected]/.insteadOf https://github.com/
BitBucket
git config --global url.ssh://[email protected]/.insteadOf https://bitbucket.org/
That tells git to always use SSH instead of HTTPS when connecting to GitHub/BitBucket, so you'll authenticate by certificate by default, instead of being prompted for a password.
You should better use jquery-confirm rather than trying to remove that checkbox.
$.confirm({
title: 'Confirm!',
content: 'Are you sure you want to refund invoice ?',
confirm: function(){
//do something
},
cancel: function(){
//do something
}
});
If the above does not work then try the following. It solved the problem for me even when the owner was well defined for the database.
SQL Server 2008 replication failing with: process could not execute 'sp_replcmds'
You can do This.
final List<String> fruits_list = new ArrayList<String>(Arrays.asList(fruits));
// Create an ArrayAdapter from List
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>
(this, android.R.layout.simple_list_item_1, fruits_list){
@Override
public View getView(int position, View convertView, ViewGroup parent){
// Get the current item from ListView
View view = super.getView(position,convertView,parent);
if(position %2 == 1)
{
// Set a background color for ListView regular row/item
view.setBackgroundColor(Color.parseColor("#FFB6B546"));
}
else
{
// Set the background color for alternate row/item
view.setBackgroundColor(Color.parseColor("#FFCCCB4C"));
}
return view;
}
};
// DataBind ListView with items from ArrayAdapter
lv.setAdapter(arrayAdapter);
}
}
It also helps to ensure libmysqlclient-dev is installed (Ubuntu 14.04)
Your datatype for @location nchar(20)
should be @location nvarchar(20)
, since nChar has a fixed length (filled with Spaces).
If Location is nchar too you will have to convert it:
... Cast(Location as nVarchar(200)) like '%'+@location+'%' ...
To enable nullable parameters with and AND
condition just use IsNull or Coalesce for comparison, which is not needed in your example using OR
.
e.g. if you would like to compare for Location AND Date and Time.
@location nchar(20),
@time time,
@date date
as
select DonationsTruck.VechileId, Phone, Location, [Date], [Time]
from Vechile, DonationsTruck
where Vechile.VechileId = DonationsTruck.VechileId
and (((Location like '%'+IsNull(@location,Location)+'%')) and [Date]=IsNUll(@date,date) and [Time] = IsNull(@time,Time))
you can use this:
Collections.max(Arrays.asList(1,2,3,4));
or create a function
public static int max(Integer... vals) {
return Collections.max(Arrays.asList(vals));
}
One needs to create a schema, and attach it to the Rdd.
Assuming val spark is a product of a SparkSession.builder...
import org.apache.spark._
import org.apache.spark.sql._
import org.apache.spark.sql.types._
/* Lets gin up some sample data:
* As RDD's and dataframes can have columns of differing types, lets make our
* sample data a three wide, two tall, rectangle of mixed types.
* A column of Strings, a column of Longs, and a column of Doubules
*/
val arrayOfArrayOfAnys = Array.ofDim[Any](2,3)
arrayOfArrayOfAnys(0)(0)="aString"
arrayOfArrayOfAnys(0)(1)=0L
arrayOfArrayOfAnys(0)(2)=3.14159
arrayOfArrayOfAnys(1)(0)="bString"
arrayOfArrayOfAnys(1)(1)=9876543210L
arrayOfArrayOfAnys(1)(2)=2.71828
/* The way to convert an anything which looks rectangular,
* (Array[Array[String]] or Array[Array[Any]] or Array[Row], ... ) into an RDD is to
* throw it into sparkContext.parallelize.
* http://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.SparkContext shows
* the parallelize definition as
* def parallelize[T](seq: Seq[T], numSlices: Int = defaultParallelism)
* so in our case our ArrayOfArrayOfAnys is treated as a sequence of ArraysOfAnys.
* Will leave the numSlices as the defaultParallelism, as I have no particular cause to change it.
*/
val rddOfArrayOfArrayOfAnys=spark.sparkContext.parallelize(arrayOfArrayOfAnys)
/* We'll be using the sqlContext.createDataFrame to add a schema our RDD.
* The RDD which goes into createDataFrame is an RDD[Row] which is not what we happen to have.
* To convert anything one tall and several wide into a Row, one can use Row.fromSeq(thatThing.toSeq)
* As we have an RDD[somethingWeDontWant], we can map each of the RDD rows into the desired Row type.
*/
val rddOfRows=rddOfArrayOfArrayOfAnys.map(f=>
Row.fromSeq(f.toSeq)
)
/* Now to construct our schema. This needs to be a StructType of 1 StructField per column in our dataframe.
* https://spark.apache.org/docs/latest/api/scala/index.html#org.apache.spark.sql.types.StructField shows the definition as
* case class StructField(name: String, dataType: DataType, nullable: Boolean = true, metadata: Metadata = Metadata.empty)
* Will leave the two default values in place for each of the columns:
* nullability as true,
* metadata as an empty Map[String,Any]
*
*/
val schema = StructType(
StructField("colOfStrings", StringType) ::
StructField("colOfLongs" , LongType ) ::
StructField("colOfDoubles", DoubleType) ::
Nil
)
val df=spark.sqlContext.createDataFrame(rddOfRows,schema)
/*
* +------------+----------+------------+
* |colOfStrings|colOfLongs|colOfDoubles|
* +------------+----------+------------+
* | aString| 0| 3.14159|
* | bString|9876543210| 2.71828|
* +------------+----------+------------+
*/
df.show
Same steps, but with fewer val declarations:
val arrayOfArrayOfAnys=Array(
Array("aString",0L ,3.14159),
Array("bString",9876543210L,2.71828)
)
val rddOfRows=spark.sparkContext.parallelize(arrayOfArrayOfAnys).map(f=>Row.fromSeq(f.toSeq))
/* If one knows the datatypes, for instance from JDBC queries as to RDBC column metadata:
* Consider constructing the schema from an Array[StructField]. This would allow looping over
* the columns, with a match statement applying the appropriate sql datatypes as the second
* StructField arguments.
*/
val sf=new Array[StructField](3)
sf(0)=StructField("colOfStrings",StringType)
sf(1)=StructField("colOfLongs" ,LongType )
sf(2)=StructField("colOfDoubles",DoubleType)
val df=spark.sqlContext.createDataFrame(rddOfRows,StructType(sf.toList))
df.show
I had many users controls but one refused to show in the Toolbox, even though I rebuilt the solution and it was checked in the Choose Items... dialog.
Solution:
Note this also requires you have the AutoToolboxPopulate option enabled. As @DaveF answer suggests.
Alternate Solution: I'm not sure if this works, and I couldn't try it since I already resolved my issue, but if you unchecked the user control from the Choose Items... dialog, hit OK, then opened it back up and checked the user control. That might also work.
You had several issues with your code.
1) Missing a closing brace, }
, within your rules
.
2) In this case, there is no reason to use a function for the required
rule. By default, the plugin can handle checkbox
and radio
inputs just fine, so using true
is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.
3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength
rule.
4) The messages
option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.
5) If a name
attribute contains brackets, you must enclose it within quotes.
DEMO: http://jsfiddle.net/K6Wvk/
$(document).ready(function () {
$('#formid').validate({ // initialize the plugin
rules: {
'test[]': {
required: true,
maxlength: 2
}
},
messages: {
'test[]': {
required: "You must check at least 1 box",
maxlength: "Check no more than {0} boxes"
}
}
});
});
To save others a few seconds, and to save them from having to read the manual, here's the short answer. Add this to the top of your make file:
.DEFAULT_GOAL := mytarget
mytarget will now be the target that is run if "make" is executed and no target is specified.
If you have an older version of make (<= 3.80), this won't work. If this is the case, then you can do what anon mentions, simply add this to the top of your make file:
.PHONY: default
default: mytarget ;
References: https://www.gnu.org/software/make/manual/html_node/How-Make-Works.html
There's nothing missing. Float was designed for the case where you want an image (for example) to sit beside several paragraphs of text, so the text flows around the image. That wouldn't happen if the text "stretched" the container. Your first paragraph would end, and then your next paragraph would begin under the image (possibly several hundred pixels below).
And that's why you're getting the result you are.
I know it's an old question but it seems unsolved still. Follows my solution...
Simply add this global handler:
$('a').click(function()
{
return ($(this).attr('disabled')) ? false : true;
});
Here's a quick demo: http://jsbin.com/akihik/3
you can even add a bit of css to give a different style to all the links with the disabled attribute.
e.g
a[disabled]
{
color: grey;
}
Anyway it seems that the disabled attribute is not valid for a
tags. If you prefer to follow the w3c specs you can easily adopt an html5 compliant data-disabled
attribute. In this case you have to modify the previous snippet and use $(this).data('disabled')
.
It depends on what your meaning is. There are practical size limits (if you have a lot of big files, it can get boringly slow). If you have a lot of files, scans can also get slow.
There aren't really inherent limits to the model, though. You can certainly use it poorly and be miserable.
Not sure why is this complicated. I would do this basic javascript
<body onresize='document.getElementsByTagName("body")[0].style[ "font-size" ] = document.body.clientWidth*(12/1280) + "px";'>
Where 12 means 12px at 1280 resolution. You decide the value you want here
This could be updated to ES6 with arrow functions and look like:
getFeed().then(data => vm.feed = data);
If you wish to use the async function
, you could also do like that:
async function myFunction(){
vm.feed = await getFeed();
// do whatever you need with vm.feed below
}
I had the same error because there was one more project under svn in workspace but with another name. So I've removed it.
Handles hex, octal, binary, decimal, and float
This solution will handle all of the string conventions for numbers (all that I know about).
def to_number(n):
''' Convert any number representation to a number
This covers: float, decimal, hex, and octal numbers.
'''
try:
return int(str(n), 0)
except:
try:
# python 3 doesn't accept "010" as a valid octal. You must use the
# '0o' prefix
return int('0o' + n, 0)
except:
return float(n)
This test case output illustrates what I'm talking about.
======================== CAPTURED OUTPUT =========================
to_number(3735928559) = 3735928559 == 3735928559
to_number("0xFEEDFACE") = 4277009102 == 4277009102
to_number("0x0") = 0 == 0
to_number(100) = 100 == 100
to_number("42") = 42 == 42
to_number(8) = 8 == 8
to_number("0o20") = 16 == 16
to_number("020") = 16 == 16
to_number(3.14) = 3.14 == 3.14
to_number("2.72") = 2.72 == 2.72
to_number("1e3") = 1000.0 == 1000
to_number(0.001) = 0.001 == 0.001
to_number("0xA") = 10 == 10
to_number("012") = 10 == 10
to_number("0o12") = 10 == 10
to_number("0b01010") = 10 == 10
to_number("10") = 10 == 10
to_number("10.0") = 10.0 == 10
to_number("1e1") = 10.0 == 10
Here is the test:
class test_to_number(unittest.TestCase):
def test_hex(self):
# All of the following should be converted to an integer
#
values = [
# HEX
# ----------------------
# Input | Expected
# ----------------------
(0xDEADBEEF , 3735928559), # Hex
("0xFEEDFACE", 4277009102), # Hex
("0x0" , 0), # Hex
# Decimals
# ----------------------
# Input | Expected
# ----------------------
(100 , 100), # Decimal
("42" , 42), # Decimal
]
values += [
# Octals
# ----------------------
# Input | Expected
# ----------------------
(0o10 , 8), # Octal
("0o20" , 16), # Octal
("020" , 16), # Octal
]
values += [
# Floats
# ----------------------
# Input | Expected
# ----------------------
(3.14 , 3.14), # Float
("2.72" , 2.72), # Float
("1e3" , 1000), # Float
(1e-3 , 0.001), # Float
]
values += [
# All ints
# ----------------------
# Input | Expected
# ----------------------
("0xA" , 10),
("012" , 10),
("0o12" , 10),
("0b01010" , 10),
("10" , 10),
("10.0" , 10),
("1e1" , 10),
]
for _input, expected in values:
value = to_number(_input)
if isinstance(_input, str):
cmd = 'to_number("{}")'.format(_input)
else:
cmd = 'to_number({})'.format(_input)
print("{:23} = {:10} == {:10}".format(cmd, value, expected))
self.assertEqual(value, expected)
This article helped me alot figuring out why it wasn't working for me either. It give me a lesson to think of the webpage loading and how angular 2 interacts as a timeline and not just the point in time i'm thinking of. I didn't see anyone else mention this point, so I will...
The reason the *ngIf is needed because it will try to check the length of that variable before the rest of the OnInit stuff happens, and throw the "length undefined" error. So thats why you add the ? because it won't exist yet, but it will soon.
I would opt for NOT EXISTS
in this case.
SELECT D1.ShortCode
FROM Domain1 D1
WHERE NOT EXISTS
(SELECT 'X'
FROM Domain2 D2
WHERE D2.ShortCode = D1.ShortCode
)
from datetime import datetime
from pyspark.sql.functions import col, udf
from pyspark.sql.types import DateType
# Creation of a dummy dataframe:
df1 = sqlContext.createDataFrame([("11/25/1991","11/24/1991","11/30/1991"),
("11/25/1391","11/24/1992","11/30/1992")], schema=['first', 'second', 'third'])
# Setting an user define function:
# This function converts the string cell into a date:
func = udf (lambda x: datetime.strptime(x, '%m/%d/%Y'), DateType())
df = df1.withColumn('test', func(col('first')))
df.show()
df.printSchema()
Here is the output:
+----------+----------+----------+----------+
| first| second| third| test|
+----------+----------+----------+----------+
|11/25/1991|11/24/1991|11/30/1991|1991-01-25|
|11/25/1391|11/24/1992|11/30/1992|1391-01-17|
+----------+----------+----------+----------+
root
|-- first: string (nullable = true)
|-- second: string (nullable = true)
|-- third: string (nullable = true)
|-- test: date (nullable = true)
This issue occurs if the server sends a "Cache-control:no-store" header or sends a "Cache-control:no-cache" header.
I got an amazing scroller on my div-popup
. To apply, add this style to your div element:
overflow-y: scroll;
height: XXXpx;
The height
you specify will be the height of the div and once if you have contents to exceed this height, you have to scroll it.
Thank you.
To much code, you can use it like this:
#include<array>
#include<functional>
int main()
{
std::array<int, 10> vec = { 1,2,3,4,5,6,7,8,9 };
std::sort(std::begin(vec),
std::end(vec),
[](int a, int b) {return a > b; });
for (auto item : vec)
std::cout << item << " ";
return 0;
}
Replace "vec" with your class and that's it.
First, keep in mind that, in its precise definition, a module is an object in the memory of a Python interpreter, often created by reading one or more files from disk. While we may informally call a disk file such as a/b/c.py
a "module," it doesn't actually become one until it's combined with information from several other sources (such as sys.path
) to create the module object.
(Note, for example, that two modules with different names can be loaded from the same file, depending on sys.path
and other settings. This is exactly what happens with python -m my.module
followed by an import my.module
in the interpreter; there will be two module objects, __main__
and my.module
, both created from the same file on disk, my/module.py
.)
A package is a module that may have submodules (including subpackages). Not all modules can do this. As an example, create a small module hierarchy:
$ mkdir -p a/b
$ touch a/b/c.py
Ensure that there are no other files under a
. Start a Python 3.4 or later interpreter (e.g., with python3 -i
) and examine the results of the following statements:
import a
a ? <module 'a' (namespace)>
a.b ? AttributeError: module 'a' has no attribute 'b'
import a.b.c
a.b ? <module 'a.b' (namespace)>
a.b.c ? <module 'a.b.c' from '/home/cjs/a/b/c.py'>
Modules a
and a.b
are packages (in fact, a certain kind of package called a "namespace package," though we wont' worry about that here). However, module a.b.c
is not a package. We can demonstrate this by adding another file, a/b.py
to the directory structure above and starting a fresh interpreter:
import a.b.c
? ImportError: No module named 'a.b.c'; 'a.b' is not a package
import a.b
a ? <module 'a' (namespace)>
a.__path__ ? _NamespacePath(['/.../a'])
a.b ? <module 'a.b' from '/home/cjs/tmp/a/b.py'>
a.b.__path__ ? AttributeError: 'module' object has no attribute '__path__'
Python ensures that all parent modules are loaded before a child module is loaded. Above it finds that a/
is a directory, and so creates a namespace package a
, and that a/b.py
is a Python source file which it loads and uses to create a (non-package) module a.b
. At this point you cannot have a module a.b.c
because a.b
is not a package, and thus cannot have submodules.
You can also see here that the package module a
has a __path__
attribute (packages must have this) but the non-package module a.b
does not.
SELECT substring(commaSeparatedTags,0,charindex(',',commaSeparatedTags))
will give you the first tag. You can proceed similarly to get the second one and so on by combining substring and charindex one layer deeper each time. That's an immediate solution but it works only with very few tags as the query grows very quickly in size and becomes unreadable. Move on to functions then, as outlined in other, more sophisticated answers to this post.
I let Eclipse do it for me when they are being used in an anonymous class, which is increasing due to my use of Google Collection API.
I had the same issue today using primefaces (primeng) and angular 7. Add the following to your style.css
p-button {
-webkit-appearance: none !important;
}
i am also using a bit of bootstrap which has a reboot.css, that overrides it with (thats why i had to add !important)
button {
-webkit-appearance: button;
}
You can't, with language primitives. As has been called out, the abc package provides this functionality in Python 2.6 and later, but there are no options for Python 2.5 and earlier. The abc
package is not a new feature of Python; instead, it adds functionality by adding explicit "does this class say it does this?" checks, with manually-implemented consistency checks to cause an error during initialization if such declarations are made falsely.
Python is a militantly dynamically-typed language. It does not specify language primitives to allow you to prevent a program from compiling because an object does not match type requirements; this can only be discovered at run time. If you require that a subclass implement a method, document that, and then just call the method in the blind hope that it will be there.
If it's there, fantastic, it simply works; this is called duck typing, and your object has quacked enough like a duck to satisfy the interface. This works just fine even if self
is the object you're calling such a method on, for the purposes of mandatory overrides due to base methods that need specific implementations of features (generic functions), because self
is a convention, not anything actually special.
The exception is in __init__
, because when your initializer is being called, the derived type's initializer hasn't, so it hasn't had the opportunity to staple its own methods onto the object yet.
If the method was't implemented, you'll get an AttributeError (if it's not there at all) or a TypeError (if something by that name is there but it's not a function or it didn't have that signature). It's up to you how you handle that- either call it programmer error and let it crash the program (and it "should" be obvious to a python developer what causes that kind of error there- an unmet duck interface), or catch and handle those exceptions when you discover that your object didn't support what you wish it did. Catching AttributeError and TypeError is important in a lot of situations, actually.
Below is example to call synchronously but you can easily change to async by using await-sync:
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>("login", "abc")
};
var content = new FormUrlEncodedContent(pairs);
var client = new HttpClient {BaseAddress = new Uri("http://localhost:6740")};
// call sync
var response = client.PostAsync("/api/membership/exist", content).Result;
if (response.IsSuccessStatusCode)
{
}
If for some reasons you don't want to override the equals
method and you want to remove duplicates based on multiple properties, then we can create a generic method to do that.
We can write it in 2 versions:
1. Modify the original list:
@SafeVarargs
public static <T> void removeDuplicatesFromList(List<T> list, Function<T, ?>... keyFunctions) {
Set<List<?>> set = new HashSet<>();
ListIterator<T> iter = list.listIterator();
while(iter.hasNext()) {
T element = iter.next();
List<?> functionResults = Arrays.stream(keyFunctions)
.map(function -> function.apply(element))
.collect(Collectors.toList());
if(!set.add(functionResults)) {
iter.remove();
}
}
}
2. Return a new list:
@SafeVarargs
public static <T> List<T> getListWithoutDuplicates(List<T> list, Function<T, ?>... keyFunctions) {
List<T> result = new ArrayList<>();
Set<List<?>> set = new HashSet<>();
for(T element : list) {
List<?> functionResults = Arrays.stream(keyFunctions)
.map(function -> function.apply(element))
.collect(Collectors.toList());
if(set.add(functionResults)) {
result.add(element);
}
}
return result;
}
In both cases we can consider any number of properties.
For example, to remove duplicates based on 4 properties title
, author
, url
and description
:
removeDuplicatesFromList(blogs, Blog::getTitle, Blog::getAuthor, Blog::getUrl, Blog::getDescription);
The methods work by leveraging the equals
method of List
, which will check the equality of its elements. In our case the elements of functionResults
are the values retrieved from the passed getters and we can use that list as an element of the Set
to check for duplicates.
Complete example:
public class Duplicates {
public static void main(String[] args) {
List<Blog> blogs = new ArrayList<>();
blogs.add(new Blog("a", "a", "a", "a"));
blogs.add(new Blog("b", "b", "b", "b"));
blogs.add(new Blog("a", "a", "a", "a")); // duplicate
blogs.add(new Blog("a", "a", "b", "b"));
blogs.add(new Blog("a", "b", "b", "b"));
blogs.add(new Blog("a", "a", "b", "b")); // duplicate
List<Blog> blogsWithoutDuplicates = getListWithoutDuplicates(blogs,
Blog::getTitle, Blog::getAuthor, Blog::getUrl, Blog::getDescription);
System.out.println(blogsWithoutDuplicates); // [a a a a, b b b b, a a b b, a b b b]
removeDuplicatesFromList(blogs,
Blog::getTitle, Blog::getAuthor, Blog::getUrl, Blog::getDescription);
System.out.println(blogs); // [a a a a, b b b b, a a b b, a b b b]
}
private static class Blog {
private String title;
private String author;
private String url;
private String description;
public Blog(String title, String author, String url, String description) {
this.title = title;
this.author = author;
this.url = url;
this.description = description;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getUrl() {
return url;
}
public String getDescription() {
return description;
}
@Override
public String toString() {
return String.join(" ", title, author, url, description);
}
}
}
val = -3.1234
fraction = abs(val - as.integer(val) )
Just my two cents:
git ls-files | grep -x relative/path
where relative/path
can be easily determined by pressing tab
within an auto-completion shell. Add an additional | wc -l
to get a 1 or 0 output.
A 32 bit floating point number has 23 + 1 bits of mantissa and an 8 bit exponent (-126 to 127 is used though) so the largest number you can represent is:
(1 + 1 / 2 + ... 1 / (2 ^ 23)) * (2 ^ 127) =
(2 ^ 23 + 2 ^ 23 + .... 1) * (2 ^ (127 - 23)) =
(2 ^ 24 - 1) * (2 ^ 104) ~= 3.4e38
You could use:
DELETE FROM tableName
where your_date_column < '2009-01-01';
but Keep in mind that the above is really
DELETE FROM tableName
where your_date_column < '2009-01-01 00:00:00';
Not
DELETE FROM tableName
where your_date_column < '2009-01-01 11:59';
Your Maven project doesn't seem to be configured as a Eclipse Java project, that is the Java nature is missing (the little 'J' in the project icon).
To enable this, the <packaging>
element in your pom.xml should be jar
(or similar).
Then, right-click the project and select Maven > Update Project Configuration
For this to work, you need to have m2eclipse installed. But since you had the _ New ... > New Maven Project_ wizard, I assume you have m2eclipse installed.
For anyone with this situation: I saw this error when I accidentally used my_first_scope::my_second_scope::true
in place of simply true
, like this:
bool my_var = my_first_scope::my_second_scope::true;
instead of:
bool my_var = true;
This is because I had a macro which caused MY_MACRO(true)
to expand into my_first_scope::my_second_scope::true
, by mistake, and I was actually calling bool my_var = MY_MACRO(true);
.
Here's a quick demo of this type of scoping error:
Program (you can run it online here: https://onlinegdb.com/BkhFBoqUw):
#include <iostream>
#include <cstdio>
namespace my_first_scope
{
namespace my_second_scope
{
} // namespace my_second_scope
} // namespace my_first_scope
int main()
{
printf("Hello World\n");
bool my_var = my_first_scope::my_second_scope::true;
std::cout << my_var << std::endl;
return 0;
}
Output (build error):
main.cpp: In function ‘int main()’: main.cpp:27:52: error: expected unqualified-id before ‘true’ bool my_var = my_first_scope::my_second_scope::true; ^~~~
Notice the error: error: expected unqualified-id before ‘true’
, and where the arrow under the error is pointing. Apparently the "unqualified-id" in my case is the double colon (::
) scope operator I have just before true
.
When I add in the macro and use it (run this new code here: https://onlinegdb.com/H1eevs58D):
#define MY_MACRO(input) my_first_scope::my_second_scope::input
...
bool my_var = MY_MACRO(true);
I get this new error instead:
main.cpp: In function ‘int main()’: main.cpp:29:28: error: expected unqualified-id before ‘true’ bool my_var = MY_MACRO(true); ^ main.cpp:16:58: note: in definition of macro ‘MY_MACRO’ #define MY_MACRO(input) my_first_scope::my_second_scope::input ^~~~~
I suggest you to edit your .vimrc file, for running a list of commands. Edit your .vimrc file, like this :
cat >> ~/.vimrc <<EOF
set ffs=unix
set encoding=utf-8
set fileencoding=utf-8
set listchars=eol:¶
set list
EOF
When you're executing vim, the commands into .vimrc are executed, and you can see this example :
My line with CRLF eol here ^M¶
((TextBox)GridView1.Rows[e.NewEditIndex].Cells[3].Controls[0]).Enabled = false;
I ran into this error while trying to get a project to run on my local dev box (OSX 10.6), using Sinatra and Postgresql (through activerecord), running on an rvm'd ruby 2.1. I found my answer here: https://github.com/wayneeseguin/rvm/issues/2511
My exact problem (after the first block of log entries):
I also get an error when trying to build native extensions for gems
The answer:
rvm reinstall 2.1.0 --disable-binary
The explanation:
OSX does not have a package manager so all libraries have to be installed manually by user, this makes it virtually impossible to link the binary dynamically, and as you can see there are problems with the (pseudo)statically linked binary.
For the sake of completeness, I had first forgotten to update rvm (rvm get head
), which yielded some other errors, but still needed the --disable-binary
flag once I had done so.
After seeing how you responded in the comments. It seems like it would be best to use push
as others have suggested. This way you don't need to know the indices, but you can still add to the array.
var arr = [];
function funcInJsFile() {
// Do Stuff
var obj = {x: 54, y: 10};
arr.push(obj);
}
In this case, every time you use that function, it will push a new object into the array.
Properties encapsulate fields, thus enabling you to perform additional processing on the value to be set or retrieved. It is typically overkill to use properties if you will not be doing any pre- or postprocessing on the field value.
I was getting the error. I simply added "proxy" in my package.json and the error went away. The error was simply there because the API request was getting made at the same port as the react app was running. You need to provide the proxy so that the API call is made to the port where your backend server is running.
@Winfield said it:
The pg gem requires the postgresql client libraries to bind against. This error usually means it can't find your Postgres libraries. Either you don't have them installed or you may need to pass the
--with-pg-dir=
to your gem install.
More than that, you only need --with-pg-config=
to install it.
If, by any chance, you also installed postgres through the website bundle on mac, it will be on somewhere like /Applications/Postgres.app/Contents/Versions/9.3/bin
.
So, either you pass it on the gem install:
gem install pg -- --with-pg-config=/Applications/Postgres.app/Contents/Versions/9.3/bin/pg_config
Or you set the PATH properly. Since that might be too much, to temporarily set the PATH:
export PATH=%PATH:/Applications/Postgres.app/Contents/Versions/9.3/bin/
In my case I was making an connection through pgAdmin with ssh tunneling and set to host field ip address but it was necessary to set localhost
I don't think you need to select anything at all. I opened two blank workbooks Book1 and Book2, put the value "A" in Range("A1") of Sheet1 in Book2, and submitted the following code in the immediate window -
Workbooks(2).Worksheets(1).Range("A1").Copy Workbooks(1).Worksheets(1).Range("A1")
The Range("A1") in Sheet1 of Book1 now contains "A".
Also, given the fact that in your code you are trying to copy from the ActiveWorkbook to "myfile.xls", the order seems to be reversed as the Copy method should be applied to a range in the ActiveWorkbook, and the destination (argument to the Copy function) should be the appropriate range in "myfile.xls".
ES6 is quite powerful in iterating through objects (strings, Array, Map, Set). Let's use a Spread Operator to solve this.
entry = prompt("Enter your name");
var count = [...entry];
console.log(count);
To mark active routes routerLinkActive
can be used
<a [routerLink]="/user" routerLinkActive="some class list">User</a>
This also works on other elements like
<div routerLinkActive="some class list">
<a [routerLink]="/user">User</a>
</div>
If partial matches should also be marked use
routerLinkActive="some class list" [routerLinkActiveOptions]="{ exact: false }"
As far as I know exact: false
is going to be the default in RC.4
Just construct a new Date
object without any arguments; this will assign the current date and time to the new object.
import java.util.Date;
Date d = new Date();
In the words of the Javadocs for the zero-argument constructor:
Allocates a Date object and initializes it so that it represents the time at which it was allocated, measured to the nearest millisecond.
Make sure you're using java.util.Date
and not java.sql.Date
-- the latter doesn't have a zero-arg constructor, and has somewhat different semantics that are the topic of an entirely different conversation. :)
I used to use an alias for that:
$ which pycclean
pycclean is aliased to `find . -name "*.pyc" | xargs -I {} rm -v "{}"'
CN refers to class name, so put in your LDAP query CN=Users. Should work.
If data frame fits in a driver memory and you want to save to local files system you can convert Spark DataFrame to local Pandas DataFrame using toPandas
method and then simply use to_csv
:
df.toPandas().to_csv('mycsv.csv')
Otherwise you can use spark-csv:
Spark 1.3
df.save('mycsv.csv', 'com.databricks.spark.csv')
Spark 1.4+
df.write.format('com.databricks.spark.csv').save('mycsv.csv')
In Spark 2.0+ you can use csv
data source directly:
df.write.csv('mycsv.csv')
I modify it in the .env APP_TIMEZONE.
For Colombia: APP_TIMEZONE = America / Bogota also for paris like this: APP_TIMEZONE = Europe / Paris
Be sure to check out verilog-mode and especially verilog-auto. http://www.veripool.org/wiki/verilog-mode/ It is a verilog mode for emacs, but plugins exist for vi(m?) for example.
An instantiation can be automated with AUTOINST. The comment is expanded with M-x verilog-auto
and can afterwards be manually edited.
subcomponent subcomponent_instance_name(/*AUTOINST*/);
Expanded
subcomponent subcomponent_instance_name (/*AUTOINST*/
//Inputs
.clk, (clk)
.rst_n, (rst_n)
.data_rx (data_rx_1[9:0]),
//Outputs
.data_tx (data_tx[9:0])
);
Implicit wires can be automated with /*AUTOWIRE*/
. Check the link for further information.
For Spring boot web apps, Spring boot provides the out-of-box solution for graceful shutdown from version 2.3.0.RELEASE
.
An excerpt from Spring doc
Refer this answer for the Code Snippet
I was able to get a great solution to this problem with iScroll, with the feel of momentum scrolling and everything https://github.com/cubiq/iscroll The github doc is great, and I mostly followed it. Here's the details of my implementation.
HTML: I wrapped the scrollable area of my content in some divs that iScroll can use:
<div id="wrapper">
<div id="scroller">
... my scrollable content
</div>
</div>
CSS: I used the Modernizr class for "touch" to target my style changes only to touch devices (because I only instantiated iScroll on touch).
.touch #wrapper {
position: absolute;
z-index: 1;
top: 0;
bottom: 0;
left: 0;
right: 0;
overflow: hidden;
}
.touch #scroller {
position: absolute;
z-index: 1;
width: 100%;
}
JS: I included iscroll-probe.js from the iScroll download, and then initialized the scroller as below, where updatePosition is my function that reacts to the new scroll position.
# coffeescript
if Modernizr.touch
myScroller = new IScroll('#wrapper', probeType: 3)
myScroller.on 'scroll', updatePosition
myScroller.on 'scrollEnd', updatePosition
You have to use myScroller to get the current position now, instead of looking at the scroll offset. Here is a function taken from http://markdalgleish.com/presentations/embracingtouch/ (a super helpful article, but a little out of date now)
function getScroll(elem, iscroll) {
var x, y;
if (Modernizr.touch && iscroll) {
x = iscroll.x * -1;
y = iscroll.y * -1;
} else {
x = elem.scrollTop;
y = elem.scrollLeft;
}
return {x: x, y: y};
}
The only other gotcha was occasionally I would lose part of my page that I was trying to scroll to, and it would refuse to scroll. I had to add in some calls to myScroller.refresh() whenever I changed the contents of the #wrapper, and that solved the problem.
EDIT: Another gotcha was that iScroll eats all the "click" events. I turned on the option to have iScroll emit a "tap" event and handled those instead of "click" events. Thankfully I didn't need much clicking in the scroll area, so this wasn't a big deal.
You can also use TempVars - note '!' syntax is essential
Click with the right mouse button on the file in your Google Drive. Choose the option to get a link which can be shared from the menu. You will see the file id now. Don't forget to undo the share.
Just need to change style as
<table style="position: relative;">
<thead>
<thead>
<tr>
<th></th>
</tr>
</thead>
</thead>
<tbody style="position: absolute;height: 300px;overflow:auto;">
<tr>
<td></td>
</tr>
</tbody>
</table>
First convert the value in a string to iterate it, Them each value can be convert to a Integer value = 12345
l = [ int(item) for item in str(value) ]
I face Same problem. In my case i solved this by following some steps.
click attached debugger to android process (It located In android tools inside run button)
if see adb not responding error dialog. then click restart of dialogue button.
Now you can see which device is connected. now close this window.
again press run button. Now you find your targeted device or emulator which is connected.
Hopefully it helps you.
There is a new player in the field, offering advanced Navigation Charts that are using Canvas for super-smooth animations and performance:
Example of charts:
Documentation: https://zoomcharts.com/en/javascript-charts-library/charts-packages/pie-chart/
What is cool about this lib:
Charts are free for non-commercial use, commercial licenses and technical support available as well.
Also interactive Time charts and Net Charts are there for you to use.
Charts come with extensive API and Settings, so you can control every aspect of the charts.
Actually this is kind of strange, with the string conversions - which the membership provider does to put them into config files. Hashes and salts are binary blobs, you don't need to convert them to strings unless you want to put them into text files.
In my book, Beginning ASP.NET Security, (oh finally, an excuse to pimp the book) I do the following
static byte[] GenerateSaltedHash(byte[] plainText, byte[] salt)
{
HashAlgorithm algorithm = new SHA256Managed();
byte[] plainTextWithSaltBytes =
new byte[plainText.Length + salt.Length];
for (int i = 0; i < plainText.Length; i++)
{
plainTextWithSaltBytes[i] = plainText[i];
}
for (int i = 0; i < salt.Length; i++)
{
plainTextWithSaltBytes[plainText.Length + i] = salt[i];
}
return algorithm.ComputeHash(plainTextWithSaltBytes);
}
The salt generation is as the example in the question. You can convert text to byte arrays using Encoding.UTF8.GetBytes(string)
. If you must convert a hash to its string representation you can use Convert.ToBase64String
and Convert.FromBase64String
to convert it back.
You should note that you cannot use the equality operator on byte arrays, it checks references and so you should simply loop through both arrays checking each byte thus
public static bool CompareByteArrays(byte[] array1, byte[] array2)
{
if (array1.Length != array2.Length)
{
return false;
}
for (int i = 0; i < array1.Length; i++)
{
if (array1[i] != array2[i])
{
return false;
}
}
return true;
}
Always use a new salt per password. Salts do not have to be kept secret and can be stored alongside the hash itself.
Try this:
<item
android:state_focused="true"
android:state_enabled="true"
android:drawable="@drawable/map_toolbar_details_selected" />
Also for colors i had success with
<selector
xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_selected="true"
android:color="@color/primary_color" />
<item
android:color="@color/secondary_color" />
</selector>
You can only use the window.close
function when you have opened the window using window.open()
, so I use the following function:
function close_window(url){
var newWindow = window.open('', '_self', ''); //open the current window
window.close(url);
}
If you don't want to use any JPA provider such as OpenJPA or Hibernate, you can just give Apache DbUtils a try.
http://commons.apache.org/proper/commons-dbutils/examples.html
Then your code will look like this:
QueryRunner run = new QueryRunner(dataSource);
// Use the BeanListHandler implementation to convert all
// ResultSet rows into a List of Person JavaBeans.
ResultSetHandler<List<Person>> h = new BeanListHandler<Person>(Person.class);
// Execute the SQL statement and return the results in a List of
// Person objects generated by the BeanListHandler.
List<Person> persons = run.query("SELECT * FROM Person", h);
Explanation: You can *ngFor on the arrays. You have your users declared as the array. But, the response from the Get returns you an object. You cannot ngFor on the object. You should have an array for that. You can explicitly cast the object to array and that will solve the issue. data to [data]
Solution
getusers() {
this.http.get(`https://api.github.com/
search/users?q=${this.input1.value}`)
.map(response => response.json())
.subscribe(
data => this.users = [data], //Cast your object to array. that will do it.
error => console.log(error)
)
Most likely you have some formatting extension installed, e.g. JS-CSS-HTML Formatter.
If it is the case, then just open Command Palette, type "Formatter" and select Formatter Config
. Then edit the value of "indent_size"
as you like.
P.S. Don't forget to restart Visual Studio Code after editing :)
A solution using recursion:
def brute(string, length, charset):
if len(string) == length:
return
for char in charset:
temp = string + char
print(temp)
brute(temp, length, charset)
Usage:
brute("", 4, "rce")
A more elegant and simple solution is to use
git stash
It will return to the most resent local version of the branch and also save your changes in stash, so if you like to undo this action do:
git stash apply
git pull is combination of a fetch followed by a merge. When git fetch happens it notes the head commit of what it fetched in FETCH_HEAD (just a file by that name in .git) And these commits are then merged into your working directory.
This is as simple I think the solution that should solve all your problems:
<input name="myvalue" id="valueText" type="text" value="ENTER VALUE">
This is your submit button:
<input type="submit" id= "submitBtn" value="Submit">
then put this small jQuery in a js file:
//this will submit only if the value is not default
$("#submitBtn").click(function () {
if ($("#valueText").val() === "ENTER VALUE")
{
alert("please insert a valid value");
return false;
}
});
//this will put default value if the field is empty
$("#valueText").blur(function () {
if(this.value == ''){
this.value = 'ENTER VALUE';
}
});
//this will empty the field is the value is the default one
$("#valueText").focus(function () {
if (this.value == 'ENTER VALUE') {
this.value = '';
}
});
And it works also in older browsers. Plus it can easily be converted to normal javascript if you need.
The best option in my opinion is to compile a custom LESS file including bootstrap.less, a custom variables.less file and your own rules :
git clone https://github.com/twbs/bootstrap.git
@icon-font-path: "../bootstrap/fonts/";
npm install
grunt watch
Now you can modify the variables any way you want, override bootstrap rules in your custom style.less file, and if some day you want to update bootstrap, you can replace the whole bootstrap folder !
EDIT: I created a Bootstrap boilerplate using this technique : https://github.com/jide/bootstrap-boilerplate
Maybe try putting it all in the end if and use a else to skip the code this will make it so that you are able not use the GoTo.
If 6 - ((Int_height(Int_Column - 1) - 1) + Int_direction(e, 1)) = 7 Or (Int_Column - 1) + Int_direction(e, 0) = -1 Or (Int_Column - 1) + Int_direction(e, 0) = 7 Then
Else
If Grid((Int_Column - 1) + Int_direction(e, 0), 6 - ((Int_height(Int_Column - 1) - 1) + Int_direction(e, 1))) = "_" Then
Console.ReadLine()
End If
End If
another way to do is get the UriInfo instead of all the QueryParam
Then you will be able to get the queryParam as per needed in your code
@GET
@Path("/query")
public Response getUsers(@Context UriInfo info) {
String param_1 = info.getQueryParameters().getFirst("param_1");
String param_2 = info.getQueryParameters().getFirst("param_2");
return Response ;
}
with Apache PDFBox it goes like this:
PDDocument document = PDDocument.load(new File("test.pdf"));
if (!document.isEncrypted()) {
PDFTextStripper stripper = new PDFTextStripper();
String text = stripper.getText(document);
System.out.println("Text:" + text);
}
document.close();
Try the rename
command in the folder with the files:
rename 's/^/Unix_/' *
The argument of rename (sed s command) indicates to replace the regex ^ with Unix_. The caret (^) is a special character that means start of the line.
The short answer is there's no great way to do this given the design you have. Here's a related question on the topic: Sum values of a single row?
If you normalized your schema and created a separate table called "Marks" which had a subject_id and a mark column this would allow you to take advantage of the SUM function as intended by a relational model.
Then your query would be
SELECT subject, SUM(mark) total
FROM Subjects s
INNER JOIN Marks m ON m.subject_id = s.id
GROUP BY s.id
Thanks for the replies.
I tried the first approach, but nothing changed. Then, I tried to log the results. I just drilled down level by level, until I finally got to where the data was being displayed.
After a while I found the problem: When I was sending the response, I was converting it to a string via .toString()
.
I fixed that and now it works brilliantly. Sorry for the false alarm.
When you run your application this way, the java excecutable read the MANIFEST inside your jar and find the main class you defined. In this class you have a static method called main. In this method you may use the command line arguments.
string time = "19851231";
DateTime theTime= DateTime.ParseExact(time,
"yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None);
I could not made your code to do the desired query, the AS is an alias only for the table abc
, not for the derived table.
Laravel Query Builder does not implicitly support derived table aliases, DB::raw is most likely needed for this.
The most straight solution I could came up with is almost identical to yours, however produces the query as you asked for:
$sql = Abc::groupBy('col1')->toSql();
$count = DB::table(DB::raw("($sql) AS a"))->count();
The produced query is
select count(*) as aggregate from (select * from `abc` group by `col1`) AS a;
To install a specific package:
conda install <pkg>=<version>
eg:
conda install matplotlib=1.4.3
I've always had a habit of just using std::endl because it is easy for me to see.
Yet another gotcha:
The framework code that calls the Drag-events swallow all exceptions. You might think your event code is running smoothly, while it is gushing exceptions all over the place. You can't see them because the framework steals them.
That's why I always put a try/catch in these event handlers, just so I know if they throw any exceptions. I usually put a Debugger.Break(); in the catch part.
Before release, after testing, if everything seems to behave, I remove or replace these with real exception handling.
you can use css to set the body tag to these settings:
body
{
padding:0px;
margin:0px;
width:100%;
height:100%;
}
I faced the same problem, went through all the suggestions above, but nothing worked. Finally I deleted both .m2 and .ivy folder and it worked for me.
I was hitting this error with phpMailer + Amazon SES. The phpMailer error is not very descriptive:
2: message: SERVER -> CLIENT: 554 Transaction failed: Expected ';', got "\"
1: message:
2: message: SMTP Error: data not accepted.
For me the issue was simply that I had the following as content type:
$phpmailer->ContentType = 'text/html; charset=utf-8\r\n';
But that it shouldn't have the linebreak in it:
$phpmailer->ContentType = 'text/html; charset=utf-8';
... I suspect this was legacy code from our older version. So basically, triple check every $phpmailer setting you're adding - the smallest detail counts.
this is the full source code to direct use,
public class CardDBDAO {
protected SQLiteDatabase database;
private DataBaseHelper dbHelper;
private Context mContext;
public CardDBDAO(Context context) {
this.mContext = context;
dbHelper = DataBaseHelper.getHelper(mContext);
open();
}
public void open() throws SQLException {
if(dbHelper == null)
dbHelper = DataBaseHelper.getHelper(mContext);
database = dbHelper.getWritableDatabase();
}
}
public class DataBaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "mydbnamedb";
private static final int DATABASE_VERSION = 1;
public static final String CARDS_TABLE = "tbl_cards";
public static final String POICATEGORIES_TABLE = "tbl_poicategories";
public static final String POILANGS_TABLE = "tbl_poilangs";
public static final String ID_COLUMN = "id";
public static final String POI_ID = "poi_id";
public static final String POICATEGORIES_COLUMN = "poi_categories";
public static final String POILANGS_COLUMN = "poi_langs";
public static final String CARDS = "cards";
public static final String CARD_ID = "card_id";
public static final String CARDS_PCAT_ID = "pcat_id";
public static final String CREATE_PLANG_TABLE = "CREATE TABLE "
+ POILANGS_TABLE + "(" + ID_COLUMN + " INTEGER PRIMARY KEY,"
+ POILANGS_COLUMN + " TEXT, " + POI_ID + " TEXT)";
public static final String CREATE_PCAT_TABLE = "CREATE TABLE "
+ POICATEGORIES_TABLE + "(" + ID_COLUMN + " INTEGER PRIMARY KEY,"
+ POICATEGORIES_COLUMN + " TEXT, " + POI_ID + " TEXT)";
public static final String CREATE_CARDS_TABLE = "CREATE TABLE "
+ CARDS_TABLE + "(" + ID_COLUMN + " INTEGER PRIMARY KEY," + CARD_ID
+ " TEXT, " + CARDS_PCAT_ID + " TEXT, " + CARDS + " TEXT)";
private static DataBaseHelper instance;
public static synchronized DataBaseHelper getHelper(Context context) {
if (instance == null)
instance = new DataBaseHelper(context);
return instance;
}
private DataBaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onOpen(SQLiteDatabase db) {
super.onOpen(db);
if (!db.isReadOnly()) {
// Enable foreign key constraints
// db.execSQL("PRAGMA foreign_keys=ON;");
}
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(CREATE_PCAT_TABLE);
db.execSQL(CREATE_PLANG_TABLE);
db.execSQL(CREATE_CARDS_TABLE);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}
public class PoiLangDAO extends CardDBDAO {
private static final String WHERE_ID_EQUALS = DataBaseHelper.ID_COLUMN
+ " =?";
public PoiLangDAO(Context context) {
super(context);
}
public long save(PLang plang_data) {
ContentValues values = new ContentValues();
values.put(DataBaseHelper.POI_ID, plang_data.getPoi_id());
values.put(DataBaseHelper.POILANGS_COLUMN, plang_data.getLangarr());
return database
.insert(DataBaseHelper.POILANGS_TABLE, null, values);
}
public long update(PLang plang_data) {
ContentValues values = new ContentValues();
values.put(DataBaseHelper.POI_ID, plang_data.getPoi_id());
values.put(DataBaseHelper.POILANGS_COLUMN, plang_data.getLangarr());
long result = database.update(DataBaseHelper.POILANGS_TABLE,
values, WHERE_ID_EQUALS,
new String[] { String.valueOf(plang_data.getId()) });
Log.d("Update Result:", "=" + result);
return result;
}
public int deleteDept(PLang plang_data) {
return database.delete(DataBaseHelper.POILANGS_TABLE,
WHERE_ID_EQUALS, new String[] { plang_data.getId() + "" });
}
public List<PLang> getPLangs1() {
List<PLang> plang_list = new ArrayList<PLang>();
Cursor cursor = database.query(DataBaseHelper.POILANGS_TABLE,
new String[] { DataBaseHelper.ID_COLUMN, DataBaseHelper.POI_ID,
DataBaseHelper.POILANGS_COLUMN }, null, null, null,
null, null);
while (cursor.moveToNext()) {
PLang plang_bin = new PLang();
plang_bin.setId(cursor.getInt(0));
plang_bin.setPoi_id(cursor.getString(1));
plang_bin.setLangarr(cursor.getString(2));
plang_list.add(plang_bin);
}
return plang_list;
}
public List<PLang> getPLangs(String pid) {
List<PLang> plang_list = new ArrayList<PLang>();
String selection = DataBaseHelper.POI_ID + "=?";
String[] selectionArgs = { pid };
Cursor cursor = database.query(DataBaseHelper.POILANGS_TABLE,
new String[] { DataBaseHelper.ID_COLUMN, DataBaseHelper.POI_ID,
DataBaseHelper.POILANGS_COLUMN }, selection,
selectionArgs, null, null, null);
while (cursor.moveToNext()) {
PLang plang_bin = new PLang();
plang_bin.setId(cursor.getInt(0));
plang_bin.setPoi_id(cursor.getString(1));
plang_bin.setLangarr(cursor.getString(2));
plang_list.add(plang_bin);
}
return plang_list;
}
public void loadPLangs(String poi_id, String langarrs) {
PLang plangbin = new PLang(poi_id, langarrs);
List<PLang> plang_arr = new ArrayList<PLang>();
plang_arr.add(plangbin);
for (PLang dept : plang_arr) {
ContentValues values = new ContentValues();
values.put(DataBaseHelper.POI_ID, dept.getPoi_id());
values.put(DataBaseHelper.POILANGS_COLUMN, dept.getLangarr());
database.insert(DataBaseHelper.POILANGS_TABLE, null, values);
}
}
}
public class PLang {
public PLang() {
super();
}
public PLang(String poi_id, String langarrs) {
// TODO Auto-generated constructor stub
this.poi_id = poi_id;
this.langarr = langarrs;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPoi_id() {
return poi_id;
}
public void setPoi_id(String poi_id) {
this.poi_id = poi_id;
}
public String getLangarr() {
return langarr;
}
public void setLangarr(String langarr) {
this.langarr = langarr;
}
private int id;
private String poi_id;
private String langarr;
}
In JavaScript you can use template literals:
let value = 100;
console.log(`The size is ${ value }`);
Send the data from the form:
$("#change_section_type").live "change", ->
url = $(this).attr("data-url")
postData = $(this).parents("#contract_setting_form").serializeArray()
$.ajax
type: "PUT"
url: url
dataType: "script"
data: postData
run > services.msc > rightclick MySQL57 > properties >set start type option to automatic
after restarting computer
At cmd
cd: C:\
C :\> cd "C:\Program Files\MySQL\MySQL Server 5.7\bin"
it will become
C:\Program Files\MySQL\MySQL Server 5.7\bin>
type mysql -u root -p
ie C:\Program Files\MySQL\MySQL Server 5.7\bin> mysql -u root -p
Enter password: ****
That's all
It will result in
mysql>
You can use the folowing to get the full path to your program like this:
Environment.CurrentDirectory
If
(1) you have a _Layout.cshtml view like this
<html>
<body>
@RenderBody()
</body>
<script type="text/javascript" src="~/lib/layout.js"></script>
@RenderSection("scripts", required: false)
</html>
(2) you have Contacts.cshtml
@section Scripts{
<script type="text/javascript" src="~/lib/contacts.js"></script>
}
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h2> Contacts</h2>
</div>
</div>
(3) you have About.cshtml
<div class="row">
<div class="col-md-6 col-md-offset-3">
<h2> Contacts</h2>
</div>
</div>
On you layout page, if required is set to false "@RenderSection("scripts", required: false)", When page renders and user is on about page, the contacts.js doesn't render.
<html>
<body><div>About<div>
</body>
<script type="text/javascript" src="~/lib/layout.js"></script>
</html>
if required is set to true "@RenderSection("scripts", required: true)", When page renders and user is on ABOUT page, the contacts.js STILL gets rendered.
<html>
<body><div>About<div>
</body>
<script type="text/javascript" src="~/lib/layout.js"></script>
<script type="text/javascript" src="~/lib/contacts.js"></script>
</html>
IN SHORT, when set to true, whether you need it or not on other pages, it will get rendered anyhow. If set to false, it will render only when the child page is rendered.
As of now, you can only store string values in localStorage. You'll need to serialize the array object and then store it in localStorage.
For example:
localStorage.setItem('session', a.join('|'));
or
localStorage.setItem('session', JSON.stringify(a));
jQuery is a multi-browser (cf. cross-browser) JavaScript library designed to simplify the client-side scripting of HTML. see http://en.wikipedia.org/wiki/JQuery
There is an open bug on Chromium: https://bugs.chromium.org/p/chromium/issues/detail?id=584905
Unfortunately they depend on Apple to open up an API in WKView for this to happen, after which maybe debugging will be available from Safari.
This is the old-school way of doing it.
It will execute faster than looping through cells (e.g. For Each cell In Selection
) and will be reliable no matter what, as long you have a rectangular selection (i.e. not Ctrl-selecting a bunch of random cells).
Sub FindUnique()
Dim varIn As Variant
Dim varUnique As Variant
Dim iInCol As Long
Dim iInRow As Long
Dim iUnique As Long
Dim nUnique As Long
Dim isUnique As Boolean
varIn = Selection
ReDim varUnique(1 To UBound(varIn, 1) * UBound(varIn, 2))
nUnique = 0
For iInRow = LBound(varIn, 1) To UBound(varIn, 1)
For iInCol = LBound(varIn, 2) To UBound(varIn, 2)
isUnique = True
For iUnique = 1 To nUnique
If varIn(iInRow, iInCol) = varUnique(iUnique) Then
isUnique = False
Exit For
End If
Next iUnique
If isUnique = True Then
nUnique = nUnique + 1
varUnique(nUnique) = varIn(iInRow, iInCol)
End If
Next iInCol
Next iInRow
'// varUnique now contains only the unique values.
'// Trim off the empty elements:
ReDim Preserve varUnique(1 To nUnique)
End Sub
I agree with @GregoryKlopper that the right way to solve the general problem of finding Waldo (or any object of interest) in an arbitrary image would be to train a supervised machine learning classifier. Using many positive and negative labeled examples, an algorithm such as Support Vector Machine, Boosted Decision Stump or Boltzmann Machine could likely be trained to achieve high accuracy on this problem. Mathematica even includes these algorithms in its Machine Learning Framework.
The two challenges with training a Waldo classifier would be:
A quick Google image search turns up some good data -- I'm going to have a go at collecting some training examples and coding this up right now!
However, even a machine learning approach (or the rule-based approach suggested by @iND) will struggle for an image like the Land of Waldos!
You can try updating as below:
Syntax: UPDATE table_name SET column_name = column_name::jsonb || '{"key":new_value}' WHERE column_name condition;
For your example:
UPDATE test SET data = data::jsonb || '{"a":new_value}' WHERE data->>'b' = '2';
all your code is okay only the things left is just go to the link https://myaccount.google.com/security
and keep scroll down and you will found Allow less secure apps: ON and keep ON, you will find no error.
I had to add a Handler to delay the exit:
mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 200, mPendingIntent);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
Runtime.getRuntime().exit(0);
}
}, 100);
ALTER IGNORE TABLE mytbl ADD UNIQUE (columnName);
is the right answer
the insert part
INSERT IGNORE INTO mytable ....
Why don't you create service and put logic in onCreate()
. In this case even if you press back button service will keep on executing. and once you enter into application it will not call
onCreate()
again. Rather it will call onStart()
I have tested @Jeff's solution on version 4.2, 4.4, 6.0. On 4.2 and 6.0, it works well. But on 4.4, it doesn't work.
I found an easy way to work around this problem. The key point is to insert an invisible character into the content of EditText at the begining, and don't let user move cursor before this character. My way is to insert a white-space character with an ImageSpan of Zero Width on it. Here is my code.
@Override
public void afterTextChanged(Editable s) {
String ss = s.toString();
if (!ss.startsWith(" ")) {
int selection = holder.editText.getSelectionEnd();
s.insert(0, " ");
ss = s.toString();
holder.editText.setSelection(selection + 1);
}
if (ss.startsWith(" ")) {
ImageSpan[] spans = s.getSpans(0, 1, ImageSpan.class);
if (spans == null || spans.length == 0) {
s.setSpan(new ImageSpan(getResources().getDrawable(R.drawable.zero_wdith_drawable)), 0 , 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}
And we need custom an EditText which has a SelectionChangeListener
public class EditTextSelectable extends android.support.v7.widget.AppCompatEditText {
public interface OnSelectChangeListener {
void onSelectChange(int start, int end);
}
private OnSelectChangeListener mListener;
public void setListener(OnSelectChangeListener listener) {
mListener = listener;
}
...constructors...
@Override
protected void onSelectionChanged(int selStart, int selEnd) {
if (mListener != null) {
mListener.onSelectChange(selStart, selEnd);
}
super.onSelectionChanged(selStart, selEnd);
}
}
And the last step
holder.editText.setListener(new EditTextSelectable.OnSelectChangeListener() {
@Override
public void onSelectChange(int start, int end) {
if (start == 0 && holder.editText.getText().length() != 0) {
holder.editText.setSelection(1, Math.max(1, end));
}
}
});
And now, we are done~ We can detect backspace key event when EditText has no actual content, and user will know nothing about our trick.
Building Matplotlib requires libpng
(and freetype
, as well) which isn't a python library, so pip
doesn't handle installing it (or freetype
).
You'll need to install something along the lines of libpng-devel
and freetype-devel
(or whatever the equivalent is for your OS).
See the building requirements/instructions for matplotlib.
If you are struggling with the connection in the XAMPP environment I suggest uncommenting the following entry in the php.ini
file.
extension = odbc
I received an error without it: Uncaught pdoexception: could not find driver
broadcast implementation on Kotlin:
private class SmsListener : BroadcastReceiver() {
override fun onReceive(context: Context?, intent: Intent?) {
Log.d(TAG, "SMS Received!")
val txt = getTextFromSms(intent?.extras)
Log.d(TAG, "message=" + txt)
}
private fun getTextFromSms(extras: Bundle?): String {
val pdus = extras?.get("pdus") as Array<*>
val format = extras.getString("format")
var txt = ""
for (pdu in pdus) {
val smsmsg = getSmsMsg(pdu as ByteArray?, format)
val submsg = smsmsg?.displayMessageBody
submsg?.let { txt = "$txt$it" }
}
return txt
}
private fun getSmsMsg(pdu: ByteArray?, format: String?): SmsMessage? {
return when {
SDK_INT >= Build.VERSION_CODES.M -> SmsMessage.createFromPdu(pdu, format)
else -> SmsMessage.createFromPdu(pdu)
}
}
companion object {
private val TAG = SmsListener::class.java.simpleName
}
}
Note: In your manifest file add the BroadcastReceiver-
<receiver android:name=".listener.SmsListener">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
</intent-filter>
</receiver>
Add this permission:
<uses-permission android:name="android.permission.RECEIVE_SMS" />
From the source code:
// Instance of WebViewClient that is the client callback.
private volatile WebViewClient mWebViewClient;
// Instance of WebChromeClient for handling all chrome functions.
private volatile WebChromeClient mWebChromeClient;
// SOME OTHER SUTFFF.......
/**
* Set the WebViewClient.
* @param client An implementation of WebViewClient.
*/
public void setWebViewClient(WebViewClient client) {
mWebViewClient = client;
}
/**
* Set the WebChromeClient.
* @param client An implementation of WebChromeClient.
*/
public void setWebChromeClient(WebChromeClient client) {
mWebChromeClient = client;
}
Using WebChromeClient allows you to handle Javascript dialogs, favicons, titles, and the progress. Take a look of this example: Adding alert() support to a WebView
At first glance, there are too many differences WebViewClient & WebChromeClient. But, basically: if you are developing a WebView that won't require too many features but rendering HTML, you can just use a WebViewClient
. On the other hand, if you want to (for instance) load the favicon of the page you are rendering, you should use a WebChromeClient
object and override the onReceivedIcon(WebView view, Bitmap icon)
.
Most of the times, if you don't want to worry about those things... you can just do this:
webView= (WebView) findViewById(R.id.webview);
webView.setWebChromeClient(new WebChromeClient());
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
And your WebView will (in theory) have all features implemented (as the android native browser).
Replace with:
$('#something').click(function() {
location.reload();
});
Here's a complete Java 7 program:
class GETHTTPResource {
public static void main(String[] args) throws Exception {
try (java.util.Scanner s = new java.util.Scanner(new java.net.URL("http://tools.ietf.org/rfc/rfc768.txt").openStream())) {
System.out.println(s.useDelimiter("\\A").next());
}
}
}
The new try-with-resources will auto-close the Scanner, which will auto-close the InputStream.
Okay, I just found the answer (on Stackoverflow, no less).
Eclipse has an option so that copy-paste of multi-line text into String literals will result in quoted newlines:
Preferences/Java/Editor/Typing/ "Escape text when pasting into a string literal"
$.post('mail.php',{name:$('#name').val(),
email:$('#e-mail').val(),
phone:$('#phone').val(),
message:$('#message').val()},
//return the data
function(data){
if(data==<when do you want to clear the form>){
$('#<form Id>').find(':input').each(function() {
switch(this.type) {
case 'password':
case 'select-multiple':
case 'select-one':
case 'text':
case 'textarea':
$(this).val('');
break;
case 'checkbox':
case 'radio':
this.checked = false;
}
});
}
});
There's no need to downgrade Android Tools. On Windows, Gradle moved from:
C:\Users\you_username\AppData\Local\Android\sdk\tools
to:
C:\Program Files\Android\Android Studio\plugins\android\lib\templates\gradle\wrapper
So you just need to adjust your path so that it points to the right folder.
Use find. Seriously, it is the best way because then you can really see what files it's operating on:
find . -name "*.sql" -exec grep -H "slow" {} \;
Note, the -H is mac-specific, it shows the filename in the results.
I assume you're asking about combinations in combinatorial sense (that is, order of elements doesn't matter, so [1 2 3]
is the same as [2 1 3]
). The idea is pretty simple then, if you understand induction / recursion: to get all K
-element combinations, you first pick initial element of a combination out of existing set of people, and then you "concatenate" this initial element with all possible combinations of K-1
people produced from elements that succeed the initial element.
As an example, let's say we want to take all combinations of 3 people from a set of 5 people. Then all possible combinations of 3 people can be expressed in terms of all possible combinations of 2 people:
comb({ 1 2 3 4 5 }, 3) =
{ 1, comb({ 2 3 4 5 }, 2) } and
{ 2, comb({ 3 4 5 }, 2) } and
{ 3, comb({ 4 5 }, 2) }
Here's C++ code that implements this idea:
#include <iostream>
#include <vector>
using namespace std;
vector<int> people;
vector<int> combination;
void pretty_print(const vector<int>& v) {
static int count = 0;
cout << "combination no " << (++count) << ": [ ";
for (int i = 0; i < v.size(); ++i) { cout << v[i] << " "; }
cout << "] " << endl;
}
void go(int offset, int k) {
if (k == 0) {
pretty_print(combination);
return;
}
for (int i = offset; i <= people.size() - k; ++i) {
combination.push_back(people[i]);
go(i+1, k-1);
combination.pop_back();
}
}
int main() {
int n = 5, k = 3;
for (int i = 0; i < n; ++i) { people.push_back(i+1); }
go(0, k);
return 0;
}
And here's output for N = 5, K = 3
:
combination no 1: [ 1 2 3 ]
combination no 2: [ 1 2 4 ]
combination no 3: [ 1 2 5 ]
combination no 4: [ 1 3 4 ]
combination no 5: [ 1 3 5 ]
combination no 6: [ 1 4 5 ]
combination no 7: [ 2 3 4 ]
combination no 8: [ 2 3 5 ]
combination no 9: [ 2 4 5 ]
combination no 10: [ 3 4 5 ]
You'd probably need clarification on what O(k) means.
Here's a trivial solution for arbitrary k: for each v in your set of numbers, accumulate the sum of 2^v. At the end, loop i from 1 to N. If sum bitwise ANDed with 2^i is zero, then i is missing. (Or numerically, if floor of the sum divided by 2^i is even. Or sum modulo 2^(i+1)) < 2^i
.)
Easy, right? O(N) time, O(1) storage, and it supports arbitrary k.
Except that you're computing enormous numbers that on a real computer would each require O(N) space. In fact, this solution is identical to a bit vector.
So you could be clever and compute the sum and the sum of squares and the sum of cubes... up to the sum of v^k, and do the fancy math to extract the result. But those are big numbers too, which begs the question: what abstract model of operation are we talking about? How much fits in O(1) space, and how long does it take to sum up numbers of whatever size you need?
you can use linkbutton for navigating to another section in the same page by using PostBackUrl="#Section2"
This works, but there might be better solutions.
asking="hello! what's your name?"
asking = ''.join([c for c in asking if c not in ('!', '?')])
print asking
First I tried this code
const peopleSchema = new mongoose.Schema({
name: String,
friends: [
{
firstName: String,
lastName: String,
},
],
});
const People = mongoose.model("person", peopleSchema);
const first = new Note({
name: "Yash Salvi",
notes: [
{
firstName: "Johnny",
lastName: "Johnson",
},
],
});
first.save();
const friendNew = {
firstName: "Alice",
lastName: "Parker",
};
People.findOneAndUpdate(
{ name: "Yash Salvi" },
{ $push: { friends: friendNew } },
function (error, success) {
if (error) {
console.log(error);
} else {
console.log(success);
}
}
);
But I noticed that only first friend (i.e. Johhny Johnson) gets saved and the objective to push array element in existing array of "friends" doesn't seem to work as when I run the code , in database in only shows "First friend" and "friends" array has only one element ! So the simple solution is written below
const peopleSchema = new mongoose.Schema({
name: String,
friends: [
{
firstName: String,
lastName: String,
},
],
});
const People = mongoose.model("person", peopleSchema);
const first = new Note({
name: "Yash Salvi",
notes: [
{
firstName: "Johnny",
lastName: "Johnson",
},
],
});
first.save();
const friendNew = {
firstName: "Alice",
lastName: "Parker",
};
People.findOneAndUpdate(
{ name: "Yash Salvi" },
{ $push: { friends: friendNew } },
{ upsert: true }
);
Adding "{ upsert: true }" solved problem in my case and once code is saved and I run it , I see that "friends" array now has 2 elements ! The upsert = true option creates the object if it doesn't exist. default is set to false.
if it doesn't work use below snippet
People.findOneAndUpdate(
{ name: "Yash Salvi" },
{ $push: { friends: friendNew } },
).exec();
The a == b
expression invokes A.__eq__
, since it exists. Its code includes self.value == other
. Since int's don't know how to compare themselves to B's, Python tries invoking B.__eq__
to see if it knows how to compare itself to an int.
If you amend your code to show what values are being compared:
class A(object):
def __eq__(self, other):
print("A __eq__ called: %r == %r ?" % (self, other))
return self.value == other
class B(object):
def __eq__(self, other):
print("B __eq__ called: %r == %r ?" % (self, other))
return self.value == other
a = A()
a.value = 3
b = B()
b.value = 4
a == b
it will print:
A __eq__ called: <__main__.A object at 0x013BA070> == <__main__.B object at 0x013BA090> ?
B __eq__ called: <__main__.B object at 0x013BA090> == 3 ?
If you are coming from java background the concept of class in scala is kind of similar to Java, but class in scala cant contain static members.
Objects in scala are singleton type you call methods inside it using object name, in scala object is a keyword and in java object is a instance of class
Maybe you can try something like this:
Using a directive
directive('watchChange', function() {
return {
scope: {
onchange: '&watchChange'
},
link: function(scope, element, attrs) {
element.on('input', function() {
scope.onchange();
});
}
};
});
Roy Fielding's comment about including a body with a GET request.
Yes. In other words, any HTTP request message is allowed to contain a message body, and thus must parse messages with that in mind. Server semantics for GET, however, are restricted such that a body, if any, has no semantic meaning to the request. The requirements on parsing are separate from the requirements on method semantics.
So, yes, you can send a body with GET, and no, it is never useful to do so.
This is part of the layered design of HTTP/1.1 that will become clear again once the spec is partitioned (work in progress).
....Roy
Yes, you can send a request body with GET but it should not have any meaning. If you give it meaning by parsing it on the server and changing your response based on its contents, then you are ignoring this recommendation in the HTTP/1.1 spec, section 4.3:
...if the request method does not include defined semantics for an entity-body, then the message-body SHOULD be ignored when handling the request.
And the description of the GET method in the HTTP/1.1 spec, section 9.3:
The GET method means retrieve whatever information ([...]) is identified by the Request-URI.
which states that the request-body is not part of the identification of the resource in a GET request, only the request URI.
Update
The RFC2616 referenced as "HTTP/1.1 spec" is now obsolete. In 2014 it was replaced by RFCs 7230-7237. Quote "the message-body SHOULD be ignored when handling the request" has been deleted. It's now just "Request message framing is independent of method semantics, even if the method doesn't define any use for a message body" The 2nd quote "The GET method means retrieve whatever information ... is identified by the Request-URI" was deleted. - From a comment
From the HTTP 1.1 2014 Spec:
A payload within a GET request message has no defined semantics; sending a payload body on a GET request might cause some existing implementations to reject the request.
Yes. Try:
class USBDevice : GenericDevice, IOurDevice
Note: The base class should come before the list of interface names.
Of course, you'll still need to implement all the members that the interfaces define. However, if the base class contains a member that matches an interface member, the base class member can work as the implementation of the interface member and you are not required to manually implement it again.
The Answer by Bhesh Gurung is correct… unless your NetBeans project is Maven based.
Under Maven, you add a "dependency". A dependency is a description of a library (its name & version number) you want to use from your code.
Or a dependency could be a description of a library which another library needs ("depends on"). Maven automatically handles this chain, libraries that need other libraries that then need other libraries and so on. For the mathematical-minded, perhaps the phrase "Maven resolves the transitive dependencies" makes sense.
Maven gets this related-ness information, and the libraries themselves from a Maven repository. A repository is basically an online database and collection of download files (the dependency library).
Adding a dependency to a Maven-based project is really quite easy. That is the whole point to Maven, to make managing dependent libraries easy and to make building them into your project easy. To get started with adding a dependency, see this Question, Adding dependencies in Maven Netbeans and my Answer with screenshot.
ALTER TABLE public.contract_termination_requests
ALTER COLUMN management_company_id DROP NOT NULL;
As the previous answers exhaustively covered the theory behind the value categories, there is just another thing I'd like to add: you can actually play with it and test it.
For some hands-on experimentation with the value categories, you can make use of the decltype specifier. Its behavior explicitly distinguishes between the three primary value categories (xvalue, lvalue, and prvalue).
Using the preprocessor saves us some typing ...
Primary categories:
#define IS_XVALUE(X) std::is_rvalue_reference<decltype((X))>::value
#define IS_LVALUE(X) std::is_lvalue_reference<decltype((X))>::value
#define IS_PRVALUE(X) !std::is_reference<decltype((X))>::value
Mixed categories:
#define IS_GLVALUE(X) (IS_LVALUE(X) || IS_XVALUE(X))
#define IS_RVALUE(X) (IS_PRVALUE(X) || IS_XVALUE(X))
Now we can reproduce (almost) all the examples from cppreference on value category.
Here are some examples with C++17 (for terse static_assert):
void doesNothing(){}
struct S
{
int x{0};
};
int x = 1;
int y = 2;
S s;
static_assert(IS_LVALUE(x));
static_assert(IS_LVALUE(x+=y));
static_assert(IS_LVALUE("Hello world!"));
static_assert(IS_LVALUE(++x));
static_assert(IS_PRVALUE(1));
static_assert(IS_PRVALUE(x++));
static_assert(IS_PRVALUE(static_cast<double>(x)));
static_assert(IS_PRVALUE(std::string{}));
static_assert(IS_PRVALUE(throw std::exception()));
static_assert(IS_PRVALUE(doesNothing()));
static_assert(IS_XVALUE(std::move(s)));
// The next one doesn't work in gcc 8.2 but in gcc 9.1. Clang 7.0.0 and msvc 19.16 are doing fine.
static_assert(IS_XVALUE(S().x));
The mixed categories are kind of boring once you figured out the primary category.
For some more examples (and experimentation), check out the following link on compiler explorer. Don't bother reading the assembly, though. I added a lot of compilers just to make sure it works across all the common compilers.
Here is my solution I've used in applications.
I disabled the body overflow and placed the entire website html inside container div's. The website containers have overflow and therefore the user may scroll the page as expected.
I then created a sibling div (#Prevent) with a higher z-index that covers the entire website. Since #Prevent has a higher z-index, it overlaps the website container. When #Prevent is visible the mouse is no longer hovering the website containers, so scrolling isn't possible.
You may of course place another div, such as your modal, with a higher z-index than #Prevent in the markup. This allows you to create pop-up windows that don't suffer from scrolling issues.
This solution is better because it doesn't hide the scrollbars (jumping affect). It doesn't require event listeners and it's easy to implement. It works in all browsers, although with IE7 & 8 you have to play around (depends on your specific code).
html
<body>
<div id="YourModal" style="display:none;"></div>
<div id="Prevent" style="display:none;"></div>
<div id="WebsiteContainer">
<div id="Website">
website goes here...
</div>
</div>
</body>
css
body { overflow: hidden; }
#YourModal {
z-index:200;
/* modal styles here */
}
#Prevent {
z-index:100;
position:absolute;
left:0px;
height:100%;
width:100%;
background:transparent;
}
#WebsiteContainer {
z-index:50;
overflow:auto;
position: absolute;
height:100%;
width:100%;
}
#Website {
position:relative;
}
jquery/js
function PreventScroll(A) {
switch (A) {
case 'on': $('#Prevent').show(); break;
case 'off': $('#Prevent').hide(); break;
}
}
disable/enable the scroll
PreventScroll('on'); // prevent scrolling
PreventScroll('off'); // allow scrolling
This worked for me:
yourViewController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
Most of the other answers are simply concatenating their HTML body with the HTML signature. However, this does not work with images, and it turns out there is a more "standard" way of doing this.1
Microsoft Outlook pre-2007 which is configured with WordEditor as its editor, and Microsoft Outlook 2007 and beyond, use a slightly cut-down version of the Word Editor to edit emails. This means we can use the Microsoft Word Document Object Model to make changes to the email.
Set objMsg = Application.CreateItem(olMailItem)
objMsg.GetInspector.Display 'Displaying an empty email will populate the default signature
Set objSigDoc = objMsg.GetInspector.WordEditor
Set objSel = objSigDoc.Windows(1).Selection
With objSel
.Collapse wdCollapseStart
.MoveEnd WdUnits.wdStory, 1
.Copy 'This will copy the signature
End With
objMsg.HTMLBody = "<p>OUR HTML STUFF HERE</p>"
With objSel
.Move WdUnits.wdStory, 1 'Move to the end of our new message
.PasteAndFormat wdFormatOriginalFormatting 'Paste the copied signature
End With
'I am not a VB programmer, wrote this originally in another language so if it does not
'compile it is because this is my first VB method :P
Keep your entitlements file in Target> Build Settings > Code Signing > Code Signing Entitlements.
Go to Target > Capabilities. Toggle On/Off or Off/On one of the capabilities.
Run.
This happens when you do not include a message when you try to commit using:
git commit
It launches an editor environment. Quit it by typing :q!
and hitting enter.
It's going to take you back to the terminal without committing, so make sure to try again, this time pass in a message:
git commit -m 'Initial commit'
Using the LOAD DATA INFILE
SQL statement you can import the CSV file, but you can't update data. However, there is a trick you can use.
Load onto this table from the CSC
LOAD DATA LOCAL INFILE '/file.csv'
INTO TABLE temp_table
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(field1, field2, field3);
UPDATE the real table joining the table
UPDATE maintable
INNER JOIN temp_table A USING (field1)
SET maintable.field1 = temp_table.field1
Just open Putty and try to establish connection to remote server you want to push your code. when the dialog appears press Yes(you trust remote) then everything would be OK.
As described in Cloaking your ASP.NET MVC Web Application on IIS 7, you can turn off the X-AspNet-Version header by applying the following configuration section to your web.config:
<system.web>
<httpRuntime enableVersionHeader="false"/>
</system.web>
and remove the X-AspNetMvc-Version header by altering your Global.asax.cs as follows:
protected void Application_Start()
{
MvcHandler.DisableMvcResponseHeader = true;
}
As described in Custom Headers You can remove the "X-Powered-By" header by applying the following configuration section to your web.config:
<system.webServer>
<httpProtocol>
<customHeaders>
<clear />
</customHeaders>
</httpProtocol>
</system.webServer>
There is no easy way to remove the "Server" response header via configuration, but you can implement an HttpModule
to remove specific HTTP Headers as described in Cloaking your ASP.NET MVC Web Application on IIS 7 and in how-to-remove-server-x-aspnet-version-x-aspnetmvc-version-and-x-powered-by-from-the-response-header-in-iis7.
Gitlab uses GitLab Flavored Markdown (GFM)
Here "all Markdown-rendered headers automatically get IDs"
One can use mouse to :
copy and save link using right mouse click
For example in README.md file I have header:
## series expansion formula of the Boettcher function
which gives a link :
Prefix can be removed so the link here is simply
file#header
which here means:
README.md#series-expansion-formula-of-the-boettcher-function
Now it can be used as :
[series expansion formula of the Boettcher function](README.md#series-expansion-formula-of-the-boettcher-function)
One can also do it manually: replace spaces with hyphen sign.
Live example is here
Version without subselect:
SELECT f.title,
f.content,
MIN(a.artist_name) artist_name
FROM feeds f
LEFT JOIN feeds_artists fa ON fa.feed_id = f.id
LEFT JOIN artists a ON fa.artist_id = a.artist_id
GROUP BY f.id
Assuming type TreeMap<String,Integer> :
for(Map.Entry<String,Integer> entry : treeMap.entrySet()) {
String key = entry.getKey();
Integer value = entry.getValue();
System.out.println(key + " => " + value);
}
(key and Value types can be any class of course)
Add the following CSS class to your stylesheet:
.my-spacer {
flex: 1 1 auto;
}
Place an empty element between the element on the left and the element you wish to right-align:
<span class="my-spacer"></span>
Check that right version is referenced in your project. E.g. the dll it is complaining about, could be from an older version and that's why there could be a version mismatch.
One is a function that prints to stdout. The other is an object that provides several member functions and overloads of operator<<
that print to stdout. There are many more differences that I could enumerate, but I'm not sure what you are after.
In spring boot 2.x you need to reference provider specific properties.
The default, hikari can be set with spring.datasource.hikari.maximum-pool-size
.
The
compile 'com.google.zxing:core:2.3.0'
unfortunately didn't work for me.
This is what worked for me:
dependencies {
compile 'com.journeyapps:zxing-android-embedded:3.0.1@aar'
compile 'com.google.zxing:core:3.2.0'
}
Please find the link here: https://github.com/journeyapps/zxing-android-embedded
Just to extend the pratical scope of the question and as an appendix to the given answers: Sometimes one might find it necessary to specify the selectors a little bit more.
By defining the the full span as display:inline-block you might have a hard time displaying images.
Therefore I prefer to define a span like so:
span {
display:block;
width:150px;
word-wrap:break-word;
}
p span, a span,
h1 span, h2 span, h3 span, h4 span, h5 span {
display:inline-block;
}
img{
display:block;
}
Here is an easy solution:
public class CapitalFirstLetters {
public static void main(String[] args) {
String word = "it's java, baby!";
String[] wordSplit;
String wordCapital = "";
wordSplit = word.split(" ");
for (int i = 0; i < wordSplit.length; i++) {
wordCapital = wordSplit[i].substring(0, 1).toUpperCase() + wordSplit[i].substring(1) + " ";
}
System.out.println(wordCapital);
}}
Would that be acceptable ? pure PHP
$country = geoip_country_code_by_name($_SERVER['REMOTE_ADDR']);
print $country;
ref: https://www.php.net/manual/en/function.geoip-country-code-by-name.php
It's pretty much the same as running a query. In your original code you are creating a command object, putting it in the cmd
variable, and never use it. Here, however, you will use that instead of da.InsertCommand
.
Also, use a using
for all disposable objects, so that you are sure that they are disposed properly:
private void button1_Click(object sender, EventArgs e) {
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
cmd.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastName.Text;
con.Open();
cmd.ExecuteNonQuery();
}
}
}
If you are using PHP, try adding the following code at the beginning of the php file:
If you are using localhost, try this:
header("Access-Control-Allow-Origin: *");
If you are using external domains such as server, try this:
header("Access-Control-Allow-Origin: http://www.website.com");
Java EE is a collection of specifications for developing and deploying enterprise applications.
In general, enterprise applications refer to software hosted on servers that provide the applications that support the enterprise.
The specifications (defined by Sun) describe services, application programming interfaces (APIs), and protocols.
The 13 core technologies that make up Java EE are:
The Java EE product provider is typically an application-server, web-server, or database-system vendor who provides classes that implement the interfaces defined in the specifications. These vendors compete on implementations of the Java EE specifications.
When a company requires Java EE experience what are they really asking for is experience using the technologies that make up Java EE. Frequently, a company will only be using a subset of the Java EE technologies.
mysql -uroot -p -hslavedb.mydomain.com mydb_production -e "select * from users;"
From the usage printout:
-e
,--execute=name
Execute command and quit. (Disables--force
and history file)
Junit4 solution with Java8 is to use this function:
public Throwable assertThrows(Class<? extends Throwable> expectedException, java.util.concurrent.Callable<?> funky) {
try {
funky.call();
} catch (Throwable e) {
if (expectedException.isInstance(e)) {
return e;
}
throw new AssertionError(
String.format("Expected [%s] to be thrown, but was [%s]", expectedException, e));
}
throw new AssertionError(
String.format("Expected [%s] to be thrown, but nothing was thrown.", expectedException));
}
Usage is then:
assertThrows(ValidationException.class,
() -> finalObject.checkSomething(null));
Note that the only limitation is to use a final
object reference in lambda expression.
This solution allows to continue test assertions instead of expecting thowable at method level using @Test(expected = IndexOutOfBoundsException.class)
solution.
You might be looking for this Microsoft Ajax Content Delivery Network So you could just add
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js" type="text/javascript"></script>
To your aspx page.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
e.Row.Attributes.Add("style", "cursor:help;");
if (e.Row.RowType == DataControlRowType.DataRow && e.Row.RowState == DataControlRowState.Alternate)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='orange'");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='#E56E94'");
e.Row.BackColor = Color.FromName("#E56E94");
}
}
else
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='orange'");
e.Row.Attributes.Add("onmouseout", "this.style.backgroundColor='gray'");
e.Row.BackColor = Color.FromName("gray");
}
}
}
import subprocess
python_path = subprocess.check_output("which python", shell=True).strip()
python_path = python_path.decode('utf-8')
I eventually installed an additional old version of Firefox (used for testing only) to resolve this, besides my regular (secure, up to date) latest Firefox installation.
This requires webdriver to know where it can find the Firefox binary, which can be set through the webdriver.firefox.bin
property.
What worked for me (mac, maven, /tmp/ff46
as installation folder) is:
mvn -Dwebdriver.firefox.bin=/tmp/ff46/Firefox.app/Contents/MacOS/firefox-bin verify
To install an old version of Firefox in a dedicated folder, create the folder, open Finder in that folder, download the Firefox dmg, and drag it to that Finder.
you can use decoration like this :
Container(
width: 60,
height: 60,
child: Icon(CustomIcons.option, size: 20,),
decoration: BoxDecoration(
shape: BoxShape.circle,
color: Color(0xFFe0f2f1)),
)
Now you have circle shape and Icon on it.
Run in a subshell to remove notifications and close STDOUT and STDERR:
(&>/dev/null script.sh &)
well, using the Macro record, and doing it manually, I ended up with this code .. which seems to work .. (although it's not a one liner like yours ;)
lrow = Selection.Row()
Rows(lrow).Select
Selection.Copy
Rows(lrow + 1).Select
Selection.Insert Shift:=xlDown
Application.CutCopyMode = False
Selection.ClearContents
(I put the ClearContents in there because you indicated you wanted format, and I'm assuming you didn't want the data ;) )
Internet Explorer (under version 9) does not natively support rounded corners.
There's an amazing script that will magically add it for you: CSS3 PIE.
I've used it a lot of times, with amazing results.
If you don't mind using a bit of non-standard stuff, Postgres version 9.4 and up has an option of storing a record of type JSON text array.
Your schema would be:
Table: Items
Columns: Item_ID:int, Title:text, Content:text
Table: Tags
Columns: Item_ID:int, Tag_Title:text[]
For more info, see this excellent post by Josh Berkus: http://www.databasesoup.com/2015/01/tag-all-things.html
There are more various options compared thoroughly for performance and the one suggested above is the best overall.
Working for me on IE:
<script type="text/javascript">
var WinNetwork = new ActiveXObject("WScript.Network");
document.write(WinNetwork.UserName);
</script>
...but ActiveX controls needs to be on in security settings.
Load the following up needed script in the callback of the previous one like:
$.getScript('scripta.js', function()
{
$.getScript('scriptb.js', function()
{
// run script that depends on scripta.js and scriptb.js
});
});
If you just want to see how your picture will look on the website without uploading it to the server or without running your website on a local server, I think a very simple solution will be to convert your picture into a Base64 and add the contents into an IMG tag or as a background-image with CSS.
The easiest command line for this, which includes the PEM output to add it to the keystore, as well as a human readable output and also supports SNI, which is important if you are working with an HTTP server is:
openssl s_client -servername example.com -connect example.com:443 \
</dev/null 2>/dev/null | openssl x509 -text
The -servername option is to enable SNI support and the openssl x509 -text prints the certificate in human readable format.
2017: If someone is still interested in the question, my solution is the following:
const arrayToCount = [1, 2, 3, 5, 2, 8, 9, 2];_x000D_
const result = arrayToCount.filter(i => i === 2).length;_x000D_
console.log('number of the found elements: ' + result);
_x000D_
Here you go
var myDate = new Date("February 04, 2011 19:00:00");
var hr = myDate.getHours();
var convHrs = "";
var ampmSwitch = "";
ampmSwitch = (hr > 12)? "PM":"AM";
convHrs = (hr >12)? hr-12:hr;
// Build back the Date / time using getMonth/ getFullYear and getDate and other functions on the myDate object. Enclose it inside a func and there you got the working 12 hrs converter ;)
And here's the converter func for yas ;) Happy coding!!
function convertTo12Hrs(yourDateTime){
var myDate = new Date(yourDateTime);
var dtObject = new Object();
var monthsCollection = {0:"January", 1:"February",2:"March",3:"April",4:"May",5:"June",6:"July",7:"August",8:"September",9:"October",10:"November",11:"December"};
dtObject.year = myDate.getFullYear();
dtObject.month = monthsCollection[myDate.getMonth()];
dtObject.day = (myDate.getDate()<10)?"0"+myDate.getDate():myDate.getDate();
dtObject.minutes = (myDate.getMinutes() < 10)? "0"+myDate.getMinutes():myDate.getMinutes();
dtObject.seconds = (myDate.getSeconds() < 10)? "0"+myDate.getSeconds():myDate.getSeconds();
// Check if hours are greater than 12? Its PM
dtObject.ampmSwitch = (myDate.getHours() > 12)? "PM":"AM";
// Convert the hours
dtObject.hour = (myDate.getHours() > 12)?myDate.getHours()-12:myDate.getHours();
// Add the 0 as prefix if its less than 10
dtObject.hour = (dtObject.hour < 10)? "0"+dtObject.hour:dtObject.hour;
// Format back the string as it was or return the dtObject object or however you like. I am returning the object here
return dtObject;
}
invoke it like convertTo12Hrs("February 04, 2011 19:00:00"); it will return you the object, which in turn you can use to format back your datetime string as you fancy...
Swift 4.2
let closure = { [weak self] (_ parameter:Int) in
guard let self = self else { return }
self.method(parameter)
}
Let's say the name was used in a variable, $Name
.
You then run this query:
INSERT INTO Students VALUES ( '$Name' )
The code is mistakenly placing anything the user supplied as the variable.
You wanted the SQL to be:
INSERT INTO Students VALUES ( 'Robert Tables` )
But a clever user can supply whatever they want:
INSERT INTO Students VALUES ( 'Robert'); DROP TABLE Students; --' )
What you get is:
INSERT INTO Students VALUES ( 'Robert' ); DROP TABLE STUDENTS; --' )
The --
only comments the remainder of the line.
var marker = new google.maps.Marker({
position: new google.maps.LatLng(23.016427,72.571156),
map: map,
icon: 'images/map_marker_icon.png',
title: 'Hi..!'
});
apply local path on icon only
We don't store the database schema, we store the changes to the database. What we do is store the schema changes so that we build a change script for any version of the database and apply it to our customer's databases. I wrote an database utility app that gets distributed with our main application that can read that script and know which updates need to be applied. It also has enough smarts to refresh views and stored procedures as needed.
You can also use as Vector instead, as vectors are thread safe and arraylist are not. Though vectors are old but they can solve your purpose easily.
But you can make your Arraylist synchronized like code given this:
Collections.synchronizedList(new ArrayList(numberOfRaceCars()));
The above solutions didn't work for me. Here is what I finally came up with:
$( "#ddl" ).find( "option:selected" ).text(); // Text
$( "#ddl" ).find( "option:selected" ).prop("value"); // Value
Put your code in a method.
Try this:
public class MyClass {
public static void main(String[] args) {
UserInput input = new UserInput();
input.name();
}
}
Then "run" the class from your IDE
I believe python arrays just admit values. So convert it to list:
kOUT = np.zeros(N+1)
kOUT = kOUT.tolist()
Another option (If you are using ASP.Net razor view) is, On your view you can do
<div>@String.Format("{0:C}", Model.total)</div>
This would format it correctly. note (item.total is double/decimal)
if in jQuery you can also use Regex
$(".totalSum").text('$' + parseFloat(total, 10).toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,").toString());
I have written a shell script which will read data from properties file and then run mysql script on shell script. sharing this may help to others.
#!/bin/bash
PROPERTY_FILE=filename.properties
function getProperty {
PROP_KEY=$1
PROP_VALUE=`cat $PROPERTY_FILE | grep "$PROP_KEY" | cut -d'=' -f2`
echo $PROP_VALUE
}
echo "# Reading property from $PROPERTY_FILE"
DB_USER=$(getProperty "db.username")
DB_PASS=$(getProperty "db.password")
ROOT_LOC=$(getProperty "root.location")
echo $DB_USER
echo $DB_PASS
echo $ROOT_LOC
echo "Writing on DB ... "
mysql -u$DB_USER -p$DB_PASS dbname<<EOFMYSQL
update tablename set tablename.value_ = "$ROOT_LOC" where tablename.name_="Root directory location";
EOFMYSQL
echo "Writing root location($ROOT_LOC) is done ... "
counter=`mysql -u${DB_USER} -p${DB_PASS} dbname -e "select count(*) from tablename where tablename.name_='Root directory location' and tablename.value_ = '$ROOT_LOC';" | grep -v "count"`;
if [ "$counter" = "1" ]
then
echo "ROOT location updated"
fi
You need to use brackets when using the fileExists
step in an if
condition or assign the returned value to a variable
Using variable:
def exists = fileExists 'file'
if (exists) {
echo 'Yes'
} else {
echo 'No'
}
Using brackets:
if (fileExists('file')) {
echo 'Yes'
} else {
echo 'No'
}
You can use slice method in javascript array object
<div ng-repeat="item in items.slice(0, 4)">{{item}}</div>
Short n sweet
Have been edited in 2020-06-15
public class Outer {
public Inner getInner(){
return new Inner(this);
}
static class Inner {
public final Outer Outer;
public Inner(Outer outer) {
this.Outer=outer;
}
}
public static void main(String[] args) {
Outer outer = new Outer();
Inner inner = outer.getInner();
Outer anotherOuter=inner.Outer;
if(anotherOuter == outer) {
System.out.println("Was able to reach out to the outer object via inner !!");
} else {
System.out.println("No luck :-( ");
}
}
}
Just a side note for similar problem (If we don't want to loop through):
How to lookup a dictionary using a variable key within Jinja template?
Here is an example:
{% set key = target_db.Schema.upper()+"__"+target_db.TableName.upper() %}
{{ dict_containing_df.get(key).to_html() | safe }}
It might be obvious. But we don't need curly braces within curly braces. Straight python syntax works. (I am posting because I was confusing to me...)
Alternatively, you can simply do
{{dict[target_db.Schema.upper()+"__"+target_db.TableName.upper()]).to_html() | safe }}
But it will spit an error when no key is found. So better to use get
in Jinja.
There are relatively few key codes so I simply listed all the corresponding values in a static array so I could simply convert the number 65
into A
using keyboardMap[65]
Not all key codes map to a printable character so some other identifiable string is returned.
You may need to modify the array to suit your needs and can simply return empty strings for all the characters you don't care to translate. The following array allows me to quickly and reliably determine which key was pressed in any environment. Enjoy!
// names of known key codes (0-255)
var keyboardMap = [
"", // [0]
"", // [1]
"", // [2]
"CANCEL", // [3]
"", // [4]
"", // [5]
"HELP", // [6]
"", // [7]
"BACK_SPACE", // [8]
"TAB", // [9]
"", // [10]
"", // [11]
"CLEAR", // [12]
"ENTER", // [13]
"ENTER_SPECIAL", // [14]
"", // [15]
"SHIFT", // [16]
"CONTROL", // [17]
"ALT", // [18]
"PAUSE", // [19]
"CAPS_LOCK", // [20]
"KANA", // [21]
"EISU", // [22]
"JUNJA", // [23]
"FINAL", // [24]
"HANJA", // [25]
"", // [26]
"ESCAPE", // [27]
"CONVERT", // [28]
"NONCONVERT", // [29]
"ACCEPT", // [30]
"MODECHANGE", // [31]
"SPACE", // [32]
"PAGE_UP", // [33]
"PAGE_DOWN", // [34]
"END", // [35]
"HOME", // [36]
"LEFT", // [37]
"UP", // [38]
"RIGHT", // [39]
"DOWN", // [40]
"SELECT", // [41]
"PRINT", // [42]
"EXECUTE", // [43]
"PRINTSCREEN", // [44]
"INSERT", // [45]
"DELETE", // [46]
"", // [47]
"0", // [48]
"1", // [49]
"2", // [50]
"3", // [51]
"4", // [52]
"5", // [53]
"6", // [54]
"7", // [55]
"8", // [56]
"9", // [57]
"COLON", // [58]
"SEMICOLON", // [59]
"LESS_THAN", // [60]
"EQUALS", // [61]
"GREATER_THAN", // [62]
"QUESTION_MARK", // [63]
"AT", // [64]
"A", // [65]
"B", // [66]
"C", // [67]
"D", // [68]
"E", // [69]
"F", // [70]
"G", // [71]
"H", // [72]
"I", // [73]
"J", // [74]
"K", // [75]
"L", // [76]
"M", // [77]
"N", // [78]
"O", // [79]
"P", // [80]
"Q", // [81]
"R", // [82]
"S", // [83]
"T", // [84]
"U", // [85]
"V", // [86]
"W", // [87]
"X", // [88]
"Y", // [89]
"Z", // [90]
"OS_KEY", // [91] Windows Key (Windows) or Command Key (Mac)
"", // [92]
"CONTEXT_MENU", // [93]
"", // [94]
"SLEEP", // [95]
"NUMPAD0", // [96]
"NUMPAD1", // [97]
"NUMPAD2", // [98]
"NUMPAD3", // [99]
"NUMPAD4", // [100]
"NUMPAD5", // [101]
"NUMPAD6", // [102]
"NUMPAD7", // [103]
"NUMPAD8", // [104]
"NUMPAD9", // [105]
"MULTIPLY", // [106]
"ADD", // [107]
"SEPARATOR", // [108]
"SUBTRACT", // [109]
"DECIMAL", // [110]
"DIVIDE", // [111]
"F1", // [112]
"F2", // [113]
"F3", // [114]
"F4", // [115]
"F5", // [116]
"F6", // [117]
"F7", // [118]
"F8", // [119]
"F9", // [120]
"F10", // [121]
"F11", // [122]
"F12", // [123]
"F13", // [124]
"F14", // [125]
"F15", // [126]
"F16", // [127]
"F17", // [128]
"F18", // [129]
"F19", // [130]
"F20", // [131]
"F21", // [132]
"F22", // [133]
"F23", // [134]
"F24", // [135]
"", // [136]
"", // [137]
"", // [138]
"", // [139]
"", // [140]
"", // [141]
"", // [142]
"", // [143]
"NUM_LOCK", // [144]
"SCROLL_LOCK", // [145]
"WIN_OEM_FJ_JISHO", // [146]
"WIN_OEM_FJ_MASSHOU", // [147]
"WIN_OEM_FJ_TOUROKU", // [148]
"WIN_OEM_FJ_LOYA", // [149]
"WIN_OEM_FJ_ROYA", // [150]
"", // [151]
"", // [152]
"", // [153]
"", // [154]
"", // [155]
"", // [156]
"", // [157]
"", // [158]
"", // [159]
"CIRCUMFLEX", // [160]
"EXCLAMATION", // [161]
"DOUBLE_QUOTE", // [162]
"HASH", // [163]
"DOLLAR", // [164]
"PERCENT", // [165]
"AMPERSAND", // [166]
"UNDERSCORE", // [167]
"OPEN_PAREN", // [168]
"CLOSE_PAREN", // [169]
"ASTERISK", // [170]
"PLUS", // [171]
"PIPE", // [172]
"HYPHEN_MINUS", // [173]
"OPEN_CURLY_BRACKET", // [174]
"CLOSE_CURLY_BRACKET", // [175]
"TILDE", // [176]
"", // [177]
"", // [178]
"", // [179]
"", // [180]
"VOLUME_MUTE", // [181]
"VOLUME_DOWN", // [182]
"VOLUME_UP", // [183]
"", // [184]
"", // [185]
"SEMICOLON", // [186]
"EQUALS", // [187]
"COMMA", // [188]
"MINUS", // [189]
"PERIOD", // [190]
"SLASH", // [191]
"BACK_QUOTE", // [192]
"", // [193]
"", // [194]
"", // [195]
"", // [196]
"", // [197]
"", // [198]
"", // [199]
"", // [200]
"", // [201]
"", // [202]
"", // [203]
"", // [204]
"", // [205]
"", // [206]
"", // [207]
"", // [208]
"", // [209]
"", // [210]
"", // [211]
"", // [212]
"", // [213]
"", // [214]
"", // [215]
"", // [216]
"", // [217]
"", // [218]
"OPEN_BRACKET", // [219]
"BACK_SLASH", // [220]
"CLOSE_BRACKET", // [221]
"QUOTE", // [222]
"", // [223]
"META", // [224]
"ALTGR", // [225]
"", // [226]
"WIN_ICO_HELP", // [227]
"WIN_ICO_00", // [228]
"", // [229]
"WIN_ICO_CLEAR", // [230]
"", // [231]
"", // [232]
"WIN_OEM_RESET", // [233]
"WIN_OEM_JUMP", // [234]
"WIN_OEM_PA1", // [235]
"WIN_OEM_PA2", // [236]
"WIN_OEM_PA3", // [237]
"WIN_OEM_WSCTRL", // [238]
"WIN_OEM_CUSEL", // [239]
"WIN_OEM_ATTN", // [240]
"WIN_OEM_FINISH", // [241]
"WIN_OEM_COPY", // [242]
"WIN_OEM_AUTO", // [243]
"WIN_OEM_ENLW", // [244]
"WIN_OEM_BACKTAB", // [245]
"ATTN", // [246]
"CRSEL", // [247]
"EXSEL", // [248]
"EREOF", // [249]
"PLAY", // [250]
"ZOOM", // [251]
"", // [252]
"PA1", // [253]
"WIN_OEM_CLEAR", // [254]
"" // [255]
];
Note: The position of each value in the array above is important. The
""
are placeholders for codes with unknown values.
Try the following code snippet using this static array lookup approach...
var keyCodes = [];_x000D_
_x000D_
$("#reset").click(function() {_x000D_
keyCodes = [];_x000D_
$("#in").val("");_x000D_
$("#key-codes").html("var keyCodes = [ ];");_x000D_
$("#key-names").html("var keyNames = [ ];");_x000D_
});_x000D_
_x000D_
$(document).keydown(function(e) {_x000D_
keyCodes.push(e.which);_x000D_
updateOutput();_x000D_
});_x000D_
_x000D_
function updateOutput() {_x000D_
var kC = "var keyCodes = [ ";_x000D_
var kN = "var keyNames = [ ";_x000D_
_x000D_
var len = keyCodes.length;_x000D_
_x000D_
for (var i = 0; i < len; i++) {_x000D_
kC += keyCodes[i];_x000D_
kN += "'"+keyboardMap[keyCodes[i]]+"'";_x000D_
if (i !== (len - 1)) {_x000D_
kC += ", ";_x000D_
kN += ", ";_x000D_
}_x000D_
}_x000D_
_x000D_
kC += " ];";_x000D_
kN += " ];";_x000D_
_x000D_
$("#key-codes").html(kC);_x000D_
$("#key-names").html(kN);_x000D_
}_x000D_
_x000D_
_x000D_
_x000D_
var keyboardMap = [_x000D_
"", // [0]_x000D_
"", // [1]_x000D_
"", // [2]_x000D_
"CANCEL", // [3]_x000D_
"", // [4]_x000D_
"", // [5]_x000D_
"HELP", // [6]_x000D_
"", // [7]_x000D_
"BACK_SPACE", // [8]_x000D_
"TAB", // [9]_x000D_
"", // [10]_x000D_
"", // [11]_x000D_
"CLEAR", // [12]_x000D_
"ENTER", // [13]_x000D_
"ENTER_SPECIAL", // [14]_x000D_
"", // [15]_x000D_
"SHIFT", // [16]_x000D_
"CONTROL", // [17]_x000D_
"ALT", // [18]_x000D_
"PAUSE", // [19]_x000D_
"CAPS_LOCK", // [20]_x000D_
"KANA", // [21]_x000D_
"EISU", // [22]_x000D_
"JUNJA", // [23]_x000D_
"FINAL", // [24]_x000D_
"HANJA", // [25]_x000D_
"", // [26]_x000D_
"ESCAPE", // [27]_x000D_
"CONVERT", // [28]_x000D_
"NONCONVERT", // [29]_x000D_
"ACCEPT", // [30]_x000D_
"MODECHANGE", // [31]_x000D_
"SPACE", // [32]_x000D_
"PAGE_UP", // [33]_x000D_
"PAGE_DOWN", // [34]_x000D_
"END", // [35]_x000D_
"HOME", // [36]_x000D_
"LEFT", // [37]_x000D_
"UP", // [38]_x000D_
"RIGHT", // [39]_x000D_
"DOWN", // [40]_x000D_
"SELECT", // [41]_x000D_
"PRINT", // [42]_x000D_
"EXECUTE", // [43]_x000D_
"PRINTSCREEN", // [44]_x000D_
"INSERT", // [45]_x000D_
"DELETE", // [46]_x000D_
"", // [47]_x000D_
"0", // [48]_x000D_
"1", // [49]_x000D_
"2", // [50]_x000D_
"3", // [51]_x000D_
"4", // [52]_x000D_
"5", // [53]_x000D_
"6", // [54]_x000D_
"7", // [55]_x000D_
"8", // [56]_x000D_
"9", // [57]_x000D_
"COLON", // [58]_x000D_
"SEMICOLON", // [59]_x000D_
"LESS_THAN", // [60]_x000D_
"EQUALS", // [61]_x000D_
"GREATER_THAN", // [62]_x000D_
"QUESTION_MARK", // [63]_x000D_
"AT", // [64]_x000D_
"A", // [65]_x000D_
"B", // [66]_x000D_
"C", // [67]_x000D_
"D", // [68]_x000D_
"E", // [69]_x000D_
"F", // [70]_x000D_
"G", // [71]_x000D_
"H", // [72]_x000D_
"I", // [73]_x000D_
"J", // [74]_x000D_
"K", // [75]_x000D_
"L", // [76]_x000D_
"M", // [77]_x000D_
"N", // [78]_x000D_
"O", // [79]_x000D_
"P", // [80]_x000D_
"Q", // [81]_x000D_
"R", // [82]_x000D_
"S", // [83]_x000D_
"T", // [84]_x000D_
"U", // [85]_x000D_
"V", // [86]_x000D_
"W", // [87]_x000D_
"X", // [88]_x000D_
"Y", // [89]_x000D_
"Z", // [90]_x000D_
"OS_KEY", // [91] Windows Key (Windows) or Command Key (Mac)_x000D_
"", // [92]_x000D_
"CONTEXT_MENU", // [93]_x000D_
"", // [94]_x000D_
"SLEEP", // [95]_x000D_
"NUMPAD0", // [96]_x000D_
"NUMPAD1", // [97]_x000D_
"NUMPAD2", // [98]_x000D_
"NUMPAD3", // [99]_x000D_
"NUMPAD4", // [100]_x000D_
"NUMPAD5", // [101]_x000D_
"NUMPAD6", // [102]_x000D_
"NUMPAD7", // [103]_x000D_
"NUMPAD8", // [104]_x000D_
"NUMPAD9", // [105]_x000D_
"MULTIPLY", // [106]_x000D_
"ADD", // [107]_x000D_
"SEPARATOR", // [108]_x000D_
"SUBTRACT", // [109]_x000D_
"DECIMAL", // [110]_x000D_
"DIVIDE", // [111]_x000D_
"F1", // [112]_x000D_
"F2", // [113]_x000D_
"F3", // [114]_x000D_
"F4", // [115]_x000D_
"F5", // [116]_x000D_
"F6", // [117]_x000D_
"F7", // [118]_x000D_
"F8", // [119]_x000D_
"F9", // [120]_x000D_
"F10", // [121]_x000D_
"F11", // [122]_x000D_
"F12", // [123]_x000D_
"F13", // [124]_x000D_
"F14", // [125]_x000D_
"F15", // [126]_x000D_
"F16", // [127]_x000D_
"F17", // [128]_x000D_
"F18", // [129]_x000D_
"F19", // [130]_x000D_
"F20", // [131]_x000D_
"F21", // [132]_x000D_
"F22", // [133]_x000D_
"F23", // [134]_x000D_
"F24", // [135]_x000D_
"", // [136]_x000D_
"", // [137]_x000D_
"", // [138]_x000D_
"", // [139]_x000D_
"", // [140]_x000D_
"", // [141]_x000D_
"", // [142]_x000D_
"", // [143]_x000D_
"NUM_LOCK", // [144]_x000D_
"SCROLL_LOCK", // [145]_x000D_
"WIN_OEM_FJ_JISHO", // [146]_x000D_
"WIN_OEM_FJ_MASSHOU", // [147]_x000D_
"WIN_OEM_FJ_TOUROKU", // [148]_x000D_
"WIN_OEM_FJ_LOYA", // [149]_x000D_
"WIN_OEM_FJ_ROYA", // [150]_x000D_
"", // [151]_x000D_
"", // [152]_x000D_
"", // [153]_x000D_
"", // [154]_x000D_
"", // [155]_x000D_
"", // [156]_x000D_
"", // [157]_x000D_
"", // [158]_x000D_
"", // [159]_x000D_
"CIRCUMFLEX", // [160]_x000D_
"EXCLAMATION", // [161]_x000D_
"DOUBLE_QUOTE", // [162]_x000D_
"HASH", // [163]_x000D_
"DOLLAR", // [164]_x000D_
"PERCENT", // [165]_x000D_
"AMPERSAND", // [166]_x000D_
"UNDERSCORE", // [167]_x000D_
"OPEN_PAREN", // [168]_x000D_
"CLOSE_PAREN", // [169]_x000D_
"ASTERISK", // [170]_x000D_
"PLUS", // [171]_x000D_
"PIPE", // [172]_x000D_
"HYPHEN_MINUS", // [173]_x000D_
"OPEN_CURLY_BRACKET", // [174]_x000D_
"CLOSE_CURLY_BRACKET", // [175]_x000D_
"TILDE", // [176]_x000D_
"", // [177]_x000D_
"", // [178]_x000D_
"", // [179]_x000D_
"", // [180]_x000D_
"VOLUME_MUTE", // [181]_x000D_
"VOLUME_DOWN", // [182]_x000D_
"VOLUME_UP", // [183]_x000D_
"", // [184]_x000D_
"", // [185]_x000D_
"SEMICOLON", // [186]_x000D_
"EQUALS", // [187]_x000D_
"COMMA", // [188]_x000D_
"MINUS", // [189]_x000D_
"PERIOD", // [190]_x000D_
"SLASH", // [191]_x000D_
"BACK_QUOTE", // [192]_x000D_
"", // [193]_x000D_
"", // [194]_x000D_
"", // [195]_x000D_
"", // [196]_x000D_
"", // [197]_x000D_
"", // [198]_x000D_
"", // [199]_x000D_
"", // [200]_x000D_
"", // [201]_x000D_
"", // [202]_x000D_
"", // [203]_x000D_
"", // [204]_x000D_
"", // [205]_x000D_
"", // [206]_x000D_
"", // [207]_x000D_
"", // [208]_x000D_
"", // [209]_x000D_
"", // [210]_x000D_
"", // [211]_x000D_
"", // [212]_x000D_
"", // [213]_x000D_
"", // [214]_x000D_
"", // [215]_x000D_
"", // [216]_x000D_
"", // [217]_x000D_
"", // [218]_x000D_
"OPEN_BRACKET", // [219]_x000D_
"BACK_SLASH", // [220]_x000D_
"CLOSE_BRACKET", // [221]_x000D_
"QUOTE", // [222]_x000D_
"", // [223]_x000D_
"META", // [224]_x000D_
"ALTGR", // [225]_x000D_
"", // [226]_x000D_
"WIN_ICO_HELP", // [227]_x000D_
"WIN_ICO_00", // [228]_x000D_
"", // [229]_x000D_
"WIN_ICO_CLEAR", // [230]_x000D_
"", // [231]_x000D_
"", // [232]_x000D_
"WIN_OEM_RESET", // [233]_x000D_
"WIN_OEM_JUMP", // [234]_x000D_
"WIN_OEM_PA1", // [235]_x000D_
"WIN_OEM_PA2", // [236]_x000D_
"WIN_OEM_PA3", // [237]_x000D_
"WIN_OEM_WSCTRL", // [238]_x000D_
"WIN_OEM_CUSEL", // [239]_x000D_
"WIN_OEM_ATTN", // [240]_x000D_
"WIN_OEM_FINISH", // [241]_x000D_
"WIN_OEM_COPY", // [242]_x000D_
"WIN_OEM_AUTO", // [243]_x000D_
"WIN_OEM_ENLW", // [244]_x000D_
"WIN_OEM_BACKTAB", // [245]_x000D_
"ATTN", // [246]_x000D_
"CRSEL", // [247]_x000D_
"EXSEL", // [248]_x000D_
"EREOF", // [249]_x000D_
"PLAY", // [250]_x000D_
"ZOOM", // [251]_x000D_
"", // [252]_x000D_
"PA1", // [253]_x000D_
"WIN_OEM_CLEAR", // [254]_x000D_
"" // [255]_x000D_
];
_x000D_
#key-codes,_x000D_
#key-names {_x000D_
font-family: courier, serif;_x000D_
font-size: 1.2em;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<input id="in" placeholder="Type here..." />_x000D_
<button id="reset">Reset</button>_x000D_
<br/>_x000D_
<br/>_x000D_
<div id="key-codes">var keyCodes = [ ];</div>_x000D_
<div id="key-names">var keyNames = [ ];</div>
_x000D_
Letters A-Z: (65-90)
keyboardMap[65]; // A
...
keyboardMap[90]; // Z
Digits 0-9: (48-57)
keyboardMap[48]; // 0
...
keyboardMap[57]; // 9
Number Pad 0-9: (96-105)
keyboardMap[96]; // NUMPAD0
...
keyboardMap[105]; // NUMPAD9
Arrow Keys: (37-40)
keyboardMap[37]; // LEFT
keyboardMap[38]; // UP
keyboardMap[39]; // RIGHT
keyboardMap[40]; // DOWN
Tab Key: (9)
keyboardMap[9]; // TAB
Enter Key: (13)
keyboardMap[13]; // ENTER
Spacebar Key: (32)
keyboardMap[32]; // SPACE
OS Specific Key (91) Windows Key (Windows) or Command Key (Mac)
keyboardMap[91]; // OS_KEY
Alt Key: (18)
keyboardMap[18]; // ALT
Control Key: (17)
keyboardMap[17]; // CONTROL
Shift Key: (16)
keyboardMap[16]; // SHIFT
Caps Lock Key: (20)
keyboardMap[20]; // CAPS_LOCK
I had the same problem, maven was complaining about a missing artifact, even though it existed in .m2/repository/[...]. In my case the problem was that I forgot to specify the correct repository in the pom.xml from which the package was downloaded originally (download by another project).
Adding the package repository to the pom.xml solved the problem.
<repositories>
<repository>
<id>SomeName</id>
<name>SomeName</name>
<url>http://url.to.repo</url>
</repository>
</repositories>
Thanks Maximilianus for the hint to those "*.repositories" files in the package directory.
$str = substr($oldstr, 0, $pos) . $str_to_insert . substr($oldstr, $pos);
Wrap that up in a function and then just return
.
=TEXT(A1,"0000")
However the TEXT function is able to do other fancy stuff like date formating, aswell.
holy errors The reason for the code below is to show how to not void main every function and not to type return; for functions...... instead push everything into the sediment for which is the print function prototype... if you need to use useful functions ... you will have to below..... (p.s. this below is for people overwhelmed by these object and T templates which allow different variable declaration types(such as float and char) to use the same passed by value in a user defined function)
char arr[ ] = "This is a test";
string str(arr);
// You can also assign directly to a string.
str = "This is another string";
can anyone tell me why c++ made arrays into pass by value one at a time and the only way to eliminate spaces and punctuation is the use of string tokens. I couldn't get around the problem when i was trying to delete spaces for a palindrome...
#include <iostream>
#include <iomanip>
using namespace std;
int getgrades(float[]);
int getaverage(float[], float);
int calculateletters(float[], float, float, float[]);
int printResults(float[], float, float, float[]);
int main()
{
int i;
float maxSize=3, size;
float lettergrades[5], numericgrades[100], average;
size=getgrades(numericgrades);
average = getaverage(numericgrades, size);
printResults(numericgrades, size, average, lettergrades);
return 0;
}
int getgrades(float a[])
{
int i, max=3;
for (i = 0; i <max; i++)
{
//ask use for input
cout << "\nPlease Enter grade " << i+1 << " : ";
cin >> a[i];
//makes sure that user enters a vlue between 0 and 100
if(a[i] < 0 || a[i] >100)
{
cout << "Wrong input. Please
enter a value between 0 and 100 only." << endl;
cout << "\nPlease Reenter grade " << i+1 << " : ";
cin >> a[i];
return i;
}
}
}
int getaverage(float a[], float n)
{
int i;
float sum = 0;
if (n == 0)
return 0;
for (i = 0; i < n; i++)
sum += a[i];
return sum / n;
}
int printResults(float a[], float n, float average, float letters[])
{
int i;
cout << "Index Number | input |
array values address in memory " << endl;
for (i = 0; i < 3; i++)
{
cout <<" "<< i<<" \t\t"<<setprecision(3)<<
a[i]<<"\t\t" << &a[i] << endl;
}
cout<<"The average of your grades is: "<<setprecision(3)<<average<<endl;
}
You could just use REPLACE
:
UPDATE myTable SET emailCol = REPLACE(emailCol, '.com', '.org')`.
But take into account an email address such as [email protected]
will be updated to [email protected]
.
If you want to be on a safer side, you should check for the last 4 characters using RIGHT
, and append .org
to the SUBSTRING
manually instead. Notice the usage of UPPER
to make the search for the .com
ending case insensitive.
UPDATE myTable
SET emailCol = SUBSTRING(emailCol, 1, LEN(emailCol)-4) + '.org'
WHERE UPPER(RIGHT(emailCol,4)) = '.COM';
See it working in this SQLFiddle.
Once you read what What Every Computer Scientist Should Know About Floating-Point Arithmetic you could use the .toFixed()
function:
var result = parseFloat('2.3') + parseFloat('2.4');
alert(result.toFixed(2));?
I would store a user ID and a token. When the user comes back to the site, compare those two pieces of information against something persistent like a database entry.
As for security, just don't put anything in there that will allow someone to modify the cookie to gain extra benefits. For example, don't store their user groups or their password. Anything that can be modified that would circumvent your security should not be stored in the cookie.
You could try to create your own color palette using the RColorBrewer
package
my_palette <- colorRampPalette(c("green", "black", "red"))(n = 1000)
and see how this looks like. But I assume in your case only scaling would help if you really want to keep the black in "the middle". You can simply use my_palette
instead of the redgreen()
I recommend that you check out the RColorBrewer package, they have pretty nice in-built palettes, and see interactive website for colorbrewer.
The first part of your question is easy. As already pointed out, cut accepts omission of either the starting or the ending index of a column range, interpreting this as meaning either “from the start to column n (inclusive)” or “from column n (inclusive) to the end,” respectively:
$ printf 'this:is:a:test' | cut -d: -f-2
this:is
$ printf 'this:is:a:test' | cut -d: -f3-
a:test
It also supports combining ranges. If you want, e.g., the first 3 and the last 2 columns in a row of 7 columns:
$ printf 'foo:bar:baz:qux:quz:quux:quuz' | cut -d: -f-3,6-
foo:bar:baz:quux:quuz
However, the second part of your question can be a bit trickier depending on what kind of input you’re expecting. If by “last n columns” you mean “last n columns (regardless of their indices in the overall row)” (i.e. because you don’t necessarily know how many columns you’re going to find in advance) then sadly this is not possible to accomplish using cut
alone. In order to effectively use cut
to pull out “the last n columns” in each line, the total number of columns present in each line must be known beforehand, and each line must be consistent in the number of columns it contains.
If you do not know how many “columns” may be present in each line (e.g. because you’re working with input that is not strictly tabular), then you’ll have to use something like awk
instead. E.g., to use awk
to pull out the last 2 “columns” (awk calls them fields, the number of which can vary per line) from each line of input:
$ printf '/a\n/a/b\n/a/b/c\n/a/b/c/d\n' | awk -F/ '{print $(NF-1) FS $(NF)}'
/a
a/b
b/c
c/d
Whenever you insert an image it just takes the width that the image has originally. You can add any other html element next to it and you will see that it will allow it. That makes image an "inline" element.
You can use the WSDL2JAVA Codegen (or) You can simply use the 'Web Service/WebServiceClient' Wizard available in the Eclipse IDE. Open the IDE and press 'Ctrl+N', selectfor 'Web Service/WebServiceClient', specify the wsdl URL, ouput folder and select finish.
It creates the complete source files that you would need.
Use \nolinebreak
\nolinebreak[number]
The \nolinebreak command prevents LaTeX from breaking the current line at the point of the command. With the optional argument, number, you can convert the \nolinebreak command from a demand to a request. The number must be a number from 0 to 4. The higher the number, the more insistent the request is.
Source: http://www.personal.ceu.hu/tex/breaking.htm#nolinebreak
One way is the following:
git fetch <remotename> <remote branch>:refs/remotes/<remotename>/<local branch>
This does not set up tracking though.
For more information, see the documentation of git fetch.
EDIT: As @user1338062 notes below: if you don't already have a local clone of the repository where you want to add the new branch, but you want to create a fresh local repository, then the git clone --branch <branch_name> --single-branch <repo_url>
provides a shorter solution.
import os
print os.getcwd() # Prints the current working directory
To set the working directory:
os.chdir('c:\\Users\\uname\\desktop\\python') # Provide the new path here
Once i did some fun project and i still use it. It's showing some animation while i copy files via cp
command coz cp
don't show anything and it's kind of frustrating. So i made this alias
alias cp="~/SCR/spiner cp"
And this is the spiner script
#!/bin/bash
#Set timer
T=$(date +%s)
#Add some color
. ~/SCR/color
#Animation sprites
sprite=( "(* ) ( *)" " (* )( *) " " ( *)(* ) " "( *) (* )" "(* ) ( *)" )
#Print empty line and hide cursor
printf "\n${COF}"
#Exit function
function bye { printf "${CON}"; [ -e /proc/$pid ] && kill -9 $pid; exit; }; trap bye INT
#Run our command and get its pid
"$@" & pid=$!
#Waiting animation
i=0; while [ -e /proc/$pid ]; do sleep 0.1
printf "\r${GRN}Please wait... ${YLW}${sprite[$i]}${DEF}"
((i++)); [[ $i = ${#sprite[@]} ]] && i=0
done
#Print time and exit
T=$(($(date +%s)-$T))
printf "\n\nTime taken: $(date -u -d @${T} +'%T')\n"
bye
It's look like this
Cycled animation)
Here is the link to a color script mentioned above. And new animation cycle)
I figured out how to do this with InjectionTokens (see example below), and if your project was built using the Angular CLI
you can use the environment files found in /environments
for static application wide settings
like an API endpoint, but depending on your project's requirements you will most likely end up using both since environment files are just object literals, while an injectable configuration using InjectionToken
's can use the environment variables and since it's a class can have logic applied to configure it based on other factors in the application, such as initial http request data, subdomain, etc.
Injection Tokens Example
/app/app-config.module.ts
import { NgModule, InjectionToken } from '@angular/core';
import { environment } from '../environments/environment';
export let APP_CONFIG = new InjectionToken<AppConfig>('app.config');
export class AppConfig {
apiEndpoint: string;
}
export const APP_DI_CONFIG: AppConfig = {
apiEndpoint: environment.apiEndpoint
};
@NgModule({
providers: [{
provide: APP_CONFIG,
useValue: APP_DI_CONFIG
}]
})
export class AppConfigModule { }
/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppConfigModule } from './app-config.module';
@NgModule({
declarations: [
// ...
],
imports: [
// ...
AppConfigModule
],
bootstrap: [AppComponent]
})
export class AppModule { }
Now you can just DI it into any component, service, etc:
/app/core/auth.service.ts
import { Injectable, Inject } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';
import { APP_CONFIG, AppConfig } from '../app-config.module';
import { AuthHttp } from 'angular2-jwt';
@Injectable()
export class AuthService {
constructor(
private http: Http,
private router: Router,
private authHttp: AuthHttp,
@Inject(APP_CONFIG) private config: AppConfig
) { }
/**
* Logs a user into the application.
* @param payload
*/
public login(payload: { username: string, password: string }) {
return this.http
.post(`${this.config.apiEndpoint}/login`, payload)
.map((response: Response) => {
const token = response.json().token;
sessionStorage.setItem('token', token); // TODO: can this be done else where? interceptor
return this.handleResponse(response); // TODO: unset token shouldn't return the token to login
})
.catch(this.handleError);
}
// ...
}
You can then also type check the config using the exported AppConfig.