Encode string as unicode.
>>> special = u"\u2022"
>>> abc = u'ABC•def'
>>> abc.replace(special,'X')
u'ABCXdef'
Are those tags on 'http://www.mywebaddress.com'?
Bear in mind the linter will follow the og:url tag as this tag should point to the canonical URL of the piece of content - so if you have a page, e.g. 'http://mywebaddress.com/article1' with an og:url
tag pointing to 'http://mywebaddress.com', Facebook will go there and read the tags there also.
Failing that, the most common reason i've seen for seemingly correct tags not being detected by the linter is user-agent detection returning different content to Facebook's crawler than the content you're seeing when you manually check
Most likely, somewhere on your webserver will be an Alias directive like this;
Alias /phpmyadmin "c:/wamp/apps/phpmyadmin3.1.3.1/"
In my wampserver / localhost setup, it was in c:/wamp/alias/phpmyadmin.conf.
Just change the alias directive and you should be good to go.
JavaScript is fired on client side and JSP is on server-side. So I can say that it is impossible.
.communicate()
writes input (there is no input in this case so it just closes subprocess' stdin to indicate to the subprocess that there is no more input), reads all output, and waits for the subprocess to exit.
The exception EOFError is raised in the child process by raw_input()
(it expected data but got EOF (no data)).
p.stdout.read()
hangs forever because it tries to read all output from the child at the same time as the child waits for input (raw_input()
) that causes a deadlock.
To avoid the deadlock you need to read/write asynchronously (e.g., by using threads or select) or to know exactly when and how much to read/write, for example:
from subprocess import PIPE, Popen
p = Popen(["python", "-u", "1st.py"], stdin=PIPE, stdout=PIPE, bufsize=1)
print p.stdout.readline(), # read the first line
for i in range(10): # repeat several times to show that it works
print >>p.stdin, i # write input
p.stdin.flush() # not necessary in this case
print p.stdout.readline(), # read output
print p.communicate("n\n")[0], # signal the child to exit,
# read the rest of the output,
# wait for the child to exit
Note: it is a very fragile code if read/write are not in sync; it deadlocks.
Beware of block-buffering issue (here it is solved by using "-u" flag that turns off buffering for stdin, stdout in the child).
To view all the changes in an un-popped stash:
git stash show -p stash@{0}
To view the changes of one particular file in an un-popped stash:
git diff HEAD stash@{0} -- path/to/filename.php
I would do this the other way round.
In the OnLoad event for your Main form show the Logon form as a dialog. If the dialog result of that is OK then allow Main to continue loading, if the result is authentication failure then abort the load and show the message box.
EDIT Code sample(s)
private void MainForm_Load(object sender, EventArgs e)
{
this.Hide();
LogonForm logon = new LogonForm();
if (logon.ShowDialog() != DialogResult.OK)
{
//Handle authentication failures as necessary, for example:
Application.Exit();
}
else
{
this.Show();
}
}
Another solution would be to show the LogonForm from the Main method in program.cs, something like this:
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
LogonForm logon = new LogonForm();
Application.Run(logon);
if (logon.LogonSuccessful)
{
Application.Run(new MainForm());
}
}
In this example your LogonForm would have to expose out a LogonSuccessful bool property that is set to true when the user has entered valid credentials
adjustResize = resize the page content
adjustPan = move page content without resizing page content
git reset --hard
This is to revert all your local changes to the origin head
Angular doesn't really provide what you are looking for out of the box. What i would do to accomplish what you're after is use the following add ons
These two will provide you with state based routing and sticky states, you can tab between states and all information will be saved as the scope "stays alive" so to speak.
Check the documentation on both as it's pretty straight forward, ui router extras also has a good demonstration of how sticky states works.
I believe you might be missing a "Grant Connect To" statement when you created the database user.
Below is the complete snippet you will need to create both a login against the SQL Server DBMS as well as a user against the database
USE [master]
GO
CREATE LOGIN [SqlServerLogin] WITH PASSWORD=N'Passwordxyz', DEFAULT_DATABASE=[master], CHECK_EXPIRATION=OFF, CHECK_POLICY=ON
GO
USE [myDatabase]
GO
CREATE USER [DatabaseUser] FOR LOGIN [SqlServerLogin] WITH DEFAULT_SCHEMA=[mySchema]
GO
GRANT CONNECT TO [DatabaseUser]
GO
-- the role membership below will allow you to run a test "select" query against the tables in your database
ALTER ROLE [db_datareader] ADD MEMBER [DatabaseUser]
GO
The location of jfxrt.jar in Oracle Java 7 is:
<JRE_HOME>/lib/jfxrt.jar
The location of jfxrt.jar in Oracle Java 8 is:
<JRE_HOME>/lib/ext/jfxrt.jar
The <JRE_HOME>
will depend on where you installed the Oracle Java and may differ between Linux distributions and installations.
jfxrt.jar is not in the Linux OpenJDK 7 (which is what you are using).
An open source package which provides JavaFX 8 for Debian based systems such as Ubuntu is available. To install this package it is necessary to install both the Debian OpenJDK 8 package and the Debian OpenJFX package. I don't run Debian, so I'm not sure where the Debian OpenJFX package installs jfxrt.jar.
Use Oracle Java 8.
With Oracle Java 8, JavaFX is both included in the JDK and is on the default classpath. This means that JavaFX classes will automatically be found both by the compiler during the build and by the runtime when your users use your application. So using Oracle Java 8 is currently the best solution to your issue.
OpenJDK for Java 8 could include JavaFX (as JavaFX for Java 8 is now open source), but it will depend on the OpenJDK package assemblers as to whether they choose to include JavaFX 8 with their distributions. I hope they do, as it should help remove the confusion you experienced in your question and it also provides a great deal more functionality in OpenJDK.
My understanding is that although JavaFX has been included with the standard JDK since version JDK 7u6
Yes, but only the Oracle JDK.
The JavaFX version bundled with Java 7 was not completely open source so it could not be included in the OpenJDK (which is what you are using).
In you need to use Java 7 instead of Java 8, you could download the Oracle JDK for Java 7 and use that. Then JavaFX will be included with Java 7. Due to the way Oracle configured Java 7, JavaFX won't be on the classpath. If you use Java 7, you will need to add it to your classpath and use appropriate JavaFX packaging tools to allow your users to run your application. Some tools such as e(fx)clipse and NetBeans JavaFX project type will take care of classpath issues and packaging tasks for you.
One of the key differences is that Websites compile dynamically and create on-the-fly assemblies. Web applicaitons compile into one large assembly.
The distinction between the two has been done away with in Visual Studio 2008.
Extending DarenW's comment.
Once typename and class are not accepted to be very different, it might be still valid to be strict on their use. Use class only if is really a class, and typename when its a basic type, such as char.
These types are indeed also accepted instead of typename
template< char myc = '/' >
which would be in this case even superior to typename or class.
Think of "hintfullness" or intelligibility to other people. And actually consider that 3rd party software/scripts might try to use the code/information to guess what is happening with the template (consider swig).
You should probably use either DateTime.ParseExact
or DateTime.TryParseExact
instead. They allow you to specify specific formats. I personally prefer the Try
-versions since I think they produce nicer code for the error cases.
Here is a generic solution using plpgsql:
CREATE OR REPLACE FUNCTION create_role_if_not_exists(rolename NAME) RETURNS TEXT AS
$$
BEGIN
IF NOT EXISTS (SELECT * FROM pg_roles WHERE rolname = rolename) THEN
EXECUTE format('CREATE ROLE %I', rolename);
RETURN 'CREATE ROLE';
ELSE
RETURN format('ROLE ''%I'' ALREADY EXISTS', rolename);
END IF;
END;
$$
LANGUAGE plpgsql;
Usage:
posgres=# SELECT create_role_if_not_exists('ri');
create_role_if_not_exists
---------------------------
CREATE ROLE
(1 row)
posgres=# SELECT create_role_if_not_exists('ri');
create_role_if_not_exists
---------------------------
ROLE 'ri' ALREADY EXISTS
(1 row)
You can use the Pattern
class for this. If you want to match only word characters inside the {}
then you can use the following regex. \w
is a shorthand for [a-zA-Z0-9_]
. If you are ok with _
then use \w
or else use [a-zA-Z0-9]
.
String URL = "https://localhost:8080/sbs/01.00/sip/dreamworks/v/01.00/cui/print/$fwVer/{$fwVer}/$lang/en/$model/{$model}/$region/us/$imageBg/{$imageBg}/$imageH/{$imageH}/$imageSz/{$imageSz}/$imageW/{$imageW}/movie/Kung_Fu_Panda_two/categories/3D_Pix/item/{item}/_back/2?$uniqueID={$uniqueID}";
Pattern pattern = Pattern.compile("/\\{\\w+\\}/");
Matcher matcher = pattern.matcher(URL);
if (matcher.find()) {
System.out.println(matcher.group(0)); //prints /{item}/
} else {
System.out.println("Match not found");
}
Boxing is required, when we have a function that needs object as a parameter, but we have different value types that need to be passed, in that case we need to first convert value types to object data types before passing it to the function.
I don't think that is true, try this instead:
class Program
{
static void Main(string[] args)
{
int x = 4;
test(x);
}
static void test(object o)
{
Console.WriteLine(o.ToString());
}
}
That runs just fine, I didn't use boxing/unboxing. (Unless the compiler does that behind the scenes?)
Java 8 introduced default methods for interfaces using which you can body to the methods. According to OOPs interfaces should act as contract between two systems/parties.
But still i found a way to achieve storing properties in the interface. I admit it is kinda ugly implementation.
import java.util.Map;
import java.util.WeakHashMap;
interface Rectangle
{
class Storage
{
private static final Map<Rectangle, Integer> heightMap = new WeakHashMap<>();
private static final Map<Rectangle, Integer> widthMap = new WeakHashMap<>();
}
default public int getHeight()
{
return Storage.heightMap.get(this);
}
default public int getWidth()
{
return Storage.widthMap.get(this);
}
default public void setHeight(int height)
{
Storage.heightMap.put(this, height);
}
default public void setWidth(int width)
{
Storage.widthMap.put(this, width);
}
}
This interface is ugly. For storing simple property it needed two hashmaps and each hashmap by default creates 16 entries by default. Additionally when real object is dereferenced JVM additionally need to remove this weak reference.
There is a DateTime constructor that takes a long.
DateTime today = new DateTime(t); // where t represents long format of dateTime
I believe it's:
git checkout master
git checkout -b good_quickfix2
git cherry-pick quickfix2^
git cherry-pick quickfix2
I think for pretty-printing something, it's very helpful to know its structure.
To get the structure you have to parse it. Because of this, I don't think it gets much easier than first parsing the JSON string you have and then using the pretty-printing method toString mentioned in the comments above.
Of course you can do similar with any JSON library you like.
get-aduser -Server "servername" -Identity %username% -Properties *
get-aduser -Server "testdomain.test.net" -Identity testuser -Properties *
These work when you have the username. Also less to type than using the -filter
property.
EDIT: Formatting.
Try this:
div{
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
width: 100px;
height: 100px;
background: red;
}
Here div is html tag. You wrote a html tag followed by a dot that is wrong.Only a class is written followed by dot.
here it's the solution for if there have any assigned values inside the string.xml file.
<string name="styled_welcome_message"><![CDATA[We are <b> %1$s </b> glad to see you.]]></string>
set in to TextView:
textView?.setText(HtmlCompat.fromHtml(getString(R.string.styled_welcome_message, "sample"), HtmlCompat.FROM_HTML_MODE_LEGACY), TextView.BufferType.SPANNABLE)
You can look at the query cache: http://www.databasejournal.com/features/mysql/article.php/3110171/MySQLs-Query-Cache.htm but it might not give you access to the actual queries and will be very hit-and-miss if it did work (subtle pun intended)
But MySQL Query Browser very likely maintains its own list of queries that it runs, outside of the MySQL engine. You would have to do the same in your app.
Edit: see dan m's comment leading to this: How to show the last queries executed on MySQL? looks sound.
If you don,t want to write a whitepaper about Email-Standards, then use my following example which just introduce a well known CSS attribute(text-transform: lowercase) to solve the problem:
<input type="email" name="email" id="email" pattern="[a-zA-Z0-9._%+-]+@[a-z0-9.-]+\.[a-zA-Z]{2,4}" style="text-transform: lowercase" placeholder="enter email here ..." title="please enter a valid email" />
_x000D_
Your last example is invalid JSON. Single quotes are not allowed in JSON except inside strings. In the second example, the single quotes are not in the string, but serve to show the start and end.
See http://www.json.org/ for the specifications.
Should add: Why do you think this: "like I seem to need to in my real code"? Then maybe we can help you come up with the solution.
Here's a little method I wrote for exactly this purpose. It uses Validate from Apache Commons.
Feel free to use it.
/**
* Converts a <code>List</code> to a map. One of the methods of the list is called to retrive
* the value of the key to be used and the object itself from the list entry is used as the
* objct. An empty <code>Map</code> is returned upon null input.
* Reflection is used to retrieve the key from the object instance and method name passed in.
*
* @param <K> The type of the key to be used in the map
* @param <V> The type of value to be used in the map and the type of the elements in the
* collection
* @param coll The collection to be converted.
* @param keyType The class of key
* @param valueType The class of the value
* @param keyMethodName The method name to call on each instance in the collection to retrieve
* the key
* @return A map of key to value instances
* @throws IllegalArgumentException if any of the other paremeters are invalid.
*/
public static <K, V> Map<K, V> asMap(final java.util.Collection<V> coll,
final Class<K> keyType,
final Class<V> valueType,
final String keyMethodName) {
final HashMap<K, V> map = new HashMap<K, V>();
Method method = null;
if (isEmpty(coll)) return map;
notNull(keyType, Messages.getString(KEY_TYPE_NOT_NULL));
notNull(valueType, Messages.getString(VALUE_TYPE_NOT_NULL));
notEmpty(keyMethodName, Messages.getString(KEY_METHOD_NAME_NOT_NULL));
try {
// return the Method to invoke to get the key for the map
method = valueType.getMethod(keyMethodName);
}
catch (final NoSuchMethodException e) {
final String message =
String.format(
Messages.getString(METHOD_NOT_FOUND),
keyMethodName,
valueType);
e.fillInStackTrace();
logger.error(message, e);
throw new IllegalArgumentException(message, e);
}
try {
for (final V value : coll) {
Object object;
object = method.invoke(value);
@SuppressWarnings("unchecked")
final K key = (K) object;
map.put(key, value);
}
}
catch (final Exception e) {
final String message =
String.format(
Messages.getString(METHOD_CALL_FAILED),
method,
valueType);
e.fillInStackTrace();
logger.error(message, e);
throw new IllegalArgumentException(message, e);
}
return map;
}
No, that's more or less what they're meant to do.
In C (and many other languages), you can insert hard-to-see/type characters using \
notation:
\a
is alert/bell\b
is backspace/rubout\n
is newline\r
is carriage return (return to left margin)\t
is tabYou can also specify the octal value of any character using \0
nnn, or the hexadecimal value of any character with \x
nn.
_
is octal 137, hex 5f, so it can also be typed \0137
or \x5f
, if your keyboard didn't have a _
key or something. This is more useful for control characters like NUL (\0
) and ESC (\033
)As someone posted (then deleted their answer before I could +1 it), there are also some less-frequently-used ones:
\f
is a form feed/new page (eject page from printer)\v
is a vertical tab (move down one line, on the same column)On screens, \f
usually works the same as \v
, but on some printers/teletypes, it will
go all the way to the next form/sheet of paper.
ES6 sample
const guid=()=> {
const s4=()=> Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
return `${s4() + s4()}-${s4()}-${s4()}-${s4()}-${s4() + s4() + s4()}`;
}
git log -n1 --format="Last committed item in this release was by %an, `git log -n1 --format=%at | awk '{print strftime("%y%m%d%H%M",$1)}'`, message: %s (%h) [%d]"
This is usually caused due to the SSH key is not matching with the remote.
Solutions:
Go to terminal and type the following command (Mac, Linux) replace with your email id.
ssh-keygen -t rsa -C "[email protected]"
Copy the generated key using following command starting from word ssh.
cat ~/.ssh/id_rsa.pub
You can try something like this using HttpClient and HttpPost:
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("mystring", "value_of_my_string"));
// etc...
// Post data to the server
HttpPost httppost = new HttpPost("http://...");
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpClient httpclient = new DefaultHttpClient();
HttpResponse httpResponse = httpclient.execute(httppost);
As mentioned in this answer, you can create a git alias and assign a set of commands for it. In this case, it would be:
git config --global alias.add-com-push '!git add . && git commit -a -m "commit" && git push'
and use it with
git add-com-push
There's an extension for Chrome (SimpleGet) that has a plugin for Windows and Linux that can execute an app with command line parameters.....
http://pinel.cc/
http://code.google.com/p/simple-get/
http://www.chromeextensions.org/other/simple-get/
UPDATE: ViewDidUnload was deprecated in iOS 6, so updated the answer accordingly.
The UIViewController lifecycle is diagrammed here:
The advantage of using Xamarin Native/Mono Touch, is that it uses the native APIs, and so it follows the same ViewController lifecycle as you would find in Apple's Documentation.
In C++ you can only use a switch statement on int and char
While Python 3 deals in Unicode, the Windows console or POSIX tty that you're running inside does not. So, whenever you print
, or otherwise send Unicode strings to stdout
, and it's attached to a console/tty, Python has to encode it.
The error message indirectly tells you what character set Python was trying to use:
File "C:\Python32\lib\encodings\cp850.py", line 19, in encode
This means the charset is cp850
.
You can test or yourself that this charset doesn't have the appropriate character just by doing '\u2013'.encode('cp850')
. Or you can look up cp850 online (e.g., at Wikipedia).
It's possible that Python is guessing wrong, and your console is really set for, say UTF-8. (In that case, just manually set sys.stdout.encoding='utf-8'
.) It's also possible that you intended your console to be set for UTF-8 but did something wrong. (In that case, you probably want to follow up at superuser.com.)
But if nothing is wrong, you just can't print that character. You will have to manually encode it with one of the non-strict error-handlers. For example:
>>> '\u2013'.encode('cp850')
UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 0: character maps to <undefined>
>>> '\u2013'.encode('cp850', errors='replace')
b'?'
So, how do you print a string that won't print on your console?
You can replace every print
function with something like this:
>>> print(r['body'].encode('cp850', errors='replace').decode('cp850'))
?
… but that's going to get pretty tedious pretty fast.
The simple thing to do is to just set the error handler on sys.stdout
:
>>> sys.stdout.errors = 'replace'
>>> print(r['body'])
?
For printing to a file, things are pretty much the same, except that you don't have to set f.errors
after the fact, you can set it at construction time. Instead of this:
with open('path', 'w', encoding='cp850') as f:
Do this:
with open('path', 'w', encoding='cp850', errors='replace') as f:
… Or, of course, if you can use UTF-8 files, just do that, as Mark Ransom's answer shows:
with open('path', 'w', encoding='utf-8') as f:
The Diagnostics messages are displayed in the Output Window.
If you are using PHP, just use the addslashes() function.
Running the following commands solved this for me 1. python manage.py migrate 2. python manage.py makemigrations 3. python manage.py makemigrations appName
Go via POSIXct
and you want to set a TZ
there -- here you see my (Chicago) default:
R> val <- 1352068320
R> as.POSIXct(val, origin="1970-01-01")
[1] "2012-11-04 22:32:00 CST"
R> as.Date(as.POSIXct(val, origin="1970-01-01"))
[1] "2012-11-05"
R>
Edit: A few years later, we can now use the anytime package:
R> library(anytime)
R> anytime(1352068320)
[1] "2012-11-04 16:32:00 CST"
R> anydate(1352068320)
[1] "2012-11-04"
R>
Note how all this works without any format or origin arguments.
var d = new Date(2011,10,30);
as months are indexed from 0 in js.
You can try it:
ImageIcon imageIcon = new ImageIcon(new ImageIcon("icon.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT));
label.setIcon(imageIcon);
Or in one line:
label.setIcon(new ImageIcon(new ImageIcon("icon.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT)));
The execution time is much more faster than File and ImageIO.
I recommend you to compare the two solutions in a loop.
It is safe to keep a horse in a stable with a half door, as a horse cannot get over a half door. Therefore I setup a horse housing service that accepts any item of type horse and puts it in a stable with a half door.
So is a horse like animal that can fly even a horse?
I used to think a lot about multiple inheritance, however now that I have been programming for over 15 years, I no longer care about implementing multiple inheritance.
More often than not, when I have tried to cope with a design that pointed toward multiple inheritance, I have later come to release that I had miss understood the problem domain.
OR
What is a monkey patch?
Simply put, monkey patching is making changes to a module or class while the program is running.
There's an example of monkey-patching in the Pandas documentation:
import pandas as pd
def just_foo_cols(self):
"""Get a list of column names containing the string 'foo'
"""
return [x for x in self.columns if 'foo' in x]
pd.DataFrame.just_foo_cols = just_foo_cols # monkey-patch the DataFrame class
df = pd.DataFrame([list(range(4))], columns=["A","foo","foozball","bar"])
df.just_foo_cols()
del pd.DataFrame.just_foo_cols # you can also remove the new method
To break this down, first we import our module:
import pandas as pd
Next we create a method definition, which exists unbound and free outside the scope of any class definitions (since the distinction is fairly meaningless between a function and an unbound method, Python 3 does away with the unbound method):
def just_foo_cols(self):
"""Get a list of column names containing the string 'foo'
"""
return [x for x in self.columns if 'foo' in x]
Next we simply attach that method to the class we want to use it on:
pd.DataFrame.just_foo_cols = just_foo_cols # monkey-patch the DataFrame class
And then we can use the method on an instance of the class, and delete the method when we're done:
df = pd.DataFrame([list(range(4))], columns=["A","foo","foozball","bar"])
df.just_foo_cols()
del pd.DataFrame.just_foo_cols # you can also remove the new method
If you're using name-mangling (prefixing attributes with a double-underscore, which alters the name, and which I don't recommend) you'll have to name-mangle manually if you do this. Since I don't recommend name-mangling, I will not demonstrate it here.
How can we use this knowledge, for example, in testing?
Say we need to simulate a data retrieval call to an outside data source that results in an error, because we want to ensure correct behavior in such a case. We can monkey patch the data structure to ensure this behavior. (So using a similar method name as suggested by Daniel Roseman:)
import datasource
def get_data(self):
'''monkey patch datasource.Structure with this to simulate error'''
raise datasource.DataRetrievalError
datasource.Structure.get_data = get_data
And when we test it for behavior that relies on this method raising an error, if correctly implemented, we'll get that behavior in the test results.
Just doing the above will alter the Structure
object for the life of the process, so you'll want to use setups and teardowns in your unittests to avoid doing that, e.g.:
def setUp(self):
# retain a pointer to the actual real method:
self.real_get_data = datasource.Structure.get_data
# monkey patch it:
datasource.Structure.get_data = get_data
def tearDown(self):
# give the real method back to the Structure object:
datasource.Structure.get_data = self.real_get_data
(While the above is fine, it would probably be a better idea to use the mock
library to patch the code. mock
's patch
decorator would be less error prone than doing the above, which would require more lines of code and thus more opportunities to introduce errors. I have yet to review the code in mock
but I imagine it uses monkey-patching in a similar way.)
You don't need to pass the quotes enclosing the custom headers to curl. Also, your variables in the middle of the data
argument should be quoted.
First, write a function that generates the post data of your script. This saves you from all sort of headaches concerning shell quoting and makes it easier to read an maintain the script than feeding the post data on curl's invocation line as in your attempt:
generate_post_data()
{
cat <<EOF
{
"account": {
"email": "$email",
"screenName": "$screenName",
"type": "$theType",
"passwordSettings": {
"password": "$password",
"passwordConfirm": "$password"
}
},
"firstName": "$firstName",
"lastName": "$lastName",
"middleName": "$middleName",
"locale": "$locale",
"registrationSiteId": "$registrationSiteId",
"receiveEmail": "$receiveEmail",
"dateOfBirth": "$dob",
"mobileNumber": "$mobileNumber",
"gender": "$gender",
"fuelActivationDate": "$fuelActivationDate",
"postalCode": "$postalCode",
"country": "$country",
"city": "$city",
"state": "$state",
"bio": "$bio",
"jpFirstNameKana": "$jpFirstNameKana",
"jpLastNameKana": "$jpLastNameKana",
"height": "$height",
"weight": "$weight",
"distanceUnit": "MILES",
"weightUnit": "POUNDS",
"heightUnit": "FT/INCHES"
}
EOF
}
It is then easy to use that function in the invocation of curl:
curl -i \
-H "Accept: application/json" \
-H "Content-Type:application/json" \
-X POST --data "$(generate_post_data)" "https://xxx:[email protected]/xxxxx/xxxx/xxxx"
This said, here are a few clarifications about shell quoting rules:
The double quotes in the -H
arguments (as in -H "foo bar"
) tell bash to keep what's inside as a single argument (even if it contains spaces).
The single quotes in the --data
argument (as in --data 'foo bar'
) do the same, except they pass all text verbatim (including double quote characters and the dollar sign).
To insert a variable in the middle of a single quoted text, you have to end the single quote, then concatenate with the double quoted variable, and re-open the single quote to continue the text: 'foo bar'"$variable"'more foo'
.
This was my solution, which is much easier to read than other suggestions here, can easily include other key combinations, and has been tested on IE, Chrome, and Firefox:
$(window).keydown(function(evt) {
var key = String.fromCharCode(evt.keyCode);
//ctrl+s
if (key.toLowerCase() === "s" && evt.ctrlKey) {
fnToRun();
evt.preventDefault(true);
return false;
}
return true;
});
Mostly in Hibernate
, need to add the Entity
class in hibernate.cfg.xml
like-
<hibernate-configuration>
<session-factory>
....
<mapping class="xxx.xxx.yourEntityName"/>
</session-factory>
</hibernate-configuration>
I prefer the count()
function instead of sizeOf()
as sizeOf()
is only an alias of count()
and does not mean the same in many other languages. Many programmers expect sizeof()
to return the amount of memory allocated.
Since pandas 0.22 update, comparison options are available like:
and many more. These functions return boolean array. Let's see how we can use them:
# sample data
df = pd.DataFrame({'col1': [0, 1, 2,3,4,5], 'col2': [10, 11, 12,13,14,15]})
# get values from col1 greater than or equals to 1
df.loc[df['col1'].ge(1),'col1']
1 1
2 2
3 3
4 4
5 5
# where co11 values is better 0 and 2
df.loc[df['col1'].between(0,2)]
col1 col2
0 0 10
1 1 11
2 2 12
# where col1 > 1
df.loc[df['col1'].gt(1)]
col1 col2
2 2 12
3 3 13
4 4 14
5 5 15
I've come across it several different times and every time it was always some error with either duplicating a tab name or in this current case it just occurred because I simply had a typo in the get_Range
where I tried to get a Cell by number and number instead of the letter and number.
Drove me crazy because the error pointed me to a few lines down but I had commented out all of the creation of the other sheets above the "error line" and the ones in the line and below were created with no issue.
Happened to scan up a few lines above and saw that I put 6 + lastword, C + lastrow
in my get_Range
statement and of course you can't have a cell starting with a number it's always letter than number.
Can't seem to edit the other answer. Has a minor error in that it is Windows-only. The more generic solution is to use os.sep as below:
sys.path might include items that aren't specifically in your PYTHONPATH environment variable. To query the variable directly, use:
import os
os.environ['PYTHONPATH'].split(os.pathsep)
//sure run it i will also test it
//we make a class that extends with the fragment
public class Example_3_1 extends Fragment implements OnClickListener
{
View vi;
EditText t;
EditText t1;
Button bu;
// that are by defult function of fragment extend class
@Override
public View onCreateView(LayoutInflater inflater,ViewGroup container,BundlesavedInstanceState)
{
vi=inflater.inflate(R.layout.example_3_1, container, false);// load the xml file
bu=(Button) vi.findViewById(R.id.button1);// get button id from example_3_1 xml file
bu.setOnClickListener(this); //on button appay click listner
t=(EditText) vi.findViewById(R.id.editText1);// id get from example_3_1 xml file
t1=(EditText) vi.findViewById(R.id.editText2);
return vi; // return the view object,that set the xml file example_3_1 xml file
}
@Override
public void onClick(View v)//on button click that called
{
switch(v.getId())// on run time get id what button os click and get id
{
case R.id.button1: // it mean if button1 click then this work
t.setText("UMTien"); //set text
t1.setText("programming");
break;
}
} }
I needed to do this same task and came upon this thread. I ended up using the array "join" to create a string using a "_" separator, then doing a bit of regex to:-
1. replace "__" or more with just one "_",
2. replace preceding "_" with nothing "" and similarly
3. replace and ending "_" with nothing ""
...then using array "split" to make a cleaned-up array:-
var myArr = new Array("","","a","b","","c","","","","","","","","","e","");
var myStr = "";
myStr = myArr.join("_");
myStr = myStr.replace(new RegExp(/__*/g),"_");
myStr = myStr.replace(new RegExp(/^_/i),"");
myStr = myStr.replace(new RegExp(/_$/i),"");
myArr = myStr.split("_");
alert("myArr=" + myArr.join(","));
...or in 1 line of code:-
var myArr = new Array("","","a","b","","c","","","","","","","","","e","");
myArr = myArr.join("_").replace(new RegExp(/__*/g),"_").replace(new RegExp(/^_/i),"").replace(new RegExp(/_$/i),"").split("_");
alert("myArr=" + myArr.join(","));
...or, extending the Array object :-
Array.prototype.clean = function() {
return this.join("_").replace(new RegExp(/__*/g),"_").replace(new RegExp(/^_/i),"").replace(new RegExp(/_$/i),"").split("_");
};
var myArr = new Array("","","a","b","","c","","","","","","","","","e","");
alert("myArr=" + myArr.clean().join(","));
Add a unique id to all your instances, i.e.
public interface Idable {
int id();
}
public class IdGenerator {
private static int id = 0;
public static synchronized int generate() { return id++; }
}
public abstract class AbstractSomething implements Idable {
private int id;
public AbstractSomething () {
this.id = IdGenerator.generate();
}
public int id() { return id; }
}
Extend from AbstractSomething and query this property. Will be safe inside a single vm (assuming no game playing with classloaders to get around statics).
You might want to do this.
input[type=checkbox] {
-ms-transform: scale(2); /* IE */
-moz-transform: scale(2); /* FF */
-webkit-transform: scale(2); /* Safari and Chrome */
-o-transform: scale(2); /* Opera */
padding: 10px;
}
Here is a full example where the parent widget controls the children widget. The parent widget updates the children widgets (Text and TextField) with a counter.
To update the Text widget, all you do is pass in the String parameter. To update the TextField widget, you need to pass in a controller, and set the text in the controller.
main.dart:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Demo',
home: Home(),
);
}
}
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Update Text and TextField demo'),
),
body: ParentWidget());
}
}
class ParentWidget extends StatefulWidget {
@override
_ParentWidgetState createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
int _counter = 0;
String _text = 'no taps yet';
var _controller = TextEditingController(text: 'initial value');
void _handleTap() {
setState(() {
_counter = _counter + 1;
_text = 'number of taps: ' + _counter.toString();
_controller.text = 'number of taps: ' + _counter.toString();
});
}
@override
Widget build(BuildContext context) {
return Container(
child: Column(children: <Widget>[
RaisedButton(
onPressed: _handleTap,
child: const Text('Tap me', style: TextStyle(fontSize: 20)),
),
Text('$_text'),
TextField(controller: _controller,),
]),
);
}
}
In Access, click Create > Module
and paste in the following code
Public Function ConvertMyStringToDateTime(strIn As String) As Date
ConvertMyStringToDateTime = CDate( _
Mid(strIn, 1, 4) & "-" & Mid(strIn, 5, 2) & "-" & Mid(strIn, 7, 2) & " " & _
Mid(strIn, 9, 2) & ":" & Mid(strIn, 11, 2) & ":" & Mid(strIn, 13, 2))
End Function
Hit Ctrl+S and save the module as modDateConversion
.
Now try using a query like
Select * from Events
Where Events.[Date] > ConvertMyStringToDateTime("20130423014854")
--- Edit ---
Alternative solution avoiding user-defined VBA function:
SELECT * FROM Events
WHERE Format(Events.[Date],'yyyyMMddHhNnSs') > '20130423014854'
Simple and straight forward way to create ArrayList of String
List<String> category = Arrays.asList("everton", "liverpool", "swansea", "chelsea");
Cheers
The following worked for me. Nothing else did, unfortunately.
npm uninstall @angular-devkit/build-angular
npm install @angular-devkit/build-angular
ng update --all --allow-dirty --force
Final answer was a combination of two of the above (I've upvoted both to show my appreciation!):
select case
when exists (
SELECT 1
FROM Sys.columns c
WHERE c.[object_id] = OBJECT_ID('dbo.Tags')
AND c.name = 'ModifiedByUserId'
)
then 1
else 0
end
You can call view.setVisibility(View.GONE)
if you want to remove it from the layout.
Or view.setVisibility(View.INVISIBLE)
if you just want to hide it.
From Android Docs:
INVISIBLE
This view is invisible, but it still takes up space for layout purposes. Use with
setVisibility(int)
andandroid:visibility
.GONE
This view is invisible, and it doesn't take any space for layout purposes. Use with
setVisibility(int)
andandroid:visibility
.
If you want to give a variable that contains the minutes.
Then I think this is a great way to achieve this.
$minutes = 10;
$maxAge = new DateTime('2011-11-17 05:05');
$maxAge->modify("+{$minutes} minutes");
A much faster method on windows (0.05s), call a bat script that does this:
get_latest.bat
@echo off
for /f %%i in ('dir \\directory\in\question /b/a-d/od/t:c') do set LAST=%%i
%LAST%
where \\directory\in\question
is the directory you want to investigate.
get_latest.py
from subprocess import Popen, PIPE
p = Popen("get_latest.bat", shell=True, stdout=PIPE,)
stdout, stderr = p.communicate()
print(stdout, stderr)
if it finds a file stdout
is the path and stderr
is None.
Use stdout.decode("utf-8").rstrip()
to get the usable string representation of the file name.
TemplateBinding is a shorthand for Binding with TemplatedParent but it does not expose all the capabilities of the Binding class, for example you can't control Binding.Mode from TemplateBinding.
If this is your detail.html
I don't see where do you load detail.js
?
Maybe this
<script src="js/index.js"></script>
should be this
<script src="js/detail.js"></script>
?
public byte UserType
public string SelectUserType
You need to get one and set different one. Selected value can not be the same item that you are about to set.
@Html.DropDownListFor(p => p.SelectUserType, new SelectList(~~UserTypeNames, "Key", "Value",UserType))
I use Enum dictionary for my list, that's why there is "key", "value" pair.
You can use command ionic info to get details of ionic CLI , angular CLI , Node JS version and NPM version
I use tortoiseGit. I had the same problem. Then in push settings I unchecked "autoload putty key", tried to push, then I checked it again, and pushed, and it worked. But seriously, I don't know why.
You can convert to an array and call array soring methods on it:
[...map].sort(/* etc */);
I would echo the Json.NET library, which can transform the JSON response into a XML document. With the XML document, you can easily query with XPath and extract the data you need. I find this pretty useful.
please set dataType config property in your ajax call and give it another try!
another point is you are using ajax call setup configuration properties as string and it is wrong as reference site
$.ajax({
url : 'http://voicebunny.comeze.com/index.php',
type : 'GET',
data : {
'numberOfWords' : 10
},
dataType:'json',
success : function(data) {
alert('Data: '+data);
},
error : function(request,error)
{
alert("Request: "+JSON.stringify(request));
}
});
I hope be helpful!
To reflect the status as of 2015:
Behaviorally both 400 and 422 response codes will be treated the same by clients and intermediaries, so it actually doesn't make a concrete difference which you use.
However I would expect to see 400 currently used more widely, and furthermore the clarifications that the HTTPbis spec provides make it the more appropriate of the two status codes:
For context, HTTPbis is a revision of the HTTP/1.1 spec that attempts to clarify areas that were unclear or inconsistent. Once it has reached approved status it will supersede RFC2616.
It's available in the HTTP referer
header. You can get it in a servlet as follows:
String referrer = request.getHeader("referer"); // Yes, with the legendary misspelling.
You, however, need to realize that this is a client-controlled value and can thus be spoofed to something entirely different or even removed. Thus, whatever value it returns, you should not use it for any critical business processes in the backend, but only for presentation control (e.g. hiding/showing/changing certain pure layout parts) and/or statistics.
For the interested, background about the misspelling can be found in Wikipedia.
One can use assign method of DataFrame:
df= (pd.DataFrame({'Year': ['2014', '2015'], 'quarter': ['q1', 'q2']}).
assign(period=lambda x: x.Year+x.quarter ))
This is the sort of thing that sed
is really good at: $ sed 's/[ \t]*$//'
. Be aware the you will probably need to literally type a TAB character instead of \t
for this to work.
Outlook adds the signature to the new unmodified messages (you should not modify the body prior to that) when you call MailItem.Display
(which causes the message to be displayed on the screen) or when you access the MailItem.GetInspector
property - you do not have to do anything with the returned Inspector object, but Outlook will populate the message body with the signature.
Once the signature is added, read the HTMLBody
property and merge it with the HTML string that you are trying to set. Note that you cannot simply concatenate 2 HTML strings - the strings need to be merged. E.g. if you want to insert your string at the top of the HTML body, look for the "<body"
substring, then find the next occurrence of ">" (this takes care of the <body>
element with attributes), then insert your HTML string after that ">".
Outlook Object Model does not expose signatures at all.
On a general note, the name of the signature is stored in the account profile data accessible through the IOlkAccountManager Extended MAPI interface. Since that interface is Extended MAPI, it can only be accessed using C++ or Delphi. You can see the interface and its data in OutlookSpy if you click the IOlkAccountManager
button.
Once you have the signature name, you can read the HTML file from the file system (keep in mind that the folder name (Signatures in English) is localized.
Also keep in mind that if the signature contains images, they must also be added to the message as attachments and the <img>
tags in the signature/message body adjusted to point the src
attribute to the attachments rather than a subfolder of the Signatures folder where the images are stored.
It will also be your responsibility to merge the HTML styles from the signature HTML file with the styles of the message itself.
If using Redemption is an option, you can use its RDOAccount object (accessible in any language, including VBA). New message signature name is stored in the 0x0016001F
property, reply signature is in 0x0017001F
.
You can also use the RDOAccount.ReplySignature
and NewSignature
properties.
Redemption also exposes RDOSignature.ApplyTo
method that takes a pointer to the RDOMail object and inserts the signature at the specified location correctly merging the images and the styles:
set Session = CreateObject("Redemption.RDOSession")
Session.MAPIOBJECT = Application.Session.MAPIOBJECT
set Drafts = Session.GetDefaultFolder(olFolderDrafts)
set Msg = Drafts.Items.Add
Msg.To = "[email protected]"
Msg.Subject = "testing signatures"
Msg.HTMLBody = "<html><body>some <b>bold</b> message text</body></html>"
set Account = Session.Accounts.GetOrder(2).Item(1) 'first mail account
if Not (Account Is Nothing) Then
set Signature = Account.NewMessageSignature
if Not (Signature Is Nothing) Then
Signature.ApplyTo Msg, false 'apply at the bottom
End If
End If
Msg.Send
EDIT: as of July 2017, MailItem.GetInspector
in Outlook 2016 no longer inserts the signature. Only MailItem.Display
does.
Use --single-branch
option to only clone history leading to tip of the tag. This saves a lot of unnecessary code from being cloned.
git clone <repo_url> --branch <tag_name> --single-branch
Editing a Parameter The set method of the URLSearchParams object sets the new value of the parameter.
After setting the new value you can get the new query string with the toString() method. This query string can be set as the new value of the search property of the URL object.
The final new url can then be retrieved with the toString() method of the URL object.
var query_string = url.search;
var search_params = new URLSearchParams(query_string);
// new value of "id" is set to "101"
search_params.set('id', '101');
// change the search property of the main url
url.search = search_params.toString();
// the new url string
var new_url = url.toString();
// output : http://demourl.com/path?id=101&topic=main
console.log(new_url);
Source - https://usefulangle.com/post/81/javascript-change-url-parameters
The Lazy<T>
version:
public sealed class Singleton
{
private static readonly Lazy<Singleton> lazy
= new Lazy<Singleton>(() => new Singleton());
public static Singleton Instance
=> lazy.Value;
private Singleton() { }
}
Requires .NET 4 and C# 6.0 (VS2015) or newer.
When a servlet 3.0 application starts the container has to scan all the classes for annotations (unless metadata-complete=true). Tomcat uses a fork (no additions, just unused code removed) of Apache Commons BCEL to do this scanning. The web app is failing to start because BCEL has come across something it doesn't understand.
If the applications runs fine on Tomcat 6, adding metadata-complete="true" in your web.xml or declaring your application as a 2.5 application in web.xml will stop the annotation scanning.
At the moment, this looks like a problem in the class being scanned. However, until we know which class is causing the problem and take a closer look we won't know. I'll need to modify Tomcat to log a more useful error message that names the class in question. You can follow progress on this point at: https://issues.apache.org/bugzilla/show_bug.cgi?id=53161
using PowerShell you can install the required feature with:
Add-WindowsFeature 'NET-HTTP-Activation'
If you have a module with a class you want to import, you can do it like this.
module = __import__(filename)
instance = module.MyClass()
If you do not know what the class is named, you can iterate through the classes available from a module.
import inspect
module = __import__(filename)
for c in module.__dict__.values():
if inspect.isclass(c):
# You may need do some additional checking to ensure
# it's the class you want
instance = c()
I solved the same problem without the temp table/view and with dataframe functions.
Of course I found that only one format works with this solution and that's yyyy-MM-DD
.
For example:
val df = sc.parallelize(Seq("2016-08-26")).toDF("Id")
val df2 = df.withColumn("Timestamp", (col("Id").cast("timestamp")))
val df3 = df2.withColumn("Date", (col("Id").cast("date")))
df3.printSchema
root
|-- Id: string (nullable = true)
|-- Timestamp: timestamp (nullable = true)
|-- Date: date (nullable = true)
df3.show
+----------+--------------------+----------+
| Id| Timestamp| Date|
+----------+--------------------+----------+
|2016-08-26|2016-08-26 00:00:...|2016-08-26|
+----------+--------------------+----------+
The timestamp of course has 00:00:00.0
as a time value.
You have to be more precise, using parentheses, otherwise Java will not use the order of operands that you want it to use.
if ((a[0] & 1 == 0) && (a[1] & 1== 0) && (a[2] & 1== 0)){
Becomes
if (((a[0] & 1) == 0) && ((a[1] & 1) == 0) && ((a[2] & 1) == 0)){
Version 12 of the ReportViewer bits is referred to as Microsoft Report Viewer 2015 Runtime and can downloaded for installation from the following link:
https://www.microsoft.com/en-us/download/details.aspx?id=45496
UPDATE:
The ReportViewer bits are also available as a NUGET package: https://www.nuget.org/packages/Microsoft.ReportViewer.Runtime.Common/12.0.2402.15
Install-Package Microsoft.ReportViewer.Runtime.Common
The string
class has a constructor that takes a NULL-terminated C-string:
char arr[ ] = "This is a test";
string str(arr);
// You can also assign directly to a string.
str = "This is another string";
// or
str = arr;
You should clear out your listbbox prior to binding:
Me.ddl2.Items.Clear()
' now set datasource and bind
This will allow both positive and negative integers
ValidationExpression="^-?[0-9]\d*(\d+)?$"
Assuming your input is a standard null-terminated C string, you want to use strchr
:
#include <string.h>
char* foo = "abcdefghijkl";
if (strchr(foo, 'a') != NULL)
{
// do stuff
}
If on the other hand your array is not null-terminated (i.e. just raw data), you'll need to use memchr
and provide a size:
#include <string.h>
char foo[] = { 'a', 'b', 'c', 'd', 'e' }; // note last element isn't '\0'
if (memchr(foo, 'a', sizeof(foo)))
{
// do stuff
}
u can also show a certain number of digit after decimal point(here 2 digits) using following code :
var num = (15.46974).toFixed(2)_x000D_
console.log(num) // 15.47_x000D_
console.log(typeof num) // string
_x000D_
Since it wasn't mentioned, you can also use the CSS white-space property
body{
white-space:pre-wrap;
}
Which tells the browser to preserve whitespace so that
<body>
<?php
echo "hello\nthere";
?>
</body>
Would display
hello
there
As Jeffrey Said, you are not checking the value of check()
. In addition, your check()
function is not returning anything. Note the difference:
def check():
with open('example.txt') as f:
datafile = f.readlines()
found = False # This isn't really necessary
for line in datafile:
if blabla in line:
# found = True # Not necessary
return True
return False # Because you finished the search without finding
Then you can test the output of check()
:
if check():
print('True')
else:
print('False')
You can not restore database (or attach) created in the upper version into lower version. The only way is to create a script for all objects and use the script to generate database.
select "Schema and Data" - if you want to Take both the things in to the Backup script file
select Schema Only - if only schema is needed.
Yes, now you have done with the Create Script with Schema and Data of the Database.
The best way is to create a variable of type Worksheet
, assign the worksheet and use it every time the VBA would implicitly use the ActiveSheet
.
This will help you avoid bugs that will eventually show up when your program grows in size.
For example something like Range("A1:C10").Sort Key1:=Range("A2")
is good when the macro works only on one sheet. But you will eventually expand your macro to work with several sheets, find out that this doesn't work, adjust it to ShTest1.Range("A1:C10").Sort Key1:=Range("A2")
... and find out that it still doesn't work.
Here is the correct way:
Dim ShTest1 As Worksheet
Set ShTest1 = Sheets("Test1")
ShTest1.Range("A1:C10").Sort Key1:=ShTest1.Range("A2")
@Robusto's solution was the simplest for what I was trying to do, I suggest you use it. I was trying to do the same thing for images in an unordered list to make a gallery... I made a js fiddle to fool around with it. Feel free to try it here.
[it was set up using robusto's sample code]
HTML:
<div id="centerDiv">
<ul class="centerUL">
<li><a href="http://www.amazon.com"><img src="http://placehold.it/200x150> </a> </li>
<li><a href="http://www.amazon.com"><img src="http://placehold.it/200x150"></a> </li>
<li><a href="http://www.amazon.com"><img src="http://placehold.it/200x150"></a></li>
</ul>
</div>
CSS:
div#centerDiv {
width: 700px;
text-align: center;
border: 1px solid red;
}
ul.centerUL {
margin: 2px auto;
line-height: 1.4;
}
.centerUL li {
display: inline;
text-align: center;
}
Here is the answer to the question here
Actually we have to get it from the sharable ContentProvider of Camera Application.
EDIT . Copying answer that worked for me
private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
function createOfferUrlArray($Offer) {
$offerArray = array();
foreach ($Offer as $key => $value) {
$offerArray[$key] = $value[4];
}
return $offerArray;
}
or
function createOfferUrlArray($offer) {
foreach ( $offer as &$value ) {
$value = $value[4];
}
unset($value);
return $offer;
}
The new version has changed.. for the latest version use the code below:
$('#UpToDate').datetimepicker({
format:'MMMM DD, YYYY',
maxDate:moment(),
defaultDate:moment()
}).on('dp.change',function(e){
console.log(e);
});
You can also use ngIf
if the situation permits:
<div ng-repeat="p in [
{ name: 'Justin' },
{ name: 'Jimi' },
{ name: 'Bob' }
]" ng-if="['Jimi', 'Bob'].indexOf(e.name) > -1">
{{ p.name }} is cool
</div>
you can use log4net.Filter.LevelMatchFilter. other options can be found at log4net tutorial - filters
in ur appender section add
<filter type="log4net.Filter.LevelMatchFilter">
<levelToMatch value="Info" />
<acceptOnMatch value="true" />
</filter>
the accept on match default is true so u can leave it out but if u set it to false u can filter out log4net filters
After a quick google:
__STDC__
and __STDC_VERSION__
, see here
def lst = ["A2", "A1", "k22", "A6", "a3", "a5", "A4", "A7"];
println lst.sort { a, b -> a.compareToIgnoreCase b }
This should be able to sort with case insensitive but I am not sure how to tackle the alphanumeric strings lists
My solution will be to keep text part of tool bar separate, to define style and say, center or whichever alignment. It can be done in XML itself. Some paddings can be specified after doing calculations when you have actions that are visible always. I have moved two attributes from toolbar to its child TextView. This textView can be provided id to be accessed from fragments.
<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true">
<com.google.android.material.appbar.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="@style/AppTheme.AppBarOverlay">
<androidx.appcompat.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="@style/AppTheme.PopupOverlay" >
<!--android:theme="@style/defaultTitleTheme"
app:titleTextColor="@color/white"-->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:paddingStart="@dimen/icon_size"
android:text="@string/title_home"
style="@style/defaultTitleTheme"
tools:ignore="RtlSymmetry" />
</androidx.appcompat.widget.Toolbar>
</com.google.android.material.appbar.AppBarLayout>
<FrameLayout
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.coordinatorlayout.widget.CoordinatorLayout>
DirectoryInfo objDir = new DirectoryInfo(direcotryPath);
DirectoryInfo [] directoryNames = objDir.GetDirectories("*.*", SearchOption.AllDirectories);
This will give you all the directories and subdirectories.
Try:
which( !is.na(p), arr.ind=TRUE)
Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:
> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3
[[2]]
[1] 4 7
[[3]]
integer(0)
[[4]]
[1] 5
[[5]]
integer(0)
Or even with smushing together with paste:
lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")
The output from which
function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:
> which( !is.na(p), arr.ind=TRUE)
row col
[1,] 1 2
[2,] 1 3
[3,] 2 4
[4,] 4 5
[5,] 2 7
Without the arr.ind
parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".
> which( !is.na(p) )
[1] 6 11 17 24 32
you can use background-clip and box-model with border proprety
.box{
box-model: border-box;
border: 3px solid transparent;
background-clip:padding-box;
}
<div class="row">
<div class="col-xs-4 box"></div>
<div class="col-xs-4 box"></div>
<div class="col-xs-4 box"></div>
</div>
Try this in your console:
javac {$PathToYourProyect}/*
If you also need any external library, try:
javac -cp {$PathToYourLibrary}.jar {$PathToYourProyect}/*
If you want to do it via javascript rather than CSS you can use:
var link = document.getElementById('nav-ask');
link.style.display = 'none'; //or
link.style.visibility = 'hidden';
depending on what you want to do.
Generally, you would not include the comma after the final entry, but Python will correct that for you.
Have added ErrorHandler to this in case the user hits the cancel button instead of selecting a folder. So instead of getting a horrible error message you get a message that a folder must be selected and then the routine ends. Below code also stores the folder path in a range name (Which is just linked to cell A1 on a sheet).
Sub SelectFolder()
Dim diaFolder As FileDialog
'Open the file dialog
On Error GoTo ErrorHandler
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
diaFolder.Title = "Select a folder then hit OK"
diaFolder.Show
Range("IC_Files_Path").Value = diaFolder.SelectedItems(1)
Set diaFolder = Nothing
Exit Sub
ErrorHandler:
Msg = "No folder selected, you must select a folder for program to run"
Style = vbError
Title = "Need to Select Folder"
Response = MsgBox(Msg, Style, Title)
End Sub
Try this:
#foo
{
position: absolute;
top: 100%;
right: 0%;
}
This will maybe give you a hint on what went wrong.
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
BigDecimal bdTest = new BigDecimal(0.745);
BigDecimal bdTest1 = new BigDecimal("0.745");
bdTest = bdTest.setScale(2, BigDecimal.ROUND_HALF_UP);
bdTest1 = bdTest1.setScale(2, BigDecimal.ROUND_HALF_UP);
System.out.println("bdTest:" + bdTest); // prints "bdTest:0.74"
System.out.println("bdTest1:" + bdTest1); // prints "bdTest:0.75"
}
}
The problem is, that your input (a double x=0.745;
) can not represent 0.745 exactly. It actually saves a value slightly lower. For BigDecimals
, this is already below 0.745, so it rounds down...
Try not to use the BigDecimal(double/float)
constructors.
From my perspective the question is pretty good as the same approach would be used not only for the "Login" window, but for any kind of window. I've reviewed a lot of suggestions and none are OK for me. Please review my suggestion that was taken from the MVVM design pattern article.
Each ViewModel class should inherit from WorkspaceViewModel
that has the RequestClose
event and CloseCommand
property of the ICommand
type. The default implementation of the CloseCommand
property will raise the RequestClose
event.
In order to get the window closed, the OnLoaded
method of your window should be overridden:
void CustomerWindow_Loaded(object sender, RoutedEventArgs e)
{
CustomerViewModel customer = CustomerViewModel.GetYourCustomer();
DataContext = customer;
customer.RequestClose += () => { Close(); };
}
or OnStartup
method of you app:
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
MainWindow window = new MainWindow();
var viewModel = new MainWindowViewModel();
viewModel.RequestClose += window.Close;
window.DataContext = viewModel;
window.Show();
}
I guess that RequestClose
event and CloseCommand
property implementation in the WorkspaceViewModel
are pretty clear, but I will show them to be consistent:
public abstract class WorkspaceViewModel : ViewModelBase
// There's nothing interesting in ViewModelBase as it only implements the INotifyPropertyChanged interface
{
RelayCommand _closeCommand;
public ICommand CloseCommand
{
get
{
if (_closeCommand == null)
{
_closeCommand = new RelayCommand(
param => Close(),
param => CanClose()
);
}
return _closeCommand;
}
}
public event Action RequestClose;
public virtual void Close()
{
if ( RequestClose != null )
{
RequestClose();
}
}
public virtual bool CanClose()
{
return true;
}
}
And the source code of the RelayCommand
:
public class RelayCommand : ICommand
{
#region Constructors
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
#endregion // Constructors
#region ICommand Members
[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter)
{
_execute(parameter);
}
#endregion // ICommand Members
#region Fields
readonly Action<object> _execute;
readonly Predicate<object> _canExecute;
#endregion // Fields
}
P.S. Don't treat me badly for those sources! If I had them yesterday that would have saved me a few hours...
P.P.S. Any comments or suggestions are welcome.
CREATE SCHEMA exe AUTHORIZATION [dbo]
GO
ALTER SCHEMA exe
TRANSFER dbo.Employees
GO
Here an example of how I do that, I don't know if it is the best solution, but works perfectly.
First, code in HTML. Look at ng-class, it's calling hasError function. Look also to the input's name declaration. I use the $index to create different input names.
<div data-ng-repeat="tipo in currentObject.Tipo"
ng-class="{'has-error': hasError(planForm, 'TipoM', 'required', $index) || hasError(planForm, 'TipoM', 'maxlength', $index)}">
<input ng-model="tipo.Nombre" maxlength="100" required
name="{{'TipoM' + $index}}"/>
And now, here is the hasError function:
$scope.hasError = function (form, elementName, errorType, index) {
if (form == undefined
|| elementName == undefined
|| errorType == undefined
|| index == undefined)
return false;
var element = form[elementName + index];
return (element != null && element.$error[errorType] && element.$touched);
};
Using the -X
flag with whatever HTTP verb you want:
curl -X PUT -d arg=val -d arg2=val2 localhost:8080
This example also uses the -d
flag to provide arguments with your PUT request.
Use the widget Wrap
.
For Column
like behavior try:
return Wrap(
direction: Axis.vertical,
spacing: 10,
children: <Widget>[...],);
For Row
like behavior try:
return Wrap(
direction: Axis.horizontal,
spacing: 10,
children: <Widget>[...],);
For more information: Wrap (Flutter Widget)
Try this
$('#testID').addClass('nameOfClass');
or
$('#testID').removeClass('nameOfClass');
I have used this library with sucess
http://plugins.krajee.com/checkbox-x
It requires jQuery and bootstrap 3.x
Download the zip here: https://github.com/kartik-v/bootstrap-checkbox-x/zipball/master
Put the contents of the zip in a folder within your project
Pop the needed libs in your header
<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link href="path/to/css/checkbox-x.min.css" media="all" rel="stylesheet" type="text/css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script src="path/to/js/checkbox-x.min.js" type="text/javascript"></script>
Add the data controls to the element using the data-size="xl" to change the size as shown here http://plugins.krajee.com/cbx-sizes-demo
<label for="element_id">CheckME</label>
<input type="checkbox" name="my_element" id="element_id" value="1" data-toggle="checkbox-x" data-three-state="false" data-size="xl"/>
There are numerous other features as well if you browse the plugin site.
The lookup time is slow because when you use mmap
to does not load content of array to memory when you invoke load
method. Data is lazy loaded when particular data is needed.
And this happens in lookup in your case. But second lookup won`t be so slow.
This is nice feature of mmap
when you have a big array you do not have to load whole data into memory.
To solve your can use joblib you can dump any object you want using joblib.dump
even two or more numpy arrays
, see the example
firstArray = np.arange(100)
secondArray = np.arange(50)
# I will put two arrays in dictionary and save to one file
my_dict = {'first' : firstArray, 'second' : secondArray}
joblib.dump(my_dict, 'file_name.dat')
There is a very simple solution using dense_rank()
dense_rank() over (partition by [Mth] order by [UserAccountKey])
+ dense_rank() over (partition by [Mth] order by [UserAccountKey] desc)
- 1
This will give you exactly what you were asking for: The number of distinct UserAccountKeys within each month.
Your "bad" output is UTF-8 displayed as CP1252.
On Windows, many editors assume the default ANSI encoding (CP1252 on US Windows) instead of UTF-8 if there is no byte order mark (BOM) character at the start of the file. While a BOM is meaningless to the UTF-8 encoding, its UTF-8-encoded presence serves as a signature for some programs. For example, Microsoft Office's Excel requires it even on non-Windows OSes. Try:
df.to_csv('file.csv',encoding='utf-8-sig')
That encoder will add the BOM.
Install .NET framework as below, it will work .NET version 4.5 as well.
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir
Some time only give aspnet_regiis.exe -i
don't work so give aspnet_regiis.exe -ir
in above path.
If you are interested to detect simple IR light blob through haar cascade, it will be very odd to do. Because simple IR blob does not have enough features to be trained through opencv like other objects (face, eyes,nose etc). Because IR is just a simple light having only one feature of brightness in my point of view. But if you want to learn how to train a classifier following link will help you alot.
http://note.sonots.com/SciSoftware/haartraining.html
And if you just want to detect IR blob, then you have two more possibilities, one is you go for DIP algorithms to detect bright region and the other one which I recommend you is you can use an IR cam which just pass the IR blob and you can detect easily the IR blob by using opencv blob functiuons. If you think an IR cam is expansive, you can make simple webcam to an IR cam by removing IR blocker (if any) and add visible light blocker i.e negative film, floppy material or any other. You can check the following link to convert simple webcam to IR cam.
http://www.metacafe.com/watch/385098/transform_your_webcam_into_an_infrared_cam/
In case that helps anybody I had the same issue with wampserver3.2.0_x64 on Windows 10 Enterprise.
Tried everything from the answers of this thread and nothing helped.
I then installed wampserver3.1.0_x86 instead and got the green light on first launch. I have no explanation but at least the desired end result.
Usually, I don't care about the order of the calls, only that they happened. In that case, I combine assert_any_call
with an assertion about call_count
.
>>> import mock
>>> m = mock.Mock()
>>> m(1)
<Mock name='mock()' id='37578160'>
>>> m(2)
<Mock name='mock()' id='37578160'>
>>> m(3)
<Mock name='mock()' id='37578160'>
>>> m.assert_any_call(1)
>>> m.assert_any_call(2)
>>> m.assert_any_call(3)
>>> assert 3 == m.call_count
>>> m.assert_any_call(4)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "[python path]\lib\site-packages\mock.py", line 891, in assert_any_call
'%s call not found' % expected_string
AssertionError: mock(4) call not found
I find doing it this way to be easier to read and understand than a large list of calls passed into a single method.
If you do care about order or you expect multiple identical calls, assert_has_calls
might be more appropriate.
Since I posted this answer, I've rethought my approach to testing in general. I think it's worth mentioning that if your test is getting this complicated, you may be testing inappropriately or have a design problem. Mocks are designed for testing inter-object communication in an object oriented design. If your design is not objected oriented (as in more procedural or functional), the mock may be totally inappropriate. You may also have too much going on inside the method, or you might be testing internal details that are best left unmocked. I developed the strategy mentioned in this method when my code was not very object oriented, and I believe I was also testing internal details that would have been best left unmocked.
Another great tool is KeyStore Explorer: http://keystore-explorer.sourceforge.net/
I had the same error. I solved it by installing CORS in my backend using npm i cors
. You'll then need to add this to your code:
const cors = require('cors');
app.use(cors());
This fixed it for me; now I can post my forms using AJAX and without needing to add any customized headers.
sed -n 's/^potato:[[:space:]]*//p' file.txt
One can think of Grep as a restricted Sed, or of Sed as a generalized Grep. In this case, Sed is one good, lightweight tool that does what you want -- though, of course, there exist several other reasonable ways to do it, too.
Looping through all the files in the folder is relatively easy:
files = dir('*.csv');
for file = files'
csv = load(file.name);
% Do some stuff
end
What about something like this:
SELECT
name,
count(*) AS num
FROM
your_table
GROUP BY
name
ORDER BY
count(*)
DESC
You are selecting the name and the number of times it appears, but grouping by name so each name is selected only once.
Finally, you order by the number of times in DESCending order, to have the most frequently appearing users come first.
You could use the ones on CodePlex or http://www.enterprisedt.com/general/press/20060818.html
Use MySQL's STR_TO_DATE()
function to parse the string that you're attempting to insert:
INSERT INTO tblInquiry (fldInquiryReceivedDateTime) VALUES
(STR_TO_DATE('5/15/2012 8:06:26 AM', '%c/%e/%Y %r'))
Since mobile doesn't give hover feedback, I want, as a user, to see instant feedback when a link is tapped. I noticed that -webkit-tap-highlight-color
is the fastest to respond (subjective).
Add the following to your body and your links will have a tap effect.
body {
-webkit-tap-highlight-color: #ccc;
}
Try an if statement ...
if @value is null
insert into t (value) values (default)
else
insert into t (value) values (@value)
While exporting your source into a jar, make sure you select runnable jar option from the options. Then select if you want to package all the dependency jars or just include them directly in the jar file. It depends on the project that you are working on.
You then run the jar directly by java -jar example.jar.
from PIL import Image
import os, os.path
imgs = []
path = "/home/tony/pictures"
valid_images = [".jpg",".gif",".png",".tga"]
for f in os.listdir(path):
ext = os.path.splitext(f)[1]
if ext.lower() not in valid_images:
continue
imgs.append(Image.open(os.path.join(path,f)))
have a look at vsnprintf as this will do what ya want http://www.cplusplus.com/reference/clibrary/cstdio/vsprintf/
you will have to init the va_list arg array first, then call it.
Example from that link: /* vsprintf example */
#include <stdio.h>
#include <stdarg.h>
void Error (char * format, ...)
{
char buffer[256];
va_list args;
va_start (args, format);
vsnprintf (buffer, 255, format, args);
//do something with the error
va_end (args);
}
I had the same problem because I changed the user from myself to someone else:
su
For some reason, after did the normal compiling I was not able to execute it (the same error message). Directly ssh to the other user account works.
Usually this region should contains the constructors of the class
Why is floatval the best option for financial comparison data? bc functions only accurately turn strings into real numbers.
Create a file called NuGet.config next to your solution file with the following contents
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="LocalPackages" value="./LocalPackages" />
</packageSources>
<activePackageSource>
<!-- this tells that all of them are active -->
<add key="All" value="(Aggregate source)" />
</activePackageSource>
</configuration>
If the solution is open in Visual Studio, close it, then re-open it.
Now your packages should appear in the browser, or be installable using Install-Package
In C++, unlike (say) Java, an instance of a nested class doesn't intrinsically belong to any instance of the enclosing class. So bar::getA
doesn't have any specific instance of foo
whose a
it can be returning. I'm guessing that what you want is something like:
class bar {
private:
foo * const owner;
public:
bar(foo & owner) : owner(&owner) { }
int getA() {return owner->a;}
};
But even for this you may have to make some changes, because in versions of C++ before C++11, unlike (again, say) Java, a nested class has no special access to its enclosing class, so it can't see the protected
member a
. This will depend on your compiler version. (Hat-tip to Ken Wayne VanderLinde for pointing out that C++11 has changed this.)
You can also throw an exception:
For the sake of readability each step of stream should be listed in new line.
players.stream()
.filter(player -> player.getName().contains(name))
.findFirst()
.orElseThrow(MyCustomRuntimeException::new);
if your logic is loosely "exception driven" such as there is one place in your code that catches all exceptions and decides what to do next. Only use exception driven development when you can avoid littering your code base with multiples try-catch
and throwing these exceptions are for very special cases that you expect them and can be handled properly.)
you may put your Auth settings into a Environment. Like:
SetEnvIf HTTP_HOST testsite.local APPLICATION_ENV=development
<IfDefine !APPLICATION_ENV>
Allow from all
AuthType Basic
AuthName "My Testseite - Login"
AuthUserFile /Users/tho/htdocs/wgh_staging/.htpasswd
Require user username
</IfDefine>
The Auth is working, but I couldn't get my environment really running.
I already have the Studio installed. But without starting (not installing) the Android Studio you can directly start the emulator with
C:\Users\YOURUSERNAME\AppData\Local\Android\Sdk\tools\emulator.exe -netdelay none -netspeed full -avd YOUR_AVD_NAME
git revert HEAD -m 1
In the above code line. "Last argument represents"
1 - reverts one commits.
2 - reverts last two commits.
n - reverts last n commits.
You need to push after this command to take the effect on remote. You have other options like specifying the range of commits to revert. This is one of the option.
Later use git commit -am "COMMIT_MESSAGE"
then git push
or git push -f
It looks like your 'trainData' is a list of strings:
['-214' '-153' '-58' ..., '36' '191' '-37']
Change your 'trainData' to a numeric type.
import numpy as np
np.array(['1','2','3']).astype(np.float)
$('#divId > input, #divId > select, #divId > textarea').serialize();
Current date is in yyyy-mm-dd
format. You can convert it into yyyymmdd
format using substring
function:
select substr(current date,1,4)||substr(current date,6,2)||substr(currentdate,9,2)
I only use static classes for helper methods, but with the advent of C# 3.0, I'd rather use extension methods for those.
I rarely use static classes methods for the same reasons why I rarely use the singleton "design pattern".
In my case it was migrating from idea 2017 to 2018 and Lombok plugin was already there. All I did is added "Enable annotation processing options" entering preferences and check the box
Your regex should be something like
[0-9\-\(\)\s]+
.
It matches numbers, dashes, parentheses and space.
If you need something more strict, matching just your example, try this:
([0-9]{10})|(\([0-9]{3}\)\s+[0-9]{3}\-[0-9]{4})
setting the overflow
should take care of it, but you need to set the height of Content
also. If the height attribute is not set, the div will grow vertically as tall as it needs to, and scrollbars wont be needed.
See Example: http://jsfiddle.net/ftkbL/1/
Use:
IF Var IS NULL THEN
var := 5;
END IF;
Oracle 9i+:
var = COALESCE(Var, 5)
Other alternatives:
var = NVL(var, 5)
Reference:
First of all, if anyone is going to store any password in a file, I would make sure it's hashed. It's not the best security, but at least it will not be in plain text.
First, create the password and hash it:
echo "password123" | md5sum | cut -d '-' -f 1 > /tmp/secret
Now, create your program to use the hash. In this case, this little program receives user input for a password without echoing, and then converts it to hash to be compared with the stored hash. If it matches the stored hash, then access is granted:
#!/bin/bash
PASSWORD_FILE="/tmp/secret"
MD5_HASH=$(cat /tmp/secret)
PASSWORD_WRONG=1
while [ $PASSWORD_WRONG -eq 1 ]
do
echo "Enter your password:"
read -s ENTERED_PASSWORD
if [ "$MD5_HASH" != "$(echo $ENTERED_PASSWORD | md5sum | cut -d '-' -f 1)" ]; then
echo "Access Deniend: Incorrenct password!. Try again"
else
echo "Access Granted"
PASSWORD_WRONG=0
fi
done
This seems the easiest way..
SELECT REPLACE(CONVERT(CHAR(10), GETDATE(), 110),'-','')
Apple uses "NSObjectProtocol" instead of "class".
public protocol UIScrollViewDelegate : NSObjectProtocol {
...
}
This also works for me and removed the errors I was seeing when trying to implement my own delegate pattern.
The new way to do it is to use enabledBorder
like this:
new TextField(
decoration: new InputDecoration(
enabledBorder: const OutlineInputBorder(
borderSide: const BorderSide(color: Colors.grey, width: 0.0),
),
focusedBorder: ...
border: ...
),
)
lvalue
means "left value" -- it should be assignable. You cannot change the value of text
since it is an array, not a pointer.
Either declare it as char pointer (in this case it's better to declare it as const char*
):
const char *text;
if(number == 2)
text = "awesome";
else
text = "you fail";
Or use strcpy:
char text[60];
if(number == 2)
strcpy(text, "awesome");
else
strcpy(text, "you fail");
Open gradle.properties file in android folder.
Replace this line:
org.gradle.jvmargs=-Xmx1536M
with:
org.gradle.jvmargs=-Xmx512m
Explanation: Max limit from Gradle document:
If the requested build environment does not specify a maximum heap size, the Daemon will use up to 512MB of heap.
Not really. There are a number of dex disassembler/decompiler suites out there such as smali, or dex2jar that will generate semi-humanreadable output (in the case of dex2jar, you can get java code through the use of something like JD-GUI but the process is not perfect and it is very unlikely that you'll be able to 100% recreate your source code. However, it could potentially give you a place to start rebuilding your source tree.
Run the following commands:
$ git checkout mobiledevice
$ git pull origin master
This would merge all the latest commits to your branch. If the merge results in some conflicts, you'll need to fix them.
I don't know if this is the best practice but works for me.
is just going to look for a div with class="outer inner", is that correct?
No, '.outer .inner'
will look for all elements with the .inner class that also have an element with the .outer class as an ancestor. '.outer.inner'
(no space) would give the results you're thinking of.
'.outer > .inner'
will look for immediate children of an element with the .outer class for elements with the .inner class.
Both '.outer .inner'
and '.outer > .inner'
should work for your example, although the selectors are fundamentally different and you should be wary of this.
You can import json files by using the node.js v14 experimental json modules flag. More details here
file.js
import data from './folder/file.json'
export default {
foo () {
console.log(data)
}
}
And you call it with node --experimental-json-modules file.js
array = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
col1 = [val[1] for val in array]
col2 = [val[2] for val in array]
col3 = [val[3] for val in array]
col4 = [val[4] for val in array]
print(col1)
print(col2)
print(col3)
print(col4)
Output:
[1, 5, 9, 13]
[2, 6, 10, 14]
[3, 7, 11, 15]
[4, 8, 12, 16]
create constant file with any name like my_constants.py declare constant like that
CONSTANT_NAME = "SOME VALUE"
For accessing constant in your code import file like that
import my_constants as constant
and access the constant value as -
constant.CONSTANT_NAME
In java config,make sure you have import your config in RootConfig like this @Import(PersistenceJPAConfig.class)
The call to InitializeComponent()
(which is usually called in the default constructor of at least Window
and UserControl
) is actually a method call to the partial class of the control (rather than a call up the object hierarchy as I first expected).
This method locates a URI to the XAML for the Window
/UserControl
that is loading, and passes it to the System.Windows.Application.LoadComponent()
static method. LoadComponent()
loads the XAML file that is located at the passed in URI, and converts it to an instance of the object that is specified by the root element of the XAML file.
In more detail, LoadComponent
creates an instance of the XamlParser
, and builds a tree of the XAML. Each node is parsed by the XamlParser.ProcessXamlNode()
. This gets passed to the BamlRecordWriter
class. Some time after this I get a bit lost in how the BAML is converted to objects, but this may be enough to help you on the path to enlightenment.
Note: Interestingly, the InitializeComponent
is a method on the System.Windows.Markup.IComponentConnector
interface, of which Window
/UserControl
implement in the partial generated class.
Hope this helps!
This has always been my approach to this little nuisance. Note the use of VirtualPathUtility.ToAbsolute(relativeUrl) allows the method to be declared as an extension in a static class.
/// <summary>
/// Converts the provided app-relative path into an absolute Url containing the
/// full host name
/// </summary>
/// <param name="relativeUrl">App-Relative path</param>
/// <returns>Provided relativeUrl parameter as fully qualified Url</returns>
/// <example>~/path/to/foo to http://www.web.com/path/to/foo</example>
public static string ToAbsoluteUrl(this string relativeUrl) {
if (string.IsNullOrEmpty(relativeUrl))
return relativeUrl;
if (HttpContext.Current == null)
return relativeUrl;
if (relativeUrl.StartsWith("/"))
relativeUrl = relativeUrl.Insert(0, "~");
if (!relativeUrl.StartsWith("~/"))
relativeUrl = relativeUrl.Insert(0, "~/");
var url = HttpContext.Current.Request.Url;
var port = url.Port != 80 ? (":" + url.Port) : String.Empty;
return String.Format("{0}://{1}{2}{3}",
url.Scheme, url.Host, port, VirtualPathUtility.ToAbsolute(relativeUrl));
}
To add a new file in SVN
svn add file_name
svn commit -m "text about changes..."
To add a new file in a directory in SVN
svn add directory_name/file_name
svn commit -m "text about changes"
To add all new files in a directory with some targets (files) are already versioned (added):
svn add directory_name/*
svn commit -m "text about changes"
enctype='multipart/form-data'
means that no characters will be encoded. that is why this type is used while uploading files to server.
So multipart/form-data
is used when a form requires binary data, like the contents of a file, to be uploaded
You can pass a mutable container datatype into a function, and it can contain anything you want.
If you need a different functionality, name the functions differently, or if you need the same interface, just write an interface function (or method) that calls the functions appropriately based on the data received.
It took a while to me to get adjusted to this coming from Java, but it really isn't a "big handicap".
I think the current answers are neglecting to highlight the actual important and significant differences and what that means for the intended usage. While they might both work in certain situations because the implementer built in support for both, they have different usage scenarios. Both can annotate properties and methods but here are some important differences:
DisplayAttribute
System.ComponentModel.DataAnnotations
namespace in the System.ComponentModel.DataAnnotations.dll
assemblyDescription
or ShortName
DisplayNameAttribute
System.ComponentModel
namespace in System.dll
The assembly and namespace speaks to the intended usage and localization support is the big kicker. DisplayNameAttribute
has been around since .NET 2 and seems to have been intended more for naming of developer components and properties in the legacy property grid, not so much for things visible to end users that may need localization and such.
DisplayAttribute
was introduced later in .NET 4 and seems to be designed specifically for labeling members of data classes that will be end-user visible, so it is more suitable for DTOs, entities, and other things of that sort. I find it rather unfortunate that they limited it so it can't be used on classes though.
EDIT: Looks like latest .NET Core source allows DisplayAttribute
to be used on classes now as well.
You can do a column transformation by using apply
Define a clean function to remove the dollar and commas and convert your data to float.
def clean(x):
x = x.replace("$", "").replace(",", "").replace(" ", "")
return float(x)
Next, call it on your column like this.
data['Revenue'] = data['Revenue'].apply(clean)
I just want to point out that most of the answers here don't work, I am new to NodeJS and IDK if throughout time the "module.exports.yourClass" method changed, or if people just entered the wrong answer.
// MyClass
module.exports.Ninja = class Ninja{
test(){
console.log('TESTING 1... 2... 3...');
};
}
//Using MyClass in seprate File
const ninjaFw = require('./NinjaFw');
let ninja = new ninjaFw.Ninja();
ninja.test();
// Ninja Framework File
class Ninja{
test(){
console.log('TESTING 1... 2... 3...');
};
}
module.exports.Ninja = Ninja;
In Python 3:
# A simple dictionary
x = {'X':"yes", 'Y':"no", 'Z':"ok"}
# To print a specific key (for example key at index 1)
print([key for key in x.keys()][1])
# To print a specific value (for example value at index 1)
print([value for value in x.values()][1])
# To print a pair of a key with its value (for example pair at index 2)
print(([key for key in x.keys()][2], [value for value in x.values()][2]))
# To print a key and a different value (for example key at index 0 and value at index 1)
print(([key for key in x.keys()][0], [value for value in x.values()][1]))
# To print all keys and values concatenated together
print(''.join(str(key) + '' + str(value) for key, value in x.items()))
# To print all keys and values separated by commas
print(', '.join(str(key) + ', ' + str(value) for key, value in x.items()))
# To print all pairs of (key, value) one at a time
for e in range(len(x)):
print(([key for key in x.keys()][e], [value for value in x.values()][e]))
# To print all pairs (key, value) in a tuple
print(tuple(([key for key in x.keys()][i], [value for value in x.values()][i]) for i in range(len(x))))
Also posted here: "background-size: cover" does not cover mobile screen
This works on Android 4.1.2 and iOS 6.1.3 (iPhone 4) and switches for desktop. Written for responsive sites.
Just in case, in your HTML head, something like this:
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
HTML:
<div class="html-mobile-background"></div>
CSS:
html {
/* Whatever you want */
}
.html-mobile-background {
position: fixed;
z-index: -1;
top: 0;
left: 0;
width: 100%;
height: 125%; /* To compensate for mobile browser address bar space */
background: url(/images/bg.jpg) no-repeat;
background-size: 100% 100%;
}
@media (min-width: 600px) {
html {
background: url(/images/bg.jpg) no-repeat center center fixed;
background-size: cover;
}
.html-mobile-background {
display: none;
}
}
In database design, iIhighly recommend using Unixtime for consistency and indexing / search / comparison performance.
UNIX_TIMESTAMP()
One can always convert to human readable formats afterwards, internationalizing as is individually most convenient.
FROM_ UNIXTIME (unix_timestamp, [format ])
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
To make this line work as expected, make sure that:
<head>
<html>
elementOtherwise some IE versions simply ignore it.
UPDATE
These two rules are simplified but they are easy to remember and to verify. Despite MSDN docs stating you can put title and other meta tags before this one, I would not recommend to do so.
How make it work with conditional comments.
Interesting article about the order of elements in the head. (blogs.msdn.com, for IE)
REFERENCE
From the MSDN documentation:
The
X-UA-Compatible
[...] must appear in the header of the webpage (the HEAD section) before all other elements except for the title element and other meta elements.
First java will not allow you to have do()
method. Instead you can make it doOperation()
.
Second You cann't invoke directly non static methods from static function. Main
is a static function. You need to instantiate the class first and then invoke method using that instance.
Third you can invoke static method directly from non static methods.
@JoinColumn
could be used on both sides of the relationship. The question was about using @JoinColumn
on the @OneToMany
side (rare case). And the point here is in physical information duplication (column name) along with not optimized SQL query that will produce some additional UPDATE
statements.
According to documentation:
Since many to one are (almost) always the owner side of a bidirectional relationship in the JPA spec, the one to many association is annotated by @OneToMany(mappedBy=...)
@Entity
public class Troop {
@OneToMany(mappedBy="troop")
public Set<Soldier> getSoldiers() {
...
}
@Entity
public class Soldier {
@ManyToOne
@JoinColumn(name="troop_fk")
public Troop getTroop() {
...
}
Troop
has a bidirectional one to many relationship with Soldier
through the troop property. You don't have to (must not) define any physical mapping in the mappedBy
side.
To map a bidirectional one to many, with the one-to-many side as the owning side, you have to remove the mappedBy
element and set the many to one @JoinColumn
as insertable
and updatable
to false. This solution is not optimized and will produce some additional UPDATE
statements.
@Entity
public class Troop {
@OneToMany
@JoinColumn(name="troop_fk") //we need to duplicate the physical information
public Set<Soldier> getSoldiers() {
...
}
@Entity
public class Soldier {
@ManyToOne
@JoinColumn(name="troop_fk", insertable=false, updatable=false)
public Troop getTroop() {
...
}
On Windows you do not link with a .dll
file directly – you must use the accompanying .lib
file instead. To do that go to Project -> Properties -> Configuration Properties -> Linker -> Additional Dependencies
and add path to your .lib as a next line.
You also must make sure that the .dll
file is either in the directory contained by the %PATH%
environment variable or that its copy is in Output Directory
(by default, this is Debug\Release
under your project's folder).
If you don't have access to the .lib
file, one alternative is to load the .dll
manually during runtime using WINAPI functions such as LoadLibrary and GetProcAddress.
You could do it yourself (thats what I did) - in order to not be bothered with exception handling, you simply extend the RuntimeException, your class could look something like this:
public class NotImplementedException extends RuntimeException {
private static final long serialVersionUID = 1L;
public NotImplementedException(){}
}
You could extend it to take a message - but if you use the method as I do (that is, as a reminder, that there is still something to be implemented), then usually there is no need for additional messages.
I dare say, that I only use this method, while I am in the process of developing a system, makes it easier for me to not lose track of which methods are still not implemented properly :)
python: read lines from compressed text files
Using gzip.GzipFile
:
import gzip
with gzip.open('input.gz','r') as fin:
for line in fin:
print('got line', line)
Better solution: use Javascript's native Array.from()
and to convert HTMLCollection object to an array, after which you can use standard array functions.
var t = document.getElementById('mytab1');
if(t) {
Array.from(t.rows).forEach((tr, row_ind) => {
Array.from(tr.cells).forEach((cell, col_ind) => {
console.log('Value at row/col [' + row_ind + ',' + col_ind + '] = ' + cell.textContent);
});
});
}
You could also reference tr.rowIndex
and cell.colIndex
instead of using row_ind
and col_ind
.
I much prefer this approach over the top 2 highest-voted answers because it does not clutter your code with global variables i
, j
, row
and col
, and therefore it delivers clean, modular code that will not have any side effects (or raise lint / compiler warnings)... without other libraries (e.g. jquery).
If you require this to run in an old version (pre-ES2015) of Javascript, Array.from
can be polyfilled.
I have the same problem. i have solved this issue by the following point.
First one is go to inside build.gradle app file and change this
android {
compileSdkVersion 22
buildToolsVersion "23.0.0 rc2"
}
with this one
android {
compileSdkVersion 22
buildToolsVersion "23.0.0"
}
I hope this will solve your issue.
Might be useful:
double a = 5.0/2.0;
Console.WriteLine (a); // 2.5
double b = 5/2;
Console.WriteLine (b); // 2
int c = 5/2;
Console.WriteLine (c); // 2
double d = 5f/2f;
Console.WriteLine (d); // 2.5
You can use the list.sort
to avoid creating new lists with sorted
and sort the lists in place.
Also you should not use list
as a variable name as it shadows python's own list.
def median(l):
half = len(l) // 2
l.sort()
if not len(l) % 2:
return (l[half - 1] + l[half]) / 2.0
return l[half]
To follow up on Theo's suggestion with my findings (apologies - I don't currently have enough reputation to post this as a comment)
First, this is how to use several named parameters:
String commandString = "INSERT INTO Users (Name, Desk, UpdateTime) VALUES (:Name, :Desk, :UpdateTime)";
using (OracleCommand command = new OracleCommand(commandString, _connection, _transaction))
{
command.Parameters.Add("Name", OracleType.VarChar, 50).Value = strategy;
command.Parameters.Add("Desk", OracleType.VarChar, 50).Value = deskName ?? OracleString.Null;
command.Parameters.Add("UpdateTime", OracleType.DateTime).Value = updated;
command.ExecuteNonQuery();
}
However, I saw no variation in speed between:
I'm using System.Data.OracleClient, deleting and inserting 2500 rows inside a transaction
^[0-9]{1,2}[:.,-]?po$
Add any other allowable non-alphanumeric characters to the middle brackets to allow them to be parsed as well.
If you're proficient in C# and Visual Studio, you might try IKVM. It's not exactly what you were asking for, but will certainly help with bridging the gap by allowing you to call into Java libraries from C# and vise versa. You can use it in Visual Studio, but it also has first class support in MonoDevelop.
The locks are always taken at DB level:-
Oracle official Document:- To avoid conflicts during a transaction, a DBMS uses locks, mechanisms for blocking access by others to the data that is being accessed by the transaction. (Note that in auto-commit mode, where each statement is a transaction, locks are held for only one statement.) After a lock is set, it remains in force until the transaction is committed or rolled back. For example, a DBMS could lock a row of a table until updates to it have been committed. The effect of this lock would be to prevent a user from getting a dirty read, that is, reading a value before it is made permanent. (Accessing an updated value that has not been committed is considered a dirty read because it is possible for that value to be rolled back to its previous value. If you read a value that is later rolled back, you will have read an invalid value.)
How locks are set is determined by what is called a transaction isolation level, which can range from not supporting transactions at all to supporting transactions that enforce very strict access rules.
One example of a transaction isolation level is TRANSACTION_READ_COMMITTED, which will not allow a value to be accessed until after it has been committed. In other words, if the transaction isolation level is set to TRANSACTION_READ_COMMITTED, the DBMS does not allow dirty reads to occur. The interface Connection includes five values that represent the transaction isolation levels you can use in JDBC.
AJAX does the magic:
$(document).ready(function(
$.ajax({ url: 'script.php?argument=value&foo=bar' });
));
An easy way to overcome this problem is to use 64 bit type
list = numpy.array(list, dtype=numpy.float64)
with Apache PDFBox it goes like this:
PDDocument document = PDDocument.load(new File("test.pdf"));
if (!document.isEncrypted()) {
PDFTextStripper stripper = new PDFTextStripper();
String text = stripper.getText(document);
System.out.println("Text:" + text);
}
document.close();
Well I can change them in chrome. Its simple and works fine in Chrome using -webkit css properties.