This is working
<form name="myform" ng-submit="create()">
<input type="number"
name="price_field"
ng-model="price"
require
ng-pattern="/^\d{0,9}(\.\d{1,9})?$/">
<span ng-show="myform.price_field.$error.pattern">Not valid number!</span>
<input type="submit" class="btn">
</form>
Yes, you are correct. If you are using a jQuery plugin, do not put the code in the controller. Instead create a directive and put the code that you would normally have inside the link
function of the directive.
There are a couple of points in the documentation that you could take a look at. You can find them here:
Common Pitfalls
Ensure that when you are referencing the script in your view, you refer it last - after the angularjs library, controllers, services and filters are referenced.
EDIT: Rather than using $(element)
, you can make use of angular.element(element)
when using AngularJS with jQuery
If you know that you'll want to see all Comment
s every time you retrieve a Topic
then change your field mapping for comments
to:
@OneToMany(fetch = FetchType.EAGER, mappedBy = "topic", cascade = CascadeType.ALL)
private Collection<Comment> comments = new LinkedHashSet<Comment>();
Collections are lazy-loaded by default, take a look at this if you want to know more.
Every solution posted here assumes that you know the dimensions of your img
, which is not a common scenario. Also, planting the dimensions into the solution is painful.
Simply set:
/* for the img inside your div */
display: block;
margin-left: auto;
margin-right: auto;
or
/* for the img inside your div */
display: block;
margin: 0 auto;
That's all.
Note, that you'll also have to set an initial min-width
for your outer div
.
Try this:
I would like to add that there is a Parallel class with ForEach function built in that can be used for this purpose.
for (let i = 0; i <= value; i+=n) { // increments by n
/*code statement*/
}
this format works for me incrementing index by n
for (let i = 0; i <= value; i+=4) { // increments by 4
/*code statement*/
}
if n = 4 this it will increment by 4
--for setting buffer size needed most of time to avoid `anonymous block completed` message
set serveroutput on size 30000;
-- declaration block in case output need to catch
DECLARE
--declaration for in and out parameter
V_OUT_1 NUMBER;
V_OUT_2 VARCHAR2(200);
BEGIN
--your stored procedure name
schema.package.procedure(
--declaration for in and out parameter
V_OUT_1 => V_OUT_1,
V_OUT_2 => V_OUT_2
);
V_OUT_1 := V_OUT_1;
V_OUT_2 := V_OUT_2;
-- console output, no need to open DBMS OUTPUT seperatly
-- also no need to print each output on seperat line
DBMS_OUTPUT.PUT_LINE('Ouput => ' || V_OUT_1 || ': ' || V_OUT_2);
END;
Found a way, thanks to the link here (with the original google group discussion here)
First, Telnet
to your server:
telnet 127.0.0.1 11211
Next, list the items to get the slab ids:
stats items STAT items:3:number 1 STAT items:3:age 498 STAT items:22:number 1 STAT items:22:age 498 END
The first number after ‘items’ is the slab id. Request a cache dump for each slab id, with a limit for the max number of keys to dump:
stats cachedump 3 100 ITEM views.decorators.cache.cache_header..cc7d9 [6 b; 1256056128 s] END stats cachedump 22 100 ITEM views.decorators.cache.cache_page..8427e [7736 b; 1256056128 s] END
var arr = ["I", "am", "", "still", "here", "", "man"]
// arr = ["I", "am", "", "still", "here", "", "man"]
arr = arr.filter(Boolean)
// arr = ["I", "am", "still", "here", "man"]
// arr = ["I", "am", "", "still", "here", "", "man"]
arr = arr.filter(v=>v!='');
// arr = ["I", "am", "still", "here", "man"]
If you want to disable editing the entire grid, you can set IsReadOnly to true on the grid. If you want to disable user to add new rows, you set the property CanUserAddRows="False"
<DataGrid IsReadOnly="True" CanUserAddRows="False" />
Further more you can set IsReadOnly on individual columns to disable editing.
You can do it using string.indexOf("{item}")
. If the result is greater than -1 {item}
is in the string
It should be 65535.
The error for me was that I read the SQL statement from a text file, and the text file was saved in the UTF-8 with BOM (byte order mark) format.
To solve this, I opened the file in Notepad++ and under Encoding, chose UTF-8. Alternatively you can remove the first three bytes of the file with a hex editor.
first use this:
LayoutInflater inflater = (LayoutInflater) Read_file.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Read file is current activity in which you want your context.
View layout = inflater.inflate(R.layout.your_layout_name,(ViewGroup)findViewById(R.id.layout_name_id));
then you can use this to find any element in layout.
ImageView myImage = (ImageView) layout.findViewById(R.id.my_image);
This feature already exists in Ubuntu and Debian, in the command-not-found
package.
Yes, there is am Empty operator
Rx.Observable.empty();
For typescript, you can use from
:
Rx.Observable<Response>.from([])
I've used PDFBox with good success. Here's a sample of what the code looks like (back from version 0.7.2), that likely came from one of the provided examples:
// load the document
System.out.println("Reading document: " + filename);
PDDocument doc = null;
doc = PDDocument.load(filename);
// look at all the document information
PDDocumentInformation info = doc.getDocumentInformation();
COSDictionary dict = info.getDictionary();
List l = dict.keyList();
for (Object o : l) {
//System.out.println(o.toString() + " " + dict.getString(o));
System.out.println(o.toString());
}
// look at the document catalog
PDDocumentCatalog cat = doc.getDocumentCatalog();
System.out.println("Catalog:" + cat);
List<PDPage> lp = cat.getAllPages();
System.out.println("# Pages: " + lp.size());
PDPage page = lp.get(4);
System.out.println("Page: " + page);
System.out.println("\tCropBox: " + page.getCropBox());
System.out.println("\tMediaBox: " + page.getMediaBox());
System.out.println("\tResources: " + page.getResources());
System.out.println("\tRotation: " + page.getRotation());
System.out.println("\tArtBox: " + page.getArtBox());
System.out.println("\tBleedBox: " + page.getBleedBox());
System.out.println("\tContents: " + page.getContents());
System.out.println("\tTrimBox: " + page.getTrimBox());
List<PDAnnotation> la = page.getAnnotations();
System.out.println("\t# Annotations: " + la.size());
When you are using a self signed cert urllib3 version 1.25.3 refuses to ignore the SSL cert
To fix remove urllib3-1.25.3 and install urllib3-1.24.3
pip3 uninstall urllib3
pip3 install urllib3==1.24.3
Tested on Linux MacOS and Window$
Use the ViewPager.onPageChangeListener
:
viewPager.addOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
// Check if this is the page you want.
}
});
Often when people are looking for "timezones", what will suffice is just "UTC offset". e.g., their server is in UTC+5 and they want to know that their client is running in UTC-8.
In plain old javascript (new Date()).getTimezoneOffset()/60
will return the current number of hours offset from UTC.
It's worth noting a possible "gotcha" in the sign of the getTimezoneOffset()
return value (from MDN docs):
The time-zone offset is the difference, in minutes, between UTC and local time. Note that this means that the offset is positive if the local timezone is behind UTC and negative if it is ahead. For example, for time zone UTC+10:00 (Australian Eastern Standard Time, Vladivostok Time, Chamorro Standard Time), -600 will be returned.
However, I recommend you use the day.js for time/date related Javascript code. In which case you can get an ISO 8601 formatted UTC offset by running:
> dayjs().format("Z")
"-08:00"
It probably bears mentioning that the client can easily falsify this information.
(Note: this answer originally recommended https://momentjs.com/, but dayjs is a more modern, smaller alternative.)
There is a special function made for this Path.Combine()
var folder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var fullpath = path.Combine(folder,"Tasks");
Go to Format Cells - Custom. Type the required format into the list first. To prefix "0" before the text characters in an Excel column, use the Format 0####. Remember, use the character "#" equal to the maximum number of digits in a cell of that column. For e.g., if there are 4 cells in a column with the entries - 123, 333, 5665, 7 - use the formula 0####. Reason - A single # refers to reference of just one digit.
You can use:
print(df[df['Value']==df['Value'].max()])
I made a class to manage this issue. This class set different margins for the items inside the recyclerView: only the first row will have a top margin and only the first column will have left margin.
public class RecyclerViewMargin extends RecyclerView.ItemDecoration {
private final int columns;
private int margin;
/**
* constructor
* @param margin desirable margin size in px between the views in the recyclerView
* @param columns number of columns of the RecyclerView
*/
public RecyclerViewMargin(@IntRange(from=0)int margin ,@IntRange(from=0) int columns ) {
this.margin = margin;
this.columns=columns;
}
/**
* Set different margins for the items inside the recyclerView: no top margin for the first row
* and no left margin for the first column.
*/
@Override
public void getItemOffsets(Rect outRect, View view,
RecyclerView parent, RecyclerView.State state) {
int position = parent.getChildLayoutPosition(view);
//set right margin to all
outRect.right = margin;
//set bottom margin to all
outRect.bottom = margin;
//we only add top margin to the first row
if (position <columns) {
outRect.top = margin;
}
//add left margin only to the first column
if(position%columns==0){
outRect.left = margin;
}
}
}
you can set it in your recyclerview this way
RecyclerViewMargin decoration = new RecyclerViewMargin(itemMargin, numColumns);
recyclerView.addItemDecoration(decoration);
Backtick quotes with a space inside and two spaces to follow. Repeat as needed for more lines:
text1 text1
`(space)`(space)(space)
`(space)`(space)(space)
text2 text2
It looks decent in Markdown source:
text1 text1
` `
` `
text2 text2
I believe the example you've posted is using HTML5, which allows you to jump to any DOM element with the matching ID
attribute. To support older browsers, you'll need to change:
<div id="timeline" name="timeline" ...>
To the old format:
<a name="timeline" />
You'll then be able to navigate to /academics/page.html#timeline
and jump right to that section.
Also, check out this similar question.
I had the same problem and when I checked the properties of the file on file explorer, it shows me the next message:
"Security: This file came from another computer and might be blocked to help protect this computer"
You click on the "Unblock" button and... you can access to the file from R without any problem, just using read.csv() function and from the directory specified as your working directory, even if is not the same as the file’s directory you are accessing to.
In either ksh93 or bash with the extglob option enabled:
if [[ $var == +([0-9]) ]]; then ...
Okay adding to @null's awesome post about using the Asset Catalog.
You may need to do the following to get the App's Icon linked and working for Ad-Hoc distributions / production to be seen in Organiser, Test flight and possibly unknown AppStore locations.
After creating the Asset Catalog, take note of the name of the Launch Images and App Icon names listed in the .xassets
in Xcode.
By Default this should be
AppIcon
LaunchImage
[To see this click on your .xassets folder/icon in Xcode.] (this can be changed, so just take note of this variable for later)
What is created now each build is the following data structures in your .app:
For App Icons:
iPhone
AppIcon57x57.png
(iPhone non retina) [Notice the Icon name prefix][email protected]
(iPhone retina)And the same format for each of the other icon resolutions.
iPad
AppIcon72x72~ipad.png
(iPad non retina) AppIcon72x72@2x~ipad.png
(iPad retina)(For iPad it is slightly different postfix)
Main Problem
Now I noticed that in my Info.plist
in Xcode 5.0.1 it automatically attempted and failed to create a key for "Icon files (iOS 5)
" after completing the creation of the Asset Catalog.
If it did create a reference successfully / this may have been patched by Apple or just worked, then all you have to do is review the image names to validate the format listed above.
Final Solution:
Add the following key to you main .plist
I suggest you open your main .plist
with a external text editor such as TextWrangler rather than in Xcode to copy and paste the following key in.
<key>CFBundleIcons</key>
<dict>
<key>CFBundlePrimaryIcon</key>
<dict>
<key>CFBundleIconFiles</key>
<array>
<string>AppIcon57x57.png</string>
<string>[email protected]</string>
<string>AppIcon72x72~ipad.png</string>
<string>AppIcon72x72@2x~ipad.png</string>
</array>
</dict>
</dict>
Please Note I have only included my example resolutions, you will need to add them all.
If you want to add this Key in Xcode without an external editor, Use the following:
Icon files (iOS 5)
- DictionaryPrimary Icon
- DictionaryIcon files
- ArrayItem 0
- String = AppIcon57x57.png
And for each other item / app icon.Now when you finally archive your project the final .xcarchive payload .plist will now include the above stated icon locations to build and use.
<key>IconPaths</key>
<array>
<string>Applications/Example.app/AppIcon57x57.png</string>
<string>Applications/Example.app/[email protected]</string>
<string>Applications/Example.app/AppIcon72x72~ipad.png</string>
<string>Applications/Example.app/AppIcon72x72@2x~ipad.png</string>
</array>
This answer is directed in large part at a comment made by @RafalDowgird:
"The minimum size of operations is int." - This would be very strange (what about architectures that efficiently support char/short operations?) Is this really in the C++ spec?
Keep in mind that the C++ standard has the all-important "as-if" rule. See section 1.8: Program Execution:
3) This provision is sometimes called the "as-if" rule, because an implementation is free to disregard any requirement of the Standard as long as the result is as if the requirement had been obeyed, as far as can be determined from the observable behavior of the program.
The compiler cannot set an int
to be 8 bits in size, even if it were the fastest, since the standard mandates a 16-bit minimum int
.
Therefore, in the case of a theoretical computer with super-fast 8-bit operations, the implicit promotion to int
for arithmetic could matter. However, for many operations, you cannot tell if the compiler actually did the operations in the precision of an int
and then converted to a char
to store in your variable, or if the operations were done in char all along.
For example, consider unsigned char = unsigned char + unsigned char + unsigned char
, where addition would overflow (let's assume a value of 200 for each). If you promoted to int
, you would get 600, which would then be implicitly down cast into an unsigned char
, which would wrap modulo 256, thus giving a final result of 88. If you did no such promotions,you'd have to wrap between the first two additions, which would reduce the problem from 200 + 200 + 200
to 144 + 200
, which is 344, which reduces to 88. In other words, the program does not know the difference, so the compiler is free to ignore the mandate to perform intermediate operations in int
if the operands have a lower ranking than int
.
This is true in general of addition, subtraction, and multiplication. It is not true in general for division or modulus.
The Android build system is the toolkit you use to build, test, run and package your apps. The build system can run as an integrated tool from the Android Studio menu and independently from the command line. You can use the features of the build system to:
The build process involves many tools and processes that generate intermediate files on the way to producing an .apk
. If you are developing in Android Studio, the complete build process is done every time you run the Gradle build task for your project or modules.
The build process is very flexible so it's useful, however, to understand what is happening under the hood since much of the build process is configurable and extensible. The following diagram depicts the different tools and processes that are involved in a build:
You can now use the Build menu options to build the release version of your application for distribution.
The build generates an APK for each build variant: the app/build/apk/
(or app/build/outputs/apk
) directory contains packages named app--.apk; for example, app-full-release.apk and app-demo-debug.apk.
Build output
The build generates an APK for each build variant in the app/build folder
: the app/build/outputs/apk/ directory
contains packages named app--.apk; for example, app-full-release.apk and app-demo-debug.apk.
Courtesy goes to Build System Overview
Detached head means you have not checked out your branch properly or you have just checked out a single commit.
If you encounter such an issue then first stash your local changes so that you won't lose your changes.
After that... checkout your desired branch using the command:
Let's say you want branch MyOriginalBranch:
git checkout -b someName origin/MyOriginalBranch
You can do it very easily with a Cloud Management software -like enStratus, RightScale or Scalr (disclaimer: I work there). With the cloned farm you can:
If you even plan on merging your branch, I highly suggest you look at this:
I hear Subversion 1.5 builds more of the merge tracking in, I have no experience with that. My project is on 1.4.x and svnmerge.py is a life saver!
I installed it using brew
.
$ brew install go
When it was done if you run this brew command it'll show the following info:
$ brew info go
go: stable 1.4.2 (bottled), HEAD
Go programming environment
https://golang.org
/usr/local/Cellar/go/1.4.2 (4676 files, 158M) *
Poured from bottle
From: https://github.com/Homebrew/homebrew/blob/master/Library/Formula/go.rb
==> Options
--with-cc-all
Build with cross-compilers and runtime support for all supported platforms
--with-cc-common
Build with cross-compilers and runtime support for darwin, linux and windows
--without-cgo
Build without cgo
--without-godoc
godoc will not be installed for you
--without-vet
vet will not be installed for you
--HEAD
Install HEAD version
==> Caveats
As of go 1.2, a valid GOPATH is required to use the `go get` command:
https://golang.org/doc/code.html#GOPATH
You may wish to add the GOROOT-based install location to your PATH:
export PATH=$PATH:/usr/local/opt/go/libexec/bin
The important pieces there are these lines:
/usr/local/Cellar/go/1.4.2 (4676 files, 158M) *
export PATH=$PATH:/usr/local/opt/go/libexec/bin
That shows where GO was installed. We need to do the following to setup GO's environment:
$ export PATH=$PATH:/usr/local/opt/go/libexec/bin
$ export GOPATH=/usr/local/opt/go/bin
You can then check using GO to see if it's configured properly:
$ go env
GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="darwin"
GOOS="darwin"
GOPATH="/usr/local/opt/go/bin"
GORACE=""
GOROOT="/usr/local/Cellar/go/1.4.2/libexec"
GOTOOLDIR="/usr/local/Cellar/go/1.4.2/libexec/pkg/tool/darwin_amd64"
CC="clang"
GOGCCFLAGS="-fPIC -m64 -pthread -fno-caret-diagnostics -Qunused-arguments -fmessage-length=0 -fno-common"
CXX="clang++"
CGO_ENABLED="1"
Looks good, so lets install json2csv
:
$ go get github.com/jehiah/json2csv
$
What just happened? It installed it. You can check like this:
$ $ ls -l $GOPATH/bin
total 5248
-rwxr-xr-x 1 sammingolelli staff 2686320 Jun 9 12:28 json2csv
OK, so why can't I type json2csv
in my shell? That's because the /bin
directory under $GOPATH
isn't on your $PATH
.
$ type -f json2csv
-bash: type: json2csv: not found
So let's temporarily add it:
$ export PATH=$GOPATH/bin:$PATH
And re-check:
$ type -f json2csv
json2csv is hashed (/usr/local/opt/go/bin/bin/json2csv)
Now it's there:
$ json2csv --help
Usage of json2csv:
-d=",": delimiter used for output values
-i="": /path/to/input.json (optional; default is stdin)
-k=[]: fields to output
-o="": /path/to/output.json (optional; default is stdout)
-p=false: prints header to output
-v=false: verbose output (to stderr)
-version=false: print version string
Add the modifications we've made to $PATH
and $GOPATH
to your $HOME/.bash_profile
to make them persist between reboots.
301 is that the requested resource has been assigned a new permanent URI and any future references to this resource should be done using one of the returned URIs.
302 is that the requested resource resides temporarily under a different URI.
Since the redirection may be altered on occasion, the client should continue to use the Request-URI for future requests.
This response is only cachable if indicated by a Cache-Control or Expires header field.
public static void main(String[] args) {
final String xmlStr = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"+
"<Emp id=\"1\"><name>Pankaj</name><age>25</age>\n"+
"<role>Developer</role><gen>Male</gen></Emp>";
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder;
try
{
builder = factory.newDocumentBuilder();
Document doc = builder.parse( new InputSource( new StringReader( xmlStr )) );
} catch (Exception e) {
e.printStackTrace();
}
}
Imagine you are developing a web-application and you decide to decouple the functionality from the presentation of the application, because it affords greater freedom.
You create an API and let others implement their own front-ends over it as well. What you just did here is implement an SOA methodology, i.e. using web-services.
Web services make functional building-blocks accessible over standard Internet protocols independent of platforms and programming languages.
So, you design an interchange mechanism between the back-end (web-service) that does the processing and generation of something useful, and the front-end (which consumes the data), which could be anything. (A web, mobile, or desktop application, or another web-service). The only limitation here is that the front-end and back-end must "speak" the same "language".
That's where SOAP and REST come in. They are standard ways you'd pick communicate with the web-service.
SOAP:
SOAP internally uses XML to send data back and forth. SOAP messages have rigid structure and the response XML then needs to be parsed. WSDL is a specification of what requests can be made, with which parameters, and what they will return. It is a complete specification of your API.
REST:
REST is a design concept.
The World Wide Web represents the largest implementation of a system conforming to the REST architectural style.
It isn't as rigid as SOAP. RESTful web-services use standard URIs and methods to make calls to the webservice. When you request a URI, it returns the representation of an object, that you can then perform operations upon (e.g. GET, PUT, POST, DELETE). You are not limited to picking XML to represent data, you could pick anything really (JSON included)
Flickr's REST API goes further and lets you return images as well.
JSON and XML, are functionally equivalent, and common choices. There are also RPC-based frameworks like GRPC based on Protobufs, and Apache Thrift that can be used for communication between the API producers and consumers. The most common format used by web APIs is JSON because of it is easy to use and parse in every language.
Sometimes this kind of error happens when you create tables with different database users and try to SELECT
with a different user.
You can grant all privileges using below query.
GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA schema_name TO username;
And also you can grant access for DML statements
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA schema_name TO username;
Along the same lines as previous answers, but a very short addition that Allows to use all Control properties without having cross thread invokation exception.
Helper Method
/// <summary>
/// Helper method to determin if invoke required, if so will rerun method on correct thread.
/// if not do nothing.
/// </summary>
/// <param name="c">Control that might require invoking</param>
/// <param name="a">action to preform on control thread if so.</param>
/// <returns>true if invoke required</returns>
public bool ControlInvokeRequired(Control c,Action a)
{
if (c.InvokeRequired) c.Invoke(new MethodInvoker(delegate { a(); }));
else return false;
return true;
}
Sample Usage
// usage on textbox
public void UpdateTextBox1(String text)
{
//Check if invoke requied if so return - as i will be recalled in correct thread
if (ControlInvokeRequired(textBox1, () => UpdateTextBox1(text))) return;
textBox1.Text = ellapsed;
}
//Or any control
public void UpdateControl(Color c,String s)
{
//Check if invoke requied if so return - as i will be recalled in correct thread
if (ControlInvokeRequired(myControl, () => UpdateControl(c,s))) return;
myControl.Text = s;
myControl.BackColor = c;
}
The biggest different is the basic concept.
From the Set and List interface. Set is mathematics concept. Set method extends collection.however not add new method. size() means cardinality(more is BitSet.cardinality, Linear counter,Log Log,HyperLogLog). addAll() means union. retainAll() means intersection. removeAll() means difference.
However List lack of these concepts. List add a lot of method to support sequence concept which Collection interface not supply. core concept is INDEX. like add(index,element),get(index),search(indexOf()),remove(index) element. List also provide "Collection View" subList. Set do not have view. do not have positional access. List also provide a lot of algorithms in Collections class. sort(List),binarySearch(List),reverse(List),shuffle(List),fill(List). the method params is List interface. duplicate elements are just the result of concepts. not the essential difference.
So the essential difference is concept. Set is mathematics set concept.List is sequence concept.
In latin1 each character is exactly one byte long. In utf8 a character can consist of more than one byte. Consequently utf8 has more characters than latin1 (and the characters they do have in common aren't necessarily represented by the same byte/bytesequence).
Dont work for me, need to put scope in plural
validates_uniqueness_of :teacher_id, :scopes => [:semester_id, :class_id]
This is what worked for me on Firefox
and Chrome
:
// The format is 'year-month-date hr:mins:seconds.milliseconds'
const d = new Date('2020-1-4 12:00:00.999')
// we use the `.` separator between seconds and milliseconds.
Good Luck...
There is a get method in HashMap:
for (String keys : objectSet.keySet())
{
System.out.println(keys + ":"+ objectSet.get(keys));
}
By utilizing string operations of JS one can do as follows;
0b1111011.toString(2).split(/0|(?=.)/).length // returns 6
or
0b1111011.toString(2).replace("0","").length // returns 6
Your return data
approach is correct, that's an example of promise chaining. If you return a promise from your .then()
callback, JavaScript will resolve that promise and pass the data to the next then()
callback.
Just be careful and make sure you handle errors with .catch()
. Promise.all()
rejects as soon as one of the promises in the array rejects.
You can put all your #m1
...#m9
divs into .target
and display them based on fragment identifier (hash) using :target
pseudo-class. It doesn't move the contents between divs, but I think the effect is close to what you wanted to achieve.
HTML
<div class="target">
<div id="m1">
dasdasdasd m1
</div>
<!-- etc... -->
<div id="m9">
dasdasdsgaswa m9
</div>
</div>
CSS
.target {
width:50%;
height:200px;
border:solid black 1px;
}
.target > div {
display:none;
}
.target > div:target{
display:block;
}
Add relative positioning to the wrapping div tag, then absolutely position the image within it like this:
CSS:
.div-wrapper {
position: relative;
height: 300px;
width: 300px;
}
.div-wrapper img {
position: absolute;
left: 0;
bottom: 0;
}
HTML:
<div class="div-wrapper">
<img src="blah.png"/>
</div>
Now the image sits at the bottom of the div.
UPDATE Table SET Column = REPLACE(Column, char(9), '')
Sometimes you do get focus but no cursor in a text field. In this case you would do this:
document.getElementById(frmObj.id).select();
What you did with the iteration is not wrong from what I can make of it based on the question. It gives you a valid array of String objects. Like mentioned in another answer it is however easier to use the toArray() method available for the ArrayList object => http://docs.oracle.com/javase/1.5.0/docs/api/java/util/ArrayList.html#toArray%28%29
Just a side note. If you would iterate your dsf array properly and print each element on its own you would get valid output. Like this:
for(String str : dsf){
System.out.println(str);
}
What you probably tried to do was print the complete Array object at once since that would give an object memory address like you got in your question. If you see that kind of output you need to provide a toString() method for the object you're printing.
Installing Aptana Studio in passive mode bypasses the installation of Git for Windows and Node.js.
Aptana_Studio_3_Setup_3.6.1 /passive /norestart
(I am unsure whether Aptana Studio will work properly without those "prerequisites", but it appears to.)
If you want a global installation in a specific directory, the command line is
Aptana_Studio_3_Setup_3.6.1.exe /passive /norestart ALLUSERS=1 APPDIR=c:\apps\AptanaStudio
If you need this solution for only few types of modals just use
style="width:90%"
attribute.
example:
div class="modal-dialog modal-lg" style="width:90%"
note: this will change only this particular modal
First, I would like to clarify something. Is this a post back (trip back to server) never occur, or is it the post back occurs, but it never gets into the ddlCountry_SelectedIndexChanged event handler?
I am not sure which case you are having, but if it is the second case, I can offer some suggestion. If it is the first case, then the following is FYI.
For the second case (event handler never fires even though request made), you may want to try the following suggestions:
Beware that when calling Control.DataBind(), view state and post back information would no longer be available from the control. In the case of view state is on, between post back, values of the DropDownList would be kept intact (the list does not to be rebound). If you issue another DataBind in OnLoad, it would clear out its view state data, and the SelectedIndexChanged event would never be fired.
In the case of view state is turned off, you have no choice but to rebind the list every time. When a post back occurs, there are internal ASP.NET calls to populate the value from Request.Params to the appropriate controls, and I suspect happen at the time between OnInit and OnLoad. In this case, restoring the list values in OnInit will enable the system to fire events correctly.
Thanks for your time reading this, and welcome everyone to correct if I am wrong.
My laptop did not have Break nor Scr Lock, so I somehow managed to make it work by pressing Ctrl + Function + Right Shift (to activate 'pause').
msgbox "This is the first line" & vbcrlf & "and this is the second line"
or in .NET msgbox "This is the first line" & Environment.NewLine & "and this is the second line"
Almost 5 years after only the direct HTML formatting works for images on GitHub and other markdown options still prevent images from loading when specifying some custom sizes even with the wrong dimensions. I prefer to specify the desired width and get the height calculated automatically, for example,
<img src="https://github.com/your_image.png" alt="Your image title" width="250"/>
_x000D_
Loop through divs every 10 seconds.
$(function () {
var counter = 0,
divs = $('#div1, #div2, #div3');
function showDiv () {
divs.hide() // hide all divs
.filter(function (index) { return index == counter % 3; }) // figure out correct div to show
.show('fast'); // and show it
counter++;
}; // function to loop through divs and show correct div
showDiv(); // show first div
setInterval(function () {
showDiv(); // show next div
}, 10 * 1000); // do this every 10 seconds
});
Simple:
byte[] data = Convert.FromBase64String(encodedString);
string decodedString = Encoding.UTF8.GetString(data);
You can simply downgrade your gradle dependency to fit your current android studio version.
dependencies {
classpath 'com.android.tools.build:gradle:3.5.2'
....
}
Worked for me.
The program is printing "Hey this is my first hello world "
, then it is moving the cursor back to the beginning of the line. How this will look on the screen depends on your environment. It appears the beginning of the string is being overwritten by something, perhaps your command line prompt.
BEGIN
DECLARE @totaldays INT;
DECLARE @weekenddays INT;
SET @totaldays = DATEDIFF(DAY, @startDate, @endDate)
SET @weekenddays = ((DATEDIFF(WEEK, @startDate, @endDate) * 2) + -- get the number of weekend days in between
CASE WHEN DATEPART(WEEKDAY, @startDate) = 1 THEN 1 ELSE 0 END + -- if selection was Sunday, won't add to weekends
CASE WHEN DATEPART(WEEKDAY, @endDate) = 6 THEN 1 ELSE 0 END) -- if selection was Saturday, won't add to weekends
Return (@totaldays - @weekenddays)
END
This is on SQL Server 2014
You can use also JAXB bindings to specify different package for each schema, e.g.
<jaxb:bindings xmlns:jaxb="http://java.sun.com/xml/ns/jaxb" xmlns:xjc="http://java.sun.com/xml/ns/jaxb/xjc"
xmlns:xs="http://www.w3.org/2001/XMLSchema" version="2.0" schemaLocation="book.xsd">
<jaxb:globalBindings>
<xjc:serializable uid="1" />
</jaxb:globalBindings>
<jaxb:schemaBindings>
<jaxb:package name="com.stackoverflow.book" />
</jaxb:schemaBindings>
</jaxb:bindings>
Then just use the new maven-jaxb2-plugin 0.8.0 <schemas>
and <bindings>
elements in the pom.xml
. Or specify the top most directory in <schemaDirectory>
and <bindingDirectory>
and by <include>
your schemas and bindings:
<schemaDirectory>src/main/resources/xsd</schemaDirectory>
<schemaIncludes>
<include>book/*.xsd</include>
<include>person/*.xsd</include>
</schemaIncludes>
<bindingDirectory>src/main/resources</bindingDirectory>
<bindingIncludes>
<include>book/*.xjb</include>
<include>person/*.xjb</include>
</bindingIncludes>
I think this is more convenient solution, because when you add a new XSD you do not need to change Maven pom.xml
, just add a new XJB binding file to the same directory.
In Netbeans please delete current you create the jar file and on the project explore of Netbeans please clean and build 2 or 3 times and right the project folder in project explore and build the jar file.
Contrary to .NET where all types derive from an "object", in TypeScript, all types derive from "any". I just wanted to add this comparison as I think it will be a common one made as more .NET developers give TypeScript a try.
You can use -v
option multiple times in docker run
command to mount multiple directory in container:
docker run -t -i \
-v '/on/my/host/test1:/on/the/container/test1' \
-v '/on/my/host/test2:/on/the/container/test2' \
ubuntu /bin/bash
To answer the underlying question of how to use a CASE expression in the WHERE clause:
First remember that the value of a CASE expression has to have a normal data type value, not a boolean value. It has to be a varchar, or an int, or something. It's the same reason you can't say SELECT Name, 76 = Age FROM [...]
and expect to get 'Frank', FALSE
in the result set.
Additionally, all expressions in a WHERE clause need to have a boolean value. They can't have a value of a varchar or an int. You can't say WHERE Name;
or WHERE 'Frank';
. You have to use a comparison operator to make it a boolean expression, so WHERE Name = 'Frank';
That means that the CASE expression must be on one side of a boolean expression. You have to compare the CASE expression to something. It can't stand by itself!
Here:
WHERE
DateDropped = 0
AND CASE
WHEN @JobsOnHold = 1 AND DateAppr >= 0 THEN 'True'
WHEN DateAppr != 0 THEN 'True'
ELSE 'False'
END = 'True'
Notice how in the end the CASE expression on the left will turn the boolean expression into either 'True' = 'True'
or 'False' = 'True'
.
Note that there's nothing special about 'False'
and 'True'
. You can use 0
and 1
if you'd rather, too.
You can typically rewrite the CASE expression into boolean expressions we're more familiar with, and that's generally better for performance. However, sometimes is easier or more maintainable to use an existing expression than it is to convert the logic.
the obvious way to debug a script
python -m pdb script.py
if you don't know exactly where that script is
python -m pdb ``which <python-script-name>``
Depending on your application and the scope of the cfg file, a properties file might be the easiest. Sure it isn't as elegant as xml but it certainly easier.
new Date(year,month,day,0,0,0,0)
is local time (as input)
new Date(year,month,day)
is UTC
I was using a function to attain YYYY-MM-DD
format to be compatible on iOS web, but that is also UTC when used in comparisons (not chained by getFullYear or similar) I've found it is best to use only the above with strong (hours,minutes,seconds,milliseconds) building a calendar, calculating with a Date objects and local references
export const zeroPad = (num) => {
var res = "0";
if (String(num).length === 1) {
res = `0${num}`;
} else {
res = num;
}
return res;
};
function handleFileSelect(evt) {_x000D_
var files = evt.target.files;_x000D_
_x000D_
// Loop through the FileList and render image files as thumbnails._x000D_
for (var i = 0, f; f = files[i]; i++) {_x000D_
_x000D_
// Only process image files._x000D_
if (!f.type.match('image.*')) {_x000D_
continue;_x000D_
}_x000D_
_x000D_
var reader = new FileReader();_x000D_
_x000D_
// Closure to capture the file information._x000D_
reader.onload = (function(theFile) {_x000D_
return function(e) {_x000D_
// Render thumbnail._x000D_
var span = document.createElement('span');_x000D_
span.innerHTML = _x000D_
[_x000D_
'<img style="height: 75px; border: 1px solid #000; margin: 5px" src="', _x000D_
e.target.result,_x000D_
'" title="', escape(theFile.name), _x000D_
'"/>'_x000D_
].join('');_x000D_
_x000D_
document.getElementById('list').insertBefore(span, null);_x000D_
};_x000D_
})(f);_x000D_
_x000D_
// Read in the image file as a data URL._x000D_
reader.readAsDataURL(f);_x000D_
}_x000D_
}_x000D_
_x000D_
document.getElementById('files').addEventListener('change', handleFileSelect, false);
_x000D_
<input type="file" id="files" multiple />_x000D_
<output id="list"></output>
_x000D_
You can't use named parameters in JDBC itself. You could try using Spring framework, as it has some extensions that allow the use of named parameters in queries.
You can also increase it via the VM arguments in your IDE. In my case, I am using Tomcat v7.0 which is running on Eclipse. To do this, double click on your server (Tomcat v7.0). Click the 'Open launch configuration' link. Go to the 'Arguments' tab. Add -XX:MaxPermSize=512m to the VM arguments list. Click 'Apply' and then 'OK'. Restart your server.
NSLog(@"%@", CGRectCreateDictionaryRepresentation(rect));
I think the usual use case is to call it when no exception was thrown in a negative test.
Something like the following pseudo-code:
test_addNilThrowsNullPointerException()
{
try {
foo.add(NIL); // we expect a NullPointerException here
fail("No NullPointerException"); // cause the test to fail if we reach this
} catch (NullNullPointerException e) {
// OK got the expected exception
}
}
Run this:
Rails.application.eager_load!
Then
ActiveRecord::Base.descendants
To return a list of models/tables
The key checks for FAST REFRESH includes the following:
1) An Oracle materialized view log must be present for each base table.
2) The RowIDs of all the base tables must appear in the SELECT list of the MVIEW query definition.
3) If there are outer joins, unique constraints must be placed on the join columns of the inner table.
No 3 is easy to miss and worth highlighting here
This method is almost identical to yours, just more numpyst (also working on numpy arrays only):
def reject_outliers(data, m=2):
return data[abs(data - np.mean(data)) < m * np.std(data)]
In newer versions of VSCode this moved to a folder-specific configuration block.
Then add a "files.exclude" block, listing the directory globs you would like to exclude:
{
"files.exclude": {
"**/bin": true,
"**/obj": true
},
}
You can also use a pretty simple for
loop:
for f in `find . -not -name "*Music*"`
do
cp $f /target/dir
done
The bundle identifier is an ID for your application used by the system as a domain for which it can store settings and reference your application uniquely.
It is represented in reverse DNS notation and it is recommended that you use your company name and application name to create it.
An example bundle ID for an App called The Best App by a company called Awesome Apps would look like:
com.awesomeapps.thebestapp
In this case the suffix is thebestapp
.
After you run MySQL Shell and you have seen following:
mysql-js>
Firstly, you should:
mysql-js>\sql
Secondly:
mysql-sql>\connect username@servername (root@localhost)
And finally:
Enter password:*********
dplyr
package does this with count
/tally
commands, or the n()
function:
First, some data:
df <- data.frame(x = rep(1:6, rep(c(1, 2, 3), 2)), year = 1993:2004, month = c(1, 1:11))
Now the count:
library(dplyr)
count(df, year, month)
#piping
df %>% count(year, month)
We can also use a slightly longer version with piping and the n()
function:
df %>%
group_by(year, month) %>%
summarise(number = n())
or the tally
function:
df %>%
group_by(year, month) %>%
tally()
I use references unless I need either of these:
Null pointers can be used as a sentinel value, often a cheap way to avoid function overloading or use of a bool.
You can do arithmetic on a pointer.
For example, p += offset;
Try this:
Encoding iso = Encoding.GetEncoding("ISO-8859-1");
Encoding utf8 = Encoding.UTF8;
byte[] utfBytes = utf8.GetBytes(Message);
byte[] isoBytes = Encoding.Convert(utf8,iso,utfBytes);
string msg = iso.GetString(isoBytes);
This simple static function calculates the fraction of months between two Datetimes, e.g.
The function assumes that the first date is smaller than the second date. To deal with negative time intervals one can modify the function easily by introducing a sign and a variable swap at the beginning.
public static double GetDeltaMonths(DateTime t0, DateTime t1)
{
DateTime t = t0;
double months = 0;
while(t<=t1)
{
int daysInMonth = DateTime.DaysInMonth(t.Year, t.Month);
DateTime endOfMonth = new DateTime(t.Year, t.Month, daysInMonth);
int cutDay = endOfMonth <= t1 ? daysInMonth : t1.Day;
months += (cutDay - t.Day + 1) / (double) daysInMonth;
t = new DateTime(t.Year, t.Month, 1).AddMonths(1);
}
return Math.Round(months,2);
}
To convert a time in one timezone to another timezone in Python, you could use datetime.astimezone():
so, below code is to convert the local time to other time zone.
# Time conversion from local time
import datetime
import pytz
dt_today = datetime.datetime.today() # Local time
dt_India = dt_today.astimezone(pytz.timezone('Asia/Kolkata'))
dt_London = dt_today.astimezone(pytz.timezone('Europe/London'))
India = (dt_India.strftime('%m/%d/%Y %H:%M'))
London = (dt_London.strftime('%m/%d/%Y %H:%M'))
print("Indian standard time: "+India+" IST")
print("British Summer Time: "+London+" BST")
import pytz
for tz in pytz.all_timezones:
print(tz)
If you want to launch VM by sending arguments, you should send VM arguments and not Program arguments.
Program arguments are arguments that are passed to your application, which are accessible via the "args" String array parameter of your main method. VM arguments are arguments such as System properties that are passed to the JavaSW interpreter. The Debug configuration above is essentially equivalent to:
java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3
The VM arguments go after the call to your Java interpreter (ie, 'java') and before the Java class. Program arguments go after your Java class.
Consider a program ArgsTest.java:
package test;
import java.io.IOException;
public class ArgsTest {
public static void main(String[] args) throws IOException {
System.out.println("Program Arguments:");
for (String arg : args) {
System.out.println("\t" + arg);
}
System.out.println("System Properties from VM Arguments");
String sysProp1 = "sysProp1";
System.out.println("\tName:" + sysProp1 + ", Value:" + System.getProperty(sysProp1));
String sysProp2 = "sysProp2";
System.out.println("\tName:" + sysProp2 + ", Value:" + System.getProperty(sysProp2));
}
}
If given input as,
java -DsysProp1=sp1 -DsysProp2=sp2 test.ArgsTest pro1 pro2 pro3
in the commandline, in project bin folder would give the following result:
Program Arguments: pro1 pro2 pro3 System Properties from VM Arguments Name:sysProp1, Value:sp1 Name:sysProp2, Value:sp2
<div id='child' style='width: 50px; height: 100px; margin:0 auto;'>Text</div>
For the sake of completeness, there is another approach wrap()
or wrapAll()
mentioned in this article. So the OP's question could possibly be solved by this (that is, assuming the <div id="destination" />
does not yet exist, the following approach will create such a wrapper from scratch - the OP was not clear about whether the wrapper already exists or not):
$("#source").wrap('<div id="destination" />')
// or
$(".source").wrapAll('<div id="destination" />')
It sounds promising. However, when I was trying to do $("[id^=row]").wrapAll("<fieldset></fieldset>")
on multiple nested structure like this:
<div id="row1">
<label>Name</label>
<input ...>
</div>
It correctly wraps those <div>...</div>
and <input>...</input>
BUT SOMEHOW LEAVES OUT the <label>...</label>
. So I ended up use the explicit $("row1").append("#a_predefined_fieldset")
instead. So, YMMV.
Whithout JavaScript, the only way I could play without errors:
<!--[if lte IE 9]>
<!-- PUT HERE A FLASH PLAYER WITH video.flv -->
<![endif]-->
<!--[if gt IE 9]><!-->
<video controls class="video">
<source src="video.mp4" type="video/mp4">
<!-- REPEAT FLASH PLAYER CODE HERE -->
</video>
<!--<![endif]-->
While most of these answers will tell you if a substring appears in your string, that's usually not what you want if you're looking for a particular word, and not a substring.
What's the difference? Substrings can appear within other words:
One way to mitigate this would be to use a regular expression coupled with word boundaries (\b
):
function containsWord($str, $word)
{
return !!preg_match('#\\b' . preg_quote($word, '#') . '\\b#i', $str);
}
This method doesn't have the same false positives noted above, but it does have some edge cases of its own. Word boundaries match on non-word characters (\W
), which are going to be anything that isn't a-z
, A-Z
, 0-9
, or _
. That means digits and underscores are going to be counted as word characters and scenarios like this will fail:
If you want anything more accurate than this, you'll have to start doing English language syntax parsing, and that's a pretty big can of worms (and assumes proper use of syntax, anyway, which isn't always a given).
Try something like:
$post_data="dispnumber=567567567&extension=6";
$url="http://xxxxxxxx.xxx/xx/xx";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
echo $result;
Use LIKE ANY(ARRAY['AAA%', 'BBB%', 'CCC%'])
as per this cool trick @maniek showed earlier today.
Using map or other similar solution do not help to clone deeply an array of object. An easier way to do this without adding a new library is using JSON.stringfy and then JSON.parse.
In your case this should work :
this.backupData = JSON.parse(JSON.stringify(genericItems));
For small objet lodash cloneDeep can be faster but for larger/deeper object json clone become faster. So in this cases you should not hesitate to use it. check https://www.measurethat.net/Benchmarks/Show/6039/0/lodash-clonedeep-vs-json-clone-larger-object and for infos https://v8.dev/blog/cost-of-javascript-2019#json
The inconvenient is that your source object must be convertible to JSON.
Probably the path you supplied was not correct. Check that.
I would recomment the article Howto: (Almost) Everything In Active Directory via C# which really helped me in the past in dealing with AD.
def bubble_sort(li):
l = len(li)
tmp = None
sorted_l = sorted(li)
while (li != sorted_l):
for ele in range(0,l-1):
if li[ele] > li[ele+1]:
tmp = li[ele+1]
li[ele+1] = li [ele]
li[ele] = tmp
return li
Here is my gradle build script that executes strings stored in heredocs:
current_directory=$( realpath "." )
GENERATED=${current_directory}/"GENERATED"
build_gradle=$( realpath build.gradle )
## touch because .gitignore ignores this folder:
touch $GENERATED
COPY_BUILD_FILE=$( cat <<COPY_BUILD_FILE_HEREDOC
cp
$build_gradle
$GENERATED/build.gradle
COPY_BUILD_FILE_HEREDOC
)
$COPY_BUILD_FILE
GRADLE_COMMAND=$( cat <<GRADLE_COMMAND_HEREDOC
gradle run
--build-file
$GENERATED/build.gradle
--gradle-user-home
$GENERATED
--no-daemon
GRADLE_COMMAND_HEREDOC
)
$GRADLE_COMMAND
The lone ")" are kind of ugly. But I have no clue how to fix that asthetic aspect.
Right click and open SVN Repo-browser:
Right click on Trunk (working copy) and choose Copy to...:
Input the respective branch's name/path:
Click OK, type the respective log message, and click OK.
You would need to add a trigger on insert, update, delete that sets a value in another table to sysdate.
When you run application, it would read the value and save it somewhere so that the next time it is run it has a reference to compare.
Would you consider that "Special Admin Stuff"?
It would be better to describe what you're actually doing so you get clearer answers.
If you use kotlin, this can be simplified by creating an extension function
fun View.setMarginExtensionFunction(left: Int, top: Int, right: Int, bottom: Int) {
val params = layoutParams as ViewGroup.MarginLayoutParams
params.setMargins(left, top, right, bottom)
layoutParams = params
}
Now all you need is a view, and this extension function can be used anywhere.
val imageView = findViewById(R.id.imageView)
imageView.setMarginExtensionFunction(0, 0, 0, 0)
You can use multiple repositories syntax for the registry
entry in your .npmrc
file:
registry=http://serverA.url/repository-uri/
//serverB.url/repository-uri/
//serverC.url/repository-uri/:_authToken=00000000-0000-0000-0000-0000000000000
//registry.npmjs.org/
That would make your npm look for packages in different servers.
I always go back to this article SQL Server 2005 XQuery and XML-DML - Part 1 to know how to use the XML features in SQL Server 2005.
For basic XPath know-how, I'd recommend the W3Schools tutorial.
I am using excelcnv.exe to convert csv into xlsx and that seemed to work properly. You will have to change the directory to where your excelcnv is. If 32 bit, it goes to Program Files (x86)
Start-Process -FilePath 'C:\Program Files\Microsoft Office\root\Office16\excelcnv.exe' -ArgumentList "-nme -oice ""$xlsFilePath"" ""$xlsToxlsxPath"""
If the two
controller is nested in One
controller.
Then you can simply call:
$scope.parentmethod();
Angular will search for parentmethod
function starting with current scope and up until it will reach the rootScope
.
Use this to obtain only the filename.
Path.GetFileName(files[0]);
After further investigating on PSExec tool, I think I got the answer. I need to add -i option to tell PSExec to launch process on remote in interactive mode:
PSExec \\RPC001 -i -u myID -p myPWD PowerShell C:\script\StartPS.ps1 par1 par2
Without -i, powershell.exe is running on the remote in waiting mode. Interesting point is that if I run a simple bat (without PS in bat), it works fine. Maybe this is something special for PS case? Welcome comments and explanations.
There are cases where you don't want to use v-model
. If you have two inputs, and each depend on each other, you might have circular referential issues. Common use cases is if you're building an accounting calculator.
In these cases, it's not a good idea to use either watchers or computed properties.
Instead, take your v-model
and split it as above answer indicates
<input
:value="something"
@input="something = $event.target.value"
>
In practice, if you are decoupling your logic this way, you'll probably be calling a method.
This is what it would look like in a real world scenario:
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
_x000D_
<div id="app">_x000D_
<input :value="extendedCost" @input="_onInputExtendedCost" />_x000D_
<p> {{ extendedCost }}_x000D_
</div>_x000D_
_x000D_
<script>_x000D_
var app = new Vue({_x000D_
el: "#app",_x000D_
data: function(){_x000D_
return {_x000D_
extendedCost: 0,_x000D_
}_x000D_
},_x000D_
methods: {_x000D_
_onInputExtendedCost: function($event) {_x000D_
this.extendedCost = parseInt($event.target.value);_x000D_
// Go update other inputs here_x000D_
}_x000D_
}_x000D_
});_x000D_
</script>
_x000D_
I needed to change an input
to an arrow in my project. Below is final work.
#in_submit {_x000D_
background-color: white;_x000D_
border-left: #B4C8E9;_x000D_
border-top: #B4C8E9;_x000D_
border-right: 3px solid black;_x000D_
border-bottom: 3px solid black;_x000D_
width: 15px;_x000D_
height: 15px;_x000D_
transform: rotate(-45deg);_x000D_
margin-top: 4px;_x000D_
margin-left: 4px;_x000D_
position: absolute;_x000D_
cursor: pointer;_x000D_
}
_x000D_
<input id="in_submit" type="button" class="convert_btn">
_x000D_
Here Fiddle
You should be able to use normal C methods in math.
#include <cmath>
pow(2,3)
if you're on a unix-like system, man cmath
Is that what you're asking?
Sujal
Please check this jQuery plugin,
with this you can overlay all the page or elements, works great for me,
Examples:
Block a div:
$('div.test').block({ message: null });
Block the page:
$.blockUI({ message: '<h1><img src="busy.gif" /> Just a moment...</h1>' });
Hope that help someone
Greetings
I always have to check my cheatsheet :-)
Step 1: right-click on the top of putty window and select 'Change settings'.
Step 2: type the name of the session and save.
That's it!. Enjoy!
You can use boost::optional
(or std::optional
for newer versions), which was developed in particular for decision of your problem:
boost::optional<int> y[50];
....
geoGraph.y[x] = nums[x];
....
const size_t size_y = sizeof(y)/sizeof(y[0]); //!!!! correct size of y!!!!
for(int i=0; i<size_y;i++){
if(y[i]) { //check for null
p[i].SetPoint(Recto.Height()-x,*y[i]);
....
}
}
P.S. Do not use C-type array -> use std::array or std::vector:
std::array<int, 50> y; //not int y[50] !!!
In current version of Jekyll, it defaults to http://127.0.0.1:4000/.
This is good, if you are connected to a network but do not want anyone else to access your application.
However it may happen that you want to see how your application runs on a mobile or from some other laptop/computer.
In that case, you can use
jekyll serve --host 0.0.0.0
This binds your application to the host & next use following to connect to it from some other host
http://host's IP adress/4000
You are on the right track about hostvars
.
This magic variable is used to access information about other hosts.
hostvars
is a hash with inventory hostnames as keys.
To access fields of each host, use hostvars['test-1']
, hostvars['test2-1']
, etc.
ansible_ssh_host
is deprecated in favor of ansible_host
since 2.0.
So you should first remove "_ssh" from inventory hosts arguments (i.e. to become "ansible_user", "ansible_host", and "ansible_port"), then in your role call it with:
{{ hostvars['your_host_group'].ansible_host }}
You can find everything you need to know about Gradle here: Gradle Plugin User Guide
Goals of the new Build System
The goals of the new build system are:
- Make it easy to reuse code and resources
- Make it easy to create several variants of an application, either for multi-apk distribution or for different flavors of an application
- Make it easy to configure, extend and customize the build process
- Good IDE integration
Why Gradle?
Gradle is an advanced build system as well as an advanced build toolkit allowing to create custom build logic through plugins.
Here are some of its features that made us choose Gradle:
- Domain Specific Language (DSL) to describe and manipulate the build logic
- Build files are Groovy based and allow mixing of declarative elements through the DSL and using code to manipulate the DSL elements to provide custom logic.
- Built-in dependency management through Maven and/or Ivy.
- Very flexible. Allows using best practices but doesn’t force its own way of doing things.
- Plugins can expose their own DSL and their own API for build files to use.
- Good Tooling API allowing IDE integration
You could do this:
find ./ -type f -ls |grep '10 Sep'
Example:
[root@pbx etc]# find /var/ -type f -ls | grep "Dec 24"
791235 4 -rw-r--r-- 1 root root 29 Dec 24 03:24 /var/lib/prelink/full
798227 288 -rw-r--r-- 1 root root 292323 Dec 24 23:53 /var/log/sa/sar24
797244 320 -rw-r--r-- 1 root root 321300 Dec 24 23:50 /var/log/sa/sa24
The concept of a HOME directory seems to be a bit vague when it comes to Windows. If the environment variables (HOMEDRIVE/HOMEPATH/USERPROFILE) aren't enough, you may have to resort to using native functions via JNI or JNA. SHGetFolderPath allows you to retrieve special folders, like My Documents (CSIDL_PERSONAL) or Local Settings\Application Data (CSIDL_LOCAL_APPDATA).
Sample JNA code:
public class PrintAppDataDir {
public static void main(String[] args) {
if (com.sun.jna.Platform.isWindows()) {
HWND hwndOwner = null;
int nFolder = Shell32.CSIDL_LOCAL_APPDATA;
HANDLE hToken = null;
int dwFlags = Shell32.SHGFP_TYPE_CURRENT;
char[] pszPath = new char[Shell32.MAX_PATH];
int hResult = Shell32.INSTANCE.SHGetFolderPath(hwndOwner, nFolder,
hToken, dwFlags, pszPath);
if (Shell32.S_OK == hResult) {
String path = new String(pszPath);
int len = path.indexOf('\0');
path = path.substring(0, len);
System.out.println(path);
} else {
System.err.println("Error: " + hResult);
}
}
}
private static Map<String, Object> OPTIONS = new HashMap<String, Object>();
static {
OPTIONS.put(Library.OPTION_TYPE_MAPPER, W32APITypeMapper.UNICODE);
OPTIONS.put(Library.OPTION_FUNCTION_MAPPER,
W32APIFunctionMapper.UNICODE);
}
static class HANDLE extends PointerType implements NativeMapped {
}
static class HWND extends HANDLE {
}
static interface Shell32 extends Library {
public static final int MAX_PATH = 260;
public static final int CSIDL_LOCAL_APPDATA = 0x001c;
public static final int SHGFP_TYPE_CURRENT = 0;
public static final int SHGFP_TYPE_DEFAULT = 1;
public static final int S_OK = 0;
static Shell32 INSTANCE = (Shell32) Native.loadLibrary("shell32",
Shell32.class, OPTIONS);
/**
* see http://msdn.microsoft.com/en-us/library/bb762181(VS.85).aspx
*
* HRESULT SHGetFolderPath( HWND hwndOwner, int nFolder, HANDLE hToken,
* DWORD dwFlags, LPTSTR pszPath);
*/
public int SHGetFolderPath(HWND hwndOwner, int nFolder, HANDLE hToken,
int dwFlags, char[] pszPath);
}
}
For swift 2.0:
let cacheSizeMemory = 4*1024*1024; // 4MB
let cacheSizeDisk = 32*1024*1024; // 32MB
let sharedCache = NSURLCache(memoryCapacity: cacheSizeMemory, diskCapacity: cacheSizeDisk, diskPath: "nsurlcache")
NSURLCache.setSharedURLCache(sharedCache)
Function to return stream that contain zip file
public static Stream ZipGenerator(List<string> files)
{
ZipArchiveEntry fileInArchive;
Stream entryStream;
int i = 0;
List<byte[]> byteArray = new List<byte[]>();
foreach (var file in files)
{
byteArray.Add(File.ReadAllBytes(file));
}
var outStream = new MemoryStream();
using (var archive = new ZipArchive(outStream, ZipArchiveMode.Create, true))
{
foreach (var file in files)
{
fileInArchive=(archive.CreateEntry(Path.GetFileName(file), CompressionLevel.Optimal));
using (entryStream = fileInArchive.Open())
{
using (var fileToCompressStream = new MemoryStream(byteArray[i]))
{
fileToCompressStream.CopyTo(entryStream);
}
i++;
}
}
}
outStream.Position = 0;
return outStream;
}
If you want , write zip to file stream.
using (var fileStream = new FileStream(@"D:\Tools\DBExtractor\DBExtractor\bin\Debug\test.zip", FileMode.Create))
{
outStream.Position = 0;
outStream.WriteTo(fileStream);
}
`
(select add_date,col2 from table_name)
union
(select add_date,col2 from table_name)
union
(select add_date,col2 from table_name)
order by add_date
Just one more line for @tofutim answer ... if you want custom field name for concatenated row ...
SELECT
(
col1 || '-' || SUBSTR('00' || col2, -2, 2) | '-' || SUBSTR('0000' || col3, -4, 4)
) AS my_column
FROM
mytable;
Tested on SQLite 3.8.8.3, Thanks!
It looks like you're close. Assuming that it's not just a typo in your submission, step 3 should be cd repo2
instead of repo1. And step 6 should be git pull
not push. Reworked list:
1. git clone repo1
2. git clone repo2
3. cd repo2
4. git remote rm origin
5. git remote add repo1
6. git pull
7. git remote rm repo1
8. git remote add newremote
I feel the above answers miss a scenario where this error occurs even when your code has a main(). When you are using JNI that uses Reflection to invoke a method. During runtime if the method is not found, you will get a
java.lang.NoSuchMethodError: No virtual method
Try confirm the data type (SqlDbType) for each parameter in the database and do it this way;
using(SqlConnection connection = new SqlConnection(ConfigurationManager.ConnectionStrings["connSpionshopString"].ConnectionString))
{
connection.Open();
string sql = "INSERT INTO klant(klant_id,naam,voornaam) VALUES(@param1,@param2,@param3)";
using(SqlCommand cmd = new SqlCommand(sql,connection))
{
cmd.Parameters.Add("@param1", SqlDbType.Int).value = klantId;
cmd.Parameters.Add("@param2", SqlDbType.Varchar, 50).value = klantNaam;
cmd.Parameters.Add("@param3", SqlDbType.Varchar, 50).value = klantVoornaam;
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
Suppose logical address space is **32 bit so total possible logical entries will be 2^32 and other hand suppose each page size is 4 byte then size of one page is *2^2*2^10=2^12...* now we know that no. of pages in page table is pages=total possible logical address entries/page size so pages=2^32/2^12 =2^20 Now suppose that each entry in page table takes 4 bytes then total size of page table in *physical memory will be=2^2*2^20=2^22=4mb***
Try this:
ISNULL(IIF (ColunmValue!='',ColunmValue, 'no units exists') , 'no units exists') AS 'ColunmValueName'
Using
find / -name virtualenvwrapper.sh
I got a TON of "permissions denied"s, and exactly one printout of the file location. I missed it until I found that file location when I uninstall/installed it again with pip.
In case you were curious, it was in
/usr/local/share/python/virtualenvwrapper.sh
Based on (dangerouslySetInnerHTML).
It's a prop that does exactly what you want. However they name it to convey that it should be use with caution
You can replace
document.getElementById(this.state.baction).addPrecent(10);
with
this.refs[this.state.baction].addPrecent(10);
<Progressbar completed={25} ref="Progress1" id="Progress1"/>
When I wanted to change namespace and the solution name I did as follows:
1) changed the namespace by selecting it and renaming it and I did the same with solution name
2) clicked on the light bulb and renamed all the instances of old namespace
3) removed all the projects from the solution
4) closed the visual studio
5) renamed all the projects in windows explorer
6) opened visual studio and added all the projects again
7) rename namespaces in all projects in their properties
8) removed bin folder (from all projects)
9) build the project again
That worked for me without any problems and my project had as well source control. All was fine after pushing those changes to the remote.
If you want to make it 2 way binding, you can use [(yourVar)]
, but you have to implement yourVarChange
event and call it everytime your variable change.
Something like this to track the hero change
@Output() heroChange = new EventEmitter();
and then when your hero get changed, call this.heroChange.emit(this.hero);
the [(hero)]
binding will do the rest for you
see example here:
In my case, I had to exclude an older hamcrest from junit-vintage:
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest</artifactId>
<version>2.1</version>
<scope>test</scope>
</dependency>
If you want to display text that cannot be edited or selected you can simply use a label
You can easily enable debugging support using an option for the @EnableWebSecurity annotation:
@EnableWebSecurity(debug = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
…
}
If you need profile-specific control the in your application-{profile}.properties file
org.springframework.security.config.annotation.web.builders.WebSecurity.debugEnabled=false
Get Detailed Post: http://www.bytefold.com/enable-disable-profile-specific-spring-security-debug-flag/
Check your browser settings.
For me, using IE, the fix was to go into Tools/Internet Options, Security tab, for the relevant zone, "custom level" and check the ActiveX settings. Setting "Initialize and script ActiveX controls not marked as safe for scripting" to "Enable" fixed this problem for me.
Set Jquery in scope
$scope.$ = $;
and call in html
ng-click="$('#novoModelo').modal('show')"
Here's another approach:
cond_list = ['cond1 == "val1"','cond2=="val2"','cond3=="val3"','cond4=="val4"']
if all([eval(i) for i in cond_list]):
do something
This also makes it easy to add another condition easily without changing the if statement by simply appending another condition to the list:
cond_list.append('cond5=="val5"')
I believe classification is classifying records in a data set into predefined classes or even defining classes on the go. I look at it as pre-requisite for any valuable data mining, I like to think of it at unsupervised learning i.e. one does not know what he/she is looking for while mining the data and classification serves as a good starting point
Clustering on the other end falls under supervised learning i.e. one know what parameters to look for, the correlation between them along with critical levels. I believe it requires some understanding of statistics and maths
The main answer left out a step for new installs where one has to open up the dbms output window.
Then the script I used:
dbms_output.put_line('Start');
Another script:
set serveroutput on format wrapped;
begin
DBMS_OUTPUT.put_line('jabberwocky');
end;
Your selector for the .show()
and .hide()
are not pointing to anything in the code.
This happened to me because I had a ddd()
or dd()
;die; in my routes/web.php file I forgot about.
I already found the solution to this problem which I forgot to post here.
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Test.class })
public class SampleTest {
@Mock
Person person;
@Test
public void testPrintName() throws Exception {
PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);
Test test= new Test();
test.testMethod();
}
}
Key points to this solution are:
Running my test cases with PowerMockRunner: @RunWith(PowerMockRunner.class)
Instruct Powermock to prepare Test.class
for manipulation of private fields: @PrepareForTest({ Test.class })
And finally mock the constructor for Person class:
PowerMockito.mockStatic(Person.class);
PowerMockito.whenNew(Person.class).withNoArguments().thenReturn(person);
Full disclosure - I'm the author of the previously mentioned talk in TLV DroidCon.
I had a chance to examine this issue across many Android applications, and discuss it with other developers who encountered it - and we all got to the same point: this issue cannot be avoided, only minimized.
I took a closer look at the default implementation of the Android Garbage collector code, to understand better why this exception is thrown and on what could be the possible causes. I even found a possible root cause during experimentation.
The root of the problem is at the point a device "Goes to Sleep" for a while - this means that the OS has decided to lower the battery consumption by stopping most User Land processes for a while, and turning Screen off, reducing CPU cycles, etc. The way this is done - is on a Linux system level where the processes are Paused mid run. This can happen at any time during normal Application execution, but it will stop at a Native system call, as the context switching is done on the kernel level. So - this is where the Dalvik GC joins the story.
The Dalvik GC code (as implemented in the Dalvik project in the AOSP site) is not a complicated piece of code. The basic way it work is covered in my DroidCon slides. What I did not cover is the basic GC loop - at the point where the collector has a list of Objects to finalize (and destroy). The loop logic at the base can be simplified like this:
starting_timestamp
,finalize()
and call native destroy()
if required,end_timestamp
,end_timestamp - starting_timestamp
) and compare against a hard coded timeout value of 10 seconds,java.util.concurrent.TimeoutException
and kill the process.Application runs along doing its thing.
This is not a user facing application, it runs in the background.
During this background operation, objects are created, used and need to be collected to release memory.
Application does not bother with a WakeLock - as this will affect the battery adversely, and seems unnecessary.
This means the Application will invoke the GC from time to time.
Normally the GC runs is completed without a hitch.
Sometimes (very rarely) the system will decide to sleep in the middle of the GC run.
This will happen if you run your application long enough, and monitor the Dalvik memory logs closely.
Now - consider the timestamp logic of the basic GC loop - it is possible for the device to start the run, take a start_stamp
, and go to sleep at the destroy()
native call on a system object.
When it wakes up and resumes the run, the destroy()
will finish, and the next end_stamp
will be the time it took the destroy()
call + the sleep time.
If the sleep time was long (more than 10 seconds), the java.util.concurrent.TimeoutException
will be thrown.
I have seen this in the graphs generated from the analysis python script - for Android System Applications, not just my own monitored apps.
Collect enough logs and you will eventually see it.
The issue cannot be avoided - you will encounter it if your app runs in the background.
You can mitigate by taking a WakeLock, and prevent the device from sleeping, but that is a different story altogether, and a new headache, and maybe another talk in another con.
You can minimize the problem by reducing GC calls - making the scenario less likely (tips are in the slides).
I have not yet had the chance to go over the Dalvik 2 (a.k.a ART) GC code - which boasts a new Generational Compacting feature, or performed any experiments on an Android Lollipop.
Added 7/5/2015:
After reviewing the Crash reports aggregation for this crash type, it looks like these crashes from version 5.0+ of Android OS (Lollipop with ART) only account for 0.5% of this crash type. This means that the ART GC changes has reduced the frequency of these crashes.
Added 6/1/2016:
Looks like the Android project has added a lot of info on how the GC works in Dalvik 2.0 (a.k.a ART).
You can read about it here - Debugging ART Garbage Collection.
It also discusses some tools to get information on the GC behavior for your app.
Sending a SIGQUIT to your app process will essentially cause an ANR, and dump the application state to a log file for analysis.
I can do it using below two methods, using function
def lensort(x):
list1 = []
for i in x:
list1.append([len(i),i])
return sorted(list1)
lista = ['a', 'bb', 'ccc', 'dddd']
a=lensort(lista)
print([l[1] for l in a])
In one Liner using Lambda, as below, a already answered above.
lista = ['a', 'bb', 'ccc', 'dddd']
lista.sort(key = lambda x:len(x))
print(lista)
I was getting the same error message when I tried to change the domain for iframe.src.
For me, the answer was to change the iframe.src to a url on the same domain, but which was actually an html re-direct page to the desired domain. The other domain then showed up in my iframe without any errors.
Worked like a charm.:)
I like the dynamic query way of Dave Rincon as it does not use cursors and is small and easy. Thank you Dave for sharing.
But for my needs on Azure SQL and with a "distinct" in the query, i had to modify the code like this:
Declare @SQL nvarchar(max);
-- Set SQL Variable
-- Prepare exec command for each distinctive tenantid found in Machines
SELECT @SQL = (Select distinct 'exec dbo.sp_S2_Laser_to_cache ' +
convert(varchar(8),tenantid) + ';'
from Dim_Machine
where iscurrent = 1
FOR XML PATH(''))
--for debugging print the sql
print @SQL;
--execute the generated sql script
exec sp_executesql @SQL;
I hope this helps someone...
Same thing happened to me, and I also tried to terminate secondary process from task manager. Do not do that. It is not a solution, but rather a hack which may cause issues later. In my case, I was not even able to uninstall Visual Studio. I tried both web installation and ISO, same issue.
Here is how it worked finally. I restored my Windows 7 to earliest restore point as possible, when there was nothing installed, so I was sure that there would be no conflicts between the different tools (Java, Android API, etc.)
I started the installation of Visual Studio 2015 Community Release Candidate at 10 p.m. At 7 a.m., it was working on Android API 19-21. A hour later, it was finally preparing Visual Studio.
This means that all you need to do is to actually wait 8 to 9 hours. Don't terminate the secondary installer at risk of breaking your Visual Studio; just wait.
SELECT * FROM tableName WHERE columnName LIKE "%#%" OR columnName LIKE "%$%" OR (etc.)
It is used in the stack unwiding tables, which you can see for instance in the assembly output of my answer to another question. As mentioned on that answer, its use is defined by the Itanium C++ ABI, where it is called the Personality Routine.
The reason it "works" by defining it as a global NULL void pointer is probably because nothing is throwing an exception. When something tries to throw an exception, then you will see it misbehave.
Of course, if nothing is using exceptions, you can disable them with -fno-exceptions
(and if nothing is using RTTI, you can also add -fno-rtti
). If you are using them, you have to (as other answers already noted) link with g++
instead of gcc
, which will add -lstdc++
for you.
Check the project properties. It's configurable there if you are using another .net windows application for example
You can use a combination of substring and lastIndexOf
Sample
var fileName = "test.jpg";
var fileExtension = fileName.substring(fileName.lastIndexOf('.') + 1);
this part :
"Your new price is: $"(float(price)
asks python to call this string:
"Your new price is: $"
just like you would a function:
function( some_args)
which will ALWAYS trigger the error:
TypeError: 'str' object is not callable
PHP7, in php.ini file, remove the ";" before extension=openssl
You don't need to encode data that is already encoded. When you try to do that, Python will first try to decode it to unicode
before it can encode it back to UTF-8. That is what is failing here:
>>> data = u'\u00c3' # Unicode data
>>> data = data.encode('utf8') # encoded to UTF-8
>>> data
'\xc3\x83'
>>> data.encode('utf8') # Try to *re*-encode it
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
Just write your data directly to the file, there is no need to encode already-encoded data.
If you instead build up unicode
values instead, you would indeed have to encode those to be writable to a file. You'd want to use codecs.open()
instead, which returns a file object that will encode unicode values to UTF-8 for you.
You also really don't want to write out the UTF-8 BOM, unless you have to support Microsoft tools that cannot read UTF-8 otherwise (such as MS Notepad).
For your MySQL insert problem, you need to do two things:
Add charset='utf8'
to your MySQLdb.connect()
call.
Use unicode
objects, not str
objects when querying or inserting, but use sql parameters so the MySQL connector can do the right thing for you:
artiste = artiste.decode('utf8') # it is already UTF8, decode to unicode
c.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
# ...
c.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
It may actually work better if you used codecs.open()
to decode the contents automatically instead:
import codecs
sql = mdb.connect('localhost','admin','ugo&(-@F','music_vibration', charset='utf8')
with codecs.open('config/index/'+index, 'r', 'utf8') as findex:
for line in findex:
if u'#artiste' not in line:
continue
artiste=line.split(u'[:::]')[1].strip()
cursor = sql.cursor()
cursor.execute('SELECT COUNT(id) AS nbr FROM artistes WHERE nom=%s', (artiste,))
if not cursor.fetchone()[0]:
cursor = sql.cursor()
cursor.execute('INSERT INTO artistes(nom,status,path) VALUES(%s, 99, %s)', (artiste, artiste + u'/'))
artists_inserted += 1
You may want to brush up on Unicode and UTF-8 and encodings. I can recommend the following articles:
Added streaming support based on the answer of @dunes:
import re
from json import JSONDecoder, JSONDecodeError
NOT_WHITESPACE = re.compile(r"[^\s]")
def stream_json(file_obj, buf_size=1024, decoder=JSONDecoder()):
buf = ""
ex = None
while True:
block = file_obj.read(buf_size)
if not block:
break
buf += block
pos = 0
while True:
match = NOT_WHITESPACE.search(buf, pos)
if not match:
break
pos = match.start()
try:
obj, pos = decoder.raw_decode(buf, pos)
except JSONDecodeError as e:
ex = e
break
else:
ex = None
yield obj
buf = buf[pos:]
if ex is not None:
raise ex
If you have already created the table then you can use
To change default value to current date time
ALTER TABLE <TABLE_NAME>
CHANGE COLUMN <COLUMN_NAME> <COLUMN_NAME> DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP;
To change default value to '2015-05-11 13:01:01'
ALTER TABLE <TABLE_NAME>
CHANGE COLUMN <COLUMN_NAME> <COLUMN_NAME> DATETIME NOT NULL DEFAULT '2015-05-11 13:01:01';
Anyone who is wondering how to get the image extension then you can try split method of string on image url:
str_arr = str(img_url).split('.')
img_ext = '.' + str_arr[3] #www.bigbasket.com/patanjali-atta.jpg (jpg is after 3rd dot so)
img_data = requests.get(img_url).content
with open(img_name + img_ext, 'wb') as handler:
handler.write(img_data)
One option would be to exclude all results that contain the directory name with grep. For example:
find . -name '*.js' | grep -v excludeddir
This should do:
gsub("[A-Z][1-9]:", "", string)
gives
[1] "E001" "E002" "E003"
Here's a command I think could be of some help :
apachectl -t -D DUMP_VHOSTS
You'll get a list of all the vhosts, you'll know which one is the default one and you'll make sure that your syntax is correct (same as apachectl configtest suggested by yojimbo87).
You'll also know where each vhost is declared. It can be handy if your config files are a mess. ;)
One very small nit to pick:
The RFC for email addresses allows the first part to include an "@" sign if it is quoted. Example:
"john@work"@myemployer.com
This is quite uncommon, but could happen. Theoretically, you should split on the last "@" symbol, not the first:
SELECT LEN(EmailField) - CHARINDEX('@', REVERSE(EmailField)) + 1
More information:
Just return (number % 10)
; i.e. take the modulus. This will be much faster than parsing in and out of a string.
If number
can be negative then use (Math.abs(number) % 10);
You cannot use IF control block OUTSIDE of functions. So that affects both of your queries.
Turn the EXISTS clause into a subquery instead within an IF function
SELECT IF( EXISTS(
SELECT *
FROM gdata_calendars
WHERE `group` = ? AND id = ?), 1, 0)
In fact, booleans are returned as 1 or 0
SELECT EXISTS(
SELECT *
FROM gdata_calendars
WHERE `group` = ? AND id = ?)
First, don't use * in select, affects their performance and hinder the use of the group by and order by. Try this query:
SELECT wp_posts.post_author, wp_posts.post_date as pdate FROM wp_posts
WHERE wp_posts.post_status='publish'
AND wp_posts.post_type='post'
GROUP BY wp_posts.post_author
ORDER BY pdate DESC
When you don't specifies the table in ORDER BY, just the alias, they will order the result of the select.
<?php
if(isset($_FILES[$input_name]) && is_array($_FILES[$input_name]['name'])){
$image_path = array();
$count = count($_FILES[$input_name]['name']);
for($key =0; $key <$count; $key++){
$_FILES['file']['name'] = $_FILES[$input_name]['name'][$key];
$_FILES['file']['type'] = $_FILES[$input_name]['type'][$key];
$_FILES['file']['tmp_name'] = $_FILES[$input_name]['tmp_name'][$key];
$_FILES['file']['error'] = $_FILES[$input_name]['error'][$key];
$_FILES['file']['size'] = $_FILES[$input_name]['size'][$key];
$config['file_name'] = $_FILES[$input_name]['name'][$key];
$this->upload->initialize($config);
if($this->upload->do_upload('file')) {
$data = $this->upload->data();
$image_path[$key] = $path ."$data[file_name]";
}else{
$error = $this->upload->display_errors();
$this->session->set_flashdata('msg_error',"image upload! ".$error);
}
}
return json_encode($image_path);
}
?>
_x000D_
Be Careful, Follow these steps and save your time
Right Click on your Project Explorer.
Select New-> Project -> Android Application Project from Existing Code
Browse upto this path only - "C:\Users**your path**\Local\Android\android-sdk\extras\google\google_play_services"
Be careful brose only upto - google_play_services and not upto google_play_services_lib
And this way you are able to import the google play service lib.
Let me know if you have any queries regarding the same.
Thanks
As asked for by @??s???? an explanation can be found at https://golang.org/pkg/fmt/#Sprint. Related explanations can be found at https://stackoverflow.com/a/44027953/12817546 and at https://stackoverflow.com/a/42302709/12817546. Here is @Yuanbo's answer in full.
package main
import "fmt"
func main() {
var data interface{} = 2
str := fmt.Sprint(data)
fmt.Println(str)
}
I understand this question is for sql server 2012, but if the same scenario for SQL Server 2017 or SQL Azure you can use Trim
directly as below:
UPDATE *tablename*
SET *columnname* = trim(*columnname*);
I naively do it this way :
<build>
<finalName>osmwse</finalName>
<sourceDirectory>src/main/java, src/interfaces, src/services</sourceDirectory>
</build>
On Angular 6, I access parent properties by injecting the parent via constructor. Not the best solution but it works:
constructor(@Optional() public parentComponentInjectionObject: ParentComponent){
// And access like this:
parentComponentInjectionObject.thePropertyYouWantToAccess;
}
Another way using jQuery:
var exists = false;
$('#yourSelect option').each(function(){
if (this.value == yourValue) {
exists = true;
}
});
In SQL Plus:
SQL> create procedure myproc (prc out sys_refcursor)
2 is
3 begin
4 open prc for select * from emp;
5 end;
6 /
Procedure created.
SQL> var rc refcursor
SQL> execute myproc(:rc)
PL/SQL procedure successfully completed.
SQL> print rc
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
---------- ---------- --------- ---------- ----------- ---------- ---------- ----------
7839 KING PRESIDENT 17-NOV-1981 4999 10
7698 BLAKE MANAGER 7839 01-MAY-1981 2849 30
7782 CLARKE MANAGER 7839 09-JUN-1981 2449 10
7566 JONES MANAGER 7839 02-APR-1981 2974 20
7788 SCOTT ANALYST 7566 09-DEC-1982 2999 20
7902 FORD ANALYST 7566 03-DEC-1981 2999 20
7369 SMITHY CLERK 7902 17-DEC-1980 9988 11 20
7499 ALLEN SALESMAN 7698 20-FEB-1981 1599 3009 30
7521 WARDS SALESMAN 7698 22-FEB-1981 1249 551 30
7654 MARTIN SALESMAN 7698 28-SEP-1981 1249 1400 30
7844 TURNER SALESMAN 7698 08-SEP-1981 1499 0 30
7876 ADAMS CLERK 7788 12-JAN-1983 1099 20
7900 JAMES CLERK 7698 03-DEC-1981 949 30
7934 MILLER CLERK 7782 23-JAN-1982 1299 10
6668 Umberto CLERK 7566 11-JUN-2009 19999 0 10
9567 ALLBRIGHT ANALYST 7788 02-JUN-2009 76999 24 10
my helpful code for others(just one aspx to do text area post)::
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication45.WebForm1" %>
<!DOCTYPE html>
enter code here
<html ng-app="htmldoc" xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script src="angular.min.js"></script>
<script src="angular-sanitize.min.js"></script>
<script>
angular.module('htmldoc', ['ngSanitize']).controller('x', function ($scope, $sce) {
//$scope.htmlContent = '<script> (function () { location = \"http://moneycontrol.com\"; } )()<\/script> In last valid content';
$scope.htmlContent = '';
$scope.withoutSanitize = function () {
return $sce.getTrustedHtml($scope.htmlContent);
};
$scope.postMessage = function () {
var ValidContent = $sce.trustAsHtml($scope.htmlContent);
//your ajax call here
};
});
</script>
</head>
<body>
<form id="form1" runat="server">
Example to show posting valid content to server with two way binding
<div ng-controller="x">
<p ng-bind-html="htmlContent"></p>
<textarea ng-model="htmlContent" ng-trim="false"></textarea>
<button ng-click="postMessage()">Send</button>
</div>
</form>
</body>
</html>
This works perfectly as we want:
Unzip files:
find . -name "*.zip" | xargs -P 5 -I FILENAME sh -c 'unzip -o -d "$(dirname "FILENAME")" "FILENAME"'
Above command does not create duplicate directories.
Remove all zip files:
find . -depth -name '*.zip' -exec rm {} \;
I usually manually set the port that I am listening on in the app.js
file (assuming you are using express.js
var server = app.listen(8080, function() {
console.log('Ready on port %d', server.address().port);
});
This will log Ready on port 8080
to your console.
This will give you DD MM YYYY YY HH Min Sec
variables and works on any Windows machine from XP Pro and later.
@echo off
for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%"
set "datestamp=%YYYY%%MM%%DD%" & set "timestamp=%HH%%Min%%Sec%"
set "fullstamp=%YYYY%-%MM%-%DD%_%HH%-%Min%-%Sec%"
echo datestamp: "%datestamp%"
echo timestamp: "%timestamp%"
echo fullstamp: "%fullstamp%"
pause
To see non-staged (non-added) changes to existing files
git diff
Note that this does not track new files. To see staged, non-commited changes
git diff --cached
I slightly modified the example from Microsoft: https://support.microsoft.com/en-us/kb/319401
This method will only sort once to sort ascending. My modifications make it sort both ways.
public class ListViewItemComparer : IComparer
{
private int col;
bool bAsc = false;
public ListViewItemComparer()
{
col = 0;
}
public ListViewItemComparer(int column, bool b)
{
col = column;
bAsc = b;
}
public int Compare(object x, object y)
{
if (bAsc)
{
return String.Compare(((ListViewItem)x).SubItems[col].Text, ((ListViewItem)y).SubItems[col].Text);
bAsc = false;
}
else
{
return String.Compare(((ListViewItem)y).SubItems[col].Text, ((ListViewItem)x).SubItems[col].Text);
bAsc = true;
}
}
}
Then I create an object of this class whenever a column header is clicked
bool sortAscending = false;
private void inventoryList_ColumnClick(object sender, ColumnClickEventArgs e)
{
if (!sortAscending)
{
sortAscending = true;
}
else
{
sortAscending = false;
}
this.inventoryList.ListViewItemSorter = new ListViewItemComparer(e.Column, sortAscending);
}
Also you can use
dirname(__DIR__, $level)
for access any folding level without traversing
You most likely get this message when the project points to an old location of the assembly where it no longer exists. Since you were able to build it once, the assembly has already been copied into your bin\Debug
/ bin\Release
folders so your project can still find a copy.
If you open the references node of the project in your solution explorer, there should be a yellow icon next to the reference. Remove the reference and add it again from the correct location.
If you want to know the location it was referenced from, you'd have to open the .csproj file in a text editor and look for the HintPath
for that assembly - the IDE for some reason does not show this information.
Yes, it's possible. But first read, "What happens when I change my username?"
To change your username, click your profile picture in the top right corner, then click Settings
. On the left side, click Account
. Then click Change username
.
sys._getframe()
is not guaranteed to be available in all implementations of Python (see ref) ,you can use the traceback
module to do the same thing, eg.
import traceback
def who_am_i():
stack = traceback.extract_stack()
filename, codeline, funcName, text = stack[-2]
return funcName
A call to stack[-1]
will return the current process details.
I've written a simple recursive function that generates file names like Windows does, by appending a sequence number prior to the file extension.
Given a desired file path of C:\MyDir\MyFile.txt
, and the file already exists, it returns a final file path of C:\MyDir\MyFile_1.txt
.
It is called like this:
var desiredPath = @"C:\MyDir\MyFile.txt";
var finalPath = UniqueFileName(desiredPath);
private static string UniqueFileName(string path, int count = 0)
{
if (count == 0)
{
if (!File.Exists(path))
{
return path;
}
}
else
{
var candidatePath = string.Format(
@"{0}\{1}_{2}{3}",
Path.GetDirectoryName(path),
Path.GetFileNameWithoutExtension(path),
count,
Path.GetExtension(path));
if (!File.Exists(candidatePath))
{
return candidatePath;
}
}
count++;
return UniqueFileName(path, count);
}
The usual method is to use the NEWID() function, which generates a unique GUID. So,
SELECT * FROM dbo.Foo ORDER BY NEWID();
Maven is trying to download m2e's lifecycle-mapping artifact, which M2E uses to determine how to process plugins within Eclipse (adding source folders, etc.). For some reason this artifact cannot be downloaded. Do you have an internet connection? Can other artifacts be downloaded from repositories? Proxy settings?
For more details from Maven, try turning M2E debug output on (Settings/Maven/Debug Output checkbox) and it might give you more details as to why it cannot download from the repository.
I used Beetroot-Betroot's solution, but instead of using contains, I used containsNC, which makes it case insensitive.
$.extend($.expr[":"], {
"containsNC": function(elem, i, match, array) {
return (elem.textContent || elem.innerText ||
"").toLowerCase().indexOf((match[3] || "").toLowerCase()) >= 0;
}
});
Try this:
If [ $a -lt 4 ] || [ $a -gt 64 ] ; then \n
Something something \n
elif [ $a -gt 4 ] || [ $a -lt 64 ] ; then \n
Something something \n
else \n
Yes it works for me :) \n
Fought the same problem for about an hour. I finally realized that I was referencing some image files in an xml file that I did not yet have in my R.drawable folder. As soon as I copied the files into the folder, the problem went away. You need to make sure you have all the necessary files present.
please try below code.
background: transparent\0/;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF)progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='image',src='assets/img/bgSmall.png'); /* IE7 */
-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF)progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='image',src='assets/img/bgSmall.png')"; /* IE8 */
There is no exactly destructor class in Java, class destroyed in java automatically by garbage collector . but you could do that using below one but it's not exact same thing :
finalize()
There was a question that spawned in-depth discussion of finalize , so that you should get more depth if required...
when you manually open the IP address (via the RUN command or mapping a network drive), your PC will send your credentials over the pipe and the file server will receive authorization from the DC.
When ASP.Net tries, then it is going to try to use the IIS worker user (unless impersonation is turned on which will list a few other issues). Traditionally, the IIS worker user does not have authorization to work across servers (or even in other folders on the web server).
I wanted a pure html approach as I wanted to collapse and expand html that was added on the fly via a template! I came up with this...
https://jsfiddle.net/3mguht2y/1/
var noJavascript = ":)";
Which might be of use to someone :)
You can achieve LinearLayout cascading like this:
LinearLayout root = (LinearLayout) findViewById(R.id.my_root);
LinearLayout llay1 = new LinearLayout(this);
root.addView(llay1);
LinearLayout llay2 = new LinearLayout(this);
llay1.addView(llay2);