While others have correctly suggested the use of array_multisort()
, for some reason no answer seems to acknowledge the existence of array_column()
, which can greatly simplify the solution. So my suggestion would be:
array_multisort(array_column($inventory, 'price'), SORT_DESC, $inventory);
Try:
which( !is.na(p), arr.ind=TRUE)
Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:
> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3
[[2]]
[1] 4 7
[[3]]
integer(0)
[[4]]
[1] 5
[[5]]
integer(0)
Or even with smushing together with paste:
lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")
The output from which
function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:
> which( !is.na(p), arr.ind=TRUE)
row col
[1,] 1 2
[2,] 1 3
[3,] 2 4
[4,] 4 5
[5,] 2 7
Without the arr.ind
parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".
> which( !is.na(p) )
[1] 6 11 17 24 32
I've just noticed that the answer that I upvoted and commented on is ambiguous. So the following is exactly what worked for me. I'm currently on Moment 2.26.0
and TS 3.8.3
:
In code:
import moment from 'moment';
In TS config:
{
"compilerOptions": {
"esModuleInterop": true,
...
}
}
I am building for both CommonJS and EMS so this config is imported into other config files.
The insight comes from this answer which relates to using Express. I figured it was worth adding here though, to help anyone who searches in relation to Moment.js, rather than something more general.
while on branch master:
git reset --hard origin/master
then do some clean up with git gc
(more about this in the man pages)
Update: You will also probably need to do a git fetch origin
(or git fetch origin master
if you only want that branch); it should not matter if you do this before or after the reset. (Thanks @eric-walker)
The solution with TextBoxFor is OK, but if you don't want to see the field like EditBox stylish (it might be a little confusing for the user) involve changes as follows:
Razor code before changes
<div class="editor-field">
@Html.EditorFor(model => model.Text)
@Html.ValidationMessageFor(model => model.Text)
</div>
After changes
<!-- New div display-field (after div editor-label) -->
<div class="display-field">
@Html.DisplayFor(model => model.Text)
</div>
<div class="editor-field">
<!-- change to HiddenFor in existing div editor-field -->
@Html.HiddenFor(model => model.Text)
@Html.ValidationMessageFor(model => model.Text)
</div>
Generally, this solution prevents field from editing, but shows value of it. There is no need for code-behind modifications.
$( document.activeElement )
Will retrieve it without having to search the whole DOM tree as recommended on the jQuery documentation
<img src="file://C:/wamp/www/site/img/mypicture.jpg"/>
A very simple solution is put the below code in your .htaccess
. I had the same issue and it solve my problem.
<IfModule mod_alias.c>
RedirectMatch 403 favicon.ico
</IfModule>
Reference: http://perishablepress.com/block-favicon-url-404-requests/
This is somewhat tricky since PHP gets evaluated server-side and javascript gets evaluated client side.
I would call your PHP file using an AJAX call from inside javascript and then use JS to insert the returned HTML somewhere on your page.
Info thanks to Bill Hernandez. I added some preferences I'm adopting.
#!/bin/bash
function Usage(){
echo " Usage: show_parameters [ arg1 ][ arg2 ]"
}
[[ ${#2} -eq 0 ]] && Usage || {
echo
echo "# arguments called with ----> ${@} "
echo "# \$1 -----------------------> $1 "
echo "# \$2 -----------------------> $2 "
echo "# path to me ---------------> ${0} " | sed "s/$USER/\$USER/g"
echo "# parent path --------------> ${0%/*} " | sed "s/$USER/\$USER/g"
echo "# my name ------------------> ${0##*/} "
echo
}
Cheers
You need to install the "xlrd" lib
For Linux (Ubuntu and Derivates):
Installing via pip: python -m pip install --user xlrd
Install system-wide via a Linux package manager: *sudo apt-get install python-xlrd
Windows:
Installing via pip: *pip install xlrd
Download the files: https://pypi.org/project/xlrd/
I know this is an old question, but thought that I should anyway present the simple solution using the paste() function as suggested to by the questioner:
data_1<-data.frame(a=data$a,"x"=paste(data$b,data$c,data$d,sep="-"))
data_1
a x
1 1 a-d-g
2 2 b-e-h
3 3 c-f-i
If one wants to create Java object from JSON and vice versa, use GSON or JACKSON third party jars etc.
//from object to JSON
Gson gson = new Gson();
gson.toJson(yourObject);
// from JSON to object
yourObject o = gson.fromJson(JSONString,yourObject.class);
But if one just want to parse a JSON string and get some values, (OR create a JSON string from scratch to send over wire) just use JaveEE jar which contains JsonReader, JsonArray, JsonObject etc. You may want to download the implementation of that spec like javax.json. With these two jars I am able to parse the json and use the values.
These APIs actually follow the DOM/SAX parsing model of XML.
Response response = request.get(); // REST call
JsonReader jsonReader = Json.createReader(new StringReader(response.readEntity(String.class)));
JsonArray jsonArray = jsonReader.readArray();
ListIterator l = jsonArray.listIterator();
while ( l.hasNext() ) {
JsonObject j = (JsonObject)l.next();
JsonObject ciAttr = j.getJsonObject("ciAttributes");
given the sorted content of your array, there is an even faster method: searchsorted.
import time
N = 10000
aa = np.arange(-N,N)
%timeit np.searchsorted(aa, N/2)+1
%timeit np.argmax(aa>N/2)
%timeit np.where(aa>N/2)[0][0]
%timeit np.nonzero(aa>N/2)[0][0]
# Output
100000 loops, best of 3: 5.97 µs per loop
10000 loops, best of 3: 46.3 µs per loop
10000 loops, best of 3: 154 µs per loop
10000 loops, best of 3: 154 µs per loop
This is borderline programming, but look into using tr:
$ echo "this is just a test" | tr -s ' ' | tr ' ' '_'
Should do it. The first invocation squeezes the spaces down, the second replaces with underscore. You probably need to add TABs and other whitespace characters, this is for spaces only.
Copy the contents of /var/lib/mongodb
to /data/db
. The files you should be looking for should have names like your_db_name.ns
and your_dbname.n
where n
is a number starting with 0. If you do not see such files under /var/lib/mongodb
, search for them on your filesystem.
Once copied over, use --dbpath=/data/db
when starting MongoDB via the mongod
command.
Clickable smartphone link code:
The following link can be used to make a clickable phone link. You can copy the code below and paste it into your webpage, then edit with your phone number. This code may not work on all phones but does work for iPhone, Droid / Android, and Blackberry.
<a href="tel:1-847-555-5555">1-847-555-5555</a>
Phone number links can be used with the dashes, as shown above, or without them as well as in the following example:
<a href="tel:18475555555">1-847-555-5555</a>
It is also possible to use any text in the link as long as the phone number is set up with the "tel:18475555555" as in this example:
<a href="tel:18475555555">Click Here To Call Support 1-847-555-5555</a>
Below is a clickable telephone hyperlink you can check out. In most non-phone browsers this link will give you a "The webpage cannot be displayed" error or nothing will happen.
NOTE: The iPhone Safari browser will automatically detect a phone number on a page and will convert the text into a call link without using any of the code on this page.
WTAI smartphone link code: The WTAI or "Wireless Telephony Application Interface" link code is shown below. This code is considered to be the correct mobile phone protocol and will work on smartphones like Droid, however, it may not work for Apple Safari on iPhone and the above code is recommended.
<a href="wtai://wp/mc;18475555555">Click Here To Call Support 1-847-555-5555</a>
I run selenium tests with Jenkins running on an Ubuntu 18 LTS linux. I had this error until I added the argument 'headless' like this (and some other arguments):
ChromeOptions options = new ChromeOptions();
options.addArguments("headless"); // headless -> no browser window. needed for jenkins
options.addArguments("disable-infobars"); // disabling infobars
options.addArguments("--disable-extensions"); // disabling extensions
options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
options.addArguments("--no-sandbox"); // Bypass OS security model
ChromeDriver driver = new ChromeDriver(options);
driver.get("www.google.com");
OO Abstraction occurs during class level design, with the objective of hiding the implementation complexity of how the the features offered by an API / design / system were implemented, in a sense simplifying the 'interface' to access the underlying implementation.
The process of abstraction can be repeated at increasingly 'higher' levels (layers) of classes, which enables large systems to be built without increasing the complexity of code and understanding at each layer.
For example, a Java developer can make use of the high level features of FileInputStream without concern for how it works (i.e. file handles, file system security checks, memory allocation and buffering will be managed internally, and are hidden from consumers). This allows the implementation of FileInputStream
to be changed, and as long as the API (interface) to FileInputStream
remains consistent, code built against previous versions will still work.
Similarly, when designing your own classes, you will want to hide internal implementation details from others as far as possible.
In the Booch definition1, OO Encapsulation is achieved through Information Hiding, and specifically around hiding internal data (fields / members representing the state) owned by a class instance, by enforcing access to the internal data in a controlled manner, and preventing direct, external change to these fields, as well as hiding any internal implementation methods of the class (e.g. by making them private).
For example, the fields of a class can be made private
by default, and only if external access to these was required, would a get()
and/or set()
(or Property
) be exposed from the class. (In modern day OO languages, fields can be marked as readonly
/ final
/ immutable
which further restricts change, even within the class).
Example where NO information hiding has been applied (Bad Practice):
class Foo {
// BAD - NOT Encapsulated - code external to the class can change this field directly
// Class Foo has no control over the range of values which could be set.
public int notEncapsulated;
}
Example where field encapsulation has been applied:
class Bar {
// Improvement - access restricted only to this class
private int encapsulatedPercentageField;
// The state of Bar (and its fields) can now be changed in a controlled manner
public void setEncapsulatedField(int percentageValue) {
if (percentageValue >= 0 && percentageValue <= 100) {
encapsulatedPercentageField = percentageValue;
}
// else throw ... out of range
}
}
Example of immutable / constructor-only initialization of a field:
class Baz {
private final int immutableField;
public void Baz(int onlyValue) {
// ... As above, can also check that onlyValue is valid
immutableField = onlyValue;
}
// Further change of `immutableField` outside of the constructor is NOT permitted, even within the same class
}
Re : Abstraction vs Abstract Class
Abstract classes are classes which promote reuse of commonality between classes, but which themselves cannot directly be instantiated with new()
- abstract classes must be subclassed, and only concrete
(non abstract) subclasses may be instantiated. Possibly one source of confusion between Abstraction
and an abstract class
was that in the early days of OO, inheritance was more heavily used to achieve code reuse (e.g. with associated abstract base classes). Nowadays, composition is generally favoured over inheritance, and there are more tools available to achieve abstraction, such as through Interfaces, events / delegates / functions, traits / mixins etc.
Re : Encapsulation vs Information Hiding
The meaning of encapsulation appears to have evolved over time, and in recent times, encapsulation
can commonly also used in a more general sense when determining which methods, fields, properties, events etc to bundle into a class.
Quoting Wikipedia:
In the more concrete setting of an object-oriented programming language, the notion is used to mean either an information hiding mechanism, a bundling mechanism, or the combination of the two.
For example, in the statement
I've encapsulated the data access code into its own class
.. the interpretation of encapsulation is roughly equivalent to the Separation of Concerns or the Single Responsibility Principal (the "S" in SOLID), and could arguably be used as a synonym for refactoring.
[1] Once you've seen Booch's encapsulation cat picture you'll never be able to forget encapsulation - p46 of Object Oriented Analysis and Design with Applications, 2nd Ed
For me "Restarting Mac System" got worked
If you want to allow all origins and keep credentials true, this worked for me:
app.use(cors({
origin: function(origin, callback){
return callback(null, true);
},
optionsSuccessStatus: 200,
credentials: true
}));
import time
now = time.time()
future = now + 10
while time.time() < future:
# do stuff
pass
Alternatively, if you've already got your loop:
while True:
if time.time() > future:
break
# do other stuff
This method works well with pygame, since it pretty much requires you to have a big main loop.
As you've noticed, you have no selectivity to your update statement so it is updating your entire table. If you want to update specific rows (ie where the IDs match) you probably want to do a coordinated subquery.
However, since you are using Oracle, it might be easier to create a materialized view for your query table and let Oracle's transaction mechanism handle the details. MVs work exactly like a table for querying semantics, are quite easy to set up, and allow you to specify the refresh interval.
Put it into a ScrollViewer
.
Instead of Googling for %02d
you should have been searching for sprintf()
function.
%02d
means "format the integer with 2 digits, left padding it with zeroes", so:
Format Data Result %02d 1 01 %02d 11 11
I have a button for a prompt that on click it opens the display dialogue and then I can write what I want to search and it goes to that location on the page. It uses javascript to answer the header.
On the .html file I have:
<button onclick="myFunction()">Load Prompt</button>
<span id="test100"><h4>Hello</h4></span>
On the .js file I have
function myFunction() {
var input = prompt("list or new or quit");
while(input !== "quit") {
if(input ==="test100") {
window.location.hash = 'test100';
return;
// else if(input.indexOf("test100") >= 0) {
// window.location.hash = 'test100';
// return;
// }
}
}
}
When I write test100 into the prompt, then it will go to where I have placed span id="test100" in the html file.
I use Google Chrome.
Note: This idea comes from linking on the same page using
<a href="#test100">Test link</a>
which on click will send to the anchor. For it to work multiple times, from experience need to reload the page.
Credit to the people at stackoverflow (and possibly stackexchange, too) can't remember how I gathered all the bits and pieces. ?
Hibernate queries are case sensitive with property names (because they end up relying on getter/setter methods on the @Entity
).
Make sure you refer to the property as fileName
in the Criteria query, not filename
.
Specifically, Hibernate will call the getter method of the filename
property when executing that Criteria query, so it will look for a method called getFilename()
. But the property is called FileName
and the getter getFileName()
.
So, change the projection like so:
criteria.setProjection(Projections.property("fileName"));
This is working for me.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/rell_main_bg"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#096d74" >
<ImageView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
android:src="@drawable/img_logo_large"
android:contentDescription="@null" />
</RelativeLayout>
In kotlin for making the textview scrollable
myTextView.movementMethod= ScrollingMovementMethod()
and also add in xml this property
android:scrollbars = "vertical"
This works:
<img src="invalid_link"
onerror="this.onerror=null;this.src='https://placeimg.com/200/300/animals';"
>
Live demo: http://jsfiddle.net/oLqfxjoz/
As Nikola pointed out in the comment below, in case the backup URL is invalid as well, some browsers will trigger the "error" event again which will result in an infinite loop. We can guard against this by simply nullifying the "error" handler via this.onerror=null;
.
@HostBinding
: This decorator binds a class property to a property of the host element.@HostListener
: This decorator binds a class method to an event of the host element.import { Component, HostListener, HostBinding } from '@angular/core';
@Component({
selector: 'app-root',
template: `<p>This is nice text<p>`,
})
export class AppComponent {
@HostBinding('style.color') color;
@HostListener('click')
onclick() {
this.color = 'blue';
}
}
In the above example the following occurs:
color
property in our AppComponent
class is bound to the style.color
property on the component. So whenever the color
property is updated so will the style.color
property of our component@Directive
:Although it can be used on component these decorators are often used in a attribute directives. When used in an @Directive
the host changes the element on which the directive is placed. For example take a look at this component template:
<p p_Dir>some paragraph</p>
Here p_Dir is a directive on the <p>
element. When @HostBinding
or @HostListener
is used within the directive class the host will now refer to the <p>
.
You can try this with your nav div
:
postion: fixed;
top: 0;
width: 100%;
holy errors The reason for the code below is to show how to not void main every function and not to type return; for functions...... instead push everything into the sediment for which is the print function prototype... if you need to use useful functions ... you will have to below..... (p.s. this below is for people overwhelmed by these object and T templates which allow different variable declaration types(such as float and char) to use the same passed by value in a user defined function)
char arr[ ] = "This is a test";
string str(arr);
// You can also assign directly to a string.
str = "This is another string";
can anyone tell me why c++ made arrays into pass by value one at a time and the only way to eliminate spaces and punctuation is the use of string tokens. I couldn't get around the problem when i was trying to delete spaces for a palindrome...
#include <iostream>
#include <iomanip>
using namespace std;
int getgrades(float[]);
int getaverage(float[], float);
int calculateletters(float[], float, float, float[]);
int printResults(float[], float, float, float[]);
int main()
{
int i;
float maxSize=3, size;
float lettergrades[5], numericgrades[100], average;
size=getgrades(numericgrades);
average = getaverage(numericgrades, size);
printResults(numericgrades, size, average, lettergrades);
return 0;
}
int getgrades(float a[])
{
int i, max=3;
for (i = 0; i <max; i++)
{
//ask use for input
cout << "\nPlease Enter grade " << i+1 << " : ";
cin >> a[i];
//makes sure that user enters a vlue between 0 and 100
if(a[i] < 0 || a[i] >100)
{
cout << "Wrong input. Please
enter a value between 0 and 100 only." << endl;
cout << "\nPlease Reenter grade " << i+1 << " : ";
cin >> a[i];
return i;
}
}
}
int getaverage(float a[], float n)
{
int i;
float sum = 0;
if (n == 0)
return 0;
for (i = 0; i < n; i++)
sum += a[i];
return sum / n;
}
int printResults(float a[], float n, float average, float letters[])
{
int i;
cout << "Index Number | input |
array values address in memory " << endl;
for (i = 0; i < 3; i++)
{
cout <<" "<< i<<" \t\t"<<setprecision(3)<<
a[i]<<"\t\t" << &a[i] << endl;
}
cout<<"The average of your grades is: "<<setprecision(3)<<average<<endl;
}
how can I fill a multidimensional array in Java without using a loop?
Multidimensional arrays are just arrays of arrays and fill(...)
doesn't check the type of the array and the value you pass in (this responsibility is upon the developer).
Thus you can't fill a multidimensional array reasonably well without using a loop.
Be aware of the fact that, unlike languages like C or C++, Java arrays are objects and in multidimensional arrays all but the last level contain references to other Array
objects. I'm not 100% sure about this, but most likely they are distributed in memory, thus you can't just fill a contiguous block without a loop, like C/C++ would allow you to do.
import java.util.ArrayList;
import java.util.List;
class ArrLst{
public static void main(String args[]){
List l=new ArrayList();
l.add(10);
l.add(11);
l.add(12);
l.add(13);
l.add(14);
l.forEach((a)->System.out.println(a));
}
}
When you declare:
new Vue({
el: '#app',
data () {
return {}
}
)}
That is typically your root Vue instance that the rest of the application descends from. This hangs off the root element declared in an html document, for example:
<html>
...
<body>
<div id="app"></div>
</body>
</html>
The other syntax is declaring a component which can be registered and reused later. For example, if you create a single file component like:
// my-component.js
export default {
name: 'my-component',
data () {
return {}
}
}
You can later import this and use it like:
// another-component.js
<template>
<my-component></my-component>
</template>
<script>
import myComponent from 'my-component'
export default {
components: {
myComponent
}
data () {
return {}
}
...
}
</script>
Also, be sure to declare your data
properties as functions, otherwise they are not going to be reactive.
Yes, we can run docker in docker, we'll need to attach the unix sockeet "/var/run/docker.sock" on which the docker daemon listens by default as volume to the parent docker using "-v /var/run/docker.sock:/var/run/docker.sock". Sometimes, permissions issues may arise for docker daemon socket for which you can write "sudo chmod 757 /var/run/docker.sock".
And also it would require to run the docker in privileged mode, so the commands would be:
sudo chmod 757 /var/run/docker.sock
docker run --privileged=true -v /var/run/docker.sock:/var/run/docker.sock -it ...
Assume if all the input elements are inside a form u can refer the below code.
// get all the inputs into an array.
var $inputs = $('#myForm :input');
// not sure if you wanted this, but I thought I'd add it.
// get an associative array of just the values.
var values = {};
$inputs.each(function() {
values[this.name] = $(this).val();
});
As is defined in RFC 1341:
In the Extended BNF notation of RFC 822, a Content-Type header field value is defined as follows:
Content-Type := type "/" subtype *[";" parameter]
type := "application" / "audio" / "image" / "message" / "multipart" / "text" / "video" / x-token
x-token := < The two characters "X-" followed, with no intervening white space, by any token >
subtype := token
parameter := attribute "=" value
attribute := token
value := token / quoted-string
token := 1*
tspecials := "(" / ")" / "<" / ">" / "@" ; Must be in / "," / ";" / ":" / "\" / <"> ; quoted-string, / "/" / "[" / "]" / "?" / "." ; to use within / "=" ; parameter values
And a list of known MIME types that can follow it (or, as Joe remarks, the IANA source).
As you can see the list is way too big for you to validate against all of them. What you can do is validate against the general format and the type
attribute to make sure that is correct (the set of options is small) and just assume that what follows it is correct (and of course catch any exceptions you might encounter when you put it to actual use).
Also note the comment above:
If another primary type is to be used for any reason, it must be given a name starting with "X-" to indicate its non-standard status and to avoid any potential conflict with a future official name.
You'll notice that a lot of HTTP requests/responses include an X-
header of some sort which are self defined, keep this in mind when validating the types.
You can use closures to pass parameters:
iframe.document.addEventListener('click', function(event) {clic(this.id);}, false);
However, I recommend that you use a better approach to access your frame (I can only assume that you are using the DOM0 way of accessing frame windows by their name - something that is only kept around for backwards compatibility):
document.getElementById("myFrame").contentDocument.addEventListener(...);
My guess is that the system-status
element is declared after the variable declaration is run. Thus, at the time the variable is declared, it is actually being set to null?
You should declare it only, then assign its value from an onLoad
handler instead, because then you will be sure that it has properly initialized (loaded) the element in question.
You could also try putting the script at the bottom of the page (or at least somewhere after the system-status
element is declared) but it's not guaranteed to always work.
The basic purpose of ValidateAntiForgeryToken attribute is to prevent cross-site request forgery attacks.
A cross-site request forgery is an attack in which a harmful script element, malicious command, or code is sent from the browser of a trusted user. For more information on this please visit http://www.asp.net/mvc/overview/security/xsrfcsrf-prevention-in-aspnet-mvc-and-web-pages.
It is simple to use, you need to decorate method with ValidateAntiForgeryToken attribute as below:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult CreateProduct(Product product)
{
if (ModelState.IsValid)
{
//your logic
}
return View(ModelName);
}
It is derived from System.Web.Mvc namespace.
And in your view, add this code to add the token so it is used to validate the form upon submission.
@Html.AntiForgeryToken()
I had a similar issue, and my solution is ugly, but it works:
void showCode() {
hideRegisterMessage(); // Hides view
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
showRegisterMessage(); // Shows view
}
}, 3000); // After 3 seconds
}
The <b> tag is alive and well. <b> is not deprecated, but its use has been clarified and limited. <b> has no semantic meaning, nor does it convey vocal emphasis such as might be spoken by a screen reader. <b> does, however, convey printed empasis, as does the <i> tag. Both have a specific place in typograpghy, but not in spoken communication, mes frères.
To quote from http://www.whatwg.org/
The b element represents a span of text to be stylistically offset from the normal prose without conveying any extra importance, such as key words in a document abstract, product names in a review, or other spans of text whose typical typographic presentation is boldened.
You have to add empty option to solve it,
I also can give you one more solution but its up to you that is fine for you or not Because User select default option after selecting other options than jsFunction will be called twice.
<select onChange="jsFunction()" id="selectOpt">
<option value="1" onclick="jsFunction()">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
function jsFunction(){
var myselect = document.getElementById("selectOpt");
alert(myselect.options[myselect.selectedIndex].value);
}
If you move your for loop, you won't have to make multiple connections. Just a quick edit to your code block (by no means completely correct):
string StrQuery;
try
{
using (SqlConnection conn = new SqlConnection(ConnString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = conn;
conn.Open();
for(int i=0; i< dataGridView1.Rows.Count;i++)
{
StrQuery= @"INSERT INTO tableName VALUES ("
+ dataGridView1.Rows[i].Cells["ColumnName"].Text+", "
+ dataGridView1.Rows[i].Cells["ColumnName"].Text+");";
comm.CommandText = StrQuery;
comm.ExecuteNonQuery();
}
}
}
}
As to executing multiple SQL commands at once, please look at this link: Multiple statements in single SqlCommand
Prevent saving changes that require table re-creation
Five swift clicks
- Tools
- Options
- Designers
- Prevent saving changes that require table re-creation
- OK.
After saving, repeat the proceudure to re-tick the box. This safe-guards against accidental data loss.
Further explanation
By default SQL Server Management Studio prevents the dropping of tables, because when a table is dropped its data contents are lost.*
When altering a column's datatype in the table Design view, when saving the changes the database drops the table internally and then re-creates a new one.
*Your specific circumstances will not pose a consequence since your table is empty. I provide this explanation entirely to improve your understanding of the procedure.
Currently, Macports has many more packages (~18.6 K) than there are Homebrew formulae (~3.1K), owing to its maturity. Homebrew is slowly catching up though.
Macport packages tend to be maintained by a single person.
Macports can keep multiple versions of packages around, and you can enable or disable them to test things out. Sometimes this list can get corrupted and you have to manually edit it to get things back in order, although this is not too hard.
Both package managers will ask to be regularly updated. This can take some time.
Note: you can have both package managers on your system! It is not one or the other. Brew might complain but Macports won't.
Also, if you are dealing with python or ruby packages, use a virtual environment wherever possible.
Check if the file path is correct and the file exists - in my case that was the issue - as I fixed it, the error disappeared
Input Dimension Clarified:
Not a direct answer, but I just realized the word Input Dimension could be confusing enough, so be wary:
It (the word dimension alone) can refer to:
a) The dimension of Input Data (or stream) such as # N of sensor axes to beam the time series signal, or RGB color channel (3): suggested word=> "InputStream Dimension"
b) The total number /length of Input Features (or Input layer) (28 x 28 = 784 for the MINST color image) or 3000 in the FFT transformed Spectrum Values, or
"Input Layer / Input Feature Dimension"
c) The dimensionality (# of dimension) of the input (typically 3D as expected in Keras LSTM) or (#RowofSamples, #of Senors, #of Values..) 3 is the answer.
"N Dimensionality of Input"
d) The SPECIFIC Input Shape (eg. (30,50,50,3) in this unwrapped input image data, or (30, 250, 3) if unwrapped Keras:
Keras has its input_dim refers to the Dimension of Input Layer / Number of Input Feature
model = Sequential()
model.add(Dense(32, input_dim=784)) #or 3 in the current posted example above
model.add(Activation('relu'))
In Keras LSTM, it refers to the total Time Steps
The term has been very confusing, is correct and we live in a very confusing world!!
I find one of the challenge in Machine Learning is to deal with different languages or dialects and terminologies (like if you have 5-8 highly different versions of English, then you need to very high proficiency to converse with different speakers). Probably this is the same in programming languages too.
Just install package Synced?Sidebar?Bg:it will change the sidebar theme based on current color scheme.But it seems that every time you change the color scheme,sidebar will be changed after you open file Preferences.sublime-settings
If you use Maven:
poi => poi-ooxml in artifactId
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.12</version>
</dependency>
The problems here are to do with the npm node-gyp module
I found the solutions offered on the build page for that project effective.
There's a fully automatic way and a manual way.
Try Collections.shuffle(list).If usage of this method is barred for solving the problem, then one can look at the actual implementation.
Very Late Answer but I will highlight some point as I had to deal with it years ago setting up my IIS site across network
168.192.x.x
or via http://his-pc-name
(do not forget the http part)Make sure your IIS is working fine on remote machine by checking localhost
which should served the default site. Also make sure your firewall is configured to allow connection via port 80 or you can just disable firewall for the time being for testing purposes.
I've seen a bunch of partial answers while researching this topic. This is what worked for me and hope it helps others. This command will display output on the command line, showing the revision number, author, revision timestamp and changes made:
svn blame -v <filename>
To make your search easier, you can write the output to a file and grep for what you're looking for.
Taking as a given you have a "large" number of data.frames with similar names (here d# where # is some positive integer), the following is a slight improvement of @mark-miller's method. It is more terse and returns a named list of data.frames, where each name in the list is the name of the corresponding original data.frame.
The key is using mget
together with ls
. If the data frames d1 and d2 provided in the question were the only objects with names d# in the environment, then
my.list <- mget(ls(pattern="^d[0-9]+"))
which would return
my.list
$d1
y1 y2
1 1 4
2 2 5
3 3 6
$d2
y1 y2
1 3 6
2 2 5
3 1 4
This method takes advantage of the pattern argument in ls
, which allows us to use regular expressions to do a finer parsing of the names of objects in the environment. An alternative to the regex "^d[0-9]+$"
is "^d\\d+$"
.
As @gregor points out, it is a better overall to set up your data construction process so that the data.frames are put into named lists at the start.
data
d1 <- data.frame(y1 = c(1,2,3),y2 = c(4,5,6))
d2 <- data.frame(y1 = c(3,2,1),y2 = c(6,5,4))
I see a lot of answers here that have you subtracting from the width of the div and/or using box-sizing, but all you need to do is apply the padding the child elements of the div in question. So, for example, if you have some markup like this:
<div id="container">
<p id="text">Find Agents</p>
</div>
All you need to do is apply this CSS:
#text {
padding: 10px;
}
Here is a fiddle showing the difference: http://jsfiddle.net/CHCVF/2/
Or, better yet, if you have multiple elements and don't feel like giving them all the same class, you can do something like this:
.container * {
padding: 5px 10px;
}
Which will select all of the child elements and assign them the padding you want. Here is a fiddle of that in action: http://jsfiddle.net/CHCVF/3/
I'm using this
DELETE TableA
FROM TableA a
INNER JOIN
TableB b on b.Bid = a.Bid
AND [condition]
and @TheTXI way is good as enough but I read answers and comments and I found one things must be answered is using condition in WHERE clause or as join condition. So I decided to test it and write an snippet but didn't find a meaningful difference between them. You can see sql script here and important point is that I preferred to write it as commnet because of this is not exact answer but it is large and can't be put in comments, please pardon me.
Declare @TableA Table
(
aId INT,
aName VARCHAR(50),
bId INT
)
Declare @TableB Table
(
bId INT,
bName VARCHAR(50)
)
Declare @TableC Table
(
cId INT,
cName VARCHAR(50),
dId INT
)
Declare @TableD Table
(
dId INT,
dName VARCHAR(50)
)
DECLARE @StartTime DATETIME;
SELECT @startTime = GETDATE();
DECLARE @i INT;
SET @i = 1;
WHILE @i < 1000000
BEGIN
INSERT INTO @TableB VALUES(@i, 'nameB:' + CONVERT(VARCHAR, @i))
INSERT INTO @TableA VALUES(@i+5, 'nameA:' + CONVERT(VARCHAR, @i+5), @i)
SET @i = @i + 1;
END
SELECT @startTime = GETDATE()
DELETE a
--SELECT *
FROM @TableA a
Inner Join @TableB b
ON a.BId = b.BId
WHERE a.aName LIKE '%5'
SELECT Duration = DATEDIFF(ms,@StartTime,GETDATE())
SET @i = 1;
WHILE @i < 1000000
BEGIN
INSERT INTO @TableD VALUES(@i, 'nameB:' + CONVERT(VARCHAR, @i))
INSERT INTO @TableC VALUES(@i+5, 'nameA:' + CONVERT(VARCHAR, @i+5), @i)
SET @i = @i + 1;
END
SELECT @startTime = GETDATE()
DELETE c
--SELECT *
FROM @TableC c
Inner Join @TableD d
ON c.DId = d.DId
AND c.cName LIKE '%5'
SELECT Duration = DATEDIFF(ms,@StartTime,GETDATE())
If you could get good reason from this script or write another useful, please share. Thanks and hope this help.
I couldn't find an off-the-shelf module that added this function, so I wrote one:
In Access, go to the Database Tools ribbon, in the Macro area click into Visual Basic. In the top left Project area, right click the name of your file and select Insert -> Module. In the module paste this:
Public Function Substring_Index(strWord As String, strDelim As String, intCount As Integer) As String
Substring_Index = delims
start = 0
test = ""
For i = 1 To intCount
oldstart = start + 1
start = InStr(oldstart, strWord, strDelim)
Substring_Index = Mid(strWord, oldstart, start - oldstart)
Next i
End Function
Save the module as module1 (the default). You can now use statements like:
SELECT Substring_Index([fieldname],",",2) FROM table
If you are not using jQuery I would suggest using it. If you do, you would want to do something like:
$( 'button' ).on(
'click'
function ( )
{
$( this ).hide( );
}
);
To clarify for the Python 2.x line, /
is neither floor division nor true division.
/
is floor division when both args are int
, but is true division when either of the args are float
.
There are several ways to implement modules in JavaScript. Here are the two most popular ones:
Browsers do not support this moduling system yet, so in order for you to use this syntax you must use a bundler like Webpack. Using a bundler is better anyway because this can combine all of your different files into a single (or a couple of related) files. This will serve the files from the server to the client faster because each HTTP request has some associated overhead accompanied with it. Thus by reducing the overall HTTP request we improve the performance. Here is an example of ES6 modules:
// main.js file
export function add (a, b) {
return a + b;
}
export default function multiply (a, b) {
return a * b;
}
// test.js file
import {add}, multiply from './main'; // For named exports between curly braces {export1, export2}
// For default exports without {}
console.log(multiply(2, 2)); // logs 4
console.log(add(1, 2)); // logs 3
This moduling system is used in Node.js. You basically add your exports to an object which is called module.exports
. You then can access this object via a require('modulePath')
. Important here is to realize that these modules are being cached, so if you require()
a certain module twice it will return the already created module.
// main.js file
function add (a, b) {
return a + b;
}
module.exports = add; // Here we add our 'add' function to the exports object
// test.js file
const add = require('./main');
console.log(add(1,2)); // logs 3
Following documentation from @Kevin's answer the below one worked for me for setting environment variable with maven sure-fire plugin
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<environmentVariables>
<WSNSHELL_HOME>conf</WSNSHELL_HOME>
</environmentVariables>
</configuration>
I create a block to reset all my sequences:
DECLARE
I_val number;
BEGIN
FOR US IN
(SELECT US.SEQUENCE_NAME FROM USER_SEQUENCES US)
LOOP
execute immediate 'select ' || US.SEQUENCE_NAME || '.nextval from dual' INTO l_val;
execute immediate 'alter sequence ' || US.SEQUENCE_NAME || ' increment by -' || l_val || ' minvalue 0';
execute immediate 'select ' || US.SEQUENCE_NAME || '.nextval from dual' INTO l_val;
execute immediate 'alter sequence ' || US.SEQUENCE_NAME || ' increment by 1 minvalue 0';
END LOOP;
END;
This is a known issue in Chrome and resolved in latest versions. Please refer https://bugs.chromium.org/p/chromium/issues/detail?id=942440 for more details.
Your model is @Messages
, change it to @message
.
To change it like you should use migration:
def change rename_table :old_table_name, :new_table_name end
Of course do not create that file by hand but use rails generator:
rails g migration ChangeMessagesToMessage
That will generate new file with proper timestamp in name in 'db
dir. Then run:
rake db:migrate
And your app should be fine since then.
Also note that redirect:
and forward:
prefixes are handled by UrlBasedViewResolver
, so you need to have at least one subclass of UrlBasedViewResolver
among your view resolvers, such as InternalResourceViewResolver
.
If you want downloads number for each customer, use:
select ssn
, sum(time)
from downloads
group by ssn
If you want just one record -- for a customer with highest number of downloads -- use:
select *
from (
select ssn
, sum(time)
from downloads
group by ssn
order by sum(time) desc
)
where rownum = 1
However if you want to see all customers with the same number of downloads, which share the highest position, use:
select *
from (
select ssn
, sum(time)
, dense_rank() over (order by sum(time) desc) r
from downloads
group by ssn
)
where r = 1
You can setup a custom error page for every location block in your nginx.conf, or a global error page for the site as a whole.
To redirect to a simple 404 not found page for a specific location:
location /my_blog {
error_page 404 /blog_article_not_found.html;
}
A site wide 404 page:
server {
listen 80;
error_page 404 /website_page_not_found.html;
...
You can append standard error codes together to have a single page for several types of errors:
location /my_blog {
error_page 500 502 503 504 /server_error.html
}
To redirect to a totally different server, assuming you had an upstream server named server2 defined in your http section:
upstream server2 {
server 10.0.0.1:80;
}
server {
location /my_blog {
error_page 404 @try_server2;
}
location @try_server2 {
proxy_pass http://server2;
}
The manual can give you more details, or you can search google for the terms nginx.conf and error_page for real life examples on the web.
<form action="javascript:completeAndRedirect();">
<input type="text" id="Edit1"
style="width:280; height:50; font-family:'Lucida Sans Unicode', 'Lucida Grande', sans-serif; font-size:22px">
</form>
Changing action to point at your function would solve the problem, in a different way.
Why are you sending it through a post if you already have it on the server (PHP) side?
Why not just save the array to the $_SESSION
variable so you can use it when the form gets submitted, that might make it more "secure" since then the client cannot change the variables by editing the source.
It will depend upon how you really want to do.
For me the issue appeared because my string file could not be parsed. I wanted to have a value like '%s - %s'
. However this appeared to be triggering a problem, it seems string will try to parse this value in a special way. Because two string values were provided in a single value an error was written in the console, but I had so many errors triggered from that, that the initial error was hidden, because of small console buffer. Adding formatted="false"
attribute to this string value of mine fixed the problem in the string file (which btw was not reported as compilation error in the file itself) and I was able to build once more.
I wrote a function to conveniently print things to the console.
// function for debugging stuff
function print(...x) {
console.log(JSON.stringify(x,null,4));
}
// how to call it
let obj = { a: 1, b: [2,3] };
print('hello',123,obj);
will output in console:
[
"hello",
123,
{
"a": 1,
"b": [
2,
3
]
}
]
(Context: My OS is Amazon linux using AWS. It seems similar to RedHat but it's stripped down a bit, it seems.)
Exit the shell, then open a new shell. The pip command now works.
That's what solved the problem at this location.
You might want to know as well: The pip commands to install software then needed to be written like this example (jupyter for example) to work correctly on my system:
pip install jupyter --user
Specifically, note the lack of sudo, and the presence of --user
Would be real nice if pip docs had said anything about all this, but that would take typing in more characters I guess.
From Bootstrap's docs about the remote
option;
This option is deprecated since v3.3.0 and has been removed in v4. We recommend instead using client-side templating or a data binding framework, or calling jQuery.load yourself.
If a remote URL is provided, content will be loaded one time via jQuery's
load
method and injected into the.modal-content
div. If you're using the data-api, you may alternatively use thehref
attribute to specify the remote source. An example of this is shown below:<a data-toggle="modal" href="remote.html" data-target="#modal">Click me</a>
That's the .modal-content
div, not .modal-body
. If you want to put content inside .modal-body
then you need to do that with custom javascript.
So I would call jQuery.load
programmatically, meaning you can keep the functionality of the dismiss and/or other buttons as required.
To do this you could use a data tag with the URL from the button that opens the modal, and use the show.bs.modal
event to load content into the .modal-body
div.
HTML Link/Button
<a href="#" data-toggle="modal" data-load-url="remote.html" data-target="#myModal">Click me</a>
jQuery
$('#myModal').on('show.bs.modal', function (e) {
var loadurl = $(e.relatedTarget).data('load-url');
$(this).find('.modal-body').load(loadurl);
});
To temporarily work around this problem, I found the following to be the quickest way:
export JAVA_TOOL_OPTIONS="-Xmx1024m -Xms1024m"
http sends/receives data as strings... this is just the way things are. You are looking to parse the string as json.
var jsonObject = JSON.parse(data);
This works fine for me.
final R.drawable drawableResources = new R.drawable();
final Class<R.drawable> c = R.drawable.class;
final Field[] fields = c.getDeclaredFields();
for (int i=0; i < fields.length;i++)
{
resourceId[i] = fields[i].getInt(drawableResources);
/* till here you get all the images into the int array resourceId.*/
}
imageview= (ImageView)findViewById(R.id.imageView);
if(your condition)
{
imageview.setImageResource(resourceId[any]);
}
you can pass multiple params in url like
http://localhost:2000/custom?brand=dell&limit=20&price=20000&sort=asc
and in order to get this query fields , you can use map like
@RequestMapping(method = RequestMethod.GET, value = "/custom")
public String controllerMethod(@RequestParam Map<String, String> customQuery) {
System.out.println("customQuery = brand " + customQuery.containsKey("brand"));
System.out.println("customQuery = limit " + customQuery.containsKey("limit"));
System.out.println("customQuery = price " + customQuery.containsKey("price"));
System.out.println("customQuery = other " + customQuery.containsKey("other"));
System.out.println("customQuery = sort " + customQuery.containsKey("sort"));
return customQuery.toString();
}
Firstly: The >>>
code you see in python examples is a way to indicate that it is Python code. It's used to separate Python code from output. Like this:
>>> 4+5
9
Here we see that the line that starts with >>>
is the Python code, and 9 is what it results in. This is exactly how it looks if you start a Python interpreter, which is why it's done like that.
You never enter the >>>
part into a .py
file.
That takes care of your syntax error.
Secondly, ctypes is just one of several ways of wrapping Python libraries. Other ways are SWIG, which will look at your Python library and generate a Python C extension module that exposes the C API. Another way is to use Cython.
They all have benefits and drawbacks.
SWIG will only expose your C API to Python. That means you don't get any objects or anything, you'll have to make a separate Python file doing that. It is however common to have a module called say "wowza" and a SWIG module called "_wowza" that is the wrapper around the C API. This is a nice and easy way of doing things.
Cython generates a C-Extension file. It has the benefit that all of the Python code you write is made into C, so the objects you write are also in C, which can be a performance improvement. But you'll have to learn how it interfaces with C so it's a little bit extra work to learn how to use it.
ctypes have the benefit that there is no C-code to compile, so it's very nice to use for wrapping standard libraries written by someone else, and already exists in binary versions for Windows and OS X.
private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
dataGridView1.Columns[i].SortMode = DataGridViewColumnSortMode.NotSortable;
}
}
Two examples that work:
(Example ONE)
// Remove from Listing the Items Checked in Checkbox for Delete
let temp_products_images = store.state.c_products.products_images
if (temp_products_images != null) {
for (var l = temp_products_images.length; l--;) {
// 'mark' is the checkbox field
if (temp_products_images[l].mark == true) {
store.state.c_products.products_images.splice(l,1); // THIS WORKS
// this.$delete(store.state.c_products.products_images,l); // THIS ALSO WORKS
}
}
}
(Example TWO)
// Remove from Listing the Items Checked in Checkbox for Delete
let temp_products_images = store.state.c_products.products_images
if (temp_products_images != null) {
let l = temp_products_images.length
while (l--)
{
// 'mark' is the checkbox field
if (temp_products_images[l].mark == true) {
store.state.c_products.products_images.splice(l,1); // THIS WORKS
// this.$delete(store.state.c_products.products_images,l); // THIS ALSO WORKS
}
}
}
I tried one subset of proposed solutions in these answers.. with no success, I finally adapted and fixed the proposed code and wrote my fixed function.
I tested it and works at least on little endian architectures--e.g.x86-- if anyone likes to try on a big endian architecture, please give me feedback.
IP2Int
code comes from this post, the other method is a fully (for my test cases) working fix of previous proposals in this question.
The code:
def IP2Int(ip):
o = map(int, ip.split('.'))
res = (16777216 * o[0]) + (65536 * o[1]) + (256 * o[2]) + o[3]
return res
def addressInNetwork(ip, net_n_bits):
ipaddr = IP2Int(ip)
net, bits = net_n_bits.split('/')
netaddr = IP2Int(net)
bits_num = int(bits)
netmask = ((1L << bits_num) - 1) << (32 - bits_num)
return ipaddr & netmask == netaddr & netmask
Hope useful,
With Moment.js simply use:
var jsDate = moment(netDateTime).toDate();
Where netDateTime
is your DateTime variable serialized, something like "/Date(1456956000000+0200)/"
.
You need to add the package containing the executable pg_config.
A prior answer should have details you need: pg_config executable not found
If you are reading directly from CSV file then do like this.
myDataFrame <- read.csv("path/to/file.csv", header = TRUE, stringsAsFactors = FALSE)
Here's the signature.
public static string ActionLink(this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
object values,
object htmlAttributes)
What you are doing is mixing the values
and the htmlAttributes
together. values
are for URL routing.
You might want to do this.
@Html.ActionLink(Context.User.Identity.Name, "Index", "Account", null,
new { @style="text-transform:capitalize;" });
As it has already been mentioned in che's answer about adding the remote part, which I believe you are still missing.
Regarding your edit for adding remote on your local USB drive. First of all you must have a 'bare repository' if you want your repository to be a shared repository i.e. to be able to push/pull/fetch/merge etc..
To create a bare/shared repository, go to your desired location. In your case:
$ cd /Volumes/500gb/
$ git init --bare myproject.git
See here for more info on creating bare repository
Once you have a bare repository set up in your desired location you can now add it to your working copy as a remote.
$ git remote add origin /Volumes/500gb/myproject.git
And now you can push your changes to your repository
$ git push origin master
''Alastair, you can use this lib and tool; DefiantJS. It enables XPath queries on JSON structures and you can test and validate this XPath:
//data[category="Politician"]
DefiantJS extends the global object with the method "search", which in turn returns an array with the matches. In Javascript, it'll look like this:
var person = JSON.search(json_data, "//people[category='Politician']");
console.log( person[0].name );
// Barack Obama
you can use transition in css3:
.carousel-fade .carousel-inner .item {_x000D_
-webkit-transition-property: opacity;_x000D_
transition-property: opacity;_x000D_
}_x000D_
.carousel-fade .carousel-inner .item,_x000D_
.carousel-fade .carousel-inner .active.left,_x000D_
.carousel-fade .carousel-inner .active.right {_x000D_
opacity: 0;_x000D_
}_x000D_
.carousel-fade .carousel-inner .active,_x000D_
.carousel-fade .carousel-inner .next.left,_x000D_
.carousel-fade .carousel-inner .prev.right {_x000D_
opacity: 1;_x000D_
}_x000D_
.carousel-fade .carousel-inner .next,_x000D_
.carousel-fade .carousel-inner .prev,_x000D_
.carousel-fade .carousel-inner .active.left,_x000D_
.carousel-fade .carousel-inner .active.right {_x000D_
left: 0;_x000D_
-webkit-transform: translate3d(0, 0, 0);_x000D_
transform: translate3d(0, 0, 0);_x000D_
}_x000D_
.carousel-fade .carousel-control {_x000D_
z-index: 2;_x000D_
}
_x000D_
For TextView and it's descendants (e.g., Button) you can get the display size from the WindowManager and then set the TextView height to be some fraction of it:
Button btn = new Button (this);
android.view.Display display = ((android.view.WindowManager)getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
btn.setHeight((int)(display.getHeight()*0.68));
I have added the following on my excel sheet
=VLOOKUP(B2,Res_partner!$A$2:$C$21208,1,FALSE)
Still doesn't seem to work. I get an #N/A
BUT
=VLOOKUP(B2,Res_partner!$C$2:$C$21208,1,FALSE)
Works
You can use dropzone.js if you want to use simple and easy upload manager with resizing before upload functions.
It has builtin resize functions, but you can provide your own if you want.
If you are using cordova try to uninstall any previous app that is build through cordova. Strange but this method solved my problem
Read up on the datetime module.
SilentGhost's answer has the details my answer leaves out and is reposted here:
>>> a = datetime.timedelta(seconds=65)
datetime.timedelta(0, 65)
>>> str(a)
'0:01:05'
find
's optionsThere is actually no exec of /bin/ls
needed;
Find has an option that does just that:
find . -maxdepth 2 -type d -ls
To see only the one level of subdirectories you are interested in, add -mindepth
to the same level as -maxdepth
:
find . -mindepth 2 -maxdepth 2 -type d -ls
When the details that get shown should be different, -printf
can show any detail about a file in custom format;
To show the symbolic permissions and the owner name of the file, use -printf
with %M
and %u
in the format
.
I noticed later you want the full ownership information, which includes
the group. Use %g
in the format for the symbolic name, or %G
for the group id (like also %U
for numeric user id)
find . -mindepth 2 -maxdepth 2 -type d -printf '%M %u %g %p\n'
This should give you just the details you need, for just the right files.
I will give an example that shows actually different values for user and group:
$ sudo find /tmp -mindepth 2 -maxdepth 2 -type d -printf '%M %u %g %p\n'
drwx------ www-data www-data /tmp/user/33
drwx------ octopussy root /tmp/user/126
drwx------ root root /tmp/user/0
drwx------ siegel root /tmp/user/1000
drwxrwxrwt root root /tmp/systemd-[...].service-HRUQmm/tmp
(Edited for readability: indented, shortened last line)
Although the execution time is mostly irrelevant for this kind of command, increase in performance is large enough here to make it worth pointing it out:
Not only do we save creating a new process for each name - a huge task -
the information does not even need to be read, as find
already knows it.
Here is a solution using a generic template type:
public static <T> List<T> copyList(List<T> source) {
List<T> dest = new ArrayList<T>();
for (T item : source) { dest.add(item); }
return dest;
}
My issue was that end users would start typing in a textbox and receive autocomplete (ACP) suggestions and update the calling control if a suggestion was selected as the ACP is designed by default. However, I also needed to update multiple other controls (textboxes, DropDowns, etc...) with data specific to the end user's selection. I have been trying to figure out an elegant solution to the issue and I feel the one I developed is worth sharing and hopefully will save you at least some time.
WebMethod (SampleWM.aspx):
PURPOSE:
NOTES:
//Call to custom function to return SP results as a DataTable
// DataTable will consist of Field0 - Field5
Dim params As ArrayList = New ArrayList
params.Add("@QueryFilter|" & QueryFilter)
Dim dt As DataTable = Data.GetDataTableFromSP("AutoComplete", params, [ConnStr])
//Create a StringBuilder Obj to hold the JSON
//IE: [{"Field0":"0","Field1":"Test","Field2":"Jason","Field3":"Smith","Field4":"32","Field5":"888-555-1212"},{"Field0":"1","Field1":"Test2","Field2":"Jane","Field3":"Doe","Field4":"25","Field5":"888-555-1414"}]
Dim jStr As StringBuilder = New StringBuilder
//Loop the DataTable and convert row into JSON String
If dt.Rows.Count > 0 Then
jStr.Append("[")
Dim RowCnt As Integer = 1
For Each r As DataRow In dt.Rows
jStr.Append("{")
Dim ColCnt As Integer = 0
For Each c As DataColumn In dt.Columns
If ColCnt = 0 Then
jStr.Append("""" & c.ColumnName & """:""" & r(c.ColumnName) & """")
Else
jStr.Append(",""" & c.ColumnName & """:""" & r(c.ColumnName) & """")
End If
ColCnt += 1
Next
If Not RowCnt = dt.Rows.Count Then
jStr.Append("},")
Else
jStr.Append("}")
End If
RowCnt += 1
Next
jStr.Append("]")
End If
//Return JSON to WebMethod Caller
Return jStr.ToString
AutoComplete jQuery (AutoComplete.aspx):
$(function() {
$("#LookUp").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "SampleWM.aspx/GetAutoCompleteData",
dataType: "json",
data:'{QueryFilter: "' + request.term + '"}',
success: function (data) {
response($.map($.parseJSON(data.d), function (item) {
var AC = new Object();
//autocomplete default values REQUIRED
AC.label = item.Field0;
AC.value = item.Field1;
//extend values
AC.FirstName = item.Field2;
AC.LastName = item.Field3;
AC.Age = item.Field4;
AC.Phone = item.Field5;
return AC
}));
}
});
},
minLength: 3,
select: function (event, ui) {
$("#txtFirstName").val(ui.item.FirstName);
$("#txtLastName").val(ui.item.LastName);
$("#ddlAge").val(ui.item.Age);
$("#txtPhone").val(ui.item.Phone);
}
});
});
DirectoryInfo d = new DirectoryInfo(@"D:\Test");//Assuming Test is your Folder
FileInfo[] Files = d.GetFiles("*.txt"); //Getting Text files
string str = "";
foreach(FileInfo file in Files )
{
str = str + ", " + file.Name;
}
Hope this will help...
Personally, I prefer changing the method signature to:
public ResponseEntity<?>
This gives the advantage of possibly returning an error message as single item for services which, when ok, return a list of items.
When returning I don't use any type (which is unused in this case anyway):
return new ResponseEntity<>(entities, HttpStatus.OK);
Java 8
If you are using Java 8 in your project and comparing java.sql.Timestamp
, you could use the LocalDate
class:
sameDate = date1.toLocalDateTime().toLocalDate().equals(date2.toLocalDateTime().toLocalDate());
If you are using java.util.Date
, have a look at Istvan answer which is less ambiguous.
To check if LocalDb is installed or not:
cmd
and type in sqllocaldb i
this should give you the installed sqllocaldb instances if found.(localdb)\V11.0
using windows authentication.If an error is raised Cannot connect to (localdb)\V11.0.
change the instance name to (localdb)\MSSQLLocalDB
and try again to connect, if you still get the same error.
Follow these steps to install LocalDb:
Start Menu
and type in search sqlLocalDb
.sqlLocalDb.msi
and click it.after finishing the installation re-run SSMS
and try connecting to either of the instances (localdb)\V11.0
or (localdb)\MSSQLLocalDB
, one of it should work depending on what Visual Studio version you have.
You can also verify that localdb
is installed using Visual Studio by simply creating new sql file and go to the connect icon on the top header of the file which by default lists all the servers you can connect to including localdb
if installed.
In addition to the above mentioned ways of finding if localdb is installed, you can also use the MS windows power shell
or windows command processor CMD
or even NuGet package manager console
on your server machine and run these commands sqllocaldb i
and sqllocaldb v
that will show you the localdb name if it is installed and the MSSQL server version installed and running on your machine.
They are actually strings, not numbers. The easiest way to produce a number from a string is to prepend it with +
:
var x = +y + +z;
In my case I have succeed with the following solution for converting field ClockInTime from ClockTime collection from string to Date type:
db.ClockTime.find().forEach(function(doc) {
doc.ClockInTime=new Date(doc.ClockInTime);
db.ClockTime.save(doc);
})
Try javax.net.ssl.keyStorePassword
instead of javax.net.ssl.keyPassword
: the latter isn't mentioned in the JSSE ref guide.
The algorithms you mention should be there by default using the default security providers. NoSuchAlgorithmException
s are often cause by other underlying exceptions (file not found, wrong password, wrong keystore type, ...). It's useful to look at the full stack trace.
You could also use -Djavax.net.debug=ssl
, or at least -Djavax.net.debug=ssl,keymanager
, to get more debugging information, if the information in the stack trace isn't sufficient.
An alternative is to use OFFSET:
Assuming the column value is stored in B1, you can use the following
C1 = OFFSET(A1, 0, B1 - 1)
This works by:
a) taking a base cell (A1)
b) adding 0 to the row (keeping it as A)
c) adding (A5 - 1) to the column
You can also use another value instead of 0 if you want to change the row value too.
I would bind two different getters/setters pair to one variable:
class Coordinates{
int red;
@JsonProperty("red")
public byte getRed() {
return red;
}
public void setRed(byte red) {
this.red = red;
}
@JsonProperty("r")
public byte getR() {
return red;
}
public void setR(byte red) {
this.red = red;
}
}
When I first started working with PDF, I found the PDF reference very hard to navigate. It might help you to know that the overview of the file structure is found in syntax, and what Adobe call the document structure is the object structure and not the file structure. That is also found in Syntax. The description of operators is hidden away in Appendix A - very useful for understanding what is happening in content streams. If you ever have the pain of working with colour spaces you will find that hidden in Graphics! Hopefully these pointers will help you find things more quickly than I did.
If you are using windows, pdftron CosEdit allows you to browse the object structure to understand it. There is a free demo available that allows you to examine the file but not save it.
If you are able to add external libs to your project. I would recommend that you try out Joda-time. It has a very clever way of working with dates.
There is a statistics library if you are using python >= 3.4
https://docs.python.org/3/library/statistics.html
You may use it's mean method like this. Let's say you have a list of numbers of which you want to find mean:-
list = [11, 13, 12, 15, 17]
import statistics as s
s.mean(list)
It has other methods too like stdev, variance, mode, harmonic mean, median etc which are too useful.
Run this
for (Method m : sex.class.getDeclaredMethods()) {
System.out.println(m);
}
you will see
public static test.Sex test.Sex.valueOf(java.lang.String)
public static test.Sex[] test.Sex.values()
These are all public methods that "sex" class has. They are not in the source code, javac.exe added them
Notes:
never use sex as a class name, it's difficult to read your code, we use Sex in Java
when facing a Java puzzle like this one, I recommend to use a bytecode decompiler tool (I use Andrey Loskutov's bytecode outline Eclispe plugin). This will show all what's inside a class
shorten(str, maxLen, appendix, separator = ' ') {
if (str.length <= maxLen) return str;
let strNope = str.substr(0, str.lastIndexOf(separator, maxLen));
return (strNope += appendix);
}
var s= "this is a long string and I cant explain all"; shorten(s, 10, '...')
/* "this is .." */
android:singleLine="true"
android:ellipsize="marquee"
are the only required attributes and scrolling even works with layout_weight
defined with layout_width=0dp
here is some sample code:
<TextView
android:id="@+id/scroller"
android:singleLine="true"
android:ellipsize="marquee"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#FFFFFF"
android:text="Some veryyyyy long text with all the characters that cannot fit in screen, it so sad :( that I will not scroll"
android:layout_marginLeft="4dp"
android:layout_weight="3"
android:layout_width="0dp"
android:layout_height="wrap_content"
/>
But what is most important is implicitely or explicitely TextView
should get selected.
You can do this with:
TextView txtView=(TextView) findViewById(R.id.scroller);
txtView.setSelected(true);
Make sure that when you cloned the repository, you did so with the SSH URL and not the HTTPS; in the clone URL box of the repo, choose the SSH protocol before copying the URL. See image below:
Instead of early binding the reference, there's an open source project called NetOffice that abstracts this from your project, making life much easier. That way you don't have to rely on your users having a specific version of Office installed.
Try to check for existence:
IF NOT EXISTS (SELECT * FROM dbo.Employee WHERE ID = @SomeID)
INSERT INTO dbo.Employee(Col1, ..., ColN)
VALUES(Val1, .., ValN)
ELSE
UPDATE dbo.Employee
SET Col1 = Val1, Col2 = Val2, ...., ColN = ValN
WHERE ID = @SomeID
You could easily wrap this into a stored procedure and just call that stored procedure from the outside (e.g. from a programming language like C# or whatever you're using).
Update: either you can just write this entire statement in one long string (doable - but not really very useful) - or you can wrap it into a stored procedure:
CREATE PROCEDURE dbo.InsertOrUpdateEmployee
@ID INT,
@Name VARCHAR(50),
@ItemName VARCHAR(50),
@ItemCatName VARCHAR(50),
@ItemQty DECIMAL(15,2)
AS BEGIN
IF NOT EXISTS (SELECT * FROM dbo.Table1 WHERE ID = @ID)
INSERT INTO dbo.Table1(ID, Name, ItemName, ItemCatName, ItemQty)
VALUES(@ID, @Name, @ItemName, @ItemCatName, @ItemQty)
ELSE
UPDATE dbo.Table1
SET Name = @Name,
ItemName = @ItemName,
ItemCatName = @ItemCatName,
ItemQty = @ItemQty
WHERE ID = @ID
END
and then just call that stored procedure from your ADO.NET code
I tried it with Java on Linux. The following possibilities are OK:
file:///home/userId/aaaa.html
file:/home/userId/aaaa.html
file:aaaa.html (if current directory is /home/userId)
not working is:
file://aaaa.html
I'd just use zip
:
In [1]: from pandas import *
In [2]: def calculate(x):
...: return x*2, x*3
...:
In [3]: df = DataFrame({'a': [1,2,3], 'b': [2,3,4]})
In [4]: df
Out[4]:
a b
0 1 2
1 2 3
2 3 4
In [5]: df["A1"], df["A2"] = zip(*df["a"].map(calculate))
In [6]: df
Out[6]:
a b A1 A2
0 1 2 2 3
1 2 3 4 6
2 3 4 6 9
Either replace double quotes around type="text"
with single quotes, Like
"<form><input type='text'/></form>"
OR
replace double quotes wrapping data-content
with singe quotes, Like
data-content='<form><input type="text"/></form>'
As mentioned by @Veneet Reddy install it via ADB.
Go to ADT Bundle/sdk/platform-tools past your .apk
file and run command prompt as administrator.
Then run adb devices
command which will list the connected devices or emulators that are running.
Then run adb -s yourDeviceID install yourApk.apk
Note: uninstall the app if you have already installed before installing again.
UltimateSAML SSO is an OASIS SAML v1.x and v2.0 specifications compliant .NET toolkit. It offers an elegant and easy way to add support for Single Sign-On and Single-Logout SAML to your ASP.NET, ASP.NET MVC, ASP.NET Core, Desktop, and Service applications. The lightweight library helps you provide SSO access to cloud and intranet websites using a single credentials entry.
I had the same program, I hope this could help.
I your using Windows 7, open Command Prompt-> run as Administrator. register your <...>.dll.
Why run as Administrator, you can register your <...>.dll using the run at the Windows Start, but still your dll only run as user even your account is administrator.
Now you can add your <...>.dll at the Project->Add Reference->Browse
Thanks
@-webkit-keyframes blinker {
0% { opacity: 1.0; }
50% { opacity: 0.0; }
100% { opacity: 1.0; }
}
@-webkit-keyframes blinker { _x000D_
0% { opacity: 1.0; }_x000D_
50% { opacity: 0.0; }_x000D_
100% { opacity: 1.0; }_x000D_
}_x000D_
_x000D_
.blink {_x000D_
width: 10px;_x000D_
height: 10px;_x000D_
border-radius: 10px;_x000D_
animation: blinker 2s linear infinite;_x000D_
background-color: red;_x000D_
margin-right: 5px;_x000D_
}_x000D_
_x000D_
.content {_x000D_
display: flex;_x000D_
flex-direction: row;_x000D_
align-items: center;_x000D_
}
_x000D_
<div class="content">_x000D_
<i class="blink"></i>_x000D_
LIVE_x000D_
</div>
_x000D_
Remove static
keyword in method definition. Keep it just in your class definition.
static
keyword placed in .cpp file means that a certain function has a static linkage, ie. it is accessible only from other functions in the same file.
There are 3 solutions available for these.
1) Enable remote login using below command - sudo systemsetup -setremotelogin on
2) In Mac, go to System Preference -> Sharing -> enable Remote Login that's it. 100% working solution
3) Final and most important solution is - Check your private area network connection . Sometime remote login isn't allow inside the local area network.
Kindly try to connect your machine using personal network like mobile network, Hotspot etc.
No, because Strings in Java are immutable. You'll have to create a new string removing the character you don't want.
For replacing a single char c
at index position idx
in string str
, do something like this, and remember that a new string will be created:
String newstr = str.substring(0, idx) + str.substring(idx + 1);
For HSQLDB:
ALTER TABLE tableName ALTER COLUMN columnName SET NULL;
encode("latin-1")
helped me in my case:
facultyname[0].encode("latin-1")
If you have both date and time information in the numeric value, then use as.POSIXct
. Data.table package IDateTime format is such a case. If you use fwrite
to save a file, the package automatically converts date-times to idatetime format which is unix time. To convert back to normal format following can be done.
Example: Let's say you have a unix time stamp with date and time info: 1442866615
> as.POSIXct(1442866615,origin="1970-01-01")
[1] "2015-09-21 16:16:54 EDT"
For exe files, I suppose the differences are nearly unimportant.
But to start an exe you don't even need CALL
.
When starting another batch it's a big difference,
as CALL
will start it in the same window and the called batch has access to the same variable context.
So it can also change variables which affects the caller.
START
will create a new cmd.exe for the called batch and without /b it will open a new window.
As it's a new context, variables can't be shared.
Using start /wait <prog>
- Changes of environment variables are lost when the <prog>
ends
- The caller waits until the <prog>
is finished
Using call <prog>
- For exe it can be ommited, because it's equal to just starting <prog>
- For an exe-prog the caller batch waits or starts the exe asynchronous, but the behaviour depends on the exe itself.
- For batch files, the caller batch continues, when the called <batch-file>
finishes, WITHOUT call the control will not return to the caller batch
Using CALL
can change the parameters (for batch and exe files), but only when they contain carets or percent signs.
call myProg param1 param^^2 "param^3" %%path%%
Will be expanded to (from within an batch file)
myProg param1 param2 param^^3 <content of path>
Your piece of script works just great. Are you sure you are not assigning anything else before the if to "i"?
A common mistake is also not to leave a space after and before the square brackets.
You might wanna clear the old Image before setting a new Image.
You also need to update the Canvas size for a new Image.
This is how I am doing in my project:
// on image load update Canvas Image
this.image.onload = () => {
// Clear Old Image and Reset Bounds
canvasContext.clearRect(0, 0, this.canvas.width, this.canvas.height);
this.canvas.height = this.image.height;
this.canvas.width = this.image.width;
// Redraw Image
canvasContext.drawImage(
this.image,
0,
0,
this.image.width,
this.image.height
);
};
Use JavaScript objects as associative arrays.
Associative Array: In simple words associative arrays use Strings instead of Integer numbers as index.
Create an object with
var dictionary = {};
JavaScript allows you to add properties to objects by using the following syntax:
Object.yourProperty = value;
An alternate syntax for the same is:
Object["yourProperty"] = value;
If you can, also create key-to-value object maps with the following syntax:
var point = { x:3, y:2 };
point["x"] // returns 3
point.y // returns 2
You can iterate through an associative array using the for..in loop construct as follows
for(var key in Object.keys(dict)){
var value = dict[key];
/* use key/value for intended purpose */
}
To all: Thanks for all the post and comments some are good, but some are better.
The first big script is good because it is delivers just what is needed. The fastest and most detailed is the one suggestion for selecting from INFORMATION_SCHEMA.COLUMNS..
My need was to find all the errant columns of approximately the same name and Several databases.. Sooo, I made my versions of both (see below) ...Either of these two below script work and deliver the goods in seconds.
The assumption in other posts on this link, is that the first code example can be used successfully with for-each-database, is to me, not desirable. This is because the information is within the specific database and the simple use of the "fedb" doesn't produce the correct results, it simply doesn't give access. SOOO to that is why I use a CURSOR to collect the databases and ignore those that are Off-line, which in this case, a utility script, it is a good use of same.
Bottom Line, I read everyone's post, incorporated all the correction from the posts and made what are two very eloquent scripts from others good works. I listed both below and have also placed the script file on my public folder at OneDrive.com which you can access with this link: http://1drv.ms/1vr8yNX
Enjoy ! Hank Freeman
Try them separately...
---------------------------
--- 1st example (works) ---
---------------------------
Declare
@DBName sysname
,@SQL_String1 nvarchar(4000)
,@SQL_String2 nvarchar(4000)
,@ColumnName nvarchar(200)
--set @ColumnName = 'Course_ID'
-------- Like Trick --------
-- IF you want to add more the @ColumnName so it looks like Course_ID,CourseID
-- then add an additional pairing of +''','''+'NewColumnSearchIDValue'
----------------------------
set @ColumnName = 'Course_ID' +''','''+'CourseID'
--select @ColumnName
-----
Declare @Column_Info table
(
[DatabaseName] nvarchar(128) NULL,
[ColumnName] sysname NULL,
[ObjectName] nvarchar(257) NOT NULL,
[ObjectType] nvarchar(60) NULL,
[DataType] nvarchar(151) NULL,
[Nullable] varchar(8) NOT NULL,
[MiscInfo] nvarchar(MAX) NOT NULL
)
--------------
Begin
set @SQL_String2 = 'SELECT
DB_NAME() as ''DatabaseName'',
s.name as ColumnName
,sh.name+''.''+o.name AS ObjectName
,o.type_desc AS ObjectType
,CASE
WHEN t.name IN (''char'',''varchar'') THEN t.name+''(''+CASE WHEN s.max_length<0 then ''MAX'' ELSE CONVERT(varchar(10),s.max_length) END+'')''
WHEN t.name IN (''nvarchar'',''nchar'') THEN t.name+''(''+CASE WHEN s.max_length<0 then ''MAX'' ELSE CONVERT(varchar(10),s.max_length/2) END+'')''
WHEN t.name IN (''numeric'') THEN t.name+''(''+CONVERT(varchar(10),s.precision)+'',''+CONVERT(varchar(10),s.scale)+'')''
ELSE t.name
END AS DataType
,CASE
WHEN s.is_nullable=1 THEN ''NULL''
ELSE ''NOT NULL''
END AS Nullable
,CASE
WHEN ic.column_id IS NULL THEN ''''
ELSE '' identity(''+ISNULL(CONVERT(varchar(10),ic.seed_value),'''')+'',''+ISNULL(CONVERT(varchar(10),ic.increment_value),'''')+'')=''+ISNULL(CONVERT(varchar(10),ic.last_value),''null'')
END
+CASE
WHEN sc.column_id IS NULL THEN ''''
ELSE '' computed(''+ISNULL(sc.definition,'''')+'')''
END
+CASE
WHEN cc.object_id IS NULL THEN ''''
ELSE '' check(''+ISNULL(cc.definition,'''')+'')''
END
AS MiscInfo
into ##Temp_Column_Info
FROM sys.columns s
INNER JOIN sys.types t ON s.system_type_id=t.user_type_id and t.is_user_defined=0
INNER JOIN sys.objects o ON s.object_id=o.object_id
INNER JOIN sys.schemas sh on o.schema_id=sh.schema_id
LEFT OUTER JOIN sys.identity_columns ic ON s.object_id=ic.object_id AND s.column_id=ic.column_id
LEFT OUTER JOIN sys.computed_columns sc ON s.object_id=sc.object_id AND s.column_id=sc.column_id
LEFT OUTER JOIN sys.check_constraints cc ON s.object_id=cc.parent_object_id AND s.column_id=cc.parent_column_id
--------------------------------------------
--- DBA - Hank 12-Feb-2015 added this specific where statement
-- where Upper(s.name) like ''COURSE%''
-- where Upper(s.name) in (''' + @ColumnName + ''')
-- where Upper(s.name) in (''cycle_Code'')
-- ORDER BY sh.name+''.''+o.name,s.column_id
order by 1,2'
--------------------
Declare DB_cursor CURSOR
FOR
SELECT name FROM sys.databases
--select * from sys.databases
WHERE STATE = 0
-- and Name not IN ('master','msdb','tempdb','model','DocxPress')
and Name not IN ('msdb','tempdb','model','DocxPress')
Open DB_cursor
Fetch next from DB_cursor into @DBName
While @@FETCH_STATUS = 0
begin
--select @DBName as '@DBName';
Set @SQL_String1 = 'USE [' + @DBName + ']'
set @SQL_String1 = @SQL_String1 + @SQL_String2
EXEC sp_executesql @SQL_String1;
--
insert into @Column_Info
select * from ##Temp_Column_Info;
drop table ##Temp_Column_Info;
Fetch next From DB_cursor into @DBName
end
CLOSE DB_cursor;
Deallocate DB_cursor;
---
select * from @Column_Info order by 2,3
----------------------------
end
---------------------------
Below is the Second script..
---------------------------
--- 2nd example (works) ---
---------------------------
-- This is by far the best/fastes of the lot for what it delivers.
--Select * into dbo.hanktst From Master.INFORMATION_SCHEMA.COLUMNS
--FileID: SCRIPT_Get_Column_info_(INFORMATION_SCHEMA.COLUMNS).sql
----------------------------------------
--FileID: SCRIPT_Get_Column_info_(INFORMATION_SCHEMA.COLUMNS).sql
-- Utility to find all columns in all databases or find specific with a like statement
-- Look at this line to find a: --> set @SQL_String2 = ' select * into ##Temp_Column_Info....
----------------------------------------
---
SET NOCOUNT ON
begin
Declare @hanktst TABLE (
[TABLE_CATALOG] NVARCHAR(128) NULL
,[TABLE_SCHEMA] NVARCHAR(128) NULL
,[TABLE_NAME] sysname NOT NULL
,[COLUMN_NAME] sysname NULL
,[ORDINAL_POSITION] INT NULL
,[COLUMN_DEFAULT] NVARCHAR(4000) NULL
,[IS_NULLABLE] VARCHAR(3) NULL
,[DATA_TYPE] NVARCHAR(128) NULL
,[CHARACTER_MAXIMUM_LENGTH] INT NULL
,[CHARACTER_OCTET_LENGTH] INT NULL
,[NUMERIC_PRECISION] TINYINT NULL
,[NUMERIC_PRECISION_RADIX] SMALLINT NULL
,[NUMERIC_SCALE] INT NULL
,[DATETIME_PRECISION] SMALLINT NULL
,[CHARACTER_SET_CATALOG] sysname NULL
,[CHARACTER_SET_SCHEMA] sysname NULL
,[CHARACTER_SET_NAME] sysname NULL
,[COLLATION_CATALOG] sysname NULL
,[COLLATION_SCHEMA] sysname NULL
,[COLLATION_NAME] sysname NULL
,[DOMAIN_CATALOG] sysname NULL
,[DOMAIN_SCHEMA] sysname NULL
,[DOMAIN_NAME] sysname NULL
)
Declare
@DBName sysname
,@SQL_String2 nvarchar(4000)
,@TempRowCnt varchar(20)
,@Dbug bit = 0
Declare DB_cursor CURSOR
FOR
SELECT name FROM sys.databases
WHERE STATE = 0
-- and Name not IN ('master','msdb','tempdb','model','DocxPress')
and Name not IN ('msdb','tempdb','model','DocxPress')
Open DB_cursor
Fetch next from DB_cursor into @DBName
While @@FETCH_STATUS = 0
begin
set @SQL_String2 = ' select * into ##Temp_Column_Info from [' + @DBName + '].INFORMATION_SCHEMA.COLUMNS
where UPPER(Column_Name) like ''COURSE%''
;'
if @Dbug = 1 Select @SQL_String2 as '@SQL_String2';
EXEC sp_executesql @SQL_String2;
insert into @hanktst
select * from ##Temp_Column_Info;
drop table ##Temp_Column_Info;
Fetch next From DB_cursor into @DBName
end
select * from @hanktst order by 4,2,3
CLOSE DB_cursor;
Deallocate DB_cursor;
set @TempRowCnt = (select cast(count(1) as varchar(10)) from @hanktst )
Print ('Rows found: '+ @TempRowCnt +' end ...')
end
--------
In Visual Studio 2017, select Project/Properties and then select the Web option. In the IIS section next to the default project URL click Create Virtual Directory. This solved the problem for me. I think in my case the default project Virtual Directory had been corrupted in some way following a debugging session.
There is actually a really easy way to do this with GitHub Desktop now that I don't believe was a feature before.
All you need to do is switch to the new branch in GitHub Desktop, and it will prompt you to leave your changes on the current branch (which will be stashed), or to bring your changes with you to the new branch. Just choose the second option, to bring the changes to the new branch. You can then commit as usual.
You can no longer just use Install-Package to point to a local file. (That's likely because the PackageReference
element doesn't support file paths; it only allows you to specify the package's Id.)
You first have to tell Visual Studio about the location of your package, and then you can add it to a project. What most people do is go into the NuGet Package Manager and add the local folder as a source (menu Tools ? Options ? NuGet Package Manager ? Package Sources). But that means your dependency's location isn't committed (to version-control) with the rest of your codebase.
This will add a package source that only applies to a specific solution, and you can use relative paths.
You need to create a nuget.config
file in the same directory as your .sln
file. Configure the file with the package source(s) you want. When you next open the solution in Visual Studio 2017, any .nupkg files from those source folders will be available. (You'll see the source(s) listed in the Package Manager, and you'll find the packages on the "Browse" tab when you're managing packages for a project.)
Here's an example nuget.config
to get you started:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<add key="MyLocalSharedSource" value="..\..\..\some\folder" />
</packageSources>
</configuration>
My use case for this functionality is that I have multiple instances of a single code repository on my machine. There's a shared library within the codebase that's published/deployed as a .nupkg file. This approach allows the various dependent solutions throughout our codebase to use the package within the same repository instance. Also, someone with a fresh install of Visual Studio 2017 can just checkout the code wherever they want, and the dependent solutions will successfully restore and build.
do like this
set classpath=%classpath%(ur jarfile);
By the time the query gets to SQL you have to have already expanded the list. The easy way of doing this, if you're using IDs from some internal, trusted data source, where you can be 100% certain they're integers (e.g., if you selected them from your database earlier) is this:
$sql = 'SELECT * WHERE id IN (' . implode(',', $ids) . ')';
If your data are coming from the user, though, you'll need to ensure you're getting only integer values, perhaps most easily like so:
$sql = 'SELECT * WHERE id IN (' . implode(',', array_map('intval', $ids)) . ')';
$cRepo = $em->getRepository('KaleLocationBundle:Country');
// Leave the first array blank
$countries = $cRepo->findBy(array(), array('name'=>'asc'));
A possible workaround would be to use the multi-cursor. select the >< part of your example use Ctrl+Shift+L or select all occurrences. Then use the arrow keys to move all the cursors between the tags and press enter to insert a newline everywhere.
This won't work in all situations.
You can also use Ctrl+D for select next match, which adds the next match to the selection and adds a cursor. And use Ctrl+K Ctrl+D to skip a selection.
adb tcpip 5555
Weird, but this only works for me if I have the USB cable connected, then I can unplug the usb and go for it with everything else adb.
and the same when returning to usb,
adb usb
will only work if usb is connected.
It doesn't matter if I issue the
setprop service.adb.tcp.port 5555
or
setprop service.adb.tcp.port -1
then stop & start adbd, I still need the usb cable in or it doesn't work.
So, if my ADB over usb wasn't working, I bet I wouldn't be able to enable ADB over WiFi either.
I used this to get to grips with Comet, I have also set up Comet using the Java Glassfish server and found lots of other examples by subscribing to cometdaily.com
Try this
Snackbar.make(findViewById(android.R.id.content), "Got the Result", Snackbar.LENGTH_LONG)
.setAction("Submit", mOnClickListener)
.setActionTextColor(Color.RED)
.show();
None of the current answers helped me here. We were getting something like:
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:
#.#.#:compile (default-compile) on project Streaming_Test: Compilation failure
[ERROR] Unable to locate the Javac Compiler in:
[ERROR] /opt/java/J7.0/../lib/tools.jar
This happens because the Java installation has determined that it is a JRE installation. It's expecting there to be JDK stuff above the JRE subdirectory, hence the ../lib
in the path. Our tools.jar
is in $JAVA_HOME/lib/tools.jar
not in $JAVA_HOME/../lib/tools.jar
.
Unfortunately, we do not have an option to install a JDK on our OS (don't ask) so that wasn't an option. I fixed the problem by adding the following to the maven pom.xml
:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<fork>true</fork> <!-- not sure if this is also needed -->
<executable>${JAVA_HOME}/bin/javac</executable>
<!-- ^^^^^^^^^^^^^^^^^^^^^^ -->
</configuration>
</plugin>
By pointing the executable to the right place this at least got past our compilation failures.
Now you can use the pluck
method on a Collection
instance:
This will return only the uuid
attribute of the Post model
App\Models\User::find(2)->posts->pluck('uuid')
=> Illuminate\Support\Collection {#983
all: [
"1",
"2",
"3",
],
}
This complete program shows how I would do it. Keep in mind I was writing C when most of you whippersnappers were a glint in your mothers eyes so it's old-school, do-the-job, long-var-names-are-for-wimps. Fix that if you wish, I'm more interested in the correctness of the code.
It handles NULLs, empty strings and all string sizes. I haven't tested it with strings of maximum size (max(size_t)) but it should work, and if you're handling strings that big, you're insane anyway :-)
#include <stdio.h>
#include <string.h>
char *revStr (char *str) {
char tmp, *src, *dst;
size_t len;
if (str != NULL)
{
len = strlen (str);
if (len > 1) {
src = str;
dst = src + len - 1;
while (src < dst) {
tmp = *src;
*src++ = *dst;
*dst-- = tmp;
}
}
}
return str;
}
char *str[] = {"", "a", "ab", "abc", "abcd", "abcde"};
int main(int argc, char *argv[]) {
int i;
char s[10000];
for (i=0; i < sizeof(str)/sizeof(str[0]); i++) {
strcpy (s, str[i]);
printf ("'%s' -> '%s'\n", str[i], revStr(s));
}
return 0;
}
The output of that is:
'' -> ''
'a' -> 'a'
'ab' -> 'ba'
'abc' -> 'cba'
'abcd' -> 'dcba'
'abcde' -> 'edcba'
You are checking Parent
properties for null in your delegate. The same should work with lambda expressions too.
List<AnalysisObject> analysisObjects = analysisObjectRepository
.FindAll()
.Where(x =>
(x.ID == packageId) ||
(x.Parent != null &&
(x.Parent.ID == packageId ||
(x.Parent.Parent != null && x.Parent.Parent.ID == packageId)))
.ToList();
this
reference a javascript object and $(this)
used to encapsulate with jQuery.
Example =>
// Getting Name and modify css property of dom object through jQuery
var name = $(this).attr('name');
$(this).css('background-color','white')
// Getting form object and its data and work on..
this = document.getElementsByName("new_photo")[0]
formData = new FormData(this)
// Calling blur method on find input field with help of both as below
$(this).find('input[type=text]')[0].blur()
//Above is equivalent to
this = $(this).find('input[type=text]')[0]
this.blur()
//Find value of a text field with id "index-number"
this = document.getElementById("index-number");
this.value
or
this = $('#index-number');
$(this).val(); // Equivalent to $('#index-number').val()
$(this).css('color','#000000')
For the go up, you just need to use scrollTop
instead of scrollBottom
:
$("#upClick").on("click", function () {
scrolled = scrolled - 300;
$(".cover").stop().animate({
scrollTop: scrolled
});
});
Also, use the .stop() method to stop the currently-running animation on the cover
div. When .stop()
is called on an element, the currently-running animation (if any) is immediately stopped.
You didn't bind all your bindings here
$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate FROM comments WHERE articleid = :art
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";
$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );
You've declared a binding called :numRows but you never actually bind anything to it.
UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion
Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.
In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)
Note: ioutil is deprecated as of Go 1.16.
If the file isn't too large, this can be done with the ioutil.ReadFile
and strings.Split
functions like so:
content, err := ioutil.ReadFile(filename)
if err != nil {
//Do something
}
lines := strings.Split(string(content), "\n")
You can read the documentation on ioutil and strings packages.
I sometimes find a variation of this useful.
Example in JavaScript:
class Scaler {
constructor(inMin, inMax, outMin, outMax) {
this.inMin = inMin;
this.inMax = inMax;
this.outMin = outMin;
this.outMax = outMax;
}
scale(value) {
const result = (value - this.inMin) * (this.outMax - this.outMin) / (this.inMax - this.inMin) + this.outMin;
if (result < this.outMin) {
return this.outMin;
} else if (result > this.outMax) {
return this.outMax;
}
return result;
}
}
This example along with a function based version comes from the page https://writingjavascript.com/scaling-values-between-two-ranges
If you run your commands in a shell you can write something like "java -cp" and add any directories you want separated by ":" if java doesnt find something in one directory it will go try and find them in the other directories, that is what I do.
Here is a list of all http-headers: http://en.wikipedia.org/wiki/List_of_HTTP_header_fields
And here is a list of all apache-logformats: http://httpd.apache.org/docs/2.0/mod/mod_log_config.html#formats
As you did write correctly, the code for logging a specific header is %{foobar}i where foobar is the name of the header. So, the only solution is to create a specific format string. When you expect a non-standard header like x-my-nonstandard-header, then use %{x-my-nonstandard-header}i
. If your server is going to ignore this non-standard-header, why should you want to write it to your logfile? An unknown header has absolutely no effect to your system.
Under the hood BeautifulSoup now uses lxml. Requests, lxml & list comprehensions makes a killer combo.
import requests
import lxml.html
dom = lxml.html.fromstring(requests.get('http://www.nytimes.com').content)
[x for x in dom.xpath('//a/@href') if '//' in x and 'nytimes.com' not in x]
In the list comp, the "if '//' and 'url.com' not in x" is a simple method to scrub the url list of the sites 'internal' navigation urls, etc.
var label = $('#current_month');
var month = label.val('month');
var year = label.val('year');
var text = label.text();
alert(text);
<label year="2010" month="6" id="current_month"> June 2010</label>
SELECT * INTO OUTFILE "c:/mydata.csv"
FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY "\n"
FROM my_table;
(the documentation for this is here: http://dev.mysql.com/doc/refman/5.0/en/select.html)
or:
$select = "SELECT * FROM table_name";
$export = mysql_query ( $select ) or die ( "Sql error : " . mysql_error( ) );
$fields = mysql_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $export , $i ) . "\t";
}
while( $row = mysql_fetch_row( $export ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
$data = "\n(0) Records Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
If you use the JSON Serializer, you can simply store your object in string format as such
myHiddenText.value = JSON.stringify( myObject );
You can then get the value back with
myObject = JSON.parse( myHiddenText.value );
However, if you're not going to pass this value across page submits, it might be easier for you, and you'll save yourself a lot of serialization, if you just tuck it away as a global javascript variable.
From what I understand you want to make a navigation bar or something similar to it. What I recommend doing is making a list and editing the items from there. Just try this;
<ul>
<li class='item col-md-12 panel' id='gameplay-title'>Title</li>
<li class='item col-md-6 col-md-offset-3 panel' id='gameplay-scoreboard'>Scoreboard</li>
</ul>
And so on... To add more categories add another ul in there. Now, for the CSS you just need this;
ul {
list-style: none;
}
.item {
display: inline;
padding-right: 20px;
}
Access 2010 has both stored procedures, and also has table triggers. And, both features are available even when you not using a server (so, in 100% file based mode).
If you using SQL Server with Access, then of course the stored procedures are built using SQL Server and not Access.
For Access 2010, you open up the table (non-design view), and then choose the table tab. You see options there to create store procedures and table triggers.
For example:
Note that the stored procedure language is its own flavor just like Oracle or SQL Server (T-SQL). Here is example code to update an inventory of fruits as a result of an update in the fruit order table
Keep in mind these are true engine-level table triggers. In fact if you open up that table with VB6, VB.NET, FoxPro or even modify the table on a computer WITHOUT Access having been installed, the procedural code and the trigger at the table level will execute. So, this is a new feature of the data engine jet (now called ACE) for Access 2010. As noted, this is procedural code that runs, not just a single statement.
The environment variable PYTHONPATH
is actually only added to the list of locations Python searches for modules. You can print out the full list in the terminal like this:
python -c "import sys; print(sys.path)"
Or if want the output in the UNIX directory list style (separated by :
) you can do this:
python -c "import sys; print(':'.join(x for x in sys.path if x))"
Which will output something like this:
/usr/local/lib/python2.7/dist-packages/feedparser-5.1.3-py2.7.egg:/usr/local/lib/ python2.7/dist-packages/stripogram-1.5-py2.7.egg:/home/qiime/lib:/home/debian:/us r/lib/python2.7:/usr/lib/python2.7/plat-linux2:/usr/lib/python2.7/lib-tk:/usr/lib /python2.7/lib-old:/usr/lib/python2.7/lib- dynload:/usr/local/lib/python2.7/dist- packages:/usr/lib/python2.7/dist-packages:/usr/lib/python2.7/dist-packages/PIL:/u sr/lib/python2.7/dist-packages/gst-0.10:/usr/lib/python2.7/dist-packages/gtk-2.0: /usr/lib/pymodules/python2.7
You can simply add your JavaScript in body segment like this:
<body>
<script src="myScript.js"> </script>
</body>
myScript
will be the file name for your JavaScript. Just write the code and enjoy!
I recommend using pyenv to manage your local python versions (both 2.x and 3.x) instead of installing new versions directly with homebrew or building new python versions from source manually. Essentially, pyenv
can do two key things for you:
pyenv install 3.8.1
will install python 3.8.1 under ~/.pyenv/versions/3.8.1
.PATH
) with shims so that when you do pyenv local 3.8.1
, calling python
will invoke the new interpreter instead of your system python.The pyenv
repo is pretty detailed on how to install for different systems and what it's actually doing, but here's the basic steps for mac:
homebrew
if you don't already have it and use it to install pyenv
with brew install pyenv
.bash_profile
file to include:if command -v pyenv 1>/dev/null 2>&1; then
eval "$(pyenv init -)"
fi
Now install some python using pyenv and then switch to it with the pyenv local
command (you can see all your versions with pyenv versions
).
pyenv install 3.8.1 && pyenv local 3.8.1
Note: you may need to create a new shell or reload your bash_profile
in your current shell for the pyenv initialization to do its thing (set up shims).
With this setup, you'll be able to keep your system macosx python and switch to whatever new version of python you want available through pyenv
.
<a onclick="MyFunc()">blabla..</a>
There is nothing more in @Html.ActionLink that you could utilize in this case. And razor is evel by itself, drop it from where you can.
Try adding a control variable:
public void Method()
{
bool doSomethingElse = true;
if(something)
{
//some code
if(!something2)
{
doSomethingElse = false;
}
}
if(doSomethingElse)
{
// The code i want to go if the second if is true
}
}
You are missing a comma in your statement.
Try this:
data[data[, "Var1"]>10, ]
Or:
data[data$Var1>10, ]
Or:
subset(data, Var1>10)
As an example, try it on the built-in dataset, mtcars
data(mtcars)
mtcars[mtcars[, "mpg"]>25, ]
mpg cyl disp hp drat wt qsec vs am gear carb
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
mtcars[mtcars$mpg>25, ]
mpg cyl disp hp drat wt qsec vs am gear carb
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
subset(mtcars, mpg>25)
mpg cyl disp hp drat wt qsec vs am gear carb
Fiat 128 32.4 4 78.7 66 4.08 2.200 19.47 1 1 4 1
Honda Civic 30.4 4 75.7 52 4.93 1.615 18.52 1 1 4 2
Toyota Corolla 33.9 4 71.1 65 4.22 1.835 19.90 1 1 4 1
Fiat X1-9 27.3 4 79.0 66 4.08 1.935 18.90 1 1 4 1
Porsche 914-2 26.0 4 120.3 91 4.43 2.140 16.70 0 1 5 2
Lotus Europa 30.4 4 95.1 113 3.77 1.513 16.90 1 1 5 2
There is angular service written angular file server Uses FileSaver.js and Blob.js
vm.download = function(text) {
var data = new Blob([text], { type: 'text/plain;charset=utf-8' });
FileSaver.saveAs(data, 'text.txt');
};
jmespath works really quite easy and well, http://jmespath.org/ It is being used by Amazon in the AWS command line interface, so it´s got to be quite stable.
.toString()
is available, or just add ""
to the end of the int
var x = 3,
toString = x.toString(),
toConcat = x + "";
Angular is simply JavaScript at the core.
This can be accomplished by Unmarshaling into a map[string]json.RawMessage
.
var objmap map[string]json.RawMessage
err := json.Unmarshal(data, &objmap)
To further parse sendMsg
, you could then do something like:
var s sendMsg
err = json.Unmarshal(objmap["sendMsg"], &s)
For say
, you can do the same thing and unmarshal into a string:
var str string
err = json.Unmarshal(objmap["say"], &str)
EDIT: Keep in mind you will also need to export the variables in your sendMsg struct to unmarshal correctly. So your struct definition would be:
type sendMsg struct {
User string
Msg string
}
Both stored procedures and functions are named blocks that reside in the database and can be executed as and when required.
The major differences are:
A stored procedure can optionally return values using out parameters, but can also be written in a manner without returning a value. But, a function must return a value.
A stored procedure cannot be used in a SELECT statement whereas a function can be used in a SELECT statement.
Practically speaking, I would go for a stored procedure for a specific group of requirements and a function for a common requirement that could be shared across multiple scenarios. For example: comparing between two strings, or trimming them or taking the last portion, if we have a function for that, we could globally use it for any application that we have.
Any password generated with Math.random() is EXTREMELY BAD.
This function uses the system time as a seed for the random number generator. Anyone who knows the time the password was generated can easily brute-force the password.
In almost all cases, this data is easily available - just take the registration_time column in a hacked database, and test out all the values generated by the Math.random() algorithm using the times from 15 to 0 minutes before.
A password generated with Math.random() is completely worthless because the time the password was first used is enough for cracking it.
My solution was to use a short nickname (less than 31 characters) and then write the entire name in cell 0.
If every input asks the same question, you should use a for
loop and an array of inputs:
Scanner dd = new Scanner(System.in);
int[] vars = new int[3];
for(int i = 0; i < vars.length; i++) {
System.out.println("Enter next var: ");
vars[i] = dd.nextInt();
}
Or as Chip suggested, you can parse the input from one line:
Scanner in = new Scanner(System.in);
int[] vars = new int[3];
System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
vars[i] = in.nextInt();
You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.
The problem appeared first right after patching DCEVM with version: DCEVM-8u181-installer.jar.
Then, temoving the flag -XX:+UseG1GC from eclipse.ini it fixed the issue.
There aren't any quotes. It's just VS debugger. Try printing to the console or saving to a file and you'll see. As a side note: always dispose disposable objects:
using (var stringWriter = new StringWriter())
using (var xmlTextWriter = XmlWriter.Create(stringWriter))
{
xmlDoc.WriteTo(xmlTextWriter);
xmlTextWriter.Flush();
return stringWriter.GetStringBuilder().ToString();
}
Your snippet of code looks like it's referencing methods from one of the popular JavaScript libraries (jQuery, ProtoType, mooTools, and so on).
There's nothing mysterious about the use of $
in JavaScript. $
is simply a valid JavaScript identifier.
JavaScript allows upper and lower letters, numbers, and $
and _
. The $
was intended to be used for machine-generated variables (such as $0001
).
Prototype, jQuery, and most javascript libraries use the $
as the primary base object (or function). Most of them also have a way to relinquish the $
so that it can be used with another library that uses it. In that case you use jQuery
instead of $
. In fact, $
is just a shortcut for jQuery
.
Use this:-
echo $select->query();
or
Zend_Debug::dump($select->query();
You can use text property in your xml file for particular Edittext fields. For example :
<EditText
android:id="@+id/ET_User"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="yourusername"/>
like this all Edittext fields contains text whatever u want,if user wants to change particular Edittext field he remove older text and enter his new text.
In Another way just you get the particular Edittext field id in activity class and set text to that one.
Another way = programmatically
Example:
EditText username=(EditText)findViewById(R.id.ET_User);
username.setText("jack");
Solution: change the ReuseStrategy to never
Since this problem is very complex and there are so many different factors which can fail I was happy to find this solution in another post: How to solve org.apache.http.NoHttpResponseException
Never reuse connections: configure in org.apache.http.impl.client.AbstractHttpClient:
httpClient.setReuseStrategy(new NoConnectionReuseStrategy());
The same can be configured on a org.apache.http.impl.client.HttpClientBuilder builder:
builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
On windows run "cmd " as administrator and execute command.
"C:\Program Files\Git\mingw64\etc>"
"git config --system core.longpaths true"
or you have to chmod for the folder whereever git is installed.
or manullay update your file manually by going to path "Git\mingw64\etc"
[http]
sslBackend = schannel
[diff "astextplain"]
textconv = astextplain
[filter "lfs"]
clean = git-lfs clean -- %f
smudge = git-lfs smudge -- %f
process = git-lfs filter-process
required = true
[credential]
helper = manager
**[core]
longpaths = true**
Views in Oracle may be updateable under specific conditions. It can be tricky, and usually is not advisable.
From the Oracle 10g SQL Reference:
Notes on Updatable Views
An updatable view is one you can use to insert, update, or delete base table rows. You can create a view to be inherently updatable, or you can create an INSTEAD OF trigger on any view to make it updatable.
To learn whether and in what ways the columns of an inherently updatable view can be modified, query the USER_UPDATABLE_COLUMNS data dictionary view. The information displayed by this view is meaningful only for inherently updatable views. For a view to be inherently updatable, the following conditions must be met:
In addition, if an inherently updatable view contains pseudocolumns or expressions, then you cannot update base table rows with an UPDATE statement that refers to any of these pseudocolumns or expressions.
If you want a join view to be updatable, then all of the following conditions must be true:
So you just have to do this right?:
@echo off
echo text shizzle
echo.
echo pause^>nul (press enter)
pause>nul
REM writing to file
(
echo XD
echo LOL
)>settings.cdb
cls
REM setting the variables out of the file
(
set /p input=
set /p input2=
)<settings.cdb
cls
REM echo'ing the variables
echo variables:
echo %input%
echo %input2%
pause>nul
if %input%==XD goto newecho
DEL settings.cdb
exit
:newecho
cls
echo If you can see this, good job!
DEL settings.cdb
pause>nul
exit
The best approach for this sort of thing is probably git rebase
. It allows you to pull changes from master into your development branch, but leave all of your development work "on top of" (later in the commit log) the stuff from master. When your new work is complete, the merge back to master is then very straightforward.
There is very easy way to do it, from your laravel query just rename any column name, it will show you an error with your query.. :)
You probably already know about $(document).ready(...). What you need is a preloading mechanism; something that fetches data (text or images or whatever) before showing it off. This can make a site feel much more professional.
Take a look at jQuery.Preload (there are others). jQuery.Preload has several ways of triggering preloading, and also provides callback functionality (when the image is preloaded, then show it). I have used it heavily, and it works great.
Here's how easy it is to get started with jQuery.Preload:
$(function() {
// First get the preload fetches under way
$.preload(["images/button-background.png", "images/button-highlight.png"]);
// Then do anything else that you would normally do here
doSomeStuff();
});
Arrays in JS have two types of properties:
Regular elements and associative properties (which are nothing but objects)
When you define a = new Array()
, you are defining an empty array. Note that there are no associative objects yet
When you define b = new Array(2)
, you are defining an array with two undefined locations.
In both your examples of 'a' and 'b', you are adding associative properties i.e. objects to these arrays.
console.log (a)
or console.log(b)
prints the array elements i.e. []
and [undefined, undefined]
respectively. But since a1/a2
and b1/b2
are associative objects inside their arrays, they can be logged only by console.log(a.a1, a.a2)
kind of syntax
Do you mean you want Class C to be the base class for A & B in that case.
public abstract class C
{
public abstract void Method1();
public abstract void Method2();
}
public class A : C
{
public override void Method1()
{
throw new NotImplementedException();
}
public override void Method2()
{
throw new NotImplementedException();
}
}
public class B : C
{
public override void Method1()
{
throw new NotImplementedException();
}
public override void Method2()
{
throw new NotImplementedException();
}
}
Your onCreate()
method has several huge flaws:
1) onCreate
prepares your Activity - so nothing that you do here will be made visible to the user until this method finishes! For example - you will never be able to alter a TextView
's text here more than ONE time as only the last change will be drawn and thus visible to the user!
2) Keep in mind that an Android program will - by default - run in ONE thread only! Thus: never use Thread.sleep()
or Thread.wait()
in your main thread which is responsible for your UI! (read "Keep your App Responsive" for further information!)
What your initialization of your Activity does is:
TextView
object t
!TextView
in the variable t
later.t
(but keep in mind: it will be displayed only after onCreate()
finishes and the main event loop of your application runs!)onCreate
method - this must never be done as it stops all UI activity and will definitely force an ANR (Application Not Responding, see link above!)onCreate()
method finishes and several other Activity lifecycle methods have been processed!The solution:
Set text only once in onCreate()
- this must be the first text that should be visible.
Create a Runnable
and a Handler
private final Runnable mUpdateUITimerTask = new Runnable() {
public void run() {
// do whatever you want to change here, like:
t.setText("Second text to display!");
}
};
private final Handler mHandler = new Handler();
install this runnable as a handler, possible in onCreate()
(but read my advice below):
// run the mUpdateUITimerTask's run() method in 10 seconds from now
mHandler.postDelayed(mUpdateUITimerTask, 10 * 1000);
Advice: be sure you know an Activity
's lifecycle! If you do stuff like that in onCreate()
this will only happen when your Activity
is created the first time! Android will possibly keep your Activity
alive for a longer period of time, even if it's not visible!
When a user "starts" it again - and it is still existing - you will not see your first text anymore!
=> Always install handlers in onResume()
and disable them in onPause()
! Otherwise you will get "updates" when your Activity
is not visible at all!
In your case, if you want to see your first text again when it is re-activated, you must set it in onResume()
, not onCreate()
!
select cast(cast(datepart(year,getdate()) as char(4))
+ '/'
+ cast(datepart(month,getdate()) as char(2))
+ '/01' as datetime)
Using the answer of @Slauma i have made a code snippet (a surrounds with snippet) for better use.
<?xml version="1.0" encoding="utf-8"?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<SnippetTypes>
<SnippetType>SurroundsWith</SnippetType>
</SnippetTypes>
<Title>ValidationErrorsTryCatch</Title>
<Author>Phoenix</Author>
<Description>
</Description>
<HelpUrl>
</HelpUrl>
<Shortcut>
</Shortcut>
</Header>
<Snippet>
<Code Language="csharp"><![CDATA[try
{
$selected$ $end$
}
catch (System.Data.Entity.Validation.DbEntityValidationException e)
{
foreach (var eve in e.EntityValidationErrors)
{
Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
eve.Entry.Entity.GetType().Name, eve.Entry.State);
foreach (var ve in eve.ValidationErrors)
{
Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
ve.PropertyName, ve.ErrorMessage);
}
}
throw;
}]]></Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
The Main
method is static inside the Program
class. You can't call an instance method from inside a static method, which is why you're getting the error.
To fix it you just need to make your GetRandomBits()
method static as well.
According to Apple documents for swift 4.1 you can use this struct so easily to create a 2D array:
Code sample:
struct Matrix {
let rows: Int, columns: Int
var grid: [Double]
init(rows: Int, columns: Int) {
self.rows = rows
self.columns = columns
grid = Array(repeating: 0.0, count: rows * columns)
}
func indexIsValid(row: Int, column: Int) -> Bool {
return row >= 0 && row < rows && column >= 0 && column < columns
}
subscript(row: Int, column: Int) -> Double {
get {
assert(indexIsValid(row: row, column: column), "Index out of range")
return grid[(row * columns) + column]
}
set {
assert(indexIsValid(row: row, column: column), "Index out of range")
grid[(row * columns) + column] = newValue
}
}
}
The exact answer depends on the context. In general, these characters must not be present (HTML 5.2 §3.2.4.2.5):
Text nodes and attribute values must consist of Unicode characters, must not contain U+0000 characters, must not contain permanently undefined Unicode characters (noncharacters), and must not contain control characters other than space characters. This specification includes extra constraints on the exact value of Text nodes and attribute values depending on their precise context.
For elements in HTML, the constraints of the Text content model also depends on the kind of element. For instance, an "<" inside a textarea element does not need to be escaped in HTML because textarea is an escapable raw text element.
These restrictions are scattered across the specification. E.g., attribute values (§8.1.2.3) must not contain an ambiguous ampersand and be either (i) empty, (ii) within single quotes (and thus must not contain U+0027 APOSTROPHE character '
), (iii) within double quotes (must not contain U+0022 QUOTATION MARK character "
), or (iv) unquoted — with the following restrictions:
... must not contain any literal space characters, any U+0022 QUOTATION MARK characters ("), U+0027 APOSTROPHE characters ('), U+003D EQUALS SIGN characters (=), U+003C LESS-THAN SIGN characters (<), U+003E GREATER-THAN SIGN characters (>), or U+0060 GRAVE ACCENT characters (`), and must not be the empty string.
A file object is an instance of Blob but a blob object is not an instance of File
new File([], 'foo.txt').constructor.name === 'File' //true
new File([], 'foo.txt') instanceof File // true
new File([], 'foo.txt') instanceof Blob // true
new Blob([]).constructor.name === 'Blob' //true
new Blob([]) instanceof Blob //true
new Blob([]) instanceof File // false
new File([], 'foo.txt').constructor.name === new Blob([]).constructor.name //false
If you must convert a file object to a blob object, you can create a new Blob object using the array buffer of the file. See the example below.
let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];
let reader = new FileReader();
reader.onload = function(e) {
let blob = new Blob([new Uint8Array(e.target.result)], {type: file.type });
console.log(blob);
};
reader.readAsArrayBuffer(file);
As pointed by @bgh you can also use the arrayBuffer method of the File object. See the example below.
let file = new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'});
//or let file = document.querySelector('input[type=file]').files[0];
file.arrayBuffer().then((arrayBuffer) => {
let blob = new Blob([new Uint8Array(arrayBuffer)], {type: file.type });
console.log(blob);
});
If your environment supports async/await you can use a one-liner like below
let fileToBlob = async (file) => new Blob([new Uint8Array(await file.arrayBuffer())], {type: file.type });
console.log(await fileToBlob(new File(['hello', ' ', 'world'], 'hello_world.txt', {type: 'text/plain'})));