To get a set of all valid timezone names (ids) from the tz database, you could use pytz
module in Python:
>>> import pytz # $ pip install pytz
>>> pytz.all_timezones_set
LazySet({'Africa/Abidjan',
'Africa/Accra',
'Africa/Addis_Ababa',
'Africa/Algiers',
'Africa/Asmara',
'Africa/Asmera',
...
'UTC',
'Universal',
'W-SU',
'WET',
'Zulu'})
First step:
pip uninstall numpy
pip uninstall opencv-python
Second step:
pip install numpy
pip install opencv-python
You can do this
textView.text = "Name: \(string1) \n" + "Phone Number: \(string2)"
The output will be
Name: output of string1 Phone Number: output of string2
I have created a generalised solution. The function below will change ids and names of cloned object. In most cases, you will need the row number so Just add "data-row-id" attribute to the object.
function renameCloneIdsAndNames( objClone ) {
if( !objClone.attr( 'data-row-id' ) ) {
console.error( 'Cloned object must have \'data-row-id\' attribute.' );
}
if( objClone.attr( 'id' ) ) {
objClone.attr( 'id', objClone.attr( 'id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } ) );
}
objClone.attr( 'data-row-id', objClone.attr( 'data-row-id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } ) );
objClone.find( '[id]' ).each( function() {
var strNewId = $( this ).attr( 'id' ).replace( /\d+$/, function( strId ) { return parseInt( strId ) + 1; } );
$( this ).attr( 'id', strNewId );
if( $( this ).attr( 'name' ) ) {
var strNewName = $( this ).attr( 'name' ).replace( /\[\d+\]/g, function( strName ) {
strName = strName.replace( /[\[\]']+/g, '' );
var intNumber = parseInt( strName ) + 1;
return '[' + intNumber + ']'
} );
$( this ).attr( 'name', strNewName );
}
});
return objClone;
}
You can also use translate(). If the third argument is too short, the corresponding characters from the second argument are deleted. Unlike regexp_replace() you don't need to worry about special characters. Source code.
If i understand you correctly then in c# the yield return
compiler magic is all you need i think.
e.g.
IEnumerable<string> myMethod(IEnumerable<string> sequence)
{
foreach(string item in sequence)
{
yield return item + "roxxors";
}
}
I came across this issue yesterday, but none of the solutions here worked exactly, however they did point me in the right direction.
Our application is a workflow tool written in C# and, overly simplified, has several stored procedures on the database, as well as a table of metadata about each parameter used by each stored procedure (name, order, data type, size, etc), allowing us to create as many new stored procedures as we need without having to change the C#.
Analysis of the problem showed that our code was setting all the correct parameters on the SqlCommand
object, however once it was executed, it threw the same error as the OP got.
Further analysis revealed that some parameters had a value of null
. I therefore must draw the conclusion that SqlCommand
objects ignore any SqlParameter
object in their .Parameters
collection with a value of null
.
There are two solutions to this problem that I found.
In our stored procedures, give a default value to each parameter, so from @Parameter int
to @Parameter int = NULL
(or some other default value as required).
In our code that generates the individual SqlParameter
objects, assigning DBNull.Value
instead of null
where the intended value is a SQL NULL
does the trick.
The original coder has moved on and the code was originally written with Solution 1 in mind, and having weighed up the benefits of both, I think I'll stick with Solution 1. It's much easier to specify a default value for a specific stored procedure when writing it, rather than it always being NULL
as defined in the code.
Hope that helps someone.
While pass by reference is nothing that fits well into python and should be rarely used there are some workarounds that actually can work to get the object currently assigned to a local variable or even reassign a local variable from inside of a called function.
The basic idea is to have a function that can do that access and can be passed as object into other functions or stored in a class.
One way is to use global
(for global variables) or nonlocal
(for local variables in a function) in a wrapper function.
def change(wrapper):
wrapper(7)
x = 5
def setter(val):
global x
x = val
print(x)
The same idea works for reading and del
eting a variable.
For just reading there is even a shorter way of just using lambda: x
which returns a callable that when called returns the current value of x. This is somewhat like "call by name" used in languages in the distant past.
Passing 3 wrappers to access a variable is a bit unwieldy so those can be wrapped into a class that has a proxy attribute:
class ByRef:
def __init__(self, r, w, d):
self._read = r
self._write = w
self._delete = d
def set(self, val):
self._write(val)
def get(self):
return self._read()
def remove(self):
self._delete()
wrapped = property(get, set, remove)
# left as an exercise for the reader: define set, get, remove as local functions using global / nonlocal
r = ByRef(get, set, remove)
r.wrapped = 15
Pythons "reflection" support makes it possible to get a object that is capable of reassigning a name/variable in a given scope without defining functions explicitly in that scope:
class ByRef:
def __init__(self, locs, name):
self._locs = locs
self._name = name
def set(self, val):
self._locs[self._name] = val
def get(self):
return self._locs[self._name]
def remove(self):
del self._locs[self._name]
wrapped = property(get, set, remove)
def change(x):
x.wrapped = 7
def test_me():
x = 6
print(x)
change(ByRef(locals(), "x"))
print(x)
Here the ByRef
class wraps a dictionary access. So attribute access to wrapped
is translated to a item access in the passed dictionary. By passing the result of the builtin locals
and the name of a local variable this ends up accessing a local variable. The python documentation as of 3.5 advises that changing the dictionary might not work but it seems to work for me.
Just because this sort of thing is fun for me, here are two more solutions.
Split into words, initial-cap each word from the split groups, and rejoin. This will change the white space separating the words into a single white space, no matter what it was.
s = 'the brown fox'
lst = [word[0].upper() + word[1:] for word in s.split()]
s = " ".join(lst)
EDIT: I don't remember what I was thinking back when I wrote the above code, but there is no need to build an explicit list; we can use a generator expression to do it in lazy fashion. So here is a better solution:
s = 'the brown fox'
s = ' '.join(word[0].upper() + word[1:] for word in s.split())
Use a regular expression to match the beginning of the string, or white space separating words, plus a single non-whitespace character; use parentheses to mark "match groups". Write a function that takes a match object, and returns the white space match group unchanged and the non-whitespace character match group in upper case. Then use re.sub()
to replace the patterns. This one does not have the punctuation problems of the first solution, nor does it redo the white space like my first solution. This one produces the best result.
import re
s = 'the brown fox'
def repl_func(m):
"""process regular expression match groups for word upper-casing problem"""
return m.group(1) + m.group(2).upper()
s = re.sub("(^|\s)(\S)", repl_func, s)
>>> re.sub("(^|\s)(\S)", repl_func, s)
"They're Bill's Friends From The UK"
I'm glad I researched this answer. I had no idea that re.sub()
could take a function! You can do nontrivial processing inside re.sub()
to produce the final result!
yum install -y yum-utils
yum-config-manager --add-repo http://repos.fedorapeople.org/repos/dchen/apache-maven/epel-apache-maven.repo
yum-config-manager --enable epel-apache-maven
yum install -y apache-maven
for JVM developer, this is a SDK manager for all the tool you need.
Install sdkman:
yum install -y zip unzip
curl -s "https://get.sdkman.io" | bash
source "$HOME/.sdkman/bin/sdkman-init.sh"
Install Maven:
sdk install maven
We can set the width for ul tag then it will align center.
#header ul {
display: block;
margin: 0 auto;
width: 420px;
max-width: 100%;
}
<T>
is a generic and can usually be read as "of type T". It depends on the type to the left of the <> what it actually means.
I don't know what a Pool
or PoolFactory
is, but you also mention ArrayList<T>
, which is a standard Java class, so I'll talk to that.
Usually, you won't see "T" in there, you'll see another type. So if you see ArrayList<Integer>
for example, that means "An ArrayList
of Integer
s." Many classes use generics to constrain the type of the elements in a container, for example. Another example is HashMap<String, Integer>
, which means "a map with String
keys and Integer
values."
Your Pool example is a bit different, because there you are defining a class. So in that case, you are creating a class that somebody else could instantiate with a particular type in place of T. For example, I could create an object of type Pool<String>
using your class definition. That would mean two things:
Pool<String>
would have an interface PoolFactory<String>
with a createObject
method that returns String
s.Pool<String>
would contain an ArrayList
of Strings.This is great news, because at another time, I could come along and create a Pool<Integer>
which would use the same code, but have Integer
wherever you see T
in the source.
This ended up being a 'user' issue with me. I had installed npm and node on the system logged in as user1, then I set-up user2. I could run node, and I could run npm commnds, but could not run any npm packages from the command line.
I uninstalled node and npm, and reinstalled under the correct user in order to solve the problem. After that I can run packages from the command-line without issue.
(Copy/paste of an answer I provided elsewhere)
Falling through switch
-case
s can be achieved by having no code in a case
(see case 0
), or using the special goto case
(see case 1
) or goto default
(see case 2
) forms:
switch (/*...*/) {
case 0: // shares the exact same code as case 1
case 1:
// do something
goto case 2;
case 2:
// do something else
goto default;
default:
// do something entirely different
break;
}
If MouseEvent.offsetX is supported by your browser (all major browsers actually support it), The jQuery Event object will contain this property.
The MouseEvent.offsetX read-only property provides the offset in the X coordinate of the mouse pointer between that event and the padding edge of the target node.
$("#seek-bar").click(function(event) {
var x = event.offsetX
alert(x);
});
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks Includes ExecCGI
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
AllowOverride All
#
# Controls who can get stuff from this server.
#
Require all granted
Write above code inside following tags < Directory "c:\projects" > < / Directory > c:(you can add any directory d: e:) is drive where you have created your project folder.
Alias /projects "c:\projects"
Now you can access the pr0jects directory on your browser :
localhost/projects/
These solutions totally make sense. Unfortunately, neither worked for me as expected. Instead of trying to hassle with it, I went with a work around:
select * from information_schema.columns
where replace(table_name,'_','!') not like '%!%'
order by table_name
RETURNING
Since PostgreSQL 8.2, that's possible with a single round-trip to the database:
INSERT INTO tbl(filename)
VALUES ('my_filename')
RETURNING tbl_id;
tbl_id
would typically be a serial
or IDENTITY
(Postgres 10 or later) column. More in the manual.
If filename
needs to include tbl_id
(redundantly), you can still use a single query.
Use lastval()
or the more specific currval()
:
INSERT INTO tbl (filename)
VALUES ('my_filename' || currval('tbl_tbl_id_seq') -- or lastval()
RETURNING tbl_id;
See:
If multiple sequences may be advanced in the process (even by way of triggers or other side effects) the sure way is to use currval('tbl_tbl_id_seq')
.
The string literal 'tbl_tbl_id_seq'
in my example is supposed to be the actual name of the sequence and is cast to regclass
, which raises an exception if no sequence of that name can be found in the current search_path
.
tbl_tbl_id_seq
is the automatically generated default for a table tbl
with a serial column tbl_id
. But there are no guarantees. A column default can fetch values from any sequence if so defined. And if the default name is taken when creating the table, Postgres picks the next free name according to a simple algorithm.
If you don't know the name of the sequence for a serial
column, use the dedicated function pg_get_serial_sequence()
. Can be done on the fly:
INSERT INTO tbl (filename)
VALUES ('my_filename' || currval(pg_get_serial_sequence('tbl', 'tbl_id'))
RETURNING tbl_id;
Initialization error occurred. There is not enough memory or disk space, or you entered an invalid drive name or invalid syntax on the command line.
So basically it could be just about anything haha...try running the command one at a time from the command prompt to figure out which part of which command is giving you trouble.
In the detached 'Tool Options' window, click on the red 'X' in the upper right corner to get rid of the window. Then on the main Gimp screen, click on 'Windows,' then 'Dockable Dialogs.' The first entry on its list will be 'Tool Options,' so click on that. Then, Tool Options will appear as a tab in the window on the right side of the screen, along with layers and undo history. Click and drag that tab over to the toolbox window on hte left and drop it inside. The tool options will again be docked in the toolbox.
Scikit-learn offers a function normalize()
that lets you apply various normalizations. The "make it sum to 1" is called L1-norm. Therefore:
from sklearn.preprocessing import normalize
matrix = numpy.arange(0,27,3).reshape(3,3).astype(numpy.float64)
# array([[ 0., 3., 6.],
# [ 9., 12., 15.],
# [ 18., 21., 24.]])
normed_matrix = normalize(matrix, axis=1, norm='l1')
# [[ 0. 0.33333333 0.66666667]
# [ 0.25 0.33333333 0.41666667]
# [ 0.28571429 0.33333333 0.38095238]]
Now your rows will sum to 1.
This code snippet worked for me. I have an issue with the parsing batch of XML files. I had to encode them to 'iso-8859-5'
import xml.etree.ElementTree as ET
tree = ET.parse(filename, parser = ET.XMLParser(encoding = 'iso-8859-5'))
As mentioned, for efficiency reasons sequential spaces are consolidated into one space the browser actually displays. Remember what the ML in HTML stand for. It's a Mark-up Language, designed to control how text is displayed.. not whitespace :p
Still, you can pretend the browser respects tabs since all the TAB does is prepend 4 spaces, and that's easy with CSS. either in line like ...
<div style="padding-left:4.00em;">Indenented text </div>
Or as a regular class in a style sheet
.tabbed {padding-left:4.00em;}
Then the HTML might look like
<p>regular paragraph regular paragraph regular paragraph</p>
<p class="tabbed">Indented text Indented text Indented text</p>
<p>regular paragraph regular paragraph regular paragraph</p>
How can I create a list without defining a class type? (
<Employee>
)
If I'm reading this correctly, you just want to avoid having to specify the type, correct?
In Java 7, you can do
List<Employee> list = new ArrayList<>();
but any of the other alternatives being discussed are just going to sacrifice type safety.
To update this for Python-3 you can do this
"{} {}".format(True, False)
However if you want to actually format the string (e.g. add white space), you encounter Python casting the boolean into the underlying C value (i.e. an int), e.g.
>>> "{:<8} {}".format(True, False)
'1 False'
To get around this you can cast True
as a string, e.g.
>>> "{:<8} {}".format(str(True), False)
'True False'
I know this is old, but the best option is to now use the new placeholder
HTML attribute if possible:
<input type="text" id="userid" name="userid" placeholder="Please enter the user ID" />
This will cause the text to show unless a value is entered, eliminating the need to select text or clear inputs.
$qry = "DELETE lg., l. FROM lessons_game lg RIGHT JOIN lessons l ON lg.lesson_id = l.id WHERE l.id = ?";
lessons is Main table and lessons_game is subtable so Right Join
It is possible with EditorConfig.
EditorConfig helps developers define and maintain consistent coding styles between different editors and IDEs.
This also includes file encoding.
EditorConfig is built-in Visual Studio 2017 by default, and I there were plugins available for versions as old as VS2012. Read more from EditorConfig Visual Studio Plugin page.
You can set up a EditorConfig configuration file high enough in your folder structure to span all your intended repos (up to your drive root should your files be really scattered everywhere) and configure the setting charset
:
charset: set to latin1, utf-8, utf-8-bom, utf-16be or utf-16le to control the character set.
You can add filters and exceptions etc on every folder level or by file name/type should you wish for finer control.
Once configured then compatible IDEs should automatically do it's thing to make matching files comform to set rules. Note that Visual Studio does not automatically convert all your files but do its bit when you work with files in IDE (open and save).
While you could have a Visual-studio-wide setup, I strongly suggest to still include an EditorConfig root to your solution version control, so that explicit settings are automatically synced to all team members as well. Your drive root editorconfig file can be the fallback should some project not have their own editorconfig files set up yet.
Here are my favorites:
Dependency:
<dependency>
<groupId>org.apache.any23</groupId>
<artifactId>apache-any23-encoding</artifactId>
<version>1.1</version>
</dependency>
Sample:
public static Charset guessCharset(InputStream is) throws IOException {
return Charset.forName(new TikaEncodingDetector().guessEncoding(is));
}
Dependency:
<dependency>
<groupId>org.codehaus.guessencoding</groupId>
<artifactId>guessencoding</artifactId>
<version>1.4</version>
<type>jar</type>
</dependency>
Sample:
public static Charset guessCharset2(File file) throws IOException {
return CharsetToolkit.guessEncoding(file, 4096, StandardCharsets.UTF_8);
}
Wrap the iframe in a class, float that left.
The paragraph with then be forced up and to the right as long as there is room for it. Then set your paragraph to display:inline-block, and add some left margin to tidy it up.
<div class="left">
<img src="http://lorempixel.com/300/300" /> <!--placeholder for iframe-->
</div>
<p>Lorem Paragraph Text</p>
.left { float: left; }
p { display: inline-block; margin-left: 30px; }
Here's a fiddle: http://jsfiddle.net/4DACH/
function my_url (base, opt)
{
var retval = ["" + base];
retval.push( opt.page_name ? "&page_name=" + opt.page_name : "");
retval.push( opt.table_name ? "&table_name=" + opt.table_name : "");
retval.push( opt.optionResult ? "&optionResult=" + opt.optionResult : "");
return retval.join("");
}
my_url("?z=z", { page_name : "pageX" /* no table_name and optionResult */ } );
/* Returns:
?z=z&page_name=pageX
*/
This avoids using typeof whatever === "undefined"
. (Also, there isn't any string concatenation.)
There's no notion of hosts or ip-addresses in the javascript standard library. So you'll have to access some external service to look up hostnames for you.
I recommend hosting a cgi-bin which looks up the ip-address of a hostname and access that via javascript.
To be able to give it input without it closing as well you could enclose the code in a while loop
while (true)
{
<INSERT CODE HERE>
}
It will continue to halt at Console.ReadLine();
, then do another loop when you input something.
BufferedImage in = ImageIO.read(img);
BufferedImage newImage = new BufferedImage(
in.getWidth(), in.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g = newImage.createGraphics();
g.drawImage(in, 0, 0, null);
g.dispose();
Since you are using Access to compose the query, you have to stick to Access's version of SQL.
To choose between several different return values, use the switch() function. So to translate and extend your example a bit:
select switch(
age > 40, 4,
age > 25, 3,
age > 20, 2,
age > 10, 1,
true, 0
) from demo
The 'true' case is the default one. If you don't have it and none of the other cases match, the function will return null.
The Office website has documentation on this but their example syntax is VBA and it's also wrong. I've given them feedback on this but you should be fine following the above example.
Use numpy.concatenate(list1 , list2)
or numpy.append()
Look into the thread at Append a NumPy array to a NumPy array.
SELECT t1.a, t2.b
FROM t1
JOIN t2 ON t1.a LIKE '%'+t2.b +'%'
because the last answer not work
Is there a specific reason you want to use FileNameExtensionFilter
? I know this works..
private File[] getNewTextFiles() {
return dir.listFiles(new FilenameFilter() {
@Override
public boolean accept(File dir, String name) {
return name.toLowerCase().endsWith(".txt");
}
});
}
os.walk
does recursive walk by default. For each dir, starting from root it yields a 3-tuple (dirpath, dirnames, filenames)
from os import walk
from os.path import splitext, join
def select_files(root, files):
"""
simple logic here to filter out interesting files
.py files in this example
"""
selected_files = []
for file in files:
#do concatenation here to get full path
full_path = join(root, file)
ext = splitext(file)[1]
if ext == ".py":
selected_files.append(full_path)
return selected_files
def build_recursive_dir_tree(path):
"""
path - where to begin folder scan
"""
selected_files = []
for root, dirs, files in walk(path):
selected_files += select_files(root, files)
return selected_files
If you are using Bootstrap responsive table, just want to set the maximum width for one particular column and make text wrapping, making the the style of this column as following also works
max-width:someValue;
word-wrap:break-word
webDriver.findElement(By.xpath("//a[@href='/docs/configuration']")).click();
The above line works fine. Please remove the space after href.
Is that element is visible in the page, if the element is not visible please scroll down the page then perform click action.
The method Class.forName()
is used to register the JDBC driver. A connection string is used to retrieve the connection to the database.
The way to retrieve the connection to the database is shown below. Ideally since you do not want to create multiple connections to the database, limit the connections to one and re-use the same connection. Therefore use the singleton pattern here when handling connections to the database.
Shown Below shows a connection string with the retrieval of the connection:
public class Database {
private String URL = "jdbc:mysql://localhost:3306/your_db_name"; //database url
private String username = ""; //database username
private String password = ""; //database password
private static Database theDatabase = new Database();
private Connection theConnection;
private Database(){
try{
Class.forName("com.mysql.jdbc.Driver"); //setting classname of JDBC Driver
this.theConnection = DriverManager.getConnection(URL, username, password);
} catch(Exception ex){
System.out.println("Error Connecting to Database: "+ex);
}
}
public static Database getDatabaseInstance(){
return theDatabase;
}
public Connection getTheConnectionObject(){
return theConnection;
}
}
As @arpanmangal, the solutions above do not work for me (matplotlib 3.0.3
, python 3.5.2
).
It seems that using .show()
in a figure, e.g., figure.show()
, is not recommended, because this method does not manage a GUI event loop and therefore the figure is just shown briefly. (See figure.show() documentation). However, I do not find any another way to show only a figure.
In my solution I get to prevent the figure for instantly closing by using click events. We do not have to close the figure — closing the figure deletes it.
I present two options:
- waitforbuttonpress(timeout=-1)
will close the figure window when clicking on the figure, so we cannot use some window functions like zooming.
- ginput(n=-1,show_clicks=False)
will wait until we close the window, but it releases an error :-.
import matplotlib.pyplot as plt
fig1, ax1 = plt.subplots(1) # Creates figure fig1 and add an axes, ax1
fig2, ax2 = plt.subplots(1) # Another figure fig2 and add an axes, ax2
ax1.plot(range(20),c='red') #Add a red straight line to the axes of fig1.
ax2.plot(range(100),c='blue') #Add a blue straight line to the axes of fig2.
#Option1: This command will hold the window of fig2 open until you click on the figure
fig2.waitforbuttonpress(timeout=-1) #Alternatively, use fig1
#Option2: This command will hold the window open until you close the window, but
#it releases an error.
#fig2.ginput(n=-1,show_clicks=False) #Alternatively, use fig1
#We show only fig2
fig2.show() #Alternatively, use fig1
a = 10 * [0]
gives you an array of length 10, filled with zeroes.
Assuming that you already downloaded chromeDriver, this error is also occurs when already multiple chrome tabs are open.
If you close all tabs and run again, the error should clear up.
I think what you have missed here is this:
https://maven.apache.org/settings.html#Servers
The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml.
This is the prefered way of using custom repos. So probably what is happening is that the url of this repo is in settings.xml of the build server.
Once you get hold of the url and credentials, you can put them in your machine here: ~/.m2/settings.xml
like this:
<settings ...>
.
.
.
<servers>
<server>
<id>internal-repository-group</id>
<username>YOUR-USERNAME-HERE</username>
<password>YOUR-PASSWORD-HERE</password>
</server>
</servers>
</settings>
EDIT:
You then need to refer this repository into project POM. The id internal-repository-group can be used in every project. You can setup multiple repos and credentials setting using different IDs in settings xml.
The advantage of this approach is that project can be shared without worrying about the credentials and don't have to mention the credentials in every project.
Following is a sample pom of a project using "internal-repository-group"
<repositories>
<repository>
<id>internal-repository-group</id>
<name>repo-name</name>
<url>http://project.com/yourrepourl/</url>
<layout>default</layout>
<releases>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</snapshots>
</repository>
</repositories>
You can use formControlName
only on directives which implement ControlValueAccessor
.
So, in order to do what you want, you have to create a component which implements ControlValueAccessor
, which means implementing the following three functions:
writeValue
(tells Angular how to write value from model into view)registerOnChange
(registers a handler function that is called when the view changes)registerOnTouched
(registers a handler to be called when the component receives a touch event, useful for knowing if the component has been focused).Then, you have to tell Angular that this directive is a ControlValueAccessor
(interface is not gonna cut it since it is stripped from the code when TypeScript is compiled to JavaScript). You do this by registering a provider.
The provider should provide NG_VALUE_ACCESSOR
and use an existing value. You'll also need a forwardRef
here. Note that NG_VALUE_ACCESSOR
should be a multi provider.
For example, if your custom directive is named MyControlComponent, you should add something along the following lines inside the object passed to @Component
decorator:
providers: [
{
provide: NG_VALUE_ACCESSOR,
multi: true,
useExisting: forwardRef(() => MyControlComponent),
}
]
Your component is ready to be used. With template-driven forms, ngModel
binding will now work properly.
With reactive forms, you can now properly use formControlName
and the form control will behave as expected.
I'v been used following code in IE. (IE8 compatible)
var dString = "2013.2.4";
var myDate = new Date( dString.replace(/(\d+)\.(\d+)\.(\d+)/,"$2/$3/$1") );
alert( "my date:"+ myDate );
If you have web services, check your URL pointing to the service. I had a simular issue which was fixed when I changed my web service URL.
Last three characters of string
:
${string: -3}
or
${string:(-3)}
(mind the space between :
and -3
in the first form).
Please refer to the Shell Parameter Expansion in the reference manual:
${parameter:offset}
${parameter:offset:length}
Expands to up to length characters of parameter starting at the character
specified by offset. If length is omitted, expands to the substring of parameter
starting at the character specified by offset. length and offset are arithmetic
expressions (see Shell Arithmetic). This is referred to as Substring Expansion.
If offset evaluates to a number less than zero, the value is used as an offset
from the end of the value of parameter. If length evaluates to a number less than
zero, and parameter is not ‘@’ and not an indexed or associative array, it is
interpreted as an offset from the end of the value of parameter rather than a
number of characters, and the expansion is the characters between the two
offsets. If parameter is ‘@’, the result is length positional parameters
beginning at offset. If parameter is an indexed array name subscripted by ‘@’ or
‘*’, the result is the length members of the array beginning with
${parameter[offset]}. A negative offset is taken relative to one greater than the
maximum index of the specified array. Substring expansion applied to an
associative array produces undefined results.
Note that a negative offset must be separated from the colon by at least one
space to avoid being confused with the ‘:-’ expansion. Substring indexing is
zero-based unless the positional parameters are used, in which case the indexing
starts at 1 by default. If offset is 0, and the positional parameters are used,
$@ is prefixed to the list.
Since this answer gets a few regular views, let me add a possibility to address John Rix's comment; as he mentions, if your string has length less than 3, ${string: -3}
expands to the empty string. If, in this case, you want the expansion of string
, you may use:
${string:${#string}<3?0:-3}
This uses the ?:
ternary if operator, that may be used in Shell Arithmetic; since as documented, the offset is an arithmetic expression, this is valid.
The previous part gives the best option when using Bash. If you want to target POSIX shells, here's an option (that doesn't use pipes or external tools like cut
):
# New variable with 3 last characters removed
prefix=${string%???}
# The new string is obtained by removing the prefix a from string
newstring=${string#"$prefix"}
One of the main things to observe here is the use of quoting for prefix
inside the parameter expansion. This is mentioned in the POSIX ref (at the end of the section):
The following four varieties of parameter expansion provide for substring processing. In each case, pattern matching notation (see Pattern Matching Notation), rather than regular expression notation, shall be used to evaluate the patterns. If parameter is '#', '*', or '@', the result of the expansion is unspecified. If parameter is unset and set -u is in effect, the expansion shall fail. Enclosing the full parameter expansion string in double-quotes shall not cause the following four varieties of pattern characters to be quoted, whereas quoting characters within the braces shall have this effect. In each variety, if word is omitted, the empty pattern shall be used.
This is important if your string contains special characters. E.g. (in dash),
$ string="hello*ext"
$ prefix=${string%???}
$ # Without quotes (WRONG)
$ echo "${string#$prefix}"
*ext
$ # With quotes (CORRECT)
$ echo "${string#"$prefix"}"
ext
Of course, this is usable only when then number of characters is known in advance, as you have to hardcode the number of ?
in the parameter expansion; but when it's the case, it's a good portable solution.
This is really old, but <font size="10">
would be about <p style= "font-size:55px">
It was my regex: @"^(?=.{3,15}$)(?:(?:\p{L}|\p{N})[._()\[\]-]?)*$"
I just added ([\w ]+)
at the end of my regex before *
@"^(?=.{3,15}$)(?:(?:\p{L}|\p{N})[._()\[\]-]?)([\w ]+)*$"
Now string is allowed to have spaces.
If someone is using react, following will be useful:
https://stackoverflow.com/a/62111884/1015678
const valueSetter = Object.getOwnPropertyDescriptor(this.textInputRef, 'value').set;
const prototype = Object.getPrototypeOf(this.textInputRef);
const prototypeValueSetter = Object.getOwnPropertyDescriptor(prototype, 'value').set;
if (valueSetter && valueSetter !== prototypeValueSetter) {
prototypeValueSetter.call(this.textInputRef, 'new value');
} else {
valueSetter.call(this.textInputRef, 'new value');
}
this.textInputRef.dispatchEvent(new Event('input', { bubbles: true }));
Try this:
Rect rect = new Rect();
Window win = this.getWindow();
win.getDecorView().getWindowVisibleDisplayFrame(rect);
int statusBarHeight = rect.top;
int contentViewTop = win.findViewById(Window.ID_ANDROID_CONTENT).getTop();
int titleBarHeight = contentViewTop - statusBarHeight;
Log.d("ID-ANDROID-CONTENT", "titleBarHeight = " + titleBarHeight );
it didn't work for me in the onCreate method for the activity, but did when I put it in an onClickListener and gave me a measurement of 25
OK, so I found the answer from http://binglongx.wordpress.com/2009/01/26/visual-c-does-not-generate-lib-file-for-a-dll-project/ says that this problem was caused by not exporting any symbols and further instructs on how to export symbols to create the lib file. To do so, add the following code to your .h file for your DLL.
#ifdef BARNABY_EXPORTS
#define BARNABY_API __declspec(dllexport)
#else
#define BARNABY_API __declspec(dllimport)
#endif
Where BARNABY_EXPORTS and BARNABY_API are unique definitions for your project. Then, each function you export you simply precede by:
BARNABY_API int add(){
}
This problem could have been prevented either by clicking the Export Symbols box on the new project DLL Wizard or by voting yes for lobotomies for computer programmers.
To remove the "keep-alive" header in requests, I just created it from the Request object and then send it with Session
headers = {
'Host' : '1.2.3.4',
'User-Agent' : 'Test client (x86_64-pc-linux-gnu 7.16.3)',
'Accept' : '*/*',
'Accept-Encoding' : 'deflate, gzip',
'Accept-Language' : 'it_IT'
}
url = "https://stream.twitter.com/1/statuses/filter.json"
#r = requests.get(url, headers = headers) #this triggers keep-alive: True
s = requests.Session()
r = requests.Request('GET', url, headers)
If jQuery's error handler is being called and the XHR object contains "parser error", that's probably a parser error coming back from the server.
Is your multiple result scenario when you call the service without a parameter, but it's breaking when you try to supply a parameter to retrieve the single record?
What backend are you returning this from?
On ASMX services, for example, that's often the case when parameters are supplied to jQuery as a JSON object instead of a JSON string. If you provide jQuery an actual JSON object for its "data" parameter, it will serialize that into standard & delimited k,v pairs instead of sending it as JSON.
@Dagon had the right idea but was a little short on details.
If you use the access 127.0.0.1/phpmyadmin
and have a close look at the Users that are setup in MysQL you should see 3 versions of the root
username.
This is because in MySQL each userid is associated with a HOST, i.e. The PC ( ip address ) that the user is allowed to sign in from. So your 3 `'root' userids are in fact the same userid which is allowed to signin from 3 seperate HOSTS. Normally out of the box the 'root' has 3 HOSTS setup, 127.0.0.1, localhost and ::1
These are :-
localhost is an alias for THIS MACHINE created from your HOSTS file ( c:\windows\system32\drivers\etc\hosts )
127.0.0.1 is the IPv4 loopback ip address of THIS MACHINE
::1 is the IPv6 loopback ip address of THIS MACHINE
What is probably happening to you is that you have set a password for [email protected] but not any of the others. Now your browser will 'arbtrarily' decide to use ::1 or 127.0.0.1 as the host ip so when it uses ::1 your login will fail.
So login using 127.0.0.1/phpmyadmin
and change all 3 'root' usernames to have the same password you should no longer see this problem.
Also make sure that your HOSTS file has these 2 entries
127.0.0.1 localhost
::1 localhost
You don't need to configure anything. Just make sure that the requests map to your PHP file and use requests with path info. For example, if you have in the root a file named handler.php
with this content:
<?php
var_dump($_SERVER['REQUEST_METHOD']);
var_dump($_SERVER['REQUEST_URI']);
var_dump($_SERVER['PATH_INFO']);
if (($stream = fopen('php://input', "r")) !== FALSE)
var_dump(stream_get_contents($stream));
The following HTTP request would work:
Established connection with 127.0.0.1 on port 81
PUT /handler.php/bla/foo HTTP/1.1
Host: localhost:81
Content-length: 5
boo
HTTP/1.1 200 OK
Date: Sat, 29 May 2010 16:00:20 GMT
Server: Apache/2.2.13 (Win32) PHP/5.3.0
X-Powered-By: PHP/5.3.0
Content-Length: 89
Content-Type: text/html
string(3) "PUT"
string(20) "/handler.php/bla/foo"
string(8) "/bla/foo"
string(5) "boo
"
Connection closed remotely.
You can hide the "php" extension with MultiViews or you can make URLs completely logical with mod_rewrite.
See also the documentation for the AcceptPathInfo directive and this question on how to make PHP not parse POST data when enctype is multipart/form-data
.
I'm going to assume you are using Web Site Projects. These automatically crawl their project directory and throw everything into source control. There's no way to stop them.
However, don't despair. Web Application Projects don't exhibit this strange and rather unexpected (imho: moronic) behavior. WAP is an addon on for VS2005 and comes direct with VS2008.
As an alternative to changing your projects to WAP, you might consider moving the Assets folder out of Source control and into a TFS Document Library. Only do this IF the project itself doesn't directly use the assets files.
This will probably have some performance costs when creating the connection but as connections are pooled, they are created only once and then reused, so it won't make any difference to your application. But as always: measure it.
UPDATE:
There are two authentication modes:
You module and class AthleteList
have the same name. Change:
import AthleteList
to:
from AthleteList import AthleteList
This now means that you are importing the module object and will not be able to access any module methods you have in AthleteList
Using modern --inspect with node the console.log is captured and relayed to the browser.
node --inspect myApp.js
or to capture early logging --inspect-brk can be used to stop the program on the first line of the first module...
node --inspect-brk myApp.js
If you have a List of type string that you want in a drop down list I do the following:
EDIT: Clarified, making it a fuller example.
public class ShipDirectory
{
public string ShipDirectoryName { get; set; }
public List<string> ShipNames { get; set; }
}
ShipDirectory myShipDirectory = new ShipDirectory()
{
ShipDirectoryName = "Incomming Vessels",
ShipNames = new List<string>(){"A", "A B"},
}
myShipDirectory.ShipNames.Add("Aunt Bessy");
@Html.DropDownListFor(x => x.ShipNames, new SelectList(Model.ShipNames), "Select a Ship...", new { @style = "width:500px" })
Which gives a drop down list like so:
<select id="ShipNames" name="ShipNames" style="width:500px">
<option value="">Select a Ship...</option>
<option>A</option>
<option>A B</option>
<option>Aunt Bessy</option>
</select>
To get the value on a controllers post; if you are using a model (e.g. MyViewModel) that has the List of strings as a property, because you have specified x => x.ShipNames you simply have the method signature as (because it will be serialised/deserialsed within the model):
public ActionResult MyActionName(MyViewModel model)
Access the ShipNames value like so: model.ShipNames
If you just want to access the drop down list on post then the signature becomes:
public ActionResult MyActionName(string ShipNames)
EDIT: In accordance with comments have clarified how to access the ShipNames property in the model collection parameter.
Building on Iain's example, I had a similar need to compose these emails with separate plaintext, HTML and multiple attachments, but using PHP. Since we are using Amazon SES to send emails with attachments, the API currently requires you to build the email from scratch using the sendRawEmail(...) function.
After much investigation (and greater than normal frustration), the problem was solved and the PHP source code posted so that it may help others experiencing a similar problem. Hope this help someone out - the troop of monkeys I forced to work on this problem are now exhausted.
PHP Source Code for sending emails with attachments using Amazon SES.
<?php
require_once('AWSSDKforPHP/aws.phar');
use Aws\Ses\SesClient;
/**
* SESUtils is a tool to make it easier to work with Amazon Simple Email Service
* Features:
* A client to prepare emails for use with sending attachments or not
*
* There is no warranty - use this code at your own risk.
* @author sbossen with assistance from Michael Deal
* http://righthandedmonkey.com
*
* Update: Error checking and new params input array provided by Michael Deal
* Update2: Corrected for allowing to send multiple attachments and plain text/html body
* Ref: Http://stackoverflow.com/questions/3902455/smtp-multipart-alternative-vs-multipart-mixed/
*/
class SESUtils {
const version = "1.0";
const AWS_KEY = "YOUR-KEY";
const AWS_SEC = "YOUR-SECRET";
const AWS_REGION = "us-east-1";
const MAX_ATTACHMENT_NAME_LEN = 60;
/**
* Usage:
$params = array(
"to" => "[email protected]",
"subject" => "Some subject",
"message" => "<strong>Some email body</strong>",
"from" => "sender@verifiedbyaws",
//OPTIONAL
"replyTo" => "[email protected]",
//OPTIONAL
"files" => array(
1 => array(
"name" => "filename1",
"filepath" => "/path/to/file1.txt",
"mime" => "application/octet-stream"
),
2 => array(
"name" => "filename2",
"filepath" => "/path/to/file2.txt",
"mime" => "application/octet-stream"
),
)
);
$res = SESUtils::sendMail($params);
* NOTE: When sending a single file, omit the key (ie. the '1 =>')
* or use 0 => array(...) - otherwise the file will come out garbled
* ie. use:
* "files" => array(
* 0 => array( "name" => "filename", "filepath" => "path/to/file.txt",
* "mime" => "application/octet-stream")
*
* For the 'to' parameter, you can send multiple recipiants with an array
* "to" => array("[email protected]", "[email protected]")
* use $res->success to check if it was successful
* use $res->message_id to check later with Amazon for further processing
* use $res->result_text to look for error text if the task was not successful
*
* @param array $params - array of parameters for the email
* @return \ResultHelper
*/
public static function sendMail($params) {
$to = self::getParam($params, 'to', true);
$subject = self::getParam($params, 'subject', true);
$body = self::getParam($params, 'message', true);
$from = self::getParam($params, 'from', true);
$replyTo = self::getParam($params, 'replyTo');
$files = self::getParam($params, 'files');
$res = new ResultHelper();
// get the client ready
$client = SesClient::factory(array(
'key' => self::AWS_KEY,
'secret' => self::AWS_SEC,
'region' => self::AWS_REGION
));
// build the message
if (is_array($to)) {
$to_str = rtrim(implode(',', $to), ',');
} else {
$to_str = $to;
}
$msg = "To: $to_str\n";
$msg .= "From: $from\n";
if ($replyTo) {
$msg .= "Reply-To: $replyTo\n";
}
// in case you have funny characters in the subject
$subject = mb_encode_mimeheader($subject, 'UTF-8');
$msg .= "Subject: $subject\n";
$msg .= "MIME-Version: 1.0\n";
$msg .= "Content-Type: multipart/mixed;\n";
$boundary = uniqid("_Part_".time(), true); //random unique string
$boundary2 = uniqid("_Part2_".time(), true); //random unique string
$msg .= " boundary=\"$boundary\"\n";
$msg .= "\n";
// now the actual body
$msg .= "--$boundary\n";
//since we are sending text and html emails with multiple attachments
//we must use a combination of mixed and alternative boundaries
//hence the use of boundary and boundary2
$msg .= "Content-Type: multipart/alternative;\n";
$msg .= " boundary=\"$boundary2\"\n";
$msg .= "\n";
$msg .= "--$boundary2\n";
// first, the plain text
$msg .= "Content-Type: text/plain; charset=utf-8\n";
$msg .= "Content-Transfer-Encoding: 7bit\n";
$msg .= "\n";
$msg .= strip_tags($body); //remove any HTML tags
$msg .= "\n";
// now, the html text
$msg .= "--$boundary2\n";
$msg .= "Content-Type: text/html; charset=utf-8\n";
$msg .= "Content-Transfer-Encoding: 7bit\n";
$msg .= "\n";
$msg .= $body;
$msg .= "\n";
$msg .= "--$boundary2--\n";
// add attachments
if (is_array($files)) {
$count = count($files);
foreach ($files as $file) {
$msg .= "\n";
$msg .= "--$boundary\n";
$msg .= "Content-Transfer-Encoding: base64\n";
$clean_filename = self::clean_filename($file["name"], self::MAX_ATTACHMENT_NAME_LEN);
$msg .= "Content-Type: {$file['mime']}; name=$clean_filename;\n";
$msg .= "Content-Disposition: attachment; filename=$clean_filename;\n";
$msg .= "\n";
$msg .= base64_encode(file_get_contents($file['filepath']));
$msg .= "\n--$boundary";
}
// close email
$msg .= "--\n";
}
// now send the email out
try {
$ses_result = $client->sendRawEmail(
array(
'RawMessage' => array(
'Data' => base64_encode($msg)
)
), array(
'Source' => $from,
'Destinations' => $to_str
)
);
if ($ses_result) {
$res->message_id = $ses_result->get('MessageId');
} else {
$res->success = false;
$res->result_text = "Amazon SES did not return a MessageId";
}
} catch (Exception $e) {
$res->success = false;
$res->result_text = $e->getMessage().
" - To: $to_str, Sender: $from, Subject: $subject";
}
return $res;
}
private static function getParam($params, $param, $required = false) {
$value = isset($params[$param]) ? $params[$param] : null;
if ($required && empty($value)) {
throw new Exception('"'.$param.'" parameter is required.');
} else {
return $value;
}
}
/**
Clean filename function - to get a file friendly
**/
public static function clean_filename($str, $limit = 0, $replace=array(), $delimiter='-') {
if( !empty($replace) ) {
$str = str_replace((array)$replace, ' ', $str);
}
$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
$clean = preg_replace("/[^a-zA-Z0-9\.\/_| -]/", '', $clean);
$clean = preg_replace("/[\/| -]+/", '-', $clean);
if ($limit > 0) {
//don't truncate file extension
$arr = explode(".", $clean);
$size = count($arr);
$base = "";
$ext = "";
if ($size > 0) {
for ($i = 0; $i < $size; $i++) {
if ($i < $size - 1) { //if it's not the last item, add to $bn
$base .= $arr[$i];
//if next one isn't last, add a dot
if ($i < $size - 2)
$base .= ".";
} else {
if ($i > 0)
$ext = ".";
$ext .= $arr[$i];
}
}
}
$bn_size = mb_strlen($base);
$ex_size = mb_strlen($ext);
$bn_new = mb_substr($base, 0, $limit - $ex_size);
// doing again in case extension is long
$clean = mb_substr($bn_new.$ext, 0, $limit);
}
return $clean;
}
}
class ResultHelper {
public $success = true;
public $result_text = "";
public $message_id = "";
}
?>
I was having the same problem until I read Jon Skeet's answer about the debugger displaying a single backslash with a double backslash even though the string may have a single backslash. I was not aware of that. So I changed my code from
text2 = text1.Replace(@"\\", @"/");
to
text2 = text1.Replace(@"\", @"/");
and that solved the problem. Note: I'm interfacing and R.Net which uses single forward slashes in path strings.
I suggest to follow the documentation and create ~/.pip/pip.conf file. Note in the documentation there are missing specified header directory, which leads to following error:
error: install-base or install-platbase supplied, but installation scheme is incomplete
The full working content of conf file is:
[install]
install-base=$HOME
install-purelib=python/lib
install-platlib=python/lib.$PLAT
install-scripts=python/scripts
install-headers=python/include
install-data=python/data
Unfortunatelly I can install, but when try to uninstall pip tells me there is no such package for uninstallation process.... so something is still wrong but the package goes to its predefined location.
Like the other answer says, in the left hand side select Products and add product. Then select Facbook Login.
I then added http://localhost:3000/ to the field 'Valid OAuth redirect URIs', and then everything worked.
Coming from someone who has tried a number of "C# IDEs" on the Mac, your best bet is to install a virtual desktop with Windows and Visual Studio. It really is the best development IDE out there for .NET, nothing even comes close.
On a related note: I hate XCode.
Update: Use Xamarin Studio. It's solid.
use appcmd to export one or all the sites out then reimport into the new server. It could be iis7.0 or 7.5 When you export out using appcmd, the passwords are decrypted, then reimport and they will reencrypt.
I had same issue with VMWare 12.5.2 and OS: Mac OS Sierra.
These are few steps to solve this issue:(which worked for me.)
There you go. It will work. Now you can power on your virtual machine.And try to connect your device with proper USB cable. Sometimes there can be issue with USB cable which are not authorized. Still if you have doubt, you can ask me here.
The real question is do you need to use historical data and active data together for reporting? If so keep them in one table, partition and create a view for active records to use in active queries. If you only need to look at them occasionally (to research leagal issues or some such) then put them in a separate table.
I also have same problem.. I tried everything solution in google, but still error.
But, now i resolved it.
I've resolved with make give double slash like that:
//$cfg['Servers'][1]['table_uiprefs'] = 'pma__table_uiprefs';
It works!!
Maybe the sample is oversimplified, but you don't need the Java stream API here. Just use the Map directly.
List<String> list1 = id1.get(1); // this will return the list from your map
My case it solved i was using
@Html.DropDownList(model => model.TypeId ...)
using
@Html.DropDownListFor(model => model.TypeId ...)
will solve it
Copy code using clone and appendTo function :
Here is also working example jsfiddle
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<div id="copy"><a href="http://brightwaay.com">Here</a> </div>
<br/>
<div id="copied"></div>
<script type="text/javascript">
$(function(){
$('#copy').clone().appendTo('#copied');
});
</script>
</body>
</html>
Our team uses dropbox for ad-hoc distribution which uses https but still our app was failing to install. After much trouble-shooting we realized that the title field is required too. Whenever we sent out a link without this field safari ignored the link and did not prompt the user to install. Sometimes for quick development tests we skipped over the title node in the xml and not populate it. In case this is helpful for anyone having this issue make sure that your .plist contains the following nodes populated:
....
<string>software</string>
<key>title</key>
<string>Your App Name</string>
...
use RowDataBound
function to bind data with a perticular cell, and to get control use
(ASP Control Name like DropDownList) GridView.FindControl("Name of Control")
If the dicts have identical sets of keys and you need all those prints for any value difference, there isn't much you can do; maybe something like:
diffkeys = [k for k in dict1 if dict1[k] != dict2[k]]
for k in diffkeys:
print k, ':', dict1[k], '->', dict2[k]
pretty much equivalent to what you have, but you might get nicer presentation for example by sorting diffkeys before you loop on it.
In my case conda Path was properly set (in .bashrc) by the conda installation bash. But to make it works I had to give executable file permissions to files in bin sub folder with chmod +x *
.
My system info:
conda 4.2.9
Operating System: Debian GNU/Linux 8 (jessie)
Kernel: Linux 3.16.0-4-amd64
Architecture: x86-64
exec
is not an expression: a statement in Python 2.x, and a function in Python 3.x. It compiles and immediately evaluates a statement or set of statement contained in a string. Example:
exec('print(5)') # prints 5.
# exec 'print 5' if you use Python 2.x, nor the exec neither the print is a function there
exec('print(5)\nprint(6)') # prints 5{newline}6.
exec('if True: print(6)') # prints 6.
exec('5') # does nothing and returns nothing.
eval
is a built-in function (not a statement), which evaluates an expression and returns the value that expression produces. Example:
x = eval('5') # x <- 5
x = eval('%d + 6' % x) # x <- 11
x = eval('abs(%d)' % -100) # x <- 100
x = eval('x = 5') # INVALID; assignment is not an expression.
x = eval('if 1: x = 4') # INVALID; if is a statement, not an expression.
compile
is a lower level version of exec
and eval
. It does not execute or evaluate your statements or expressions, but returns a code object that can do it. The modes are as follows:
compile(string, '', 'eval')
returns the code object that would have been executed had you done eval(string)
. Note that you cannot use statements in this mode; only a (single) expression is valid.
compile(string, '', 'exec')
returns the code object that would have been executed had you done exec(string)
. You can use any number of statements here.
compile(string, '', 'single')
is like the exec
mode but expects exactly one expression/statement, eg compile('a=1 if 1 else 3', 'myf', mode='single')
I do it like Bradley Braithwaite suggests in his blog:
app
.factory('searchService', ['$q', '$http', function($q, $http) {
var service = {};
service.search = function search(query) {
// We make use of Angular's $q library to create the deferred instance
var deferred = $q.defer();
$http
.get('http://localhost/v1?=q' + query)
.success(function(data) {
// The promise is resolved once the HTTP call is successful.
deferred.resolve(data);
})
.error(function(reason) {
// The promise is rejected if there is an error with the HTTP call.
deferred.reject(reason);
});
// The promise is returned to the caller
return deferred.promise;
};
return service;
}])
.controller('SearchController', ['$scope', 'searchService', function($scope, searchService) {
// The search service returns a promise API
searchService
.search($scope.query)
.then(function(data) {
// This is set when the promise is resolved.
$scope.results = data;
})
.catch(function(reason) {
// This is set in the event of an error.
$scope.error = 'There has been an error: ' + reason;
});
}])
Key Points:
The resolve function links to the .then function in our controller i.e. all is well, so we can keep our promise and resolve it.
The reject function links to the .catch function in our controller i.e. something went wrong, so we can’t keep our promise and need to reject it.
It is quite stable and safe and if you have other conditions to reject the promise you can always filter your data in the success function and call deferred.reject(anotherReason)
with the reason of the rejection.
As Ryan Vice suggested in the comments, this may not be seen as useful unless you fiddle a bit with the response, so to speak.
Because success
and error
are deprecated since 1.4 maybe it is better to use the regular promise methods then
and catch
and transform the response within those methods and return the promise of that transformed response.
I am showing the same example with both approaches and a third in-between approach:
success
and error
approach (success
and error
return a promise of an HTTP response, so we need the help of $q
to return a promise of data):
function search(query) {
// We make use of Angular's $q library to create the deferred instance
var deferred = $q.defer();
$http.get('http://localhost/v1?=q' + query)
.success(function(data,status) {
// The promise is resolved once the HTTP call is successful.
deferred.resolve(data);
})
.error(function(reason,status) {
// The promise is rejected if there is an error with the HTTP call.
if(reason.error){
deferred.reject({text:reason.error, status:status});
}else{
//if we don't get any answers the proxy/api will probably be down
deferred.reject({text:'whatever', status:500});
}
});
// The promise is returned to the caller
return deferred.promise;
};
then
and catch
approach (this is a bit more difficult to test, because of the throw):
function search(query) {
var promise=$http.get('http://localhost/v1?=q' + query)
.then(function (response) {
// The promise is resolved once the HTTP call is successful.
return response.data;
},function(reason) {
// The promise is rejected if there is an error with the HTTP call.
if(reason.statusText){
throw reason;
}else{
//if we don't get any answers the proxy/api will probably be down
throw {statusText:'Call error', status:500};
}
});
return promise;
}
There is a halfway solution though (this way you can avoid the throw
and anyway you'll probably need to use $q
to mock the promise behavior in your tests):
function search(query) {
// We make use of Angular's $q library to create the deferred instance
var deferred = $q.defer();
$http.get('http://localhost/v1?=q' + query)
.then(function (response) {
// The promise is resolved once the HTTP call is successful.
deferred.resolve(response.data);
},function(reason) {
// The promise is rejected if there is an error with the HTTP call.
if(reason.statusText){
deferred.reject(reason);
}else{
//if we don't get any answers the proxy/api will probably be down
deferred.reject({statusText:'Call error', status:500});
}
});
// The promise is returned to the caller
return deferred.promise;
}
Any kind of comments or corrections are welcome.
I insert this code in my tag and it works correctly:
ng-show="!Contract.BuyerName.trim()" >
A stack overflow is usually called by nesting function calls too deeply (especially easy when using recursion, i.e. a function that calls itself) or allocating a large amount of memory on the stack where using the heap would be more appropriate.
Just check if you have set the buffering option to false (by default its true). For response.redirect to work,
sometimes it happens that server do made some mistakes. try log out/sign in and everything might be right then. (Yes it happened this afternoon to me.)
You need Three Tools to decompile an APK
file.
for more how-to-use-dextojar. Hope this will help You and all! :)
@RD /S /Q "D:\PHP_Projects\testproject\Release\testfolder"
Removes (deletes) a directory.
RMDIR [/S] [/Q] [drive:]path RD [/S] [/Q] [drive:]path /S Removes all directories and files in the specified directory in addition to the directory itself. Used to remove a directory tree. /Q Quiet mode, do not ask if ok to remove a directory tree with /S
If this folder is the first in the command then it won't work with a space in the folder name, so replace the space in the folder name with an underscore.
You can use the IHttpConnectionFeature
for getting this information.
var remoteIpAddress = httpContext.GetFeature<IHttpConnectionFeature>()?.RemoteIpAddress;
Assuming that I have understood your scenario correctly, this is what I would call the right way to do this:
Start from a higher-level description of your database! You have employees, and employees can be "ce" employees and "sn" employees (whatever those are). In object-oriented terms, there is a class "employee", with two sub-classes called "ce employee" and "sn employee".
Then you translate this higher-level description to three tables: employees
, employees_ce
and employees_sn
:
employees(id, name)
employees_ce(id, ce-specific stuff)
employees_sn(id, sn-specific stuff)
Since all employees are employees (duh!), every employee will have a row in the employees
table. "ce" employees also have a row in the employees_ce
table, and "sn" employees also have a row in the employees_sn
table. employees_ce.id
is a foreign key to employees.id
, just as employees_sn.id
is.
To refer to an employee of any kind (ce or sn), refer to the employees
table. That is, the foreign key you had trouble with should refer to that table!
How about
<img style="display: none;" src="a.gif">
That will disable the display completely, and not leave a placeholder
In your model,
class Contact
self.email_providers = %w[Gmail Yahoo MSN]
validates :email_provider, :inclusion => email_providers
end
In your form,
<%= f.select :email_provider,
options_for_select(Contact.email_providers, @contact.email_provider) %>
the second arg of the options_for_select will have any current email_provider selected.
The documentation on counting says that for group_by
queries it is better to use func.count()
:
from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()
It happens cause of multiple reasons but the answer missing above there's the "className" while extending your controller.
Make sure your class name is the same as your controller name is your controllers. e.g., If your controller name is Settings.php, you must extend the controller like.
class Settings extends CI_Controller
{
// some actions like...
public function __construct(){
// and so and so...
}
}
If you take a look at @types/node-fetch you will see the body definition
export class Body {
bodyUsed: boolean;
body: NodeJS.ReadableStream;
json(): Promise<any>;
json<T>(): Promise<T>;
text(): Promise<string>;
buffer(): Promise<Buffer>;
}
That means that you could use generics in order to achieve what you want. I didn't test this code, but it would looks something like this:
import { Actor } from './models/actor';
fetch(`http://swapi.co/api/people/1/`)
.then(res => res.json<Actor>())
.then(res => {
let b:Actor = res;
});
I finally got it to work.
I'm not sure if the spaces in the path were breaking things but I changed the workspace of my Aptana installation to something without spaces.
Then I uninstalled XAMPP and reinstalled it because I was thinking maybe I made a typo somewhere without noticing and figured I should be working from scratch.
Turns out Windows 7 has a service somewhere that uses port 80 which blocks apache from starting (giving it the -1) error. So I changed the port it listens to port 8080, no more conflict.
Finally I restarted my computer, for some reason XAMPP doesn't like me messing with ini files and just restarting apache wasn't doing the trick.
Anyway, this has been the most frustrating day ever so I really hope my answer ends up helping someone out!
First Create folder same as path which you Specified. after then create File
File dir = new File("C:\\USER\\Semple_file\\");
File file = new File("C:\\USER\\Semple_file\\abc.txt");
if(!file.exists())
{
dir.mkdir();
file.createNewFile();
System.out.println("File,Folder Created.);
}
Yes, running a 64-bit OS in VMWare is possible from a 32-bit OS if you have a 64 bit processor.
I have an old Intel Core 2 Duo with Windows XP Professional 2002 running on it, and I got it to work.
First of all, see if your CPU is capable of running a 64-bit OS. Search for 'Processor check for 64-bit compatibility' on the VMware site. Run the program.
If it says your processor is capable, restart your computer and go into the BIOS and see if you have 'Virtualization' and are able to enable it. I was able to and got Windows Server 2008 R2 running under VMware on this old laptop.
I hope it works for you!
It seems many regex given miss one thing or another. This has been working for me so far:
(?i)^\s*[+-]?(?:inf(inity)?|nan|(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)\s*$
It allows for infinity (or inf) with sign, nan, no digit before the
decimal, and leading/trailing spaces (if desired). The ^
and $
are
needed to keep from partially matching something like 1.2f-2
as 1.2
.
You could use [ed]
instead of just e
if you need to parse some files
where D
is used for double-precision scientific notation. You would
want to replace it afterward or just replace them before checking since
the float()
function won't allow it.
How about defining your own view? I have used the class below, using a LinearLayout around a view whose background color is set. This allows me to pre-define layout parameters for it. If you don't need that just extend View and set the background color instead.
public class HorizontalRulerView extends LinearLayout {
static final int COLOR = Color.DKGRAY;
static final int HEIGHT = 2;
static final int VERTICAL_MARGIN = 10;
static final int HORIZONTAL_MARGIN = 5;
static final int TOP_MARGIN = VERTICAL_MARGIN;
static final int BOTTOM_MARGIN = VERTICAL_MARGIN;
static final int LEFT_MARGIN = HORIZONTAL_MARGIN;
static final int RIGHT_MARGIN = HORIZONTAL_MARGIN;
public HorizontalRulerView(Context context) {
this(context, null);
}
public HorizontalRulerView(Context context, AttributeSet attrs) {
this(context, attrs, android.R.attr.textViewStyle);
}
public HorizontalRulerView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setOrientation(VERTICAL);
View v = new View(context);
v.setBackgroundColor(COLOR);
LayoutParams lp = new LayoutParams(
LayoutParams.MATCH_PARENT,
HEIGHT
);
lp.topMargin = TOP_MARGIN;
lp.bottomMargin = BOTTOM_MARGIN;
lp.leftMargin = LEFT_MARGIN;
lp.rightMargin = RIGHT_MARGIN;
addView(v, lp);
}
}
Use it programmatically or in Eclipse (Custom & Library Views -- just pull it into your layout).
Making local variables and method parameters final
is essential if you want to pass those parameters into anonymous classes - like you instantiate an anonymous Thread and want to access those params in the body of the run() method.
Apart from that I am not sure of the performance benefits w.r.t better performance through compiler optimization. It is up to the specific compiler implementation whether it wants to optimize it at all...
It will be good to know of any performance stats from using final
...
This is how you can approach these problems in general on your own:
The first of the pair can be picked in N (=100) ways. You don't want to pick this item again, so the second of the pair can be picked in N-1 (=99) ways. In total you can pick 2 items out of N in N(N-1) (= 100*99=9900) different ways.
But hold on, this way you count also different orderings: AB and BA are both counted. Since every pair is counted twice you have to divide N(N-1) by two (the number of ways that you can order a list of two items). The number of subsets of two that you can make with a set of N is then N(N-1)/2 (= 9900/2 = 4950).
Another method could be to split the string by ":" and then pop off the end.
var newString = string.split(":").pop();
Copy below code and paste AndroidManifest.xml file in under First Activity Tag.
<activity
android:name="com.SplashActivity"
android:clearTaskOnLaunch="true"
android:launchMode="singleTask"
android:excludeFromRecents="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER"
/>
</intent-filter>
</activity>
Also Add this below code in all under Activity Tag in AndroidManifest.xml file
android:finishOnTaskLaunch="true"
For Activities shown within TabActivities use getParent()
final AlertDialog.Builder builder = new AlertDialog.Builder(getParent());
instead of
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
You can also take advantage of the built-in Service Parameters system, which lets you isolate or reuse the value:
# app/config/parameters.yml
parameters:
ga_tracking: UA-xxxxx-x
# app/config/config.yml
twig:
globals:
ga_tracking: "%ga_tracking%"
Now, the variable ga_tracking is available in all Twig templates:
<p>The google tracking code is: {{ ga_tracking }}</p>
The parameter is also available inside the controllers:
$this->container->getParameter('ga_tracking');
You can also define a service as a global Twig variable (Symfony2.2+):
# app/config/config.yml
twig:
# ...
globals:
user_management: "@acme_user.user_management"
http://symfony.com/doc/current/templating/global_variables.html
If the global variable you want to set is more complicated - say an object - then you won't be able to use the above method. Instead, you'll need to create a Twig Extension and return the global variable as one of the entries in the getGlobals method.
Here is a ready to run source code for random number generator using c taken from this site: http://www.random-number.com/random-number-c/ . The implementation here is more general (a function that gets 3 parameters: min,max and number of random numbers to generate)
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
// the random function
void RandomNumberGenerator(const int nMin, const int nMax, const int nNumOfNumsToGenerate)
{
int nRandonNumber = 0;
for (int i = 0; i < nNumOfNumsToGenerate; i++)
{
nRandonNumber = rand()%(nMax-nMin) + nMin;
printf("%d ", nRandonNumber);
}
printf("\n");
}
void main()
{
srand(time(NULL));
RandomNumberGenerator(1,70,5);
}
Note The accepted is perfectly fine - but wanted to add a version4 example because they are different enough.
import React from 'react';
import { Link } from 'react-router';
export default class Nav extends React.Component {
render() {
return (
<nav className="Nav">
<div className="Nav__container">
<Link to="/" className="Nav__brand">
<img src="logo.svg" className="Nav__logo" />
</Link>
<div className="Nav__right">
<ul className="Nav__item-wrapper">
<li className="Nav__item">
<Link className="Nav__link" to="/path1">Link 1</Link>
</li>
<li className="Nav__item">
<Link className="Nav__link" to="/path2">Link 2</Link>
</li>
<li className="Nav__item">
<Link className="Nav__link" to="/path3">Link 3</Link>
</li>
</ul>
</div>
</div>
</nav>
);
}
}
import React from 'react';
import { Link, Switch, Route } from 'react-router';
import Nav from './nav';
import Page1 from './page1';
import Page2 from './page2';
import Page3 from './page3';
export default class App extends React.Component {
render() {
return (
<div className="App">
<Router>
<div>
<Nav />
<Switch>
<Route exactly component={Landing} pattern="/" />
<Route exactly component={Page1} pattern="/path1" />
<Route exactly component={Page2} pattern="/path2" />
<Route exactly component={Page3} pattern="/path3" />
<Route component={Page404} />
</Switch>
</div>
</Router>
</div>
);
}
}
Alternatively, if you want a more dynamic nav, you can look at the excellent v4 docs: https://reacttraining.com/react-router/web/example/sidebar
A few people have asked about a page without the Nav, such as a login page. I typically approach it with a wrapper Route component
import React from 'react';
import { Link, Switch, Route } from 'react-router';
import Nav from './nav';
import Page1 from './page1';
import Page2 from './page2';
import Page3 from './page3';
const NavRoute = ({exact, path, component: Component}) => (
<Route exact={exact} path={path} render={(props) => (
<div>
<Header/>
<Component {...props}/>
</div>
)}/>
)
export default class App extends React.Component {
render() {
return (
<div className="App">
<Router>
<Switch>
<NavRoute exactly component={Landing} pattern="/" />
<Route exactly component={Login} pattern="/login" />
<NavRoute exactly component={Page1} pattern="/path1" />
<NavRoute exactly component={Page2} pattern="/path2" />
<NavRoute component={Page404} />
</Switch>
</Router>
</div>
);
}
}
To answer the original question: yes, you can access the index value of a row in apply()
. It is available under the key name
and requires that you specify axis=1
(because the lambda processes the columns of a row and not the rows of a column).
Working example (pandas 0.23.4):
>>> import pandas as pd
>>> df = pd.DataFrame([[1,2,3],[4,5,6]], columns=['a','b','c'])
>>> df.set_index('a', inplace=True)
>>> df
b c
a
1 2 3
4 5 6
>>> df['index_x10'] = df.apply(lambda row: 10*row.name, axis=1)
>>> df
b c index_x10
a
1 2 3 10
4 5 6 40
SELECT name,
type
FROM dbo.sysobjects
WHERE (type = 'P')
First of all, you do not have to develop any form yourself : phpMyAdmin, depending on its configuration (i.e. config.inc.php
) will display an identification form, asking for a login and password.
To get that form, you should not use :
$cfg['Servers'][$i]['auth_type'] = 'config';
But you should use :
$cfg['Servers'][$i]['auth_type'] = 'cookie';
(At least, that's what I have on a server which prompts for login/password, using a form)
For more informations, you can take a look at the documentation :
'config'
authentication ($auth_type = 'config'
) is the plain old way: username and password are stored in config.inc.php.'cookie'
authentication mode ($auth_type = 'cookie'
) as introduced in 2.2.3 allows you to log in as any valid MySQL user with the help of cookies.
Username and password are stored in cookies during the session and password is deleted when it ends.
This should also work:
AggregateValues("hello", MyList.ConvertAll(c => c.Name).ToArray())
I was getting the same error today:
Error:Execution failed for task ':app:preDebugAndroidTestBuild'.> Conflict with dependency 'com.android.support:support-annotations' in project ':app'. Resolved versions for app (26.1.0) and test app (27.1.1) differ.
What I did:
27.1.1
instead of 26.1.0
compileSdkVersion 27
and targetSdkVersion 27
which were 26
earlierAnd com.android.support:support-annotations
error was gone!
For Ref:
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.0'
implementation 'com.android.support:design:27.1.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}
Dim inputString As String = "ra"
Enumerable.Range(0, arr.Length).Where(Function(x) arr(x).ToLower().Contains(inputString.ToLower()))
The for...in loop improves upon the weaknesses of the for loop by eliminating the counting logic and exit condition.
Example:
const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for (const index in digits) {
console.log(digits[index]);
}
But, you still have to deal with the issue of using an index to access the values of the array, and that stinks; it almost makes it more confusing than before.
Also, the for...in loop can get you into big trouble when you need to add an extra method to an array (or another object). Because for...in loops loop over all enumerable properties, this means if you add any additional properties to the array's prototype, then those properties will also appear in the loop.
Array.prototype.decimalfy = function() {
for (let i = 0; i < this.length; i++) {
this[i] = this[i].toFixed(2);
}
};
const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for (const index in digits) {
console.log(digits[index]);
}
Prints:
0
1
2
3
4
5
6
7
8
9
function() { for (let i = 0; i < this.length; i++) { this[i] = this[i].toFixed(2); } }
This is why for...in loops are discouraged when looping over arrays.
NOTE: The forEach loop is another type of for loop in JavaScript. However,
forEach()
is actually an array method, so it can only be used exclusively with arrays. There is also no way to stop or break a forEach loop. If you need that type of behavior in your loop, you’ll have to use a basic for loop.
The for...of loop is used to loop over any type of data that is iterable.
Example:
const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for (const digit of digits) {
console.log(digit);
}
Prints:
0
1
2
3
4
5
6
7
8
9
This makes the for...of loop the most concise version of all the for loops.
But wait, there’s more! The for...of loop also has some additional benefits that fix the weaknesses of the for and for...in loops.
You can stop or break a for...of loop at anytime.
const digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
for (const digit of digits) {
if (digit % 2 === 0) {
continue;
}
console.log(digit);
}
Prints:
1
3
5
7
9
And you don’t have to worry about adding new properties to objects. The for...of loop will only loop over the values in the object.
You can set a layout manager like BorderLayout and then define more specifically, where your panel should go:
MainPanel mainPanel = new MainPanel();
JFrame mainFrame = new JFrame();
mainFrame.setLayout(new BorderLayout());
mainFrame.add(mainPanel, BorderLayout.CENTER);
mainFrame.pack();
mainFrame.setVisible(true);
This puts the panel into the center area of the frame and lets it grow automatically when resizing the frame.
This sub will populate a Collection with all files matching the filename or pattern you pass in.
Sub GetFiles(StartFolder As String, Pattern As String, _
DoSubfolders As Boolean, ByRef colFiles As Collection)
Dim f As String, sf As String, subF As New Collection, s
If Right(StartFolder, 1) <> "\" Then StartFolder = StartFolder & "\"
f = Dir(StartFolder & Pattern)
Do While Len(f) > 0
colFiles.Add StartFolder & f
f = Dir()
Loop
If DoSubfolders then
sf = Dir(StartFolder, vbDirectory)
Do While Len(sf) > 0
If sf <> "." And sf <> ".." Then
If (GetAttr(StartFolder & sf) And vbDirectory) <> 0 Then
subF.Add StartFolder & sf
End If
End If
sf = Dir()
Loop
For Each s In subF
GetFiles CStr(s), Pattern, True, colFiles
Next s
End If
End Sub
Usage:
Dim colFiles As New Collection
GetFiles "C:\Users\Marek\Desktop\Makro\", FName & ".xls", True, colFiles
If colFiles.Count > 0 Then
'work with found files
End If
To join Array1 and Array2, create a new array say JointArray
Dim JointArray As Variant
ReDim JointArray(UBound(Array1) + UBound(Array2) + 1) As Variant
For i = 0 To UBound(JointArray)
If i <= UBound(Array1) Then
JointArray(i) = Array1(i)
Else
JointArray(i) = Array2(i - UBound(Array1) - 1)
End If
Next
You can use the finish
command.
finish
: Continue running until just after function in the selected stack frame returns. Print the returned value (if any). This command can be abbreviated asfin
.
(See 5.2 Continuing and Stepping.)
You should do it like this:
function getResults(str) {
$.ajax({
url:'suggest.html',
type:'POST',
data: 'q=' + str,
dataType: 'json',
success: function( json ) {
$.each(json, function(i, optionHtml){
$('#myselect').append(optionHtml);
});
}
});
};
Cheers
If you want a big database of real data to play with, you could sign up for the Netflix Prize contest and get access to their data, which is pretty large (a few gigs of entries).
The URL above does not contain the dataset anylonger (october 2016). The wikipedia page about the Netflix Prize reports that a law suit was settled regarding privacy concerns.
I wrote a function a while back to handle it for my stored procedures:
print 'Creating safeDivide Stored Proc ...'
go
if exists (select * from dbo.sysobjects where name = 'safeDivide') drop function safeDivide;
go
create function dbo.safeDivide( @Numerator decimal(38,19), @divisor decimal(39,19))
returns decimal(38,19)
begin
-- **************************************************************************
-- Procedure: safeDivide()
-- Author: Ron Savage, Central, ex: 1282
-- Date: 06/22/2004
--
-- Description:
-- This function divides the first argument by the second argument after
-- checking for NULL or 0 divisors to avoid "divide by zero" errors.
-- Change History:
--
-- Date Init. Description
-- 05/14/2009 RS Updated to handle really freaking big numbers, just in
-- case. :-)
-- 05/14/2009 RS Updated to handle negative divisors.
-- **************************************************************************
declare @p_product decimal(38,19);
select @p_product = null;
if ( @divisor is not null and @divisor <> 0 and @Numerator is not null )
select @p_product = @Numerator / @divisor;
return(@p_product)
end
go
In my case... with MySQL:
SELECT ... GROUP BY TIMESTAMPADD(HOUR, HOUR(columName), DATE(columName))
It happens when you do not have a $HOME/.gitconfig initialized. You may fix this as:
git config --global user.name "you name"
git config --global user.email [email protected]
git commit --amend --reset-author
tested with git version 1.7.5.4
sudo apt install libssl-dev
works on ubuntu 18.04.
You can't decrypt password in mysql, because password is hashed by using md5 hash algorithm, which is not an encoding algorithm.
JPanel jPanel = new JPanel();
jPanel.setBorder(BorderFactory.createLineBorder(Color.black));
Here not only jPanel, you can add border to any Jcomponent
CHARINDEX()
searches for a substring within a larger string, and returns the position of the match, or 0 if no match is found
if CHARINDEX('ME',@mainString) > 0
begin
--do something
end
Edit or from daniels answer, if you're wanting to find a word (and not subcomponents of words), your CHARINDEX
call would look like:
CHARINDEX(' ME ',' ' + REPLACE(REPLACE(@mainString,',',' '),'.',' ') + ' ')
(Add more recursive REPLACE() calls for any other punctuation that may occur)
Your first approach should be to find all references to Thread.sleep and check that:
Sleeping is the right thing to do - you should use some sort of wait mechanism if possible - perhaps careful use of a BlockingQueue
would help.
If sleeping is the right thing to do, are you sleeping for the right amount of time - this is often a very difficult question to answer.
The most common mistake in multi-threaded design is to believe that all you need to do when waiting for something to happen is to check for it and sleep for a while in a tight loop. This is rarely an effective solution - you should always try to wait
for the occurrence.
The second most common issue is to loop without sleeping. This is even worse and is a little less easy to track down.
One method to do this is to add:
pointer-events: none;
to the element, you want to disable hover on.
(Note: this also disables javascript events on that element too, click events will actually fall through to the element behind ).
Browser Support ( 98.12% as of Jan 1, 2021 )
This seems to be much cleaner
/**
* This allows you to disable hover events for any elements
*/
.disabled {
pointer-events: none; /* <----------- */
opacity: 0.2;
}
.button {
border-radius: 30px;
padding: 10px 15px;
border: 2px solid #000;
color: #FFF;
background: #2D2D2D;
text-shadow: 1px 1px 0px #000;
cursor: pointer;
display: inline-block;
margin: 10px;
}
.button-red:hover {
background: red;
}
.button-green:hover {
background:green;
}
_x000D_
<div class="button button-red">I'm a red button hover over me</div>
<br />
<div class="button button-green">I'm a green button hover over me</div>
<br />
<div class="button button-red disabled">I'm a disabled red button</div>
<br />
<div class="button button-green disabled">I'm a disabled green button</div>
_x000D_
It sucks but you can get the bean by using the ApplicationContextAware
interface. Something like :
public class Boo implements ApplicationContextAware {
private static ApplicationContext appContext;
@Autowired
Foo foo;
public static void randomMethod() {
Foo fooInstance = appContext.getBean(Foo.class);
fooInstance.doStuff();
}
@Override
public void setApplicationContext(ApplicationContext appContext) {
Boo.appContext = appContext;
}
}
The new versions of jQuery require this file http://code.jquery.com/jquery-1.10.2.min.map
The usability of this file is described here http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/
Update:
jQuery 1.11.0/2.1.0
// sourceMappingURL comment is not included in the compressed file.
I think you need separately date parts like (day, Month, Year)
DateTime today = DateTime.Today;
Will not work for your case. You can get date separately so you don't need variable today
to be as a DateTime
Type, so lets just give today
variable int
Type because the day is only int. So today is 10 March 2020 then the result of
int today = DateTime.Today.Day;
int month = DateTime.Today.Month;
int year = DateTime.Today.Year;
MessageBox.Show(today.ToString()+ " - this is day. "+month.ToString()+ " - this is month. " + year.ToString() + " - this is year");
would be "10 - this is day. 3 - this is month. 2020 - this is year"
Parallel.ForEach will optimize(may not even start new threads) and block until the loop is finished, and Task.Factory will explicitly create a new task instance for each item, and return before they are finished (asynchronous tasks). Parallel.Foreach is much more efficient.
For those looking for an inline example, here is one:
<audio controls style="width: 200px;">
<source src="http://somewhere.mp3" type="audio/mpeg">
</audio>
It doesn't seem to respect a "height" setting, at least not awesomely. But you can always "customize" the controls but creating your own controls (instead of using the built-in ones) or using somebody's widget that similarly creates its own :)
You can't use IF like that. You can do what you want with AND and OR:
SELECT t.first_name,
t.last_name,
t.employid,
t.status
FROM employeetable t
WHERE ((status_flag = STATUS_ACTIVE AND t.status = 'A')
OR (status_flag = STATUS_INACTIVE AND t.status = 'T')
OR (source_flag = SOURCE_FUNCTION AND t.business_unit = 'production')
OR (source_flag = SOURCE_USER AND t.business_unit = 'users'))
AND t.first_name LIKE firstname
AND t.last_name LIKE lastname
AND t.employid LIKE employeeid;
Figure sizes are specified in inches and can be included as a global option of the document output format. For example:
---
title: "My Document"
output:
html_document:
fig_width: 6
fig_height: 4
---
And the plot's size in the graphic device can be increased at the chunk level:
```{r, fig.width=14, fig.height=12} #Expand the plot width to 14 inches
ggplot(aes(x=mycolumn1, y=mycolumn2)) + #specify the x and y aesthetic
geom_line(size=2) + #makes the line thicker
theme_grey(base_size = 25) #increases the size of the font
```
You can also use the out.width
and out.height
arguments to directly define the size of the plot in the output file:
```{r, out.width="200px", out.height="200px"} #Expand the plot width to 200 pixels
ggplot(aes(x=mycolumn1, y=mycolumn2)) + #specify the x and y aesthetic
geom_line(size=2) + #makes the line thicker
theme_grey(base_size = 25) #increases the size of the font
```
Here's the code I used to quickly bind jQuery scrollTo to all anchor links:
// Smooth scroll
$('a[href*=#]').click(function () {
var hash = $(this).attr('href');
hash = hash.slice(hash.indexOf('#') + 1);
$.scrollTo(hash == 'top' ? 0 : 'a[name='+hash+']', 500);
window.location.hash = '#' + hash;
return false;
});
Use "fontPath" attribute directly in xml file.
for use in style.xml
<item name="fontPath">fonts/ProximaNovaSemibold.ttf</item>
for use in direct layout file
fontPath="fonts/ProximaNovaBold.ttf"
(Note : No need to use app/android attribute in prefix)
My own experience has been that it's best to stick to one of two kinds of assembly references:
I've found (much like you've described) other methods to either be too easily broken or have annoying maintenance requirements.
Any assembly I don't want to GAC, has to live in the execution directory. Any assembly that isn't or can't be in the execution directory I GAC (managed by automatic build events).
This hasn't given me any problems so far. While I'm sure there's a situation where it won't work, the usual answer to any problem has been "oh, just GAC it!". 8 D
Hope that helps!
You need to use the string concatenation operator +
String both = name + "-" + dest;
This script demonstrates a few ways to show the local timezone using astimezone()
:
#!/usr/bin/env python3
import pytz
from datetime import datetime, timezone
from tzlocal import get_localzone
utc_dt = datetime.now(timezone.utc)
PST = pytz.timezone('US/Pacific')
EST = pytz.timezone('US/Eastern')
JST = pytz.timezone('Asia/Tokyo')
NZST = pytz.timezone('Pacific/Auckland')
print("Pacific time {}".format(utc_dt.astimezone(PST).isoformat()))
print("Eastern time {}".format(utc_dt.astimezone(EST).isoformat()))
print("UTC time {}".format(utc_dt.isoformat()))
print("Japan time {}".format(utc_dt.astimezone(JST).isoformat()))
# Use astimezone() without an argument
print("Local time {}".format(utc_dt.astimezone().isoformat()))
# Use tzlocal get_localzone
print("Local time {}".format(utc_dt.astimezone(get_localzone()).isoformat()))
# Explicitly create a pytz timezone object
# Substitute a pytz.timezone object for your timezone
print("Local time {}".format(utc_dt.astimezone(NZST).isoformat()))
It outputs the following:
$ ./timezones.py
Pacific time 2019-02-22T17:54:14.957299-08:00
Eastern time 2019-02-22T20:54:14.957299-05:00
UTC time 2019-02-23T01:54:14.957299+00:00
Japan time 2019-02-23T10:54:14.957299+09:00
Local time 2019-02-23T14:54:14.957299+13:00
Local time 2019-02-23T14:54:14.957299+13:00
Local time 2019-02-23T14:54:14.957299+13:00
As of python 3.6 calling astimezone()
without a timezone object defaults to the local zone (docs). This means you don't need to import tzlocal
and can simply do the following:
#!/usr/bin/env python3
from datetime import datetime, timezone
utc_dt = datetime.now(timezone.utc)
print("Local time {}".format(utc_dt.astimezone().isoformat()))
You should use the for
command, here is an example:
@echo off
rem Commands go here
exit /b
:output
for /f "tokens=* useback" %%a in (`%~1`) do set "output=%%a"
and you can use call :output "Command goes here"
then the output will be in the %output%
variable.
Note: If you have a command output that is multiline, this tool will set
the output to the last line of your multiline command.
DPAPI is just for this purpose. Use DPAPI to encrypt the password the first time the user enters is, store it in a secure location (User's registry, User's application data directory, are some choices). Whenever the app is launched, check the location to see if your key exists, if it does use DPAPI to decrypt it and allow access, otherwise deny it.
Although not directly applicable to this question, because it wants some information for the user, google brought me here when I wanted to run my .bat file elevated from task scheduler.
The simplest approach was to create a shortcut to the .bat file, because for a shortcut you can set Run as administrator
directly from the advanced properties.
Running the shortcut from task scheduler, runs the .bat file elevated.
Your @JsonSubTypes
declaration does not make sense: it needs to list implementation (sub-) classes, NOT the class itself (which would be pointless). So you need to modify that entry to list sub-class(es) there are; or use some other mechanism to register sub-classes (SimpleModule
has something like addAbstractTypeMapping
).
I've encapsulated tags manipulation in an experimental plugin of mine.
Regarding C++ development in vim, I've already answered there: I use my own suite, and a few other plugins.
Because it's not.
Indexing is covered by IList
. IEnumerable
means "I have some of the powers of IList, but not all of them."
Some collections (like a linked list), cannot be indexed in a practical way. But they can be accessed item-by-item. IEnumerable
is intended for collections like that. Note that a collection can implement both IList & IEnumerable (and many others). You generally only find IEnumerable
as a function parameter, meaning the function can accept any kind of collection, because all it needs is the simplest access mode.
As you have already stated in your question you have more than one option. A very basic approach would be using the tag referencing your PHP file in the method attribute. However as esoteric as it may sound AJAX is a more complete approach. Considering that an AJAX call (in combination with jQuery) can be as simple as:
$.post("yourfile.php", {data : "This can be as long as you want"});
And you get a more flexible solution, for example triggering a function after the server request is completed. Hope this helps.
May not be the most efficient, requires an extra pass to remove duplicates.
Functional implementation :
arr = np.array(['a','a','b','b','b','c'])
print(set(map(lambda x : (x , list(arr).count(x)) , arr)))
returns :
{('c', 1), ('b', 3), ('a', 2)}
or return as dict
:
print(dict(map(lambda x : (x , list(arr).count(x)) , arr)))
returns :
{'b': 3, 'c': 1, 'a': 2}
If you want a more intuitive writing, it exist a gem called squeel that will let you write your instruction like this:
User.where{id > 200}
Notice the 'brace' characters { } and id
being just a text.
All you have to do is to add squeel to your Gemfile:
gem "squeel"
This might ease your life a lot when writing complex SQL statement in Ruby.
To find a very long list of words in big files, it can be more efficient to use egrep:
remove the last \n of A
$ tr '\n' '|' < A > A_regex
$ egrep -f A_regex B
Obfuscating the value by using the CustomFormat
property, using checkbox cbEnableEndDate
as the flag to indicate whether other code should ignore the value:
If dateTaskEnd > Date.FromOADate(0) Then
dtTaskEnd.Format = DateTimePickerFormat.Custom
dtTaskEnd.CustomFormat = "yyyy-MM-dd"
dtTaskEnd.Value = dateTaskEnd
dtTaskEnd.Enabled = True
cbEnableEndDate.Checked = True
Else
dtTaskEnd.Format = DateTimePickerFormat.Custom
dtTaskEnd.CustomFormat = " "
dtTaskEnd.Value = Date.FromOADate(0)
dtTaskEnd.Enabled = False
cbEnableEndDate.Checked = False
End If
I also got this error, but for a .h
file. The fix was to go into the file Properties
(via Solution Explorer's file popup menu) and set the file type correctly. It was set to C/C++ Compiler
instead of the correct C/C++ header
.
A correct snprintf
implementation:
int count = snprintf(NULL, 0, "%i", x);
Based on your question history, you're using JSF 2.x. So, here's a JSF 2.x targeted answer. In JSF 1.x you would be forced to wrap item values/labels in ugly SelectItem
instances. This is fortunately not needed anymore in JSF 2.x.
To answer your question directly, just use <f:selectItems>
whose value
points to a List<T>
property which you preserve from the DB during bean's (post)construction. Here's a basic kickoff example assuming that T
actually represents a String
.
<h:selectOneMenu value="#{bean.name}">
<f:selectItems value="#{bean.names}" />
</h:selectOneMenu>
with
@ManagedBean
@RequestScoped
public class Bean {
private String name;
private List<String> names;
@EJB
private NameService nameService;
@PostConstruct
public void init() {
names = nameService.list();
}
// ... (getters, setters, etc)
}
Simple as that. Actually, the T
's toString()
will be used to represent both the dropdown item label and value. So, when you're instead of List<String>
using a list of complex objects like List<SomeEntity>
and you haven't overridden the class' toString()
method, then you would see com.example.SomeEntity@hashcode
as item values. See next section how to solve it properly.
Also note that the bean for <f:selectItems>
value does not necessarily need to be the same bean as the bean for <h:selectOneMenu>
value. This is useful whenever the values are actually applicationwide constants which you just have to load only once during application's startup. You could then just make it a property of an application scoped bean.
<h:selectOneMenu value="#{bean.name}">
<f:selectItems value="#{data.names}" />
</h:selectOneMenu>
Whenever T
concerns a complex object (a javabean), such as User
which has a String
property of name
, then you could use the var
attribute to get hold of the iteration variable which you in turn can use in itemValue
and/or itemLabel
attribtues (if you omit the itemLabel
, then the label becomes the same as the value).
Example #1:
<h:selectOneMenu value="#{bean.userName}">
<f:selectItems value="#{bean.users}" var="user" itemValue="#{user.name}" />
</h:selectOneMenu>
with
private String userName;
private List<User> users;
@EJB
private UserService userService;
@PostConstruct
public void init() {
users = userService.list();
}
// ... (getters, setters, etc)
Or when it has a Long
property id
which you would rather like to set as item value:
Example #2:
<h:selectOneMenu value="#{bean.userId}">
<f:selectItems value="#{bean.users}" var="user" itemValue="#{user.id}" itemLabel="#{user.name}" />
</h:selectOneMenu>
with
private Long userId;
private List<User> users;
// ... (the same as in previous bean example)
Whenever you would like to set it to a T
property in the bean as well and T
represents an User
, then you would need to bake a custom Converter
which converts between User
and an unique string representation (which can be the id
property). Do note that the itemValue
must represent the complex object itself, exactly the type which needs to be set as selection component's value
.
<h:selectOneMenu value="#{bean.user}" converter="#{userConverter}">
<f:selectItems value="#{bean.users}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>
with
private User user;
private List<User> users;
// ... (the same as in previous bean example)
and
@ManagedBean
@RequestScoped
public class UserConverter implements Converter {
@EJB
private UserService userService;
@Override
public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
if (submittedValue == null || submittedValue.isEmpty()) {
return null;
}
try {
return userService.find(Long.valueOf(submittedValue));
} catch (NumberFormatException e) {
throw new ConverterException(new FacesMessage(String.format("%s is not a valid User ID", submittedValue)), e);
}
}
@Override
public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
if (modelValue == null) {
return "";
}
if (modelValue instanceof User) {
return String.valueOf(((User) modelValue).getId());
} else {
throw new ConverterException(new FacesMessage(String.format("%s is not a valid User", modelValue)), e);
}
}
}
(please note that the Converter
is a bit hacky in order to be able to inject an @EJB
in a JSF converter; normally one would have annotated it as @FacesConverter(forClass=User.class)
, but that unfortunately doesn't allow @EJB
injections)
Don't forget to make sure that the complex object class has equals()
and hashCode()
properly implemented, otherwise JSF will during render fail to show preselected item(s), and you'll on submit face Validation Error: Value is not valid.
public class User {
private Long id;
@Override
public boolean equals(Object other) {
return (other != null && getClass() == other.getClass() && id != null)
? id.equals(((User) other).id)
: (other == this);
}
@Override
public int hashCode() {
return (id != null)
? (getClass().hashCode() + id.hashCode())
: super.hashCode();
}
}
Head to this answer: Implement converters for entities with Java Generics.
The JSF utility library OmniFaces offers a special converter out the box which allows you to use complex objects in <h:selectOneMenu>
without the need to create a custom converter. The SelectItemsConverter
will simply do the conversion based on readily available items in <f:selectItem(s)>
.
<h:selectOneMenu value="#{bean.user}" converter="omnifaces.SelectItemsConverter">
<f:selectItems value="#{bean.users}" var="user" itemValue="#{user}" itemLabel="#{user.name}" />
</h:selectOneMenu>
use map() on collection followed with toMap
val map = list.map(e => (e, e.length)).toMap
Use this link http://ip-api.com/json ,this will provide all the information as json. From this json you can get the country easily. This site works using your current IP,it automatically detects the IP and sendback details.
Docs http://ip-api.com/docs/api:json Hope it helps.
Example json
{
"status": "success",
"country": "United States",
"countryCode": "US",
"region": "CA",
"regionName": "California",
"city": "San Francisco",
"zip": "94105",
"lat": "37.7898",
"lon": "-122.3942",
"timezone": "America/Los_Angeles",
"isp": "Wikimedia Foundation",
"org": "Wikimedia Foundation",
"as": "AS14907 Wikimedia US network",
"query": "208.80.152.201"
}
note : As this is a 3rd party solution, only use if others didn't work.
These work for me and fit the WebView to screen width:
// get from xml, with all size set "fill_parent"
webView = (WebView) findViewById(R.id.webview_in_layout);
// fit the width of screen
webView.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
// remove a weird white line on the right size
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
Thanks above advises and White line in eclipse Web view
IIS was the main offender for me. My IIS was running and it restrains any new socket connections from opening.
The problem resolved for me by stopping IIS by running the command "iisreset -stop
"
// Store original location in loc like: http://test.com/one/ (ending slash)
var loc = location.href;
// If the last char is a slash trim it, otherwise return the original loc
loc = loc.lastIndexOf('/') == (loc.length -1) ? loc.substr(0,loc.length-1) : loc.substr(0,loc.lastIndexOf('/'));
var targetValue = loc.substr(loc.lastIndexOf('/') + 1);
targetValue = one
If your url looks like:
or
or
Then loc ends up looking like: http://test.com/one
Now, since you want the last item, run the next step to load the value (targetValue) you originally wanted.
var targetValue = loc.substr(loc.lastIndexOf('/') + 1);
The easiest way to send (simulate) KeyStrokes to any window is to use the SendKeys.Send method of .NET Framework.
Checkout this very intuitive MSDN article http://msdn.microsoft.com/en-us/library/system.windows.forms.sendkeys.aspx
Particularly for your case, if your browser window is in focus, sending F5 would just involve the following line of code:
SendKeys.Send("{F5}");
If you are using 11G XE with Windows, along with tns listener restart, make sure Windows Event Log service is started.
Solve this problem by doing this.
Enter your Mac Login Password and Choose "Always Allow"
One or More dialogs opened and positioned in the same dialog, repeat step 1 until all dialogs closed. (So you thought your password wrong but repeat "Always Allow" with your Mac login password tricky part :) )
Hope it will work.
This is what I use. I do this first query to find the sessions and the users:
select s.sid, s.serial#, p.spid, s.username, s.schemaname
, s.program, s.terminal, s.osuser
from v$session s
join v$process p
on s.paddr = p.addr
where s.type != 'BACKGROUND';
This will let me know if there are multiple sessions for the same user. Then I usually check to verify if a session is blocking the database.
SELECT SID, SQL_ID, USERNAME, BLOCKING_SESSION, COMMAND, MODULE, STATUS FROM v$session WHERE BLOCKING_SESSION IS NOT NULL;
Then I run an ALTER statement to kill a specific session in this format:
ALTER SYSTEM KILL SESSION 'sid,serial#';
For example:
ALTER SYSTEM KILL SESSION '314, 2643';
As I see in your code, it seems you are following an old documentation/tutorial about OOP in PHP based on PHP4 (OOP wasn't supported but adapted somehow to be used in a simple ways), since PHP5 an official support was added and the notation has been changed from what it was.
Please see this code review here:
<?php
class my_class{
public $my_value = array();
function __construct( $value ) { // the constructor name is __construct instead of the class name
$this->my_value[] = $value;
}
function set_value ($value){
// Error occurred from here as Undefined variable: my_value
$this->my_value = $value; // remove the $ sign
}
}
$a = new my_class ('a');
$a->my_value[] = 'b';
$a->set_value ('c'); // your array variable here will be replaced by a simple string
// $a->my_class('d'); // you can call this if you mean calling the contructor
// at this stage you can't loop on the variable since it have been replaced by a simple string ('c')
foreach ($a->my_value as &$value) { // look for foreach samples to know how to use it well
echo $value;
}
?>
I hope it helps
This query comes from two other answers:
Get size of all tables in database
How to find largest objects in a SQL Server database?
, but I enhanced this to be universal. It uses sys.objects
dictionary:
SELECT
s.NAME as SCHEMA_NAME,
t.NAME AS OBJ_NAME,
t.type_desc as OBJ_TYPE,
i.name as indexName,
sum(p.rows) as RowCounts,
sum(a.total_pages) as TotalPages,
sum(a.used_pages) as UsedPages,
sum(a.data_pages) as DataPages,
(sum(a.total_pages) * 8) / 1024 as TotalSpaceMB,
(sum(a.used_pages) * 8) / 1024 as UsedSpaceMB,
(sum(a.data_pages) * 8) / 1024 as DataSpaceMB
FROM
sys.objects t
INNER JOIN
sys.schemas s ON t.SCHEMA_ID = s.SCHEMA_ID
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
sys.allocation_units a ON p.partition_id = a.container_id
WHERE
t.NAME NOT LIKE 'dt%' AND
i.OBJECT_ID > 255 AND
i.index_id <= 1
GROUP BY
s.NAME, t.NAME, t.type_desc, i.object_id, i.index_id, i.name
ORDER BY
sum(a.total_pages) DESC
;
Please make sure that your applicationContext.xml file is loaded by specifying it in your web.xml file:
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
Taken from the latest stable Oracle production version 12.2: Data Types
The major difference is that VARCHAR2
is an internal data type and VARCHAR
is an external data type. So we need to understand the difference between an internal and external data type...
Inside a database, values are stored in columns in tables. Internally, Oracle represents data in particular formats known as internal data types.
In general, OCI (Oracle Call Interface) applications do not work with internal data type representations of data, but with host language data types that are predefined by the language in which they are written. When data is transferred between an OCI client application and a database table, the OCI libraries convert the data between internal data types and external data types.
External types provide a convenience for the programmer by making it possible to work with host language types instead of proprietary data formats. OCI can perform a wide range of data type conversions when transferring data between an Oracle database and an OCI application. There are more OCI external data types than Oracle internal data types.
The VARCHAR2
data type is a variable-length string of characters with a maximum length of 4000 bytes. If the init.ora parameter max_string_size is default, the maximum length of a VARCHAR2
can be 4000 bytes. If the init.ora parameter max_string_size = extended, the maximum length of a VARCHAR2
can be 32767 bytes
The VARCHAR
data type stores character strings of varying length. The first 2 bytes contain the length of the character string, and the remaining bytes contain the string. The specified length of the string in a bind or a define call must include the two length bytes, so the largest VARCHAR
string that can be received or sent is 65533 bytes long, not 65535.
A quick test in a 12.2 database suggests that as an internal data type, Oracle still treats a VARCHAR
as a pseudotype for VARCHAR2
. It is NOT a SYNONYM
which is an actual object type in Oracle.
SQL> select substr(banner,1,80) from v$version where rownum=1;
Oracle Database 12c Enterprise Edition Release 12.2.0.1.0 - 64bit Production
SQL> create table test (my_char varchar(20));
Table created.
SQL> desc test
Name Null? Type
MY_CHAR VARCHAR2(20)
There are also some implications of VARCHAR
for ProC/C++ Precompiler options. For programmers who are interested, the link is at: Pro*C/C++ Programmer's Guide
Callback from service to activity to update UI.
ResultReceiver receiver = new ResultReceiver(new Handler()) {
protected void onReceiveResult(int resultCode, Bundle resultData) {
//process results or update UI
}
}
Intent instructionServiceIntent = new Intent(context, InstructionService.class);
instructionServiceIntent.putExtra("receiver", receiver);
context.startService(instructionServiceIntent);
Some solutions listed here had some strange glitches when stretching the elastic scrolling. To fix that I used:
body.lock-position {
height: 100%;
overflow: hidden;
width: 100%;
position: fixed;
}
Source: http://www.teamtownend.com/2013/07/ios-prevent-scrolling-on-body/
I really have the same problem, finally, i solved it.
its likey not the Swift Mail's problem. It's Yaml parser's problem. if your password only the digits, the password senmd to swift finally not the same one.
swiftmailer:
transport: smtp
encryption: ssl
auth_mode: login
host: smtp.gmail.com
username: your_username
password: 61548921
you need fix it with double quotes password: "61548921"
I have tested the suggested solutions, they should all work:
select * from dual where (105 = to_number('105'))
=> delivers one dummy row
select * from dual where (10 = to_number('105'))
=> empty result
select * from dual where ('105' = to_char(105))
=> delivers one dummy row
select * from dual where ('105' = to_char(10))
=> empty result
Try:
if (_checkbox.addEventListener) {
_checkbox.addEventListener("click", setCheckedValues, false);
}
else {
_checkbox.attachEvent("onclick", setCheckedValues);
}
Update:: For Internet Explorer versions prior to IE9, attachEvent method should be used to register the specified listener to the EventTarget it is called on, for others addEventListener should be used.
To expand on Berry's answer, that setting the access level to protected allows __get and __set to be used with explicitly declared properties (when accessed outside the class, at least) and the speed being considerably slower, I'll quote a comment from another question on this topic and make a case for using it anyway:
I agree that __get is more slow to a custom get function (doing the same things), this is 0.0124455 the time for __get() and this 0.0024445 is for custom get() after 10000 loops. – Melsi Nov 23 '12 at 22:32 Best practice: PHP Magic Methods __set and __get
According to Melsi's tests, considerably slower is about 5 times slower. That is definitely considerably slower, but also note that the tests show that you can still access a property with this method 10,000 times, counting time for loop iteration, in roughly 1/100 of a second. It is considerably slower in comparison with actual get and set methods defined, and that is an understatement, but in the grand scheme of things, even 5 times slower is never actually slow.
The computing time of the operation is still negligible and not worth considering in 99% of real world applications. The only time it should really be avoided is when you're actually going to be accessing the properties over 10,000 times in a single request. High traffic sites are doing something really wrong if they can't afford throwing a few more servers up to keep their applications running. A single line text ad on the footer of a high traffic site where the access rate becomes an issue could probably pay for a farm of 1,000 servers with that line of text. The end user is never going to be tapping their fingers wondering what is taking the page so long to load because your application's property access takes a millionth of a second.
I say this speaking as a developer coming from a background in .NET, but invisible get and set methods to the consumer is not .NET's invention. They simply aren't properties without them, and these magic methods are PHP's developer's saving grace for even calling their version of properties "properties" at all. Also, the Visual Studio extension for PHP does support intellisense with protected properties, with that trick in mind, I'd think. I would think with enough developers using the magic __get and __set methods in this way, the PHP developers would tune up the execution time to cater to the developer community.
Edit: In theory, protected properties seemed like it'd work in most situation. In practice, it turns out that there's a lot of times you're going to want to use your getters and setters when accessing properties within the class definition and extended classes. A better solution is a base class and interface for when extending other classes, so you can just copy the few lines of code from the base class into the implementing class. I'm doing a bit more with my project's base class, so I don't have an interface to provide right now, but here is the untested stripped down class definition with magic property getting and setting using reflection to remove and move the properties to a protected array:
/** Base class with magic property __get() and __set() support for defined properties. */
class Component {
/** Gets the properties of the class stored after removing the original
* definitions to trigger magic __get() and __set() methods when accessed. */
protected $properties = array();
/** Provides property get support. Add a case for the property name to
* expand (no break;) or replace (break;) the default get method. When
* overriding, call parent::__get($name) first and return if not null,
* then be sure to check that the property is in the overriding class
* before doing anything, and to implement the default get routine. */
public function __get($name) {
$caller = array_shift(debug_backtrace());
$max_access = ReflectionProperty::IS_PUBLIC;
if (is_subclass_of($caller['class'], get_class($this)))
$max_access = ReflectionProperty::IS_PROTECTED;
if ($caller['class'] == get_class($this))
$max_access = ReflectionProperty::IS_PRIVATE;
if (!empty($this->properties[$name])
&& $this->properties[$name]->class == get_class()
&& $this->properties[$name]->access <= $max_access)
switch ($name) {
default:
return $this->properties[$name]->value;
}
}
/** Provides property set support. Add a case for the property name to
* expand (no break;) or replace (break;) the default set method. When
* overriding, call parent::__set($name, $value) first, then be sure to
* check that the property is in the overriding class before doing anything,
* and to implement the default set routine. */
public function __set($name, $value) {
$caller = array_shift(debug_backtrace());
$max_access = ReflectionProperty::IS_PUBLIC;
if (is_subclass_of($caller['class'], get_class($this)))
$max_access = ReflectionProperty::IS_PROTECTED;
if ($caller['class'] == get_class($this))
$max_access = ReflectionProperty::IS_PRIVATE;
if (!empty($this->properties[$name])
&& $this->properties[$name]->class == get_class()
&& $this->properties[$name]->access <= $max_access)
switch ($name) {
default:
$this->properties[$name]->value = $value;
}
}
/** Constructor for the Component. Call first when overriding. */
function __construct() {
// Removing and moving properties to $properties property for magic
// __get() and __set() support.
$reflected_class = new ReflectionClass($this);
$properties = array();
foreach ($reflected_class->getProperties() as $property) {
if ($property->isStatic()) { continue; }
$properties[$property->name] = (object)array(
'name' => $property->name, 'value' => $property->value
, 'access' => $property->getModifier(), 'class' => get_class($this));
unset($this->{$property->name}); }
$this->properties = $properties;
}
}
My apologies if there are any bugs in the code.
html, body {
min-height: 100%;
}
Will do the trick.
By default, even html and body are only as big as the content they hold, but never more than the width/height of the windows. This can often lead to quite strange results.
You might also want to read http://css-tricks.com/perfect-full-page-background-image/
There are some great ways do achieve a very good and scalable full background image.
If you use two databases you can add another DataClasses.dbml and map the second database into it.
It works.
Cause you Only Call Hooks from React Functions
. See more here https://reactjs.org/docs/hooks-rules.html#only-call-hooks-from-react-functions. Just convert Allowance
class component to functional component. The demo working here https://codesandbox.io/s/amazing-poitras-k2fuf
const Allowance = () => {
const [allowances, setAllowances] = useState([]);
useEffect(() => {
fetch("http://127.0.0.1:8000/allowances")
.then(data => {
return data.json();
})
.then(data => {
setAllowances(data);
})
.catch(err => {
console.log(123123);
});
}, []);
const classes = useStyles();
return (
<Paper className={classes.root}>
<Table className={classes.table}>
<TableHead>
<TableRow>
<TableCell>Allow ID</TableCell>
<TableCell align="right">Description</TableCell>
<TableCell align="right">Allow Amount</TableCell>
<TableCell align="right">AllowType</TableCell>
</TableRow>
</TableHead>
<TableBody>
{allowances.map(row => (
<TableRow key={row.id}>
<TableCell component="th" scope="row">
{row.AllowID}
</TableCell>
<TableCell align="right">{row.AllowDesc}</TableCell>
<TableCell align="right">{row.AllowAmt}</TableCell>
<TableCell align="right">{row.AllowType}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</Paper>
);
};
export default Allowance;
Just to note that prefixing the tagName in a selector is slower than just using the id. In your case jQuery will get all the inputs rather than just using the getElementById. Just use $('#textbox')
Use the timeIntervalSinceDate
method
NSTimeInterval secondsElapsed = [secondDate timeIntervalSinceDate:firstDate];
NSTimeInterval
is just a double
, define in NSDate
like this:
typedef double NSTimeInterval;
datetime.date(2011, 1, 1) < datetime.date(2011, 1, 2)
will return True
.
datetime.date(2011, 1, 1) - datetime.date(2011, 1, 2)
will return datetime.timedelta(-1)
.
datetime.date(2011, 1, 1) + datetime.date(2011, 1, 2)
will return datetime.timedelta(1)
.
see the docs.
input(prompt)
is basically equivalent to
def input(prompt):
print(prompt, end='', file=sys.stderr)
return sys.stdin.readline()
You can read directly from sys.stdin
if you like.
lines = sys.stdin.readlines()
lines = [line for line in sys.stdin]
five_lines = list(itertools.islice(sys.stdin, 5))
The first two require that the input end somehow, either by reaching the end of a file or by the user typing Control-D (or Control-Z in Windows) to signal the end. The last one will return after five lines have been read, whether from a file or from the terminal/keyboard.
I think You should use the textView.setTextSize(float size) method to set the size of text. textView.setText(arg) used to set the text in the Text View.
Here are the various ways to do this so you can compare how it looks and choose what you like. I've ordered them in a way that I think is most "pythonic", and commented the pros and cons that might not be obvious at first glance:
Using collections.defaultdict
:
import collections
dict_x = collections.defaultdict(list)
...
dict_x[key].append(value)
Pros: Probably best performance. Cons: Not available in Python 2.4.x.
Using dict().setdefault()
:
dict_x = {}
...
dict_x.setdefault(key, []).append(value)
Cons: Inefficient creation of unused list()
s.
Using try ... except
:
dict_x = {}
...
try:
values = dict_x[key]
except KeyError:
values = dict_x[key] = []
values.append(value)
Or:
try:
dict_x[key].append(value)
except KeyError:
dict_x[key] = [value]
i think csrf only works with spring forms
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
change to form:form
tag and see it that works.
You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...
For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.
In my case I had special instruction into nginx configuration file:
location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
try_files $uri =404;
}
All clients have received '404' because nginx nothing known about Flask.
I hope it help someone.
Load each query into a datatable:
http://www.dotnetcurry.com/ShowArticle.aspx?ID=143
load both datatables into the dataset:
http://msdn.microsoft.com/en-us/library/aeskbwf7%28v=vs.80%29.aspx
@martinho as a newbie using Flask and Python myself, I think the previous answers here took for granted that you had a good understanding of the fundamentals. In case you or other viewers don't know the fundamentals, I'll give more context to understand the answer...
... the request.args
is bringing a "dictionary" object for you. The "dictionary" object is similar to other collection-type of objects in Python, in that it can store many elements in one single object. Therefore the answer to your question
And how many parameters
request.args.get()
takes.
It will take only one object, a "dictionary" type of object (as stated in the previous answers). This "dictionary" object, however, can have as many elements as needed... (dictionaries have paired elements called Key, Value).
Other collection-type of objects besides "dictionaries", would be "tuple", and "list"... you can run a google search on those and "data structures" in order to learn other Python fundamentals. This answer is based Python; I don't have an idea if the same applies to other programming languages.
+-------------------+-----------------+------------------------------+
| Greedy quantifier | Lazy quantifier | Description |
+-------------------+-----------------+------------------------------+
| * | *? | Star Quantifier: 0 or more |
| + | +? | Plus Quantifier: 1 or more |
| ? | ?? | Optional Quantifier: 0 or 1 |
| {n} | {n}? | Quantifier: exactly n |
| {n,} | {n,}? | Quantifier: n or more |
| {n,m} | {n,m}? | Quantifier: between n and m |
+-------------------+-----------------+------------------------------+
Add a ? to a quantifier to make it ungreedy i.e lazy.
Example:
test string : stackoverflow
greedy reg expression : s.*o
output: stackoverflow
lazy reg expression : s.*?o
output: stackoverflow
I have a different proposal which is a pure function (with the same API as the threading suggestion) and seems to work fine (based on suggestions on this thread)
def timeout(func, args=(), kwargs={}, timeout_duration=1, default=None):
import signal
class TimeoutError(Exception):
pass
def handler(signum, frame):
raise TimeoutError()
# set the timeout handler
signal.signal(signal.SIGALRM, handler)
signal.alarm(timeout_duration)
try:
result = func(*args, **kwargs)
except TimeoutError as exc:
result = default
finally:
signal.alarm(0)
return result
some guys who still might have the problem like me (FOR IRANIAN and all the coutries who have sanctions) , this is error can be fixed with proxy
i used this free proxy for android studio 3.2
https://github.com/freedomofdevelopers/fod
just to to Settings (Ctrl + Alt + S)
and search HTTP proxy
then check Manual proxy configuration
then add fodev.org
for host name
and 8118
for Port number
git log origin/master..master
or, more generally:
git log <since>..<until>
You can use this with grep to check for a specific, known commit:
git log <since>..<until> | grep <commit-hash>
Or you can also use git-rev-list to search for a specific commit:
git rev-list origin/master | grep <commit-hash>
I would like to refer a previous question, Because I have faced same problem and solved by this solution.
First of all a constraint is always built with a Hash
value in it's name. So problem is this HASH
is varies in different Machine or Database. For example DF__Companies__IsGlo__6AB17FE4
here 6AB17FE4
is the hash value(8 bit). So I am referring a single script which will be fruitful to all
DECLARE @Command NVARCHAR(MAX)
declare @table_name nvarchar(256)
declare @col_name nvarchar(256)
set @table_name = N'ProcedureAlerts'
set @col_name = N'EmailSent'
select @Command ='Alter Table dbo.ProcedureAlerts Drop Constraint [' + ( select d.name
from
sys.tables t
join sys.default_constraints d on d.parent_object_id = t.object_id
join sys.columns c on c.object_id = t.object_id
and c.column_id = d.parent_column_id
where
t.name = @table_name
and c.name = @col_name) + ']'
--print @Command
exec sp_executesql @Command
It will drop your default constraint. However if you want to create it again you can simply try this
ALTER TABLE [dbo].[ProcedureAlerts] ADD DEFAULT((0)) FOR [EmailSent]
Finally, just simply run a DROP
command to drop the column.