Use the CSS pointer-events:none on fields you want to "disable" (possibly together with a greyed background) which allows the POST action, like:
<input type="text" class="disable">
.disable{
pointer-events:none;
background:grey;
}
Ref: https://developer.mozilla.org/en-US/docs/Web/CSS/pointer-events
This answer is for everyone that realizes the accepted answer does not address the question as it currently written.
The question asks how to find a value in an array. The accepted answer shows how to check whether a value exists in an array.
There is already an example using index
, so I am providing an example using the select
method.
1.9.3-p327 :012 > x = [1,2,3,4,5]
=> [1, 2, 3, 4, 5]
1.9.3-p327 :013 > x.select {|y| y == 1}
=> [1]
var test = '0test';
test = test.replace(/0(.*)/, '$1');
I use: /drawable/circulo.xml
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="oval">
<solid android:angle="270"
android:color="@color/your_color" />
</shape>
And then I use it in my TextView as:
android:background="@drawable/circulo"
no need to complicated it.
Hope it's working for you
function GetSelectedItem()
{
var index = document.getElementById(select1).selectedIndex;
alert("value =" + document.getElementById(select1).value); // show selected value
alert("text =" + document.getElementById(select1).options[index].text); // show selected text
}
Let me just put this here for my own reference. I know that it is not good Python code, but I needed a script for a project I was working on and I wanted to put the script in a scripts
directory.
import os.path
import sys
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
git reset --hard origin/master
says: throw away all my staged and unstaged changes, forget everything on my current local branch and make it exactly the same as origin/master
.
You probably wanted to ask this before you ran the command. The destructive nature is hinted at by using the same words as in "hard reset".
As per George Jempty's
request to have the algorithm account for ties, I propose a modified version of Matthew Flaschen's
algorithm.
function modeString(array) {
if (array.length == 0) return null;
var modeMap = {},
maxEl = array[0],
maxCount = 1;
for (var i = 0; i < array.length; i++) {
var el = array[i];
if (modeMap[el] == null) modeMap[el] = 1;
else modeMap[el]++;
if (modeMap[el] > maxCount) {
maxEl = el;
maxCount = modeMap[el];
} else if (modeMap[el] == maxCount) {
maxEl += "&" + el;
maxCount = modeMap[el];
}
}
return maxEl;
}
This will now return a string with the mode element(s) delimited by a &
symbol. When the result is received it can be split on that &
element and you have your mode(s).
Another option would be to return an array of mode element(s) like so:
function modeArray(array) {
if (array.length == 0) return null;
var modeMap = {},
maxCount = 1,
modes = [];
for (var i = 0; i < array.length; i++) {
var el = array[i];
if (modeMap[el] == null) modeMap[el] = 1;
else modeMap[el]++;
if (modeMap[el] > maxCount) {
modes = [el];
maxCount = modeMap[el];
} else if (modeMap[el] == maxCount) {
modes.push(el);
maxCount = modeMap[el];
}
}
return modes;
}
In the above example you would then be able to handle the result of the function as an array of modes.
Replace
data: { patientID: "1" },
with
data: "{ 'patientID': '1' }",
Further reading: 3 mistakes to avoid when using jQuery with ASP.NET
In bash 4, you can use associative arrays:
declare -A foo
foo[0]="bar"
foo[35]="baz"
for key in "${!foo[@]}"
do
echo "key: $key, value: ${foo[$key]}"
done
# output
# $ key: 0, value bar.
# $ key: 35, value baz.
In bash 3, this works (also works in zsh):
map=( )
map+=("0:bar")
map+=("35:baz")
for keyvalue in "${map[@]}" ; do
key=${keyvalue%%:*}
value=${keyvalue#*:}
echo "key: $key, value $value."
done
What makes jQuery easy to use is that you don't have to apply attributes to each element. The jQuery object contains an array of elements, and the methods of the jQuery object applies the same attributes to all the elements in the array.
There is also a shorter form for $(document).ready(function(){...})
in $(function(){...})
.
So, this is all you need:
$(function(){
$('div.easy_editor').css('border','9px solid red');
});
If you want the code to work for any element with that class, you can just specify the class in the selector without the tag name:
$(function(){
$('.easy_editor').css('border','9px solid red');
});
Pelo Hyper-V:
private PerformanceCounter theMemCounter = new PerformanceCounter(
"Hyper-v Dynamic Memory VM",
"Physical Memory",
Process.GetCurrentProcess().ProcessName);
You can set environment variables in the notebook using os.environ
. Do the following before initializing TensorFlow to limit TensorFlow to first GPU.
import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"]="0"
You can double check that you have the correct devices visible to TF
from tensorflow.python.client import device_lib
print device_lib.list_local_devices()
I tend to use it from utility module like notebook_util
import notebook_util
notebook_util.pick_gpu_lowest_memory()
import tensorflow as tf
Sometimes you still need to use FirstOrDefault if you have to do different tests. If the Key component of your dictionnary is nullable, you can do this:
thisTag = _tags.FirstOrDefault(t => t.Key.SubString(1,1) == 'a');
if(thisTag.Key != null) { ... }
Using FirstOrDefault, the returned KeyValuePair's key and value will both be null if no match is found.
Heres an easy option. Just set your list option then set its text as selected value:
$("#ddlScheduleFrequency option").selected(text("Select One..."));
When you build for iPhone in Unity it does Ahead of Time (AOT) compilation of your mono assembly (written in C# or JavaScript) to native ARM code.
The authoring tool also creates a stub xcode project and references that compiled lib. You can add objective C code to this xcode project if there is native stuff you want to do that isn't exposed in Unity's environment yet (e.g. accessing the compass and/or gyroscope).
In case you are willing to use Curl for the calls with JSON 2 and Spring 3.2.0 in hand checkout the FAQ here. As AnnotationMethodHandlerAdapter is deprecated and replaced by RequestMappingHandlerAdapter.
there are gotchas with this - but ultimately the simplest way will be to use
string s = [yourlongstring];
string[] values = s.Split(',');
If the number of commas and entries isn't important, and you want to get rid of 'empty' values then you can use
string[] values = s.Split(",".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
One thing, though - this will keep any whitespace before and after your strings. You could use a bit of Linq magic to solve that:
string[] values = s.Split(',').Select(sValue => sValue.Trim()).ToArray();
That's if you're using .Net 3.5 and you have the using System.Linq declaration at the top of your source file.
I think this is what you are seeking :
SELECT name, min(date)
FROM myTable
GROUP BY name
ORDER BY min(date)
For the time, you have to make a mysql date via STR_TO_DATE :
STR_TO_DATE(date + ' ' + time, '%Y-%m-%d %h:%i:%s')
So :
SELECT name, min(STR_TO_DATE(date + ' ' + time, '%Y-%m-%d %h:%i:%s'))
FROM myTable
GROUP BY name
ORDER BY min(STR_TO_DATE(date + ' ' + time, '%Y-%m-%d %h:%i:%s'))
There is a better way to write polar(), here it is:
def polar(x,y):
`returns r, theta(degrees)`
return math.hypot(x,y),math.degrees(math.atan2(y,x))
From here (Google is your friend):
In a DTD, PCDATA and CDATA are used to assert something about the allowable content of elements and attributes, respectively. In an element's content model, #PCDATA says that the element contains (may contain) "any old text." (With exceptions as noted below.) In an attribute's declaration, CDATA is one sort of constraint you can put on the attribute's allowable values (other sorts, all mutually exclusive, include ID, IDREF, and NMTOKEN). An attribute whose allowable values are CDATA can (like PCDATA in an element) contain "any old text."
A potentially really confusing issue is that there's another "CDATA," also referred to as marked sections. A marked section is a portion of element (#PCDATA) content delimited with special strings: to close it. If you remember that PCDATA is "parsed character data," a CDATA section is literally the same thing, without the "parsed." Parsers transmit the content of a marked section to downstream applications without hiccupping every time they encounter special characters like < and &. This is useful when you're coding a document that contains lots of those special characters (like scripts and code fragments); it's easier on data entry, and easier on reading, than the corresponding entity reference.
So you can infer that the exception to the "any old text" rule is that PCDATA cannot include any of these unescaped special characters, UNLESS they fall within the scope of a CDATA marked section.
"Ambiguous column" usually means that the same column name appears in at least two tables; the database engine can't tell which one you want. Use full table names or table aliases to remove the ambiguity.
Here's an example I happened to have in my editor. It's from someone else's problem, but should make sense anyway.
select P.*
from product_has_image P
inner join highest_priority_images H
on (H.id_product = P.id_product and H.priority = p.priority)
Technically, the size of your body
and html
are wider than the screen, so you will have scrolling. You will need to set margin:0;
and padding:0;
to avoid the scrolling behavior, and add some margin/padding to #content
instead.
Just do:
git push origin <your_branch_name> --force
or if you have a specific repo:
git push https://git.... --force
This will delete your previous commit(s) and push your current one.
It may not be proper, but if anyone stumbles upon this page, thought they might want a simple solution...
Also note that -f
is short for --force
, so
git push origin <your_branch_name> -f
will also work.
Java 6 ships the javax.xml.bind.DatatypeConverter
. This class provides two static methods that support the same decoding & encoding:
parseBase64Binary() / printBase64Binary()
Update: Since Java 8 we now have a much better Base64 Support.
Use this and you will not need an extra library, like Apache Commons Codec
.
If you want help an object go away, set its reference to null.
String x = "sadfasdfasd";
// do stuff
x = null;
Setting reference to null will make it more likely that the object will be garbage collected, as long as there are no other references to the object.
First you need to make sure if both of your files are in the same working directory. Next, you can import the whole file. For example,
import myClass
or you can import the entire class and entire functions from the file. For example,
from myClass import
Finally, you need to create an instance of the class from the original file and call the instance objects.
Simple way:
function displayChange(){
$(content_id).click(function(){
$(elem_id).toggle();}
)}
This worked for me:
import win32com.client as client
required_command = "cmd" # Enter your command here
required_password = "Simple1" # Enter your password here
def run_as(required_command, required_password):
shell = client.Dispatch("WScript.shell")
shell.Run(f"runas /user:administrator {required_command}")
time.sleep(1)
shell.SendKeys(f"{required_password}\r\n", 0)
if __name__ = '__main__':
run_as(required_command, required_password)
Below are the references I used for above code: https://win32com.goermezer.de/microsoft/windows/controlling-applications-via-sendkeys.html https://www.oreilly.com/library/view/python-cookbook/0596001673/ch07s16.html
I don't know about Visual Studio 2010, but in Visual Studio 2008 the code snippet is 'ctor'.
The order of items in the PATH matters. If there are multiple entries for various java installations, the first one in your PATH will be used.
I have had similar issues after installing a product, like Oracle, that puts it's JRE at the beginning of the PATH.
Ensure that the JDK you want to be loaded is the first entry in your PATH (or at least that it appears before C:\Program Files\Java\jre6\bin
appears).
You just need to add these 3 lines of code. Replace the icon with your own icon. If you want to generate icons use this
getSupportActionBar().setHomeAsUpIndicator(R.drawable.icon_back_arrow);
getActionBar().setHomeButtonEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
If anyone getting this in unit/instrumentation testing, make sure you call getFilesDir()
on the app context, not the test context. i.e. use:
Context appContext = getInstrumentation().getTargetContext().getApplicationContext();
not
Context appContext = InstrumentationRegistry.getContext;
In Xcode 5.1
Enable Done Button
Hide Keyboard when Done is pressed
Add this method to your ViewController
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
[textField resignFirstResponder];
return YES;
}
A method without any dependency and takes care of .. , . and duplicate separators.
public static String getFileName(String filePath) {
if( filePath==null || filePath.length()==0 )
return "";
filePath = filePath.replaceAll("[/\\\\]+", "/");
int len = filePath.length(),
upCount = 0;
while( len>0 ) {
//remove trailing separator
if( filePath.charAt(len-1)=='/' ) {
len--;
if( len==0 )
return "";
}
int lastInd = filePath.lastIndexOf('/', len-1);
String fileName = filePath.substring(lastInd+1, len);
if( fileName.equals(".") ) {
len--;
}
else if( fileName.equals("..") ) {
len -= 2;
upCount++;
}
else {
if( upCount==0 )
return fileName;
upCount--;
len -= fileName.length();
}
}
return "";
}
Test case:
@Test
public void testGetFileName() {
assertEquals("", getFileName("/"));
assertEquals("", getFileName("////"));
assertEquals("", getFileName("//C//.//../"));
assertEquals("", getFileName("C//.//../"));
assertEquals("C", getFileName("C"));
assertEquals("C", getFileName("/C"));
assertEquals("C", getFileName("/C/"));
assertEquals("C", getFileName("//C//"));
assertEquals("C", getFileName("/A/B/C/"));
assertEquals("C", getFileName("/A/B/C"));
assertEquals("C", getFileName("/C/./B/../"));
assertEquals("C", getFileName("//C//./B//..///"));
assertEquals("user", getFileName("/user/java/.."));
assertEquals("C:", getFileName("C:"));
assertEquals("C:", getFileName("/C:"));
assertEquals("java", getFileName("C:\\Program Files (x86)\\java\\bin\\.."));
assertEquals("C.ext", getFileName("/A/B/C.ext"));
assertEquals("C.ext", getFileName("C.ext"));
}
Maybe getFileName is a bit confusing, because it returns directory names also. It returns the name of file or last directory in a path.
select name, count(*) from DBS, TBLS
where DBS.DB_ID = TBLS.DB_ID
group by NAME into outfile '/tmp/QueryOut1.csv'
fields terminated by ',' lines terminated by '\n';
CREATE TABLE UserGroup
(
[User_Id] INT Foreign Key,
[Group_Id] INT foreign key,
PRIMARY KEY ([User_Id], [Group_Id])
)
git bash is a shell where:
sh.exe
(packaged with msysgit, as share/WinGit/Git Bash.vbs
)$HOME
is definedSee "Fix msysGit Portable $HOME
location":
On a Windows 64:
C:\Windows\SysWOW64\cmd.exe /c ""C:\Prog\Git\1.7.1\bin\sh.exe" --login -i"
This differs from git-cmd.bat
, which provides git commands in a plain DOS command prompt.
A tool like GitHub for Windows (G4W) provides different shell for git (including a PowerShell one)
Update April 2015:
Note: the git bash in msysgit/Git for windows 1.9.5 is an old one:
GNU bash, version 3.1.20(4)-release (i686-pc-msys)
Copyright (C) 2005 Free Software Foundation, Inc.
But with the phasing out of msysgit (Q4 2015) and the new Git For Windows (Q2 2015), you now have Git for Windows 2.3.5.
It has a much more recent bash, based on the 64bits msys2 project, an independent rewrite of MSYS, based on modern Cygwin (POSIX compatibility layer) and MinGW-w64 with the aim of better interoperability with native Windows software. msys2
comes with its own installer too.
The git bash is now (with the new Git For Windows):
GNU bash, version 4.3.33(3)-release (x86_64-pc-msys)
Copyright (C) 2013 Free Software Foundation, Inc.
Original answer (June 2013) More precisely, from msygit wiki:
Historically, Git on Windows was only officially supported using Cygwin.
To help make a native Windows version, this project was started, based on the mingw fork.To make the milky 'soup' of project names more clear, we say like this:
- msysGit - is the name of this project, a build environment for Git for Windows, which releases the official binaries
- MinGW - is a minimalist development environment for native Microsoft Windows applications.
It is really a very thin compile-time layer over the Microsoft Runtime; MinGW programs are therefore real Windows programs, with no concept of Unix-style paths or POSIX niceties such as afork()
call- MSYS - is a Bourne Shell command line interpreter system, is used by MinGW (and others), was forked in the past from Cygwin
- Cygwin - a Linux like environment, which was used in the past to build Git for Windows, nowadays has no relation to msysGit
So, your two lines description about "git bash" are:
"Git bash
" is a msys shell included in "Git for Windows", and is a slimmed-down version of Cygwin (an old version at that), whose only purpose is to provide enough of a POSIX layer to run a bash.
Reminder:
msysGit is the development environment to compile Git for Windows. It is complete, in the sense that you just need to install msysGit, and then you can build Git. Without installing any 3rd-party software.
msysGit is not Git for Windows; that is an installer which installs Git -- and only Git.
See more in "Difference between msysgit and Cygwin + git?".
Be aware if you want to execute AJAX requests inside the event handler function for the click event. For some reason Chrome (and maybe other browsers) will not open a new tab/window.
Try this, Its working:
mysql -h {hostname} -u{username} -p{password} -N -e "{query to execute}"
var data = [_x000D_
{ "name": "bill", "age": 20 },_x000D_
{ "name": "jhon", "age": 19 },_x000D_
{ "name": "steve", "age": 16 },_x000D_
{ "name": "larry", "age": 22 },_x000D_
null, null, null_x000D_
];_x000D_
_x000D_
//eliminate all the null values from the data_x000D_
data = data.filter(function(x) { return x !== null }); _x000D_
_x000D_
console.log("data: " + JSON.stringify(data));
_x000D_
This method doesn't call the disambiguation dialog asking you to open either your app or a browser.
If you register the following in your Manifest
<manifest package="com.myApp" .. >
<application ...>
<activity ...>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="gallery"
android:scheme="myApp" />
</intent-filter>
</activity>
..
and click this url from an email on your phone for example
<a href="intent://gallery?directLink=true#Intent;scheme=myApp;package=com.myApp;end">
Click me
</a>
then android will try to find an app with the package com.myApp that responds to your gallery intent and has a myApp scheme. In case it can't, it will take you to the store, looking for com.myApp, which should be your app.
use rgba
(rgb with alpha transparency
):
border: 10px solid rgba(0,0,0,0.5); // 0.5 means 50% of opacity
The alpha transparency
variate between 0 (0% opacity = 100% transparent) and 1 (100 opacity = 0% transparent)
It is worth mentioning Gaphor. A Python modelling/UML tool.
Additionally, if you are debugging as Tom mentioned, you can use var_dump to see the array.
in your for loop use a Redim on the array like here:
For i = 0 to 3
ReDim Preserve test(i)
test(i) = 3 + i
Next i
There are two things you can do:
@Deprecated
annotation to the method, and@deprecated
tag to the javadoc of the methodYou should do both!
Quoting the java documentation on this subject:
Starting with J2SE 5.0, you deprecate a class, method, or field by using the @Deprecated annotation. Additionally, you can use the @deprecated Javadoc tag tell developers what to use instead.
Using the annotation causes the Java compiler to generate warnings when the deprecated class, method, or field is used. The compiler suppresses deprecation warnings if a deprecated compilation unit uses a deprecated class, method, or field. This enables you to build legacy APIs without generating warnings.
You are strongly recommended to use the Javadoc @deprecated tag with appropriate comments explaining how to use the new API. This ensures developers will have a workable migration path from the old API to the new API
The point of an interface is to specify the public API. An interface has no state. Any variables that you create are really constants (so be careful about making mutable objects in interfaces).
Basically an interface says here are all of the methods that a class that implements it must support. It probably would have been better if the creators of Java had not allowed constants in interfaces, but too late to get rid of that now (and there are some cases where constants are sensible in interfaces).
Because you are just specifying what methods have to be implemented there is no idea of state (no instance variables). If you want to require that every class has a certain variable you need to use an abstract class.
Finally, you should, generally speaking, not use public variables, so the idea of putting variables into an interface is a bad idea to begin with.
Short answer - you can't do what you want because it is "wrong" in Java.
Edit:
class Tile
implements Rectangle
{
private int height;
private int width;
@Override
public int getHeight() {
return height;
}
@Override
public int getWidth() {
return width;
}
@Override
public void setHeight(int h) {
height = h;
}
@Override
public void setWidth(int w) {
width = w;
}
}
an alternative version would be:
abstract class AbstractRectangle
implements Rectangle
{
private int height;
private int width;
@Override
public int getHeight() {
return height;
}
@Override
public int getWidth() {
return width;
}
@Override
public void setHeight(int h) {
height = h;
}
@Override
public void setWidth(int w) {
width = w;
}
}
class Tile
extends AbstractRectangle
{
}
Another way with lodash
creating pairs, and then either construct a object or ES6 Map
easily
_(params).map(v=>[v.name, v.input]).fromPairs().value()
or
_.fromPairs(params.map(v=>[v.name, v.input]))
Here is a working example
var params = [_x000D_
{ name: 'foo', input: 'bar' },_x000D_
{ name: 'baz', input: 'zle' }_x000D_
];_x000D_
_x000D_
var obj = _(params).map(v=>[v.name, v.input]).fromPairs().value();_x000D_
_x000D_
console.log(obj);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
_x000D_
In addition to the previous answers, if you use the tool pgAdmin III you can set the time zone as follows:
One more variant is using very powerfull JOOR library https://github.com/jOOQ/jOOR
MyObject myObject = new MyObject()
on(myObject).get("privateField");
It allows to modify any fields like final static constants and call yne protected methods without specifying concrete class in the inheritance hierarhy
<!-- https://mvnrepository.com/artifact/org.jooq/joor-java-8 -->
<dependency>
<groupId>org.jooq</groupId>
<artifactId>joor-java-8</artifactId>
<version>0.9.7</version>
</dependency>
How about: "$env:computername.$env:userdnsdomain"
This actually only works if the user is logged into a domain (i.e. no local accounts), logged into the same domain as the server, and doesn't work with disjointed name space AD configurations.
Use this as referenced in another answer:
$myFQDN=(Get-WmiObject win32_computersystem).DNSHostName+"."+(Get-WmiObject win32_computersystem).Domain ; Write-Host $myFQDN
Sometimes the column you are looking for may be part of the name of many other things that you are not interested in.
For example I was recently looking for a column called "BQR", which also forms part of many other columns such as "BQR_OWNER", "PROP_BQR", etc.
So I would like to have the checkbox that word processors have to indicate "Whole words only".
Unfortunately LIKE has no such functionality, but REGEXP_LIKE can help.
SELECT *
FROM user_source
WHERE regexp_like(text, '(\s|\.|,|^)bqr(\s|,|$)');
This is the regular expression to find this column and exclude the other columns with "BQR" as part of the name:
(\s|\.|,|^)bqr(\s|,|$)
The regular expression matches white-space (\s), or (|) period (.), or (|) comma (,), or (|) start-of-line (^), followed by "bqr", followed by white-space, comma or end-of-line ($).
You can use this code
<script>
// Replace the <textarea id="editor"> with a CKEditor
// instance, using default configuration.
CKEDITOR.config.filebrowserImageBrowseUrl = '/admin/laravel-filemanager?type=Files';
CKEDITOR.config.filebrowserImageUploadUrl = '/admin/laravel-filemanager/upload?type=Images&_token=';
CKEDITOR.config.filebrowserBrowseUrl = '/admin/laravel-filemanager?type=Files';
CKEDITOR.config.filebrowserUploadUrl = '/admin/laravel-filemanager/upload?type=Files&_token=';
CKEDITOR.replaceAll( 'editor');
</script>
The CD / DVD wanted to be on the IDE controller on my system, not the SATA controller
I know it's too late but I'd like to add this update:
I'm using the Conventional Model Metadata Provider which presented by Phil Haacked it's more powerful and easy to apply take look at it : ConventionalModelMetadataProvider
Here if you wanna support many types of resources:
public class LocalizedDisplayNameAttribute : DisplayNameAttribute
{
private readonly PropertyInfo nameProperty;
public LocalizedDisplayNameAttribute(string displayNameKey, Type resourceType = null)
: base(displayNameKey)
{
if (resourceType != null)
{
nameProperty = resourceType.GetProperty(base.DisplayName,
BindingFlags.Static | BindingFlags.Public);
}
}
public override string DisplayName
{
get
{
if (nameProperty == null)
{
return base.DisplayName;
}
return (string)nameProperty.GetValue(nameProperty.DeclaringType, null);
}
}
}
Then use it like this:
[LocalizedDisplayName("Password", typeof(Res.Model.Shared.ModelProperties))]
public string Password { get; set; }
For the full localization tutorial see this page.
This is a very simple adaptation of the modifyList function by Sarkar. Because it is recursive, it will handle more complex situations than mapply
would, and it will handle mismatched name situations by ignoring the items in 'second' that are not in 'first'.
appendList <- function (x, val)
{
stopifnot(is.list(x), is.list(val))
xnames <- names(x)
for (v in names(val)) {
x[[v]] <- if (v %in% xnames && is.list(x[[v]]) && is.list(val[[v]]))
appendList(x[[v]], val[[v]])
else c(x[[v]], val[[v]])
}
x
}
> appendList(first,second)
$a
[1] 1 2
$b
[1] 2 3
$c
[1] 3 4
You can use :
$query->getSQL();
If you are using MySQL you can use Workbench to view running SQL statements. You can also use view the running query from mysql by using the following :
SHOW FULL PROCESSLIST \G
My solution is to display an empty message first (with default signature!) and insert the intended strHTMLBody
into the existing HTMLBody
.
If, like PowerUser states, the signature is wiped out while editing HTMLBody you might consider storing the contents of ObjMail.HTMLBody
into variable strTemp
immediately after ObjMail.Display
and add strTemp
afterwards but that should not be necessary.
Sub X(strTo as string, strSubject as string, strHTMLBody as string)
Dim OlApp As Outlook.Application
Dim ObjMail As Outlook.MailItem
Set OlApp = Outlook.Application
Set ObjMail = OlApp.CreateItem(olMailItem)
ObjMail.To = strTo
ObjMail.Subject = strSubject
ObjMail.Display
'You now have the default signature within ObjMail.HTMLBody.
'Add this after adding strHTMLBody
ObjMail.HTMLBody = strHTMLBody & ObjMail.HTMLBody
'ObjMail.Send 'send immediately or
'ObjMail.close olSave 'save as draft
'Set OlApp = Nothing
End sub
I was looking for the same thing and I just found this list
From ScottGu's blog:
Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:
The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:
Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).
Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.
This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.
Also see this.
In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".
Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.
Wikipedia
There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.
This command helped me to solve the problem:
export DISPLAY=:0
Of course it does. After replacing the variable, it reads [ !-z ]
, which is not a valid [
command. Use double quotes, or [[
.
if [ ! -z "$errorstatus" ]
if [[ ! -z $errorstatus ]]
Please find the actual css from Bootstrap
.container-fluid {
padding-right: 15px;
padding-left: 15px;
margin-right: auto;
margin-left: auto;
}
.row {
margin-right: -15px;
margin-left: -15px;
}
When you add a .container-fluid
class, it adds a horizontal padding of 15px, and the same will be removed when you add a .row
class as a child element by the negative margin set on row.
You can use this pod called 'SVGParser'. https://cocoapods.org/pods/SVGParser.
After adding it in your pod file, all you have to do is to import this module to the class that you want to use it. You should show the SVG image in an ImageView.
There are three cases you can show this SVGimage:
You can also find an example project in GitHub: https://github.com/AndreyMomot/SVGParser. Just download the project and run it to see how it works.
The tcpdf file that causes the "data has already been output" is in the tcpdf folder called tcpdf.php. You can modify it:
add the line ob_end_clean(); as below (3rd last line):
public function Output($name='doc.pdf', $dest='I') {
//LOTS OF CODE HERE....}
switch($dest) {
case 'I': {
// Send PDF to the standard output
if (ob_get_contents()) {
$this->Error('Some data has already been output, can\'t send PDF file');}
//some code here....}
case 'D': { // download PDF as file
if (ob_get_contents()) {
$this->Error('Some data has already been output, can\'t send PDF file');}
break;}
case 'F':
case 'FI':
case 'FD': {
// save PDF to a local file
//LOTS OF CODE HERE..... break;}
case 'E': {
// return PDF as base64 mime email attachment)
case 'S': {
// returns PDF as a string
return $this->getBuffer();
}
default: {
$this->Error('Incorrect output destination: '.$dest);
}
}
ob_end_clean(); //add this line here
return '';
}
Now lets look at your code.
I see you have $rs and $sql mixed up. These are 2 different things working together.
$conn=odbc_connect('northwind','****','*****');
if (!$conn) {
exit("Connection Failed: " . $conn);
}
$sql="SELECT * FROM products"; //is products your table name?
$rs=odbc_exec($conn,$sql);
if (!$rs) {
exit("Error in SQL");
}
while (odbc_fetch_row($rs)) {
$prodname=odbc_result($rs,"Product Name"); //but preferably never use spaces for table names.
$prodid=odbc_result($rs,"ProdID"); //prodID is assumed attribute
echo "$prodname";
echo "$prodid";
}
odbc_close($conn);
now you can use the $prodname and output it to the TCPDF output.
and I assume your are connecting to a MS access database.
You can use setattr
name = 'varname'
value = 'something'
setattr(self, name, value) #equivalent to: self.varname= 'something'
print (self.varname)
#will print 'something'
But, since you should inform an object to receive the new variable, this only works inside classes or modules.
Check out yowsup
https://github.com/tgalal/yowsup
Yowsup is a python library that allows you to do all the previous in your own app. Yowsup allows you to login and use the Whatsapp service and provides you with all capabilities of an official Whatsapp client, allowing you to create a full-fledged custom Whatsapp client.
A solid example of Yowsup's usage is Wazapp. Wazapp is full featured Whatsapp client that is being used by hundreds of thousands of people around the world. Yowsup is born out of the Wazapp project. Before becoming a separate project, it was only the engine powering Wazapp. Now that it matured enough, it was separated into a separate project, allowing anyone to build their own Whatsapp client on top of it. Having such a popular client as Wazapp, built on Yowsup, helped bring the project into a much advanced, stable and mature level, and ensures its continuous development and maintaince.
Yowsup also comes with a cross platform command-line frontend called yowsup-cli. yowsup-cli allows you to jump into connecting and using Whatsapp service directly from command line.
Adding to SimonHawesome's excellent answer. I've made an succinct version which utilizes some of the new typescript features. I realize that SimonHawesome's version is intentionally verbose as to explain the underlying details. I've also added an early-out check so that the pipe works for falsy values. E.g., if the map is null
.
Note that using a iterator transform (as done here) can be more efficient since we do not need to allocate memory for a temporary array (as done in some of the other answers).
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({
name: 'mapToIterable'
})
export class MapToIterable implements PipeTransform {
transform(map: { [key: string]: any }, ...parameters: any[]) {
if (!map)
return undefined;
return Object.keys(map)
.map((key) => ({ 'key': key, 'value': map[key] }));
}
}
Try using collections to store the values of a key:
Map<Key, Collection<Value>>
you have to maintain the value list yourself
Have a look at the advanced wheres documentation for Fluent: http://laravel.com/docs/queries#advanced-wheres
Here's an example of what you're trying to achieve:
DB::table('users')
->whereIn('id', function($query)
{
$query->select(DB::raw(1))
->from('orders')
->whereRaw('orders.user_id = users.id');
})
->get();
This will produce:
select * from users where id in (
select 1 from orders where orders.user_id = users.id
)
Bill Horst's - Converting SQL to LINQ is a very good resource for this task (as well as LINQPad).
LINQ Tools has a decent list of tools as well but I do not believe there is anything else out there that can do what Linqer did.
Generally speaking, LINQ is a higher-level querying language than SQL which can cause translation loss when trying to convert SQL to LINQ. For one, LINQ emits shaped results and SQL flat result sets. The issue here is that an automatic translation from SQL to LINQ will often have to perform more transliteration than translation - generating examples of how NOT to write LINQ queries. For this reason, there are few (if any) tools that will be able to reliably convert SQL to LINQ. Analogous to learning C# 4 by first converting VB6 to C# 4 and then studying the resulting conversion.
$(document).on('keyup keydown', function(e){shifted = e.shiftKey} );
You need to set line-height.
<div style="border: 1px solid red;">
<span style="font-size: 38px; vertical-align:middle; float:left; line-height: 38px">Hejsan</span>
<span style="font-size: 13px; vertical-align:middle; float:right; line-height: 38px">svejsan</span>
<div style="clear: both;"></div>
If you want to submit files using ajax use "jquery.form.js" This submits all form elements easily.
Samples http://jquery.malsup.com/form/#ajaxSubmit
rough view :
<form id='AddPhotoForm' method='post' action='../photo/admin_save_photo.php' enctype='multipart/form-data'>
<script type="text/javascript">
function showResponseAfterAddPhoto(responseText, statusText)
{
information= responseText;
callAjaxtolist();
$("#AddPhotoForm").resetForm();
$("#photo_msg").html('<div class="album_msg">Photo uploaded Successfully...</div>');
};
$(document).ready(function(){
$('.add_new_photo_div').live('click',function(){
var options = {success:showResponseAfterAddPhoto};
$("#AddPhotoForm").ajaxSubmit(options);
});
});
</script>
This seems to work for me at least when i tried on visual studio 2017.
public static class Words
{
public const string temp = "What";
public const string temp2 = "the";
}
var i = "the";
switch (i)
{
case Words.temp:
break;
case Words.temp2:
break;
}
You can do this via a couple ways.
One is when you run your application, you can pass it a flag.
java -Dgate.home="http://gate.ac.uk/wiki/code-repository" your_application
Or set it programmatically in code before the piece of code that needs this property set. Java keeps a Properties
object for System
wide configuration.
Properties props = System.getProperties();
props.setProperty("gate.home", "http://gate.ac.uk/wiki/code-repository");
A DIV is by default a BLOCK display element, meaning it sits on its own line. If you add the CSS property display:inline it will behave the way you want. But perhaps you should be considering a SPAN instead?
Don't try fixed window.orientation queries (0, 90 etc doesn't mean portrait, landscape etc):
http://www.matthewgifford.com/blog/2011/12/22/a-misconception-about-window-orientation/
Even on iOS7 depending how you come into the browser 0 isn't always portrait
public static void main(String[] args)
{
String strDate="Feb 2013";
String[] strArray=strDate.split("\\s+");
Calendar cal = Calendar.getInstance();
cal.setTime(new SimpleDateFormat("MMM").parse(strArray[0].toString()));
int monthInt = cal.get(Calendar.MONTH);
monthInt++;
cal.set(Calendar.YEAR, Integer.parseInt(strArray[1]));
strDate=strArray[1].toString()+"-"+monthInt+"-"+cal.getActualMaximum(Calendar.DAY_OF_MONTH);
System.out.println(strDate);
}
If you like Vim, it has built-in syntax highlighting for the syslog file, e.g. it will highlight error messages in red.
vi +'syntax on' /var/log/syslog
I found this approach which parse JSON into a dynamic object, it extends a DynamicObject
and JavascriptConverter
to turn the string into an object.
DynamicJsonObject
public class DynamicJsonObject : DynamicObject
{
private IDictionary<string, object> Dictionary { get; set; }
public DynamicJsonObject(IDictionary<string, object> dictionary)
{
this.Dictionary = dictionary;
}
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
result = this.Dictionary[binder.Name];
if (result is IDictionary<string, object>)
{
result = new DynamicJsonObject(result as IDictionary<string, object>);
}
else if (result is ArrayList && (result as ArrayList) is IDictionary<string, object>)
{
result = new List<DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary<string, object>)));
}
else if (result is ArrayList)
{
result = new List<object>((result as ArrayList).ToArray());
}
return this.Dictionary.ContainsKey(binder.Name);
}
}
Converter
public class DynamicJsonConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
if (type == typeof(object))
{
return new DynamicJsonObject(dictionary);
}
return null;
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override IEnumerable<Type> SupportedTypes
{
get { return new ReadOnlyCollection<Type>(new List<Type>(new Type[] { typeof(object) })); }
}
}
Usage (sample json):
JavaScriptSerializer jss = new JavaScriptSerializer();
jss.RegisterConverters(new JavaScriptConverter[] { new DynamicJsonConverter() });
dynamic glossaryEntry = jss.Deserialize(json, typeof(object)) as dynamic;
Console.WriteLine("glossaryEntry.glossary.title: " + glossaryEntry.glossary.title);
Console.WriteLine("glossaryEntry.glossary.GlossDiv.title: " + glossaryEntry.glossary.GlossDiv.title);
Console.WriteLine("glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.ID: " + glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.ID);
Console.WriteLine("glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.para: " + glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.para);
foreach (var also in glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso)
{
Console.WriteLine("glossaryEntry.glossary.GlossDiv.GlossList.GlossEntry.GlossDef.GlossSeeAlso: " + also);
}
This method has to return true, otherwise it will throw an error. E.g. you can throw an error if a key does not exist.
Returning true
and emptying result
will return an empty value rather than throwing an error.
public override bool TryGetMember(GetMemberBinder binder, out object result)
{
if (!this.Dictionary.ContainsKey(binder.Name))
{
result = "";
}
else
{
result = this.Dictionary[binder.Name];
}
if (result is IDictionary<string, object>)
{
result = new DynamicJsonObject(result as IDictionary<string, object>);
}
else if (result is ArrayList && (result as ArrayList) is IDictionary<string, object>)
{
result = new List<DynamicJsonObject>((result as ArrayList).ToArray().Select(x => new DynamicJsonObject(x as IDictionary<string, object>)));
}
else if (result is ArrayList)
{
result = new List<object>((result as ArrayList).ToArray());
}
return true; // this.Dictionary.ContainsKey(binder.Name);
}
You need an HTML element for each column in your layout.
I’d suggest:
<div class="two-col">
<div class="col1">
<label for="field1">Field One:</label>
<input id="field1" name="field1" type="text">
</div>
<div class="col2">
<label for="field2">Field Two:</label>
<input id="field2" name="field2" type="text">
</div>
</div>
.two-col {
overflow: hidden;/* Makes this div contain its floats */
}
.two-col .col1,
.two-col .col2 {
width: 49%;
}
.two-col .col1 {
float: left;
}
.two-col .col2 {
float: right;
}
.two-col label {
display: block;
}
Just to expand on Matt DeKrey's answer, just deleting the csproj.user file (without needing to recreate solutions) was able to fix the problem for me.
The only side effect I had was I needed to reset the Start Action back to using a specific page.
The line in your controller code, which reads $scope.myFunc={
should be $scope.myFunc = function() {
the function()
part is important to indicate, it is a function!
The updated controller code would be
app.controller('myCtrl',['$scope',function($cope){
$scope.myFunc = function() {
console.log("function called");
};
}]);
I eventually stumbled upon an example of the usage I was looking for - to assign an error to the Model in general, rather than one of it's properties, as usual you call:
ModelState.AddModelError(string key, string errorMessage);
but use an empty string for the key:
ModelState.AddModelError(string.Empty, "There is something wrong with Foo.");
The error message will present itself in the <%: Html.ValidationSummary() %>
as you'd expect.
Let's start with this small df:
import pandas as pd
import time as tm
import numpy as np
n=10
a=np.arange(0,n**2)
df=pd.DataFrame(a.reshape(n,n))
We'll so have
df
Out[25]:
0 1 2 3 4 5 6 7 8 9
0 0 1 2 3 4 5 6 7 8 9
1 10 11 12 13 14 15 16 17 18 19
2 20 21 22 23 24 25 26 27 28 29
3 30 31 32 33 34 35 36 37 38 39
4 40 41 42 43 44 45 46 47 48 49
5 50 51 52 53 54 55 56 57 58 59
6 60 61 62 63 64 65 66 67 68 69
7 70 71 72 73 74 75 76 77 78 79
8 80 81 82 83 84 85 86 87 88 89
9 90 91 92 93 94 95 96 97 98 99
With this we have:
df.iloc[3,3]
Out[33]: 33
df.iat[3,3]
Out[34]: 33
df.iloc[:3,:3]
Out[35]:
0 1 2 3
0 0 1 2 3
1 10 11 12 13
2 20 21 22 23
3 30 31 32 33
df.iat[:3,:3]
Traceback (most recent call last):
... omissis ...
ValueError: At based indexing on an integer index can only have integer indexers
Thus we cannot use .iat for subset, where we must use .iloc only.
But let's try both to select from a larger df and let's check the speed ...
# -*- coding: utf-8 -*-
"""
Created on Wed Feb 7 09:58:39 2018
@author: Fabio Pomi
"""
import pandas as pd
import time as tm
import numpy as np
n=1000
a=np.arange(0,n**2)
df=pd.DataFrame(a.reshape(n,n))
t1=tm.time()
for j in df.index:
for i in df.columns:
a=df.iloc[j,i]
t2=tm.time()
for j in df.index:
for i in df.columns:
a=df.iat[j,i]
t3=tm.time()
loc=t2-t1
at=t3-t2
prc = loc/at *100
print('\nloc:%f at:%f prc:%f' %(loc,at,prc))
loc:10.485600 at:7.395423 prc:141.784987
So with .loc we can manage subsets and with .at only a single scalar, but .at is faster than .loc
:-)
In WSDL definition, bindings contain operations, here comes style for each operation.
Document : In WSDL file, it specifies types details either having inline Or imports XSD document, which describes the structure(i.e. schema) of the complex data types being exchanged by those service methods which makes loosely coupled. Document style is default.
In WSDL types element looks as follows:
<types>
<xsd:schema>
<xsd:import schemaLocation="http://localhost:9999/ws/hello?xsd=1" namespace="http://ws.peter.com/"/>
</xsd:schema>
</types>
The schema is importing from external reference.
RPC :In WSDL file, it does not creates types schema, within message elements it defines name and type attributes which makes tightly coupled.
<types/>
<message name="getHelloWorldAsString">
<part name="arg0" type="xsd:string"/>
</message>
<message name="getHelloWorldAsStringResponse">
<part name="return" type="xsd:string"/>
</message>
RPC : No types in WSDL
Document: Types section would be available in WSDL
componentDidMount(){
//http://localhost:3000/service/anas
//<Route path="/service/:serviceName" component={Service} />
const {params} =this.props.match;
this.setState({
title: params.serviceName ,
content: data.Content
})
}
for anyone tunnelling with SSH; you can create a version of the gem
command that uses SOCKS proxy:
socksify
with gem install socksify
(you'll need to be able to do this step without proxy, at least)Copy your existing gem exe
cp $(command which gem) /usr/local/bin/proxy_gem
Open it in your favourite editor and add this at the top (after the shebang)
require 'socksify'
if ENV['SOCKS_PROXY']
require 'socksify'
host, port = ENV['SOCKS_PROXY'].split(':')
TCPSocket.socks_server = host || 'localhost'
TCPSocket.socks_port = port.to_i || 1080
end
Set up your tunnel
ssh -D 8123 -f -C -q -N user@proxy
Run your gem command with proxy_gem
SOCKS_PROXY=localhost:8123 proxy_gem push mygem
i tried all mentioned solutions available on the internet but no solution working on my Mac, then i created a provisioning profile manually on apple developer website from certificates and identifiers. By importing that file manually app successfully uploaded on appStore follow below steps
On Developer website
1-go to this link https://developer.apple.com/account/resources/certificates
2- In profile Section create new profile by using app bundle identifier
3-Download it and save it an where
On Xcode
1-Go to Signing and certificates
2-Disable automatically manage signing
3- Select provisioning profile in its section
4- Archive the app
5-Click Distribute App ->ApStore connect ->Upload->Next-> Then Select Profile from XXXX-app section when it download it show inside this section and now upload it
public boolean isAlertPresent()
{
try
{
driver.switchTo().alert();
return true;
} // try
catch (NoAlertPresentException Ex)
{
return false;
} // catch
} // isAlertPresent()
check the link here https://groups.google.com/forum/?fromgroups#!topic/webdriver/1GaSXFK76zY
Try this..
function getdata($csvFile){
$file_handle = fopen($csvFile, 'r');
while (!feof($file_handle) ) {
$line_of_text[] = fgetcsv($file_handle, 1024);
}
fclose($file_handle);
return $line_of_text;
}
// Set path to CSV file
$csvFile = 'test.csv';
$csv = getdata($csvFile);
echo '<pre>';
print_r($csv);
echo '</pre>';
Array
(
[0] => Array
(
[0] => Project
[1] => Date
[2] => User
[3] => Activity
[4] => Issue
[5] => Comment
[6] => Hours
)
[1] => Array
(
[0] => test
[1] => 04/30/2015
[2] => test
[3] => test
[4] => test
[5] =>
[6] => 6.00
));
Try this one:
Color color = new Color (10,10,10)
myPaint.setColor(color.getRGB());
I had this problem after upgrading WAMP but having no database backup.
This worked for me:
Stop new WAMP
Copy over database directories you need and ibdata1 file from old WAMP installation
Delete ib_logfile0
and ib_logfile1
Start WAMP
You should now be able to make backups of your databases. However after your server restarts again you will still have problems. So now reinstall WAMP and import your databases.
apnerve's answer was correct before HTML 5 came out, now it's a little more complicated.
For example, the script
element, according to the HTML 5 specification, has two global attributes which change how the src
attribute functions: async
and defer
. These change how the script (embedded inline or imported from external file) should be executed.
This means there are three possible modes that can be selected using these attributes:
async
attribute is present, then the script will be executed asynchronously, as soon as it is available. async
attribute is not present but the defer
attribute is present, then the script is executed when the page has finished parsing. For details please see HTML 5 recommendation
I just wanted to update with a new answer for whoever occasionally visits this topic. Some of the answers should be checked and archived by stackoverflow and every one of us.
I had to go to bash
(from ZSH) first. Then
sudo -H pip install 'requests[security]' --upgrade
fixed the problem.
Here is what I would recommend.
It should conform to C89, and be completely portable. In particular, it works also on pipes and sockets on POSIXy systems.
The idea is that we read the input in large-ish chunks (READALL_CHUNK
), dynamically reallocating the buffer as we need it. We only use realloc()
, fread()
, ferror()
, and free()
:
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
/* Size of each input chunk to be
read and allocate for. */
#ifndef READALL_CHUNK
#define READALL_CHUNK 262144
#endif
#define READALL_OK 0 /* Success */
#define READALL_INVALID -1 /* Invalid parameters */
#define READALL_ERROR -2 /* Stream error */
#define READALL_TOOMUCH -3 /* Too much input */
#define READALL_NOMEM -4 /* Out of memory */
/* This function returns one of the READALL_ constants above.
If the return value is zero == READALL_OK, then:
(*dataptr) points to a dynamically allocated buffer, with
(*sizeptr) chars read from the file.
The buffer is allocated for one extra char, which is NUL,
and automatically appended after the data.
Initial values of (*dataptr) and (*sizeptr) are ignored.
*/
int readall(FILE *in, char **dataptr, size_t *sizeptr)
{
char *data = NULL, *temp;
size_t size = 0;
size_t used = 0;
size_t n;
/* None of the parameters can be NULL. */
if (in == NULL || dataptr == NULL || sizeptr == NULL)
return READALL_INVALID;
/* A read error already occurred? */
if (ferror(in))
return READALL_ERROR;
while (1) {
if (used + READALL_CHUNK + 1 > size) {
size = used + READALL_CHUNK + 1;
/* Overflow check. Some ANSI C compilers
may optimize this away, though. */
if (size <= used) {
free(data);
return READALL_TOOMUCH;
}
temp = realloc(data, size);
if (temp == NULL) {
free(data);
return READALL_NOMEM;
}
data = temp;
}
n = fread(data + used, 1, READALL_CHUNK, in);
if (n == 0)
break;
used += n;
}
if (ferror(in)) {
free(data);
return READALL_ERROR;
}
temp = realloc(data, used + 1);
if (temp == NULL) {
free(data);
return READALL_NOMEM;
}
data = temp;
data[used] = '\0';
*dataptr = data;
*sizeptr = used;
return READALL_OK;
}
Above, I've used a constant chunk size, READALL_CHUNK
== 262144 (256*1024
). This means that in the worst case, up to 262145 chars are wasted (allocated but not used), but only temporarily. At the end, the function reallocates the buffer to the optimal size. Also, this means that we do four reallocations per megabyte of data read.
The 262144-byte default in the code above is a conservative value; it works well for even old minilaptops and Raspberry Pis and most embedded devices with at least a few megabytes of RAM available for the process. Yet, it is not so small that it slows down the operation (due to many read calls, and many buffer reallocations) on most systems.
For desktop machines at this time (2017), I recommend a much larger READALL_CHUNK
, perhaps #define READALL_CHUNK 2097152
(2 MiB).
Because the definition of READALL_CHUNK
is guarded (i.e., it is defined only if it is at that point in the code still undefined), you can override the default value at compile time, by using (in most C compilers) -DREADALL_CHUNK=2097152
command-line option -- but do check your compiler options for defining a preprocessor macro using command-line options.
An update to the correct answer phil provided, for more recent versions of Pycharm (e.g. 2019.2).
Go to File > Settings and find your project, then select Project Interpreter. Now click the button with a cog to the right of the selected project interpreter (used to be a ...).
From the drop-down menu select Show All... and in the dialog that opens click the icon with a folder and two sub-folders.
You are presented with a dialog with the current interpreter paths, click on + to add one more.
Because Intent has size limit . I use public static object to do pass bitmap from service to broadcast ....
public class ImageBox {
public static Queue<Bitmap> mQ = new LinkedBlockingQueue<Bitmap>();
}
pass in my service
private void downloadFile(final String url){
mExecutorService.submit(new Runnable() {
@Override
public void run() {
Bitmap b = BitmapFromURL.getBitmapFromURL(url);
synchronized (this){
TaskCount--;
}
Intent i = new Intent(ACTION_ON_GET_IMAGE);
ImageBox.mQ.offer(b);
sendBroadcast(i);
if(TaskCount<=0)stopSelf();
}
});
}
My BroadcastReceiver
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
LOG.d(TAG, "BroadcastReceiver get broadcast");
String action = intent.getAction();
if (DownLoadImageService.ACTION_ON_GET_IMAGE.equals(action)) {
Bitmap b = ImageBox.mQ.poll();
if(b==null)return;
if(mListener!=null)mListener.OnGetImage(b);
}
}
};
There is a Java TFS client in the Team Explorer Everywhere installation (together with an Eclipse plugin). Look at http://www.microsoft.com/en-us/download/details.aspx?id=30661
One possibility would be to use a Google Drawing, part of Google Drive, if you want a more visual and easy-to-edit option. You can create the cards by grouping a color-filled rectangle and one or more text fields together. Being a sufficiently free-form online vector drawing program, it doesn't really limit your possibilities like if you use a more dedicated solution.
The only real downsides are that you have to first create the building blocks from the beginning, and don't get numerical statistics like with a more structured tool.
function numberToEnglish( n ) {
var string = n.toString(), units, tens, scales, start, end, chunks, chunksLen, chunk, ints, i, word, words, and = 'and';
/* Remove spaces and commas */
string = string.replace(/[, ]/g,"");
/* Is number zero? */
if( parseInt( string ) === 0 ) {
return 'zero';
}
/* Array of units as words */
units = [ '', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen' ];
/* Array of tens as words */
tens = [ '', '', 'twenty', 'thirty', 'forty', 'fifty', 'sixty', 'seventy', 'eighty', 'ninety' ];
/* Array of scales as words */
scales = [ '', 'thousand', 'million', 'billion', 'trillion', 'quadrillion', 'quintillion', 'sextillion', 'septillion', 'octillion', 'nonillion', 'decillion', 'undecillion', 'duodecillion', 'tredecillion', 'quatttuor-decillion', 'quindecillion', 'sexdecillion', 'septen-decillion', 'octodecillion', 'novemdecillion', 'vigintillion', 'centillion' ];
/* Split user argument into 3 digit chunks from right to left */
start = string.length;
chunks = [];
while( start > 0 ) {
end = start;
chunks.push( string.slice( ( start = Math.max( 0, start - 3 ) ), end ) );
}
/* Check if function has enough scale words to be able to stringify the user argument */
chunksLen = chunks.length;
if( chunksLen > scales.length ) {
return '';
}
/* Stringify each integer in each chunk */
words = [];
for( i = 0; i < chunksLen; i++ ) {
chunk = parseInt( chunks[i] );
if( chunk ) {
/* Split chunk into array of individual integers */
ints = chunks[i].split( '' ).reverse().map( parseFloat );
/* If tens integer is 1, i.e. 10, then add 10 to units integer */
if( ints[1] === 1 ) {
ints[0] += 10;
}
/* Add scale word if chunk is not zero and array item exists */
if( ( word = scales[i] ) ) {
words.push( word );
}
/* Add unit word if array item exists */
if( ( word = units[ ints[0] ] ) ) {
words.push( word );
}
/* Add tens word if array item exists */
if( ( word = tens[ ints[1] ] ) ) {
words.push( word );
}
/* Add 'and' string after units or tens integer if: */
if( ints[0] || ints[1] ) {
/* Chunk has a hundreds integer or chunk is the first of multiple chunks */
if( ints[2] || ! i && chunksLen ) {
words.push( and );
}
}
/* Add hundreds word if array item exists */
if( ( word = units[ ints[2] ] ) ) {
words.push( word + ' hundred' );
}
}
}
return words.reverse().join( ' ' );
}
// - - - - - Tests - - - - - -
function test(v) {
var sep = ('string'==typeof v)?'"':'';
console.log("numberToEnglish("+sep + v.toString() + sep+") = "+numberToEnglish(v));
}
test(2);
test(721);
test(13463);
test(1000001);
test("21,683,200,000,621,384");
_x000D_
Check out Javascript's Array API for details on the exact syntax for Array methods. Modifying your code to use the correct syntax would be:
var array = [];
calendars.forEach(function(item) {
array.push(item.id);
});
console.log(array);
You can also use the map()
method to generate an Array filled with the results of calling the specified function on each element. Something like:
var array = calendars.map(function(item) {
return item.id;
});
console.log(array);
And, since ECMAScript 2015 has been released, you may start seeing examples using let
or const
instead of var
and the =>
syntax for creating functions. The following is equivalent to the previous example (except it may not be supported in older node versions):
let array = calendars.map(item => item.id);
console.log(array);
<> means not equal. however, in some versions of SQL, you can write !=
select regexp_replace(field, E'[\\n\\r\\u2028]+', ' ', 'g' )
I had the same problem in my postgres d/b, but the newline in question wasn't the traditional ascii CRLF, it was a unicode line separator, character U2028. The above code snippet will capture that unicode variation as well.
Update... although I've only ever encountered the aforementioned characters "in the wild", to follow lmichelbacher's advice to translate even more unicode newline-like characters, use this:
select regexp_replace(field, E'[\\n\\r\\f\\u000B\\u0085\\u2028\\u2029]+', ' ', 'g' )
I think this would be easiest one:
test1.ForEach(str => test2.RemoveAll(x=>x.Contains(str)));
Ultimately they both produce the same HTML but Html.TextBoxFor() is strongly typed where as Html.TextBox isn't.
1: @Html.TextBox("Name")
2: Html.TextBoxFor(m => m.Name)
will both produce
<input id="Name" name="Name" type="text" />
So what does that mean in terms of use?
Generally two things:
TextBoxFor
will generate your input names for you. This is usually just the property name but for properties of complex types can include an underscore such as 'customer_name'TextBoxFor
version will allow you to use compile time checking. So if you change your model then you can check whether there are any errors in your views.It is generally regarded as better practice to use the strongly typed versions of the HtmlHelpers that were added in MVC2.
Generally these are either:
Lossless compression Lossless compression algorithms reduce file size without losing image quality, though they are not compressed into as small a file as a lossy compression file. When image quality is valued above file size, lossless algorithms are typically chosen.
Lossy compression
Lossy compression algorithms take advantage of the inherent limitations of the human eye and discard invisible information. Most lossy compression algorithms allow for variable quality levels (compression) and as these levels are increased, file size is reduced. At the highest compression levels, image deterioration becomes noticeable as "compression artifacting". The images below demonstrate the noticeable artifacting of lossy compression algorithms; select the thumbnail image to view the full size version.
Each format is different as described below:
JPEG JPEG (Joint Photographic Experts Group) files are (in most cases) a lossy format; the DOS filename extension is JPG (other OS might use JPEG). Nearly every digital camera can save images in the JPEG format, which supports 8 bits per color (red, green, blue) for a 24-bit total, producing relatively small files. When not too great, the compression does not noticeably detract from the image's quality, but JPEG files suffer generational degradation when repeatedly edited and saved. Photographic images may be better stored in a lossless non-JPEG format if they will be re-edited, or if small "artifacts" (blemishes caused by the JPEG's compression algorithm) are unacceptable. The JPEG format also is used as the image compression algorithm in many Adobe PDF files.
TIFF The TIFF (Tagged Image File Format) is a flexible format that normally saves 8 bits or 16 bits per color (red, green, blue) for 24-bit and 48-bit totals, respectively, using either the TIFF or the TIF filenames. The TIFF's flexibility is both blessing and curse, because no single reader reads every type of TIFF file. TIFFs are lossy and lossless; some offer relatively good lossless compression for bi-level (black&white) images. Some digital cameras can save in TIFF format, using the LZW compression algorithm for lossless storage. The TIFF image format is not widely supported by web browsers. TIFF remains widely accepted as a photograph file standard in the printing business. The TIFF can handle device-specific colour spaces, such as the CMYK defined by a particular set of printing press inks.
PNG The PNG (Portable Network Graphics) file format was created as the free, open-source successor to the GIF. The PNG file format supports truecolor (16 million colours) while the GIF supports only 256 colours. The PNG file excels when the image has large, uniformly coloured areas. The lossless PNG format is best suited for editing pictures, and the lossy formats, like JPG, are best for the final distribution of photographic images, because JPG files are smaller than PNG files. Many older browsers currently do not support the PNG file format, however, with Internet Explorer 7, all contemporary web browsers fully support the PNG format. The Adam7-interlacing allows an early preview, even when only a small percentage of the image data has been transmitted.
GIF GIF (Graphics Interchange Format) is limited to an 8-bit palette, or 256 colors. This makes the GIF format suitable for storing graphics with relatively few colors such as simple diagrams, shapes, logos and cartoon style images. The GIF format supports animation and is still widely used to provide image animation effects. It also uses a lossless compression that is more effective when large areas have a single color, and ineffective for detailed images or dithered images.
BMP
The BMP file format (Windows bitmap) handles graphics files within the Microsoft Windows OS. Typically, BMP files are uncompressed, hence they are large; the advantage is their simplicity, wide acceptance, and use in Windows programs.
Use for Web Pages / Web Applications
The following is a brief summary for these image formats when using them with a web page / application.
Source: Image File Formats
Sorry, most efficient way with out stuffing your proj file is.
rebuild.
Congratulate your self for being smarter than everyone else and not ****ing you project. For me this exercise took under 10 seconds. Where as manually trying to input the compile... line into the csproj not only can render your project unusable but it is also impossible to maintain on large scale application. Better to keep source version control software to do the updates. If you need to cross merge branches then doing the above is amazing :).
You could also use function exposed by the axes object of the scatter plot
scatter = plt.scatter(x, y)
ax = scatter.axes
ax.invert_xaxis()
ax.invert_yaxis()
SELECT RIGHT('0'
+ CONVERT(VARCHAR(2), Month( column_name )), 2)
FROM table
Regarding the freezing issue, we found this occurred when processing CSV files with at least one extremely long line.
To reproduce:
[print(x) for x in (['A' * 54790] + (['a' * 1421] * 10))]
However, it appears to have been fixed in PyCharm 4.5.4, so if you experience this, try updating your PyCharm.
You can use the following SQL to compare both date and time -
Select * From temp where mydate > STR_TO_DATE('2009-06-29 04:00:44', '%Y-%m-%d %H:%i:%s');
Attached mysql output when I used same SQL on same kind of table and field that you mentioned in the problem-
It should work perfect.
If you use IEnumerable
instead, it will work (at least in C# 4.0, I have not tried previous versions). This is just a cast, of course, it will still be a list.
Instead of -
List<A> listOfA = new List<C>(); // compiler Error
In the original code of the question, use -
IEnumerable<A> listOfA = new List<C>(); // compiler error - no more! :)
$("#idform").validate({
rules: {
'roles': {
required: true,
},
},
messages: {
'roles': {
required: "One Option please",
},
}
});
Working from VaLo's answer:
cd %directory to browser%
%browser's name to main executable (firefox, chrome, opera, etc.)% https://www.google.com
start https://www.google.com
doesn't seem to work (at least in my environment)
Modified Murtaza Hussain answer:
function unserializeForm($str) {
$strArray = explode("&", $str);
foreach($strArray as $item) {
$array = explode("=", $item);
$returndata[] = $array;
}
return $returndata;
}
Only two steps:
Install the latest release "pandoc" from here:
Call the function pandoc
in the library(knitr)
library(knitr)
pandoc('input.md', format = 'latex')
Thus, you can convert your "input.md" into "input.pdf".
Based on my experience, even with python 3.3+, an empty __init__.py
is still needed sometimes. One situation is when you want to refer a subfolder as a package. For example, when I ran python -m test.foo
, it didn't work until I created an empty __init__.py
under the test folder. And I'm talking about 3.6.6 version here which is pretty recent.
Apart from that, even for reasons of compatibility with existing source code or project guidelines, its nice to have an empty __init__.py
in your package folder.
From here:
http://www.christianengvall.se/undo-pushed-merge-git/
git revert -m 1 <merge commit hash>
Git revert adds a new commit that rolls back the specified commit.
Using -m 1 tells it that this is a merge and we want to roll back to the parent commit on the master branch. You would use -m 2 to specify the develop branch.
The initial problem is that the the configuration specifies a property suffix=".jsp"
so the ViewResolver implementing class will add .jsp
to the end of the view name being returned from your method.
However since you commented out the InternalResourceViewResolver
then, depending on the rest of your application configuration, there might not be any other ViewResolver registered. You might find that nothing is working now.
Since .html
files are static and do not require processing by a servlet then it is more efficient, and simpler, to use an <mvc:resources/>
mapping. This requires Spring 3.0.4+.
For example:
<mvc:resources mapping="/static/**" location="/static/" />
which would pass through all requests starting with /static/
to the webapp/static/
directory.
So by putting index.html
in webapp/static/
and using return "static/index.html";
from your method, Spring should find the view.
I ended up coming up with an alternative solution that solved the problem.
I've upvoted the other two answers that provided valid yet ugly solutions for an uglier question:)
Remember that when you write:
MyArray = Range("A1:A5000")
you are really writing
MyArray = Range("A1:A5000").Value
You can also use names:
MyArray = Names("MyWSTable").RefersToRange.Value
But Value is not the only property of Range. I have used:
MyArray = Range("A1:A5000").NumberFormat
I doubt
MyArray = Range("A1:A5000").Font
would work but I would expect
MyArray = Range("A1:A5000").Font.Bold
to work.
I do not know what formats you want to copy so you will have to try.
However, I must add that when you copy and paste a large range, it is not as much slower than doing it via an array as we all thought.
Post Edit information
Having posted the above I tried by own advice. My experiments with copying Font.Color and Font.Bold to an array have failed.
Of the following statements, the second would fail with a type mismatch:
ValueArray = .Range("A1:T5000").Value
ColourArray = .Range("A1:T5000").Font.Color
ValueArray must be of type variant. I tried both variant and long for ColourArray without success.
I filled ColourArray with values and tried the following statement:
.Range("A1:T5000").Font.Color = ColourArray
The entire range would be coloured according to the first element of ColourArray and then Excel looped consuming about 45% of the processor time until I terminated it with the Task Manager.
There is a time penalty associated with switching between worksheets but recent questions about macro duration have caused everyone to review our belief that working via arrays was substantially quicker.
I constructed an experiment that broadly reflects your requirement. I filled worksheet Time1 with 5000 rows of 20 cells which were selectively formatted as: bold, italic, underline, subscript, bordered, red, green, blue, brown, yellow and gray-80%.
With version 1, I copied every 7th cells from worksheet "Time1" to worksheet "Time2" using copy.
With version 2, I copied every 7th cells from worksheet "Time1" to worksheet "Time2" by copying the value and the colour via an array.
With version 3, I copied every 7th cells from worksheet "Time1" to worksheet "Time2" by copying the formula and the colour via an array.
Version 1 took an average of 12.43 seconds, version 2 took an average of 1.47 seconds while version 3 took an average of 1.83 seconds. Version 1 copied formulae and all formatting, version 2 copied values and colour while version 3 copied formulae and colour. With versions 1 and 2 you could add bold and italic, say, and still have some time in hand. However, I am not sure it would be worth the bother given that copying 21,300 values only takes 12 seconds.
** Code for Version 1**
I do not think this code includes anything that needs an explanation. Respond with a comment if I am wrong and I will fix.
Sub SelectionCopyAndPaste()
Dim ColDestCrnt As Integer
Dim ColSrcCrnt As Integer
Dim NumSelect As Long
Dim RowDestCrnt As Integer
Dim RowSrcCrnt As Integer
Dim StartTime As Single
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
NumSelect = 1
ColDestCrnt = 1
RowDestCrnt = 1
With Sheets("Time2")
.Range("A1:T715").EntireRow.Delete
End With
StartTime = Timer
Do While True
ColSrcCrnt = (NumSelect Mod 20) + 1
RowSrcCrnt = (NumSelect - ColSrcCrnt) / 20 + 1
If RowSrcCrnt > 5000 Then
Exit Do
End If
Sheets("Time1").Cells(RowSrcCrnt, ColSrcCrnt).Copy _
Destination:=Sheets("Time2").Cells(RowDestCrnt, ColDestCrnt)
If ColDestCrnt = 20 Then
ColDestCrnt = 1
RowDestCrnt = RowDestCrnt + 1
Else
ColDestCrnt = ColDestCrnt + 1
End If
NumSelect = NumSelect + 7
Loop
Debug.Print Timer - StartTime
' Average 12.43 secs
Application.Calculation = xlCalculationAutomatic
End Sub
** Code for Versions 2 and 3**
The User type definition must be placed before any subroutine in the module. The code works through the source worksheet copying values or formulae and colours to the next element of the array. Once selection has been completed, it copies the collected information to the destination worksheet. This avoids switching between worksheets more than is essential.
Type ValueDtl
Value As String
Colour As Long
End Type
Sub SelectionViaArray()
Dim ColDestCrnt As Integer
Dim ColSrcCrnt As Integer
Dim InxVLCrnt As Integer
Dim InxVLCrntMax As Integer
Dim NumSelect As Long
Dim RowDestCrnt As Integer
Dim RowSrcCrnt As Integer
Dim StartTime As Single
Dim ValueList() As ValueDtl
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
' I have sized the array to more than I expect to require because ReDim
' Preserve is expensive. However, I will resize if I fill the array.
' For my experiment I know exactly how many elements I need but that
' might not be true for you.
ReDim ValueList(1 To 25000)
NumSelect = 1
ColDestCrnt = 1
RowDestCrnt = 1
InxVLCrntMax = 0 ' Last used element in ValueList.
With Sheets("Time2")
.Range("A1:T715").EntireRow.Delete
End With
StartTime = Timer
With Sheets("Time1")
Do While True
ColSrcCrnt = (NumSelect Mod 20) + 1
RowSrcCrnt = (NumSelect - ColSrcCrnt) / 20 + 1
If RowSrcCrnt > 5000 Then
Exit Do
End If
InxVLCrntMax = InxVLCrntMax + 1
If InxVLCrntMax > UBound(ValueList) Then
' Resize array if it has been filled
ReDim Preserve ValueList(1 To UBound(ValueList) + 1000)
End If
With .Cells(RowSrcCrnt, ColSrcCrnt)
ValueList(InxVLCrntMax).Value = .Value ' Version 2
ValueList(InxVLCrntMax).Value = .Formula ' Version 3
ValueList(InxVLCrntMax).Colour = .Font.Color
End With
NumSelect = NumSelect + 7
Loop
End With
With Sheets("Time2")
For InxVLCrnt = 1 To InxVLCrntMax
With .Cells(RowDestCrnt, ColDestCrnt)
.Value = ValueList(InxVLCrnt).Value ' Version 2
.Formula = ValueList(InxVLCrnt).Value ' Version 3
.Font.Color = ValueList(InxVLCrnt).Colour
End With
If ColDestCrnt = 20 Then
ColDestCrnt = 1
RowDestCrnt = RowDestCrnt + 1
Else
ColDestCrnt = ColDestCrnt + 1
End If
Next
End With
Debug.Print Timer - StartTime
' Version 2 average 1.47 secs
' Version 3 average 1.83 secs
Application.Calculation = xlCalculationAutomatic
End Sub
<!DOCTYPE html>
<html>
<head>
<style>
.cardDetaileclips{
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 3; /* after 3 line show ... */
-webkit-box-orient: vertical;
}
</style>
</head>
<body>
<div style="width:100px;">
<div class="cardDetaileclips">
My Name is Manoj and pleasure to help you.
</div>
</div>
</body>
</html>
A bit more elaborate version (to use from another window):
#!/bin/bash
DELAY=3
TERM_PID=$(echo `ps -C gnome-terminal -o pid= | head -1`) # get first gnome-terminal's PID
WID=$(wmctrl -lp | awk -v pid=$TERM_PID '$3==pid{print $1;exit;}') # get window id
xdotool windowfocus $WID
xdotool key alt+t # my key map
xdotool sleep $DELAY # it may take a while to start new shell :(
xdotool type --delay 1 --clearmodifiers "$@"
xdotool key Return
wmctrl -i -a $WID # go to that window (WID is numeric)
# vim:ai
# EOF #
SELECT @variable1 = col1, @variable2 = col2
FROM table1
I know it's already answered but here is a solution I find more elegant:
arsort($array);
reset($array);
echo key($array);
and voila!
As well as using lapply
or some other looping construct in R you could merge your CSV files into one file.
In Unix, if the files had no headers, then its as easy as:
cat *.csv > all.csv
or if there are headers, and you can find a string that matches headers and only headers (ie suppose header lines all start with "Age"), you'd do:
cat *.csv | grep -v ^Age > all.csv
I think in Windows you could do this with COPY
and SEARCH
(or FIND
or something) from the DOS command box, but why not install cygwin
and get the power of the Unix command shell?
I comment out //api 'com.google.android.gms:play-services-ads:15.0.1'
it worked for me after sync
I Have faced the same issue.After a lot of struggle I found that the real issue is with the com.amazonaws dependencies.After adding dependencies this error got disappeared.
I'll add a map and filter version because why not.
sum(map(lambda x:x>5, j))
sum(1 for _ in filter(lambda x:x>5, j))
This issue could be because of wrong entity framework reference or sometimes the Class name not matching the entity name in database. Make sure the Table name matches with class name.
If you are using multiple flavors?
-make sure the resource file is not declared/added both in only one of the flavors and in main.
Example: a_layout_file.xml
file containing the symbol variable(s)
src:
flavor1/res/layout/(no file)
flavor2/res/layout/a_layout_file.xml
main/res/layout/a_layout_file.xml
This setup will give the error: cannot find symbol variable, this is because the resource file can only be in both flavors or only in the main.
Use geom_boxplot(outlier.shape = NA)
to not display the outliers and scale_y_continuous(limits = c(lower, upper))
to change the axis limits.
An example.
n <- 1e4L
dfr <- data.frame(
y = exp(rlnorm(n)), #really right-skewed variable
f = gl(2, n / 2)
)
p <- ggplot(dfr, aes(f, y)) +
geom_boxplot()
p # big outlier causes quartiles to look too slim
p2 <- ggplot(dfr, aes(f, y)) +
geom_boxplot(outlier.shape = NA) +
scale_y_continuous(limits = quantile(dfr$y, c(0.1, 0.9)))
p2 # no outliers plotted, range shifted
Actually, as Ramnath showed in his answer (and Andrie too in the comments), it makes more sense to crop the scales after you calculate the statistic, via coord_cartesian
.
coord_cartesian(ylim = quantile(dfr$y, c(0.1, 0.9)))
(You'll probably still need to use scale_y_continuous
to fix the axis breaks.)
First of all, CORS is definitely a server-side problem and not client-side but I was more than sure that server code was correct in my case since other apps were working using the same server on different domains. The solution for this described in more details in other answers.
My problem started when I started using axios
with my custom instance. In my case, it was a very specific problem when we use a baseURL in axios
instance and then try to make GET
or POST
calls from anywhere, axios adds a slash / between baseURL and request URL. This makes sense too, but it was the hidden problem. My Laravel server was redirecting to remove the trailing slash which was causing this problem.
In general, the pre-flight OPTIONS
request doesn't like redirects. If your server is redirecting with 301 status code, it might be cached at different levels. So, definitely check for that and avoid it.
Thanks @clone45 for the nice solution. But I had just one important problem with Appendix b of his solution. Immediately after I changed the home directory to var/www/html then I couldn't connect to server through ssh and sftp because it always shows following errors
permission denied (public key)
or in FileZilla I received this error:
No supported authentication methods available (server: public key)
But I could access the server through normal FTP connection.
If you encountered to the same error then just undo the appendix b of @clone45 solution by set the default home directory for the user:
sudo usermod -d /home/username/ username
But when you set user's default home directory then the user have access to many other folders outside /var/www/http. So to secure your server then follow these steps:
1- Make sftponly group Make a group for all users you want to restrict their access to only ftp and sftp access to var/www/html. to make the group:
sudo groupadd sftponly
2- Jail the chroot To restrict access of this group to the server via sftp you must jail the chroot to not to let group's users to access any folder except html folder inside its home directory. to do this open /etc/ssh/sshd.config in the vim with sudo. At the end of the file please comment this line:
Subsystem sftp /usr/libexec/openssh/sftp-server
And then add this line below that:
Subsystem sftp internal-sftp
So we replaced subsystem with internal-sftp. Then add following lines below it:
Match Group sftponly
ChrootDirectory /var/www
ForceCommand internal-sftp
AllowTcpForwarding no
After adding this line I saved my changes and then restart ssh service by:
sudo service sshd restart
3- Add the user to sftponly group Any user you want to restrict their access must be a member of sftponly group. Therefore we join it to sftponly by: sudo usermod -G sftponly username
4- Restrict user access to just var/www/html To restrict user access to just var/www/html folder we need to make a directory in the home directory (with name of 'html') of that user and then mount /var/www to /home/username/html as follow:
sudo mkdir /home/username/html
sudo mount --bind /var/www /home/username/html
5- Set write access If the user needs write access to /var/www/html, then you must jail the user at /var/www which must have root:root ownership and permissions of 755. You then need to give /var/www/html ownership of root:sftponly and permissions of 775 by adding following lines:
sudo chmod 755 /var/www
sudo chown root:root /var/www
sudo chmod 775 /var/www/html
sudo chown root:www /var/www/html
6- Block shell access If you want restrict access to not access to shell to make it more secure then just change the default shell to bin/false as follow:
sudo usermod -s /bin/false username
That will only work if register_globals
is on, and it should never be on (unless of course you are defining that variable somewhere else).
Try setting the form
's action
attribute to ?
...
<form method="post" action="?">
...
</form>
You can also set it to be blank (""
), but older WebKit versions had a bug.
Piece of cake.
Use 960Grids Go to the automatic layout builder and make a two column, fluid design. Build a left column to the width of grids that works....this is the only challenge using grids and it's very easy once you read a tutorial. In a nutshell, each column in a grid is a certain width, and you set the amount of columns you want to use. To get a column that's exactly a certain width, you have to adjust your math so that your column width is exact. Not too tough.
No chance of wrapping because others have already fought that battle for you. Compatibility back as far as you likely will ever need to go. Quick and easy....Now, download, customize and deploy.
Voila. Grids FTW.
The easisest thing to do is to wrap your code in a transaction, and then execute each batch of T-SQL code line by line.
For example,
Begin Transaction
-Do some T-SQL queries here.
Rollback transaction -- OR commit transaction
If you want to incorporate error handling you can do so by using a TRY...CATCH BLOCK. Should an error occur you can then rollback the tranasction within the catch block.
For example:
USE AdventureWorks;
GO
BEGIN TRANSACTION;
BEGIN TRY
-- Generate a constraint violation error.
DELETE FROM Production.Product
WHERE ProductID = 980;
END TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage;
IF @@TRANCOUNT > 0
ROLLBACK TRANSACTION;
END CATCH;
IF @@TRANCOUNT > 0
COMMIT TRANSACTION;
GO
See the following link for more details.
http://msdn.microsoft.com/en-us/library/ms175976.aspx
Hope this helps but please let me know if you need more details.
Consider making your route:
_files_manage:
pattern: /files/management/{project}/{user}
defaults: { _controller: AcmeTestBundle:File:manage }
since they are required fields. It will make your url's prettier, and be a bit easier to manage.
Your Controller would then look like
public function projectAction($project, $user)
System.out.println("Managers choice this week" + anyItem + "our recommendation to you");
You havent the variable anyItem initialized or even declared.
This code: + anyItem +
means get value of toString method of Object anyItem
The second thing why this wont work. You have System.out.print after return statement. Program could never reach tha line.
You probably want something like:
public Item anyItem() {
int index = randomGenerator.nextInt(catalogue.size());
System.out.println("Managers choice this week" + catalogue.get(index) + "our recommendation to you");
return catalogue.get(index);
}
btw: in Java its convetion to place the curly parenthesis on the same line as the declaration of the function.
Use mongodump
:
$ ./mongodump --host prod.example.com
connected to: prod.example.com
all dbs
DATABASE: log to dump/log
log.errors to dump/log/errors.bson
713 objects
log.analytics to dump/log/analytics.bson
234810 objects
DATABASE: blog to dump/blog
blog.posts to dump/log/blog.posts.bson
59 objects
DATABASE: admin to dump/admin
Source: http://www.mongodb.org/display/DOCS/Import+Export+Tools
If you want to see data updates you could use this technique with required permissions:
SELECT OBJECT_NAME(OBJECT_ID) AS DatabaseName, last_user_update,*
FROM sys.dm_db_index_usage_stats
WHERE database_id = DB_ID( 'DATABASE')
AND OBJECT_ID=OBJECT_ID('TABLE')
You might miss @author and inside of @param you need to explain what's that parameter for, how to use it, etc.
The current documentation has a good explanation of what .NET Core is, areas to use and so on. The following characteristics best define .NET Core:
Flexible deployment: Can be included in your app or installed side-by-side user- or machine-wide.
Cross-platform: Runs on Windows, macOS and Linux; can be ported to other OSes. The supported operating systems (OSes), CPUs and application scenarios will grow over time, provided by Microsoft, other companies, and individuals.
Command-line tools: All product scenarios can be exercised at the command-line.
Compatible: .NET Core is compatible with .NET Framework, Xamarin and Mono, via the .NET Standard Library.
Open source: The .NET Core platform is open source, using MIT and Apache 2 licenses. Documentation is licensed under CC-BY. .NET Core is a .NET Foundation project.
Supported by Microsoft: .NET Core is supported by Microsoft, per .NET Core Support
And here is what .NET Core includes:
A .NET runtime, which provides a type system, assembly loading, a garbage collector, native interoperability and other basic services.
A set of framework libraries, which provide primitive data types, application composition types and fundamental utilities.
A set of SDK tools and language compilers that enable the base developer experience, available in the .NET Core SDK.
The 'dotnet' application host, which is used to launch .NET Core applications. It selects the runtime and hosts the runtime, provides an assembly loading policy and launches the app. The same host is also used to launch SDK tools in much the same way.
Try this one.. It is working... Here JSBIN
table tbody { height:300px; overflow-y:scroll; display:block; }
table thead { display:block; }
The basic problem while migrating from MySQL I faced was, I thought of the term database
to be same in PostgreSQL also, but it is not. So if we are going to switch the database from our application or pgAdmin
, the result would not be as expected.
As in my case, we have separate schemas (Considering PostgreSQL terminology here.) for each customer and separate admin schema. So in application, I have to switch between schemas.
For this, we can use the SET search_path
command. This does switch the current schema to the specified schema name for the current session.
example:
SET search_path = different_schema_name;
This changes the current_schema to the specified schema for the session. To change it permanently, we have to make changes in postgresql.conf
file.
Yes that is correct. "Boolean variables only have two possible values: true (1) and false (0)." cpp tutorial on boolean values
This has nothing to do with the MULTILINE flag; what you're seeing is the difference between the find()
and matches()
methods. find()
succeeds if a match can be found anywhere in the target string, while matches()
expects the regex to match the entire string.
Pattern p = Pattern.compile("xyz");
Matcher m = p.matcher("123xyzabc");
System.out.println(m.find()); // true
System.out.println(m.matches()); // false
Matcher m = p.matcher("xyz");
System.out.println(m.matches()); // true
Furthermore, MULTILINE
doesn't mean what you think it does. Many people seem to jump to the conclusion that you have to use that flag if your target string contains newlines--that is, if it contains multiple logical lines. I've seen several answers here on SO to that effect, but in fact, all that flag does is change the behavior of the anchors, ^
and $
.
Normally ^
matches the very beginning of the target string, and $
matches the very end (or before a newline at the end, but we'll leave that aside for now). But if the string contains newlines, you can choose for ^
and $
to match at the start and end of any logical line, not just the start and end of the whole string, by setting the MULTILINE flag.
So forget about what MULTILINE
means and just remember what it does: changes the behavior of the ^
and $
anchors. DOTALL
mode was originally called "single-line" (and still is in some flavors, including Perl and .NET), and it has always caused similar confusion. We're fortunate that the Java devs went with the more descriptive name in that case, but there was no reasonable alternative for "multiline" mode.
In Perl, where all this madness started, they've admitted their mistake and gotten rid of both "multiline" and "single-line" modes in Perl 6 regexes. In another twenty years, maybe the rest of the world will have followed suit.
UPDATE yourtable
SET field_or_column =REPLACE ('current string','findpattern', 'replacepattern')
WHERE 1
You can do this by writing a manifest for your jar. Have a look at the Class-Path header. Eclipse has an option for choosing your own manifest on export.
The alternative is to add the dependency to the classpath at the time you invoke the application:
win32: java.exe -cp app.jar;dependency.jar foo.MyMainClass
*nix: java -cp app.jar:dependency.jar foo.MyMainClass
I branched off from the accepted answer to only run when the click is being HELD down and dragged.
My function was running when I wasn't holding the mouse down. Here's the updated code if you also want this functionality:
var isDragging = false;
var mouseDown = false;
$('.test_area')
.mousedown(function() {
isDragging = false;
mouseDown = true;
})
.mousemove(function(e) {
isDragging = true;
if (isDragging === true && mouseDown === true) {
my_special_function(e);
}
})
.mouseup(function(e) {
var wasDragging = isDragging;
isDragging = false;
mouseDown = false;
if ( ! wasDragging ) {
my_special_function(e);
}
}
);
A Scala solution, adapted from Vasya Novikov's answer and specialized for binary trees:
/** An immutable Binary Tree. */
case class BTree[T](value: T, left: Option[BTree[T]], right: Option[BTree[T]]) {
/* Adapted from: http://stackoverflow.com/a/8948691/643684 */
def pretty: String = {
def work(tree: BTree[T], prefix: String, isTail: Boolean): String = {
val (line, bar) = if (isTail) ("+-- ", " ") else ("+-- ", "¦")
val curr = s"${prefix}${line}${tree.value}"
val rights = tree.right match {
case None => s"${prefix}${bar} +-- Ø"
case Some(r) => work(r, s"${prefix}${bar} ", false)
}
val lefts = tree.left match {
case None => s"${prefix}${bar} +-- Ø"
case Some(l) => work(l, s"${prefix}${bar} ", true)
}
s"${curr}\n${rights}\n${lefts}"
}
work(this, "", true)
}
}
Returning falsy value in the render() function will render nothing. So you can just do
render() {
let finalClasses = "" + (this.state.classes || "");
return !isTimeout && <div>{this.props.children}</div>;
}
From http://sed.sourceforge.net/sed1line.txt: (Please don't ask me how this works ;-) )
# delete duplicate, consecutive lines from a file (emulates "uniq").
# First line in a set of duplicate lines is kept, rest are deleted.
sed '$!N; /^\(.*\)\n\1$/!P; D'
# delete duplicate, nonconsecutive lines from a file. Beware not to
# overflow the buffer size of the hold space, or else use GNU sed.
sed -n 'G; s/\n/&&/; /^\([ -~]*\n\).*\n\1/d; s/\n//; h; P'
The following code returns dataframe with the 'Category' column replaced by categorical columns:
df_with_dummies = pd.get_dummies(df, prefix='Category_', columns=['Category'])
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.get_dummies.html
Start your IDE with administrative privilege( Windows: right click and run as admin), so that it has read write access to tomact folder for deployment. It worked for me.
From the docs:
In npm 1.0, there are two ways to install things:
globally —- This drops modules in
{prefix}/lib/node_modules
, and puts executable files in{prefix}/bin
, where{prefix}
is usually something like/usr/local
. It also installs man pages in{prefix}/share/man
, if they’re supplied.locally —- This installs your package in the current working directory. Node modules go in
./node_modules
, executables go in./node_modules/.bin/
, and man pages aren’t installed at all.
You can get your {prefix}
with npm config get prefix
. (Useful when you installed node with nvm).
I prefers using Guava :
import com.google.common.base.Charsets;
import com.google.common.io.Files;
File file = new File("/path/to/file", Charsets.UTF_8);
String content = Files.toString(file);
As Luke Smith says, image load is a mess. It's not reliable on all browsers. This fact has given me great pain. A cached image will not fire the event at all in some browsers, so those who said "image load is better than setTimeout" are wrong.
Luke Smith's solution is here.
And there is an interesting discussion about how this mess might be handled in jQuery 1.4.
I have found that it's pretty reliable to set the width to 0, then wait for the "complete" property to go true and the width property to come in greater than zero. You should watch for errors, too.
ExecutorService.invokeAll()
does it for you.
ExecutorService taskExecutor = Executors.newFixedThreadPool(4);
List<Callable<?>> tasks; // your tasks
// invokeAll() returns when all tasks are complete
List<Future<?>> futures = taskExecutor.invokeAll(tasks);
use
~/.bash_profile
or
~/.MacOSX/environment.plist
(see Runtime Configuration Guidelines)
If you're getting this problem with an insert that looks like the one below, the problem may simply be the lack of a space between --
and the comment text:
insert into myTable (a, b, c)
values (
123 --something
,345 --something else
,567 --something something else
);
The problem with this is that the --something
should actually be -- something
with a space.
add your default theme this line;
<item name="colorControlNormal">@color/my_color</item>
I had the same issue, and it ended up being a problem with the php max post size. Increasing it solved the problem.
In MySQL, you can do this as well:
SELECT count(*) AS total
, sum(myCol) AS countTrue --yes, you can add TRUEs as TRUE=1 and FALSE=0 !!
FROM yourTable
;
I think that in Postgres, this works:
SELECT count(*) AS total
, sum(myCol::int) AS countTrue --convert Boolean to Integer
FROM yourTable
;
or better (to avoid :: and use standard SQL syntax):
SELECT count(*) AS total
, sum(CAST(myCol AS int)) AS countTrue --convert Boolean to Integer
FROM yourTable
;
Just try the following coding...very simple to generate CSV with the values of HTML Tables. No browser issues will come
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://www.csvscript.com/dev/html5csv.js"></script>
<script>
$(document).ready(function() {
$('table').each(function() {
var $table = $(this);
var $button = $("<button type='button'>");
$button.text("Export to CSV");
$button.insertAfter($table);
$button.click(function() {
CSV.begin('table').download('Export.csv').go();
});
});
})
</script>
</head>
<body>
<div id='PrintDiv'>
<table style="width:100%">
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td>Eve</td>
<td>Jackson</td>
<td>94</td>
</tr>
<tr>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
</div>
</body>
</html>
For systemd style init scripts it's really easy. You just add a User= in the [Service] section.
Here is an init script I use for qbittorrent-nox on CentOS 7:
[Unit]
Description=qbittorrent torrent server
[Service]
User=<username>
ExecStart=/usr/bin/qbittorrent-nox
Restart=on-abort
[Install]
WantedBy=multi-user.target
In case you want to use that padding space... then here's something:
All the colors are background colors.
Actually the main purpose of the RecyclerView
is to compensate for ListView
and ScrollView
. Instead of doing what you're actually doing: Having a RecyclerView
in a ScrollView
, I would suggest having only a RecyclerView
that can handle many types of children.
There are two problems with your xpath - first you need to remove the child selector from after Data
like phihag mentioned. Also you forgot to include root
in your xpath. Here is what you want to do:
select="/root/DataSet/Data[@Value1='2']/@Value2"
I found this code working:
from distutils.dir_util import copy_tree
# copy subdirectory example
fromDirectory = "/a/b/c"
toDirectory = "/x/y/z"
copy_tree(fromDirectory, toDirectory)
Reference:
Answers
Q: What is a lambda expression in C++11?
A: Under the hood, it is the object of an autogenerated class with overloading operator() const. Such object is called closure and created by compiler. This 'closure' concept is near with the bind concept from C++11. But lambdas typically generate better code. And calls through closures allow full inlining.
Q: When would I use one?
A: To define "simple and small logic" and ask compiler perform generation from previous question. You give a compiler some expressions which you want to be inside operator(). All other stuff compiler will generate to you.
Q: What class of problem do they solve that wasn't possible prior to their introduction?
A: It is some kind of syntax sugar like operators overloading instead of functions for custom add, subrtact operations...But it save more lines of unneeded code to wrap 1-3 lines of real logic to some classes, and etc.! Some engineers think that if the number of lines is smaller then there is a less chance to make errors in it (I'm also think so)
Example of usage
auto x = [=](int arg1){printf("%i", arg1); };
void(*f)(int) = x;
f(1);
x(1);
Extras about lambdas, not covered by question. Ignore this section if you're not interest
1. Captured values. What you can to capture
1.1. You can reference to a variable with static storage duration in lambdas. They all are captured.
1.2. You can use lambda for capture values "by value". In such case captured vars will be copied to the function object (closure).
[captureVar1,captureVar2](int arg1){}
1.3. You can capture be reference. & -- in this context mean reference, not pointers.
[&captureVar1,&captureVar2](int arg1){}
1.4. It exists notation to capture all non-static vars by value, or by reference
[=](int arg1){} // capture all not-static vars by value
[&](int arg1){} // capture all not-static vars by reference
1.5. It exists notation to capture all non-static vars by value, or by reference and specify smth. more. Examples: Capture all not-static vars by value, but by reference capture Param2
[=,&Param2](int arg1){}
Capture all not-static vars by reference, but by value capture Param2
[&,Param2](int arg1){}
2. Return type deduction
2.1. Lambda return type can be deduced if lambda is one expression. Or you can explicitly specify it.
[=](int arg1)->trailing_return_type{return trailing_return_type();}
If lambda has more then one expression, then return type must be specified via trailing return type. Also, similar syntax can be applied to auto functions and member-functions
3. Captured values. What you can not capture
3.1. You can capture only local vars, not member variable of the object.
4. ?onversions
4.1 !! Lambda is not a function pointer and it is not an anonymous function, but capture-less lambdas can be implicitly converted to a function pointer.
p.s.
More about lambda grammar information can be found in Working draft for Programming Language C++ #337, 2012-01-16, 5.1.2. Lambda Expressions, p.88
In C++14 the extra feature which has named as "init capture" have been added. It allow to perform arbitarily declaration of closure data members:
auto toFloat = [](int value) { return float(value);};
auto interpolate = [min = toFloat(0), max = toFloat(255)](int value)->float { return (value - min) / (max - min);};
This indicates the linux has delivered a SIGTERM
to your process. This is usually at the request of some other process (via kill()
) but could also be sent by your process to itself (using raise()
). This signal requests an orderly shutdown of your process.
If you need a quick cheatsheet of signal numbers, open a bash shell and:
$ kill -l
1) SIGHUP 2) SIGINT 3) SIGQUIT 4) SIGILL
5) SIGTRAP 6) SIGABRT 7) SIGBUS 8) SIGFPE
9) SIGKILL 10) SIGUSR1 11) SIGSEGV 12) SIGUSR2
13) SIGPIPE 14) SIGALRM 15) SIGTERM 16) SIGSTKFLT
17) SIGCHLD 18) SIGCONT 19) SIGSTOP 20) SIGTSTP
21) SIGTTIN 22) SIGTTOU 23) SIGURG 24) SIGXCPU
25) SIGXFSZ 26) SIGVTALRM 27) SIGPROF 28) SIGWINCH
29) SIGIO 30) SIGPWR 31) SIGSYS 34) SIGRTMIN
35) SIGRTMIN+1 36) SIGRTMIN+2 37) SIGRTMIN+3 38) SIGRTMIN+4
39) SIGRTMIN+5 40) SIGRTMIN+6 41) SIGRTMIN+7 42) SIGRTMIN+8
43) SIGRTMIN+9 44) SIGRTMIN+10 45) SIGRTMIN+11 46) SIGRTMIN+12
47) SIGRTMIN+13 48) SIGRTMIN+14 49) SIGRTMIN+15 50) SIGRTMAX-14
51) SIGRTMAX-13 52) SIGRTMAX-12 53) SIGRTMAX-11 54) SIGRTMAX-10
55) SIGRTMAX-9 56) SIGRTMAX-8 57) SIGRTMAX-7 58) SIGRTMAX-6
59) SIGRTMAX-5 60) SIGRTMAX-4 61) SIGRTMAX-3 62) SIGRTMAX-2
63) SIGRTMAX-1 64) SIGRTMAX
You can determine the sender by using an appropriate signal handler like:
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
void sigterm_handler(int signal, siginfo_t *info, void *_unused)
{
fprintf(stderr, "Received SIGTERM from process with pid = %u\n",
info->si_pid);
exit(0);
}
int main (void)
{
struct sigaction action = {
.sa_handler = NULL,
.sa_sigaction = sigterm_handler,
.sa_mask = 0,
.sa_flags = SA_SIGINFO,
.sa_restorer = NULL
};
sigaction(SIGTERM, &action, NULL);
sleep(60);
return 0;
}
Notice that the signal handler also includes a call to exit()
. It's also possible for your program to continue to execute by ignoring the signal, but this isn't recommended in general (if it's a user doing it there's a good chance it will be followed by a SIGKILL if your process doesn't exit, and you lost your opportunity to do any cleanup then).
git rev-parse --show-toplevel
could be enough if executed within a git repo.
From git rev-parse
man page:
--show-toplevel
Show the absolute path of the top-level directory.
For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":
git rev-parse --git-dir
That would give the path of the .git
directory.
The OP mentions:
git rev-parse --show-prefix
which returns the local path under the git repo root. (empty if you are at the git repo root)
Note: for simply checking if one is in a git repo, I find the following command quite expressive:
git rev-parse --is-inside-work-tree
And yes, if you need to check if you are in a .git
git-dir folder:
git rev-parse --is-inside-git-dir
useStyles
is a React hook which are meant to be used in functional components and can not be used in class components.
Hooks let you use state and other React features without writing a class.
Also you should call useStyles
hook inside your function like;
function Welcome() {
const classes = useStyles();
...
If you want to use hooks, here is your brief class component changed into functional component;
import React from "react";
import { Container, makeStyles } from "@material-ui/core";
const useStyles = makeStyles({
root: {
background: "linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)",
border: 0,
borderRadius: 3,
boxShadow: "0 3px 5px 2px rgba(255, 105, 135, .3)",
color: "white",
height: 48,
padding: "0 30px"
}
});
function Welcome() {
const classes = useStyles();
return (
<Container className={classes.root}>
<h1>Welcome</h1>
</Container>
);
}
export default Welcome;
on ↓ CodeSandBox ↓
In Drupal 7, you can modify the memory limit in the settings.php file located in your sites/default folder. Around line 260, you'll see this:
ini_set('memory_limit', '128M');
Even if your php.ini settings are high enough, you won't be able to consume more than 128 MB if this isn't set in your Drupal settings.php file.
The easiest answer is number_format()
.
echo "$ ".number_format($value, 2);
If you want your application to be able to work with multiple currencies and locale-aware formatting (1.000,00
for some of us Europeans for example), it becomes a bit more complex.
There is money_format()
but it doesn't work on Windows and relies on setlocale()
, which is rubbish in my opinion, because it requires the installation of (arbitrarily named) locale packages on server side.
If you want to seriously internationalize your application, consider using a full-blown internationalization library like Zend Framework's Zend_Locale and Zend_Currency.
Use this.
java.util.Date date = new Date("Sat Dec 01 00:00:00 GMT 2012");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
String format = formatter.format(date);
System.out.println(format);
you will get the output as
2012-12-01
Presumably the method does something, and doesn't simply return?
Assuming this is the case, then:
If youy let us know what the method does, I could be more specific.
You can use a split
on a filename
:
f_extns = filename.split(".")
print ("The extension of the file is : " + repr(f_extns[-1]))
This does not require additional library
byte[] seed = (SALT2 + username + password).getBytes();
SecureRandom random = new SecureRandom(seed);
KeyGenerator generator;
generator = KeyGenerator.getInstance("AES");
generator.init(random);
generator.init(256);
Key keyObj = generator.generateKey();
Wouldn't this
"d+|D+"
do the job instead of the cumbersome:
"(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"
?
You can customise the credits, changing the URL, text, Position etc. All the info is documented here: http://api.highcharts.com/highcharts/credits. To simply disable them altogether, use:
credits: {
enabled: false
},
I think you'll struggle with keyup event - as it first triggers keypress - and you won't be able to stop the propagation of the second one if you want to exclude the Enter Key.
Try this in input field:
[readonly]="true"
Hope, this will work.
See the official documentation (http://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements001.htm#i54330)
Variable-length character string having maximum length size bytes or characters. Maximum size is 4000 bytes or characters, and minimum is 1 byte or 1 character. You must specify size for VARCHAR2. BYTE indicates that the column will have byte length semantics; CHAR indicates that the column will have character semantics.
But in Oracle Databast 12c maybe 32767 (http://docs.oracle.com/database/121/SQLRF/sql_elements001.htm#SQLRF30020)
Variable-length character string having maximum length size bytes or characters. You must specify size for VARCHAR2. Minimum size is 1 byte or 1 character. Maximum size is: 32767 bytes or characters if MAX_STRING_SIZE = EXTENDED 4000 bytes or characters if MAX_STRING_SIZE = STANDARD
Use
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class test {
public static void main(String[] args){
try {
File fileDir = new File("PATH_TO_FILE");
BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream(fileDir), "UTF-8"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
}
catch (UnsupportedEncodingException e)
{
System.out.println(e.getMessage());
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
You need to put UTF-8 in quotes
Since scipy
's imread
is deprecated, use imageio.imread
.
pip install imageio
height, width, channels = imageio.imread(filepath).shape
If I may expand on user987361's answer:
From the offline access portion of the OAuth2.0 docs:
When your application receives a refresh token, it is important to store that refresh token for future use. If your application loses the refresh token, it will have to re-prompt the user for consent before obtaining another refresh token. If you need to re-prompt the user for consent, include the
approval_prompt
parameter in the authorization code request, and set the value toforce
.
So, when you have already granted access, subsequent requests for a grant_type
of authorization_code
will not return the refresh_token
, even if access_type
was set to offline
in the query string of the consent page.
As stated in the quote above, in order to obtain a new refresh_token
after already receiving one, you will need to send your user back through the prompt, which you can do by setting approval_prompt
to force
.
Cheers,
PS This change was announced in a blog post as well.
This works in MariaDB:
SELECT Req_ID, (R1+R2+R3+R4+R5)/5 AS Average
FROM Request
GROUP BY Req_ID;
Use XmlTextReader
, XmlReader
, XmlNodeReader
and the System.Xml.XPath
namespace. And (XPathNavigator
, XPathDocument
, XPathExpression
, XPathnodeIterator
).
Usually XPath
makes reading XML easier, which is what you might be looking for.
$('#signup').on("submit", function(event) {
$form = $(this); //wrap this in jQuery
alert('the action is: ' + $form.attr('action'));
});
vector<string> func1() const
{
vector<string> parts;
return vector<string>(parts.begin(),parts.end()) ;
}
Everything you need here can be found in this quickstart guide.
A straightforward solution would be [A-Za-z][A-Za-z]\d\d\d\d\d\d
or [A-Za-z]{2}\d{6}
.
If you want to accept only capital letters then replace [A-Za-z]
with [A-Z]
.