@praneeth-nidarshan has covered mostly all the steps, except some:
$ sudo apt-get install php-pear
sh: phpize: not found
ERROR: `phpize’ failed
$ sudo apt-get install php7.2-dev
$ sudo pecl install mcrypt-1.0.1
extension=mcrypt.so
to your php.ini configuration file; if you don't know where it is, search with:$ sudo php -i | grep 'Configuration File'
I got this error because I was using
import ReactDOM from 'react-dom'
without importing react, once I changed it to below:
import React from 'react';
import ReactDOM from 'react-dom';
The error was solved :)
Here is the proper solution. You should use jquery datepicker everywhere
<script>
$( function() {
$( ".simple_date" ).datepicker();
} );
</script>
Below is the link to get the complete code
https://tutorialvilla.com/how/how-to-solve-the-problem-of-html-date-picker
Triggering change events on arbitrary elements creates dependencies between components which are hard to reason about. It's better to stick with React's one-way data flow.
There is no simple snippet to trigger React's change event. The logic is implemented in ChangeEventPlugin.js and there are different code branches for different input types and browsers. Moreover, the implementation details vary across versions of React.
I have built react-trigger-change that does the thing, but it is intended to be used for testing, not as a production dependency:
let node;
ReactDOM.render(
<input
onChange={() => console.log('changed')}
ref={(input) => { node = input; }}
/>,
mountNode
);
reactTriggerChange(node); // 'changed' is logged
You can use following code:
sendButton.enabled = YES;
sendButton.alpha = 1.0;
or
sendButton.enabled = NO;
sendButton.alpha = 0.5;
It's probably easiest to create your query object directly as:
Test.find({
$and: [
{ $or: [{a: 1}, {b: 1}] },
{ $or: [{c: 1}, {d: 1}] }
]
}, function (err, results) {
...
}
But you can also use the Query#and
helper that's available in recent 3.x Mongoose releases:
Test.find()
.and([
{ $or: [{a: 1}, {b: 1}] },
{ $or: [{c: 1}, {d: 1}] }
])
.exec(function (err, results) {
...
});
Here is a really simple, but very effective, example. Once you have the basics down you can easily build off of it.
There are two main parts to using a Cursor Adapter with SQLite:
Create a proper Cursor from the Database.
Create a custom Cursor Adapter that takes the Cursor data from the database and pairs it with the View you intend to represent the data with.
In your Activity:
SQLiteOpenHelper sqLiteOpenHelper = new SQLiteOpenHelper(
context, DATABASE_NAME, null, DATABASE_VERSION);
SQLiteDatabase sqLiteDatabase = sqLiteOpenHelper.getReadableDatabase();
String query = "SELECT * FROM clients ORDER BY company_name ASC"; // No trailing ';'
Cursor cursor = sqLiteDatabase.rawQuery(query, null);
ClientCursorAdapter adapter = new ClientCursorAdapter(
this, R.layout.clients_listview_row, cursor, 0 );
this.setListAdapter(adapter);
Note: Extending from ResourceCursorAdapter
assumes you use XML to create your views.
public class ClientCursorAdapter extends ResourceCursorAdapter {
public ClientCursorAdapter(Context context, int layout, Cursor cursor, int flags) {
super(context, layout, cursor, flags);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
TextView name = (TextView) view.findViewById(R.id.name);
name.setText(cursor.getString(cursor.getColumnIndex("name")));
TextView phone = (TextView) view.findViewById(R.id.phone);
phone.setText(cursor.getString(cursor.getColumnIndex("phone")));
}
}
I know this is an old thread, but if anyone is looking for an answer of why their procedures doesn't work in the workbench and think the only result is "Query canceled" or anything like that without clues:
the output with errors or problems is hiddenl. I do not know why, I do understand it's annoying, but it is there. just move your cursor above the line above the message, it will turn in an double arrow (up and down) you can then click and drag that line up, then you will see a console with the message you missed!
You neglected to say which version of C you are concerned about. Let's assume it's this one:
http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1570.pdf
As you can see by reading the specification, the standard definitions of true
and false
are 1 and 0, yes.
If your question is about a different version of C, or about non-standard definitions for true
and false
, then ask a more specific question.
Create a bi-directional relationship, like this:
@Entity
public class Parent implements Serializable {
@Id
@GeneratedValue
private long id;
@OneToMany(mappedBy = "parent", cascade = CascadeType.REMOVE)
private Set<Child> children;
}
Remove the starting semicolon ( ; )
Like:
;extension=php_intl.dll
to extension=php_intl.dll
This helped me.
I have tried very hard on all the answers above. However, they did not actually help because I used a mac. The rio library has this import function which can basically import any type of data file into Rstudio, even those file using languages other than English!
Try codes below:
library(rio)
AB <- import("C:/AB_DNA_Tag_Numbers.xlsx")
AB <- AB[,1]
Hope this help. For more detailed reference: https://cran.r-project.org/web/packages/rio/vignettes/rio.html
For me, I forgot to add the default serial id.
private static final long serialVersionUID = 1L;
It can be convenient to select count with filter by indexed field. Try this
EXPLAIN SELECT * FROM table_name WHERE key < anything;
To get class name you can use ReflectionClass
class MyClass {
public function myNameIs(){
return (new \ReflectionClass($this))->getShortName();
}
}
Temp table variable is saved to the temp.db and the scope is limited to the current execution. Hence, unlike dropping a Temp tables e.g drop table #tempTable, we don't have to explicitly drop Temp table variable @tempTableVariable. It is automatically taken care by the sql server.
drop table @tempTableVariable -- Invalid
Here’s a variant of Darin Dimitrov’s answer that doesn’t modify the Array
prototype:
const applyToArray = (func, array) => func.apply(Math, array)
applyToArray(Math.min, [1,2,3,4]) // 1
applyToArray(Math.max, [1,2,3,4]) // 4
Laravel 4.2 and beyond, may use try relationship querying:-
Products::whereHas('product_category', function($query) {
$query->whereIn('category_id', ['223', '15']);
});
public function product_category() {
return $this->hasMany('product_category', 'product_id');
}
SELECT ID , Date , Name into #temp from [TableName]
as long as "lots of stuff" isn't doing something asynchronous this is absolutely unneccessary - the event will call every handler on his way in sequence, so if theres a onklick-event on a parent-element this will fire after the onclik-event of the child has processed completely. javascript doesn't do some kind of "multithreading" here that makes "stopping" the event processing neccessary. conclusion: "pausing" an event just to resume it in the same handler doesn't make any sense.
if "lots of stuff" is something asynchronous this also doesn't make sense as it prevents the asynchonous things to do what they should do (asynchonous stuff) and make them bahave like everything is in sequence (where we come back to my first paragraph)
n % x == 0
Means that n can be divided by x. So... for instance, in your case:
boolean isDivisibleBy20 = number % 20 == 0;
Also, if you want to check whether a number is even or odd (whether it is divisible by 2 or not), you can use a bitwise operator:
boolean even = (number & 1) == 0;
boolean odd = (number & 1) != 0;
#!/usr/bin/python
import sys
col = int(sys.argv[1]) - 1
for line in sys.stdin:
columns = line.split()
try:
print(columns[col])
except IndexError:
# ignore
pass
Then, supposing you name the script as co, say, do something like this to get the sizes of files (the example assumes you're using Linux, but the script itself is OS-independent) :-
ls -lh | co 5
I know this post is old but it was the first one that popped up when I did a search. I tried @Kim Kling RegExp but it failed miserably. Also prior to finding this forum I had tried almost all the other variations listed here. In the end, none of them worked except this one I created; it works fine, plus it is es6:
const regex = new RegExp(/[^0-9]/, 'g');
const val = document.forms["myForm"]["age"].value;
if (val.match(regex)) {
alert("Must be a valid number");
}
Below Code will work for this IFF it in the same order as its mentionened make sure you order is type then name, ng-model ng-init, value. thats It.
An expression of non-boolean type specified in a context where a condition is expected
I also got this error when I forgot to add ON condition when specifying my join clause.
@import url("http://netdna.bootstrapcdn.com/bootstrap/3.0.0-wip/css/bootstrap.min.css");
.row {
height: 100px;
background-color: green;
}
.container {
margin-top: 50px;
box-shadow: 0 0 30px black;
padding:0 15px 0 15px;
}
<div class="container">
<div class="row">one</div>
<div class="row">two</div>
<div class="row">three</div>
</div>
</body>
As far as I know, display: inline-block
is what you probably need. That will make it seem like it's sort of inline but still allow you to use things like margins and such.
or, like I did..just uninstall virtualenvwrapper
sudo pip uninstall virtualenvwrapper
and then install it with easy_install
sudo easy_install virtualenvwrapper
this time I found the file "/usr/local/bin/virtualenvwrapper.sh" installed... Before that I weren't finding that file anywhere even by this command
find / -name virtualenvwrapper.sh
type=submit
it is a Submit Button type=button
it is just a button, It does not submit your form inputs. and also you don't want to use both of these
If I understand you correctly, you want to compose a multipart request manually from an HTTP/REST console. The multipart format is simple; a brief introduction can be found in the HTML 4.01 spec. You need to come up with a boundary, which is a string not found in the content, let’s say HereGoes
. You set request header Content-Type: multipart/form-data; boundary=HereGoes
. Then this should be a valid request body:
--HereGoes
Content-Disposition: form-data; name="myJsonString"
Content-Type: application/json
{"foo": "bar"}
--HereGoes
Content-Disposition: form-data; name="photo"
Content-Type: image/jpeg
Content-Transfer-Encoding: base64
<...JPEG content in base64...>
--HereGoes--
You don't need to create the SSH keys on the Jenkins server, nor do you need to store the SSH keys on the Jenkins server's filesystem. This bit of information is crucial in environments where Jenkins servers instances may be created and destroyed frequently.
On any machine (Windows, Linux, MacOS ...doesn't matter) generate an SSH key pair. Use this article as guide:
On the target server, you will need to place the content of the public key (id_rsa.pub
per the above article) into the .ssh/authorized_keys
file under the home directory of the user which Jenkins will be using for deployment.
Ref: https://plugins.jenkins.io/publish-over-ssh/
Visit: Jenkins
> Manage Jenkins
> Configure System
> Publish over SSH
id_rsa
per the above article) into the "Key" fieldVisit: Jenkins
> Credentials
> System
> Global credentials (unrestricted)
> Add Credentials
id_rsa
per the above article)]Since you can also input numbers as well as fixed type strings, the answer should actually be:
function isBlank(value) {
return $.trim(value);
}
If using WORD for mac enable 'use maths autocorrect rules outside maths regions' Type \therefore
You can achieve this using below method. just pass the total no. of columns present in the DataFrame as arg to
'display.max_columns'
For eg :
df= DataFrame(..)
with pd.option_context('display.max_rows', None, 'display.max_columns', df.shape[1]):
print(df)
You can avoid much trouble by using this --
myButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
myButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
This will align all your content automatically to left (or wherever you want it)
Swift 3:
myButton.contentHorizontalAlignment = UIControlContentHorizontalAlignment.left;
myButton.contentVerticalAlignment = UIControlContentVerticalAlignment.center;
You might implement your class model by composition, having the book object have a map of chapter objects contained within it (map chapter number to chapter object). Your search function could be given a list of books into which to search by asking each book to search its chapters. The book object would then iterate over each chapter, invoking the chapter.search() function to look for the desired key and return some kind of index into the chapter. The book's search() would then return some data type which could combine a reference to the book and some way to reference the data that it found for the search. The reference to the book could be used to get the name of the book object that is associated with the collection of chapter search hits.
put a int
infront of the all the voxelCoord
's...Like this below :
patch = numpyImage [int(voxelCoord[0]),int(voxelCoord[1])- int(voxelWidth/2):int(voxelCoord[1])+int(voxelWidth/2),int(voxelCoord[2])-int(voxelWidth/2):int(voxelCoord[2])+int(voxelWidth/2)]
To get individual colour values you can use Color like following for pixel(x,y).
import java.awt.Color;
import java.awt.image.BufferedImage;
Color c = new Color(buffOriginalImage.getRGB(x,y));
int red = c.getRed();
int green = c.getGreen();
int blue = c.getBlue();
The above will give you the integer values of Red, Green and Blue in range of 0 to 255.
To set the values from RGB you can do so by:
Color myColour = new Color(red, green, blue);
int rgb = myColour.getRGB();
//Change the pixel at (x,y) ti rgb value
image.setRGB(x, y, rgb);
Please be advised that the above changes the value of a single pixel. So if you need to change the value entire image you may need to iterate over the image using two for loops.
#distance beetween segment ab and point c in 2D space
getDistance_ort_2 <- function(a, b, c){
#go to complex numbers
A<-c(a[1]+1i*a[2],b[1]+1i*b[2])
q=c[1]+1i*c[2]
#function to get coefficients of line (ab)
getAlphaBeta <- function(A)
{ a<-Re(A[2])-Re(A[1])
b<-Im(A[2])-Im(A[1])
ab<-as.numeric()
ab[1] <- -Re(A[1])*b/a+Im(A[1])
ab[2] <-b/a
if(Im(A[1])==Im(A[2])) ab<- c(Im(A[1]),0)
if(Re(A[1])==Re(A[2])) ab <- NA
return(ab)
}
#function to get coefficients of line ortogonal to line (ab) which goes through point q
getAlphaBeta_ort<-function(A,q)
{ ab <- getAlphaBeta(A)
coef<-c(Re(q)/ab[2]+Im(q),-1/ab[2])
if(Re(A[1])==Re(A[2])) coef<-c(Im(q),0)
return(coef)
}
#function to get coordinates of interception point
#between line (ab) and its ortogonal which goes through point q
getIntersection_ort <- function(A, q){
A.ab <- getAlphaBeta(A)
q.ab <- getAlphaBeta_ort(A,q)
if (!is.na(A.ab[1])&A.ab[2]==0) {
x<-Re(q)
y<-Im(A[1])}
if (is.na(A.ab[1])) {
x<-Re(A[1])
y<-Im(q)
}
if (!is.na(A.ab[1])&A.ab[2]!=0) {
x <- (q.ab[1] - A.ab[1])/(A.ab[2] - q.ab[2])
y <- q.ab[1] + q.ab[2]*x}
xy <- x + 1i*y
return(xy)
}
intersect<-getIntersection_ort(A,q)
if ((Mod(A[1]-intersect)+Mod(A[2]-intersect))>Mod(A[1]-A[2])) {dist<-min(Mod(A[1]-q),Mod(A[2]-q))
} else dist<-Mod(q-intersect)
return(dist)
}
I was just tinkering with danteuno's answer and found that while good-intentioned, sadly it's broken on several browsers that are not IE. This is because IE will be quite strict about what it accepts as the argument to the Date
constructor, but others will not. For example, Chrome 18 gives
> new Date("66")
Sat Jan 01 1966 00:00:00 GMT+0200 (GTB Standard Time)
This causes the code to take the "compare dates" path and it all goes downhill from there (e.g. new Date("11")
is greater than new Date("66")
and this is obviously the opposite of the desired effect).
Therefore after consideration I modified the code to give priority to the "numbers" path over the "dates" path and validate that the input is indeed numeric with the excellent method provided in Validate decimal numbers in JavaScript - IsNumeric().
In the end, the code becomes:
$.validator.addMethod(
"greaterThan",
function(value, element, params) {
var target = $(params).val();
var isValueNumeric = !isNaN(parseFloat(value)) && isFinite(value);
var isTargetNumeric = !isNaN(parseFloat(target)) && isFinite(target);
if (isValueNumeric && isTargetNumeric) {
return Number(value) > Number(target);
}
if (!/Invalid|NaN/.test(new Date(value))) {
return new Date(value) > new Date(target);
}
return false;
},
'Must be greater than {0}.');
You can use flex: 1
styling on an <Image>
element to have it fill the whole screen. You can then use one of the Image resize modes to have the image completely fill the element:
<Image source={require('image!egg')} style={styles.backgroundImage} />
Style:
import React from 'react-native';
let { StyleSheet } = React;
let styles = StyleSheet.create({
backgroundImage: {
flex: 1,
resizeMode: 'cover', // or 'stretch'
}
});
I'm pretty sure you can get rid of the <View>
wrapping your image and this will work.
you need to convert to char first because converting to int adds those days to 1900-01-01
select CONVERT (datetime,convert(char(8),rnwl_efctv_dt ))
here are some examples
select CONVERT (datetime,5)
1900-01-06 00:00:00.000
select CONVERT (datetime,20100101)
blows up, because you can't add 20100101 days to 1900-01-01..you go above the limit
convert to char first
declare @i int
select @i = 20100101
select CONVERT (datetime,convert(char(8),@i))
First, you need to check the port 9042 whether this open or not if open then check below things like rpc_address and listen_address. you should set the server own IP address instead 0.0.0.0 or 127.0.0.1.
If all okay then please run below command to connect cqlsh.
cqlsh IP address 9042
If you enable authentication and authorization you have to put user/pass with this command.
In BBEdit works this (ex.: changing the ID values to lowercase):
Search any value: <a id="(?P<x>.*?)"></a>
Replace with the same in lowercase: <a id="\L\P<x>\E"></a>
Was: <a id="VALUE"></a>
Became: <a id="value"></a>
This worked for me:
Seems like something went south when I originally created the site. I hate solutions that are similar to "Restart your machine, then reinstall windows" without knowing what caused the error. But, this worked for me. Quick and simple. Hope it helps someone else.
Jon, you have some syntax errors, see below, this worked for me.
<script type="text/javascript">
$(document).ready(function () {
$.validator.addMethod(
"australianDate",
function (value, element) {
// put your own logic here, this is just a (crappy) example
return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
},
"Please enter a date in the format dd/mm/yyyy"
);
$('#testForm').validate({
rules: {
"myDate": {
australianDate: true
}
}
});
});
Another useful solution, you can work with this string as array of String
for (String s : "xyz".split("")) {
System.out.println(s);
}
Can you not find out using Request.Form Collection? If process is clicked the request.form["process"] will not be empty
Path.GetDirectoryName(filename);
you could add an column of the md5 of long columns
Extract the jar, and put it somewhere in your Java project (usually under a "lib" subdirectory).
Right click the project, open its preferences, go for Java build path, and then the Libraries tab. You can add the library there with "add a jar".
If your jar is not open source, you may want to store it elsewhere and connect to it as an external jar.
Use the files
filelist of the element instead of val()
$("input[type=file]").on('change',function(){
alert(this.files[0].name);
});
Members with a constructor will have their default constructor called for initialisation.
You cannot depend on the contents of the other types.
Try this one -
DECLARE @i FLOAT = 6.677756
SELECT
ROUND(@i, 2)
, FORMAT(@i, 'N2')
, CAST(@i AS DECIMAL(18,2))
, SUBSTRING(PARSENAME(CAST(@i AS VARCHAR(10)), 1), PATINDEX('%.%', CAST(@i AS VARCHAR(10))) - 1, 2)
, FLOOR((@i - FLOOR(@i)) * 100)
Output:
----------------------
6,68
6.68
6.68
67
67
The general problem here is that git fetch
will fetch +refs/heads/*:refs/remotes/$remote/*
. If any of these commits have tags, those tags will also be fetched. However if there are tags not reachable by any branch on the remote, they will not be fetched.
The --tags
option switches the refspec to +refs/tags/*:refs/tags/*
. You could ask git fetch
to grab both. I'm pretty sure to just do a git fetch && git fetch -t
you'd use the following command:
git fetch origin "+refs/heads/*:refs/remotes/origin/*" "+refs/tags/*:refs/tags/*"
And if you wanted to make this the default for this repo, you can add a second refspec to the default fetch:
git config --local --add remote.origin.fetch "+refs/tags/*:refs/tags/*"
This will add a second fetch =
line in the .git/config
for this remote.
I spent a while looking for the way to handle this for a project. This is what I came up with.
git fetch -fup origin "+refs/*:refs/*"
In my case I wanted these features
refs/*:refs/*
+
before the refspec-u
-p
-f
I have also used following link as others have suggested you for bluetooth communication.
http://developer.android.com/guide/topics/connectivity/bluetooth.html
The thing is all you need is a class BluetoothChatService.java
this class has following threads:
Now when you call start function of the BluetoothChatService like:
mChatService.start();
It starts accept thread which means it will start looking for connection.
Now when you call
mChatService.connect(<deviceObject>,false/true);
Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.
connect
function will start connecting thread which will look for any device which is running accept thread.
When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:
connected(mmSocket, mmDevice, mSocketType);
this method starts connected thread in both the devices:
Using this socket object connected thread obtains the input and output stream to the other device.
And calls read
function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.
BluetoothChatService also has a write
method which takes byte[]
as input and calls write method on connected thread.
mChatService.write("your message".getByte());
write method in connected thread just write this byte data to outputsream of the other device.
public void write(byte[] buffer) {
try {
mmOutStream.write(buffer);
// Share the sent message back to the UI Activity
// mHandler.obtainMessage(
// BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
// buffer).sendToTarget();
} catch (IOException e) {
Log.e(TAG, "Exception during write", e);
}
}
Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.
In my case the problem was due to some phantom files under the project's obj directory. The following fixed the issue for me:
To extend on @tredder's answer you can alter the environmentVariables using appcmd
Staging
%windir%\system32\inetsrv\appcmd set config "staging.example.com" /section:system.webServer/aspNetCore /+environmentVariables.[name='ASPNETCORE_ENVIRONMENT',value='Staging'] /commit:APPHOST
Production
%windir%\system32\inetsrv\appcmd set config "example.com" /section:system.webServer/aspNetCore /+environmentVariables.[name='ASPNETCORE_ENVIRONMENT',value='Production'] /commit:APPHOST
Just an update since I was trying all this stuff today in response to a customer issue
Java doesn't have a Random generator between two values in the same way that Python does. It actually only takes one value in to generate the Random. What you need to do, then, is add ONE CERTAIN NUMBER to the number generated, which will cause the number to be within a range. For instance:
package RandGen;
import java.util.Random;
public class RandGen {
public static Random numGen =new Random();
public static int RandNum(){
int rand = Math.abs((100)+numGen.nextInt(100));
return rand;
}
public static void main(String[]Args){
System.out.println(RandNum());
}
}
This program's function lies entirely in line 6 (The one beginning with "int rand...". Note that Math.abs() simply converts the number to absolute value, and it's declared as an int, that's not really important. The first (100) is the number I am ADDING to the random one. This means that the new output number will be the random number + 100. numGen.nextInt() is the value of the random number itself, and because I put (100) in its parentheses, it is any number between 1 and 100. So when I add 100, it becomes a number between 101 and 200. You aren't actually GENERATING a number between 100 and 200, you are adding to the one between 1 and 100.
I have put my working gmail java class up on pastebin for your review, pay special attention to the "startSessionWithTLS" method and you may be able adjust JavaMail to provide the same functionality. http://pastebin.com/VE8Mqkqp
You can install ECMerge diff/merge tool on your Linux, Mac or Windows. It is pre-configured in Git, so just using git mergetool
will do the job.
The first parameter of Html.RadioButtonFor() should be the property name you're using, and the second parameter should be the value of that specific radio button. Then they'll have the same name attribute value and the helper will select the given radio button when/if it matches the property value.
Example:
<div class="editor-field">
<%= Html.RadioButtonFor(m => m.Gender, "M" ) %> Male
<%= Html.RadioButtonFor(m => m.Gender, "F" ) %> Female
</div>
Here's a more specific example:
I made a quick MVC project named "DeleteMeQuestion" (DeleteMe prefix so I know that I can remove it later after I forget about it).
I made the following model:
namespace DeleteMeQuestion.Models
{
public class QuizModel
{
public int ParentQuestionId { get; set; }
public int QuestionId { get; set; }
public string QuestionDisplayText { get; set; }
public List<Response> Responses { get; set; }
[Range(1,999, ErrorMessage = "Please choose a response.")]
public int SelectedResponse { get; set; }
}
public class Response
{
public int ResponseId { get; set; }
public int ChildQuestionId { get; set; }
public string ResponseDisplayText { get; set; }
}
}
There's a simple range validator in the model, just for fun. Next up, I made the following controller:
namespace DeleteMeQuestion.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index(int? id)
{
// TODO: get question to show based on method parameter
var model = GetModel(id);
return View(model);
}
[HttpPost]
public ActionResult Index(int? id, QuizModel model)
{
if (!ModelState.IsValid)
{
var freshModel = GetModel(id);
return View(freshModel);
}
// TODO: save selected answer in database
// TODO: get next question based on selected answer (hard coded to 999 for now)
var nextQuestionId = 999;
return RedirectToAction("Index", "Home", new {id = nextQuestionId});
}
private QuizModel GetModel(int? questionId)
{
// just a stub, in lieu of a database
var model = new QuizModel
{
QuestionDisplayText = questionId.HasValue ? "And so on..." : "What is your favorite color?",
QuestionId = 1,
Responses = new List<Response>
{
new Response
{
ChildQuestionId = 2,
ResponseId = 1,
ResponseDisplayText = "Red"
},
new Response
{
ChildQuestionId = 3,
ResponseId = 2,
ResponseDisplayText = "Blue"
},
new Response
{
ChildQuestionId = 4,
ResponseId = 3,
ResponseDisplayText = "Green"
},
}
};
return model;
}
}
}
Finally, I made the following view that makes use of the model:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<DeleteMeQuestion.Models.QuizModel>" %>
<asp:Content ContentPlaceHolderID="TitleContent" runat="server">
Home Page
</asp:Content>
<asp:Content ContentPlaceHolderID="MainContent" runat="server">
<% using (Html.BeginForm()) { %>
<div>
<h1><%: Model.QuestionDisplayText %></h1>
<div>
<ul>
<% foreach (var item in Model.Responses) { %>
<li>
<%= Html.RadioButtonFor(m => m.SelectedResponse, item.ResponseId, new {id="Response" + item.ResponseId}) %>
<label for="Response<%: item.ResponseId %>"><%: item.ResponseDisplayText %></label>
</li>
<% } %>
</ul>
<%= Html.ValidationMessageFor(m => m.SelectedResponse) %>
</div>
<input type="submit" value="Submit" />
<% } %>
</asp:Content>
As I understand your context, you have questions with a list of available answers. Each answer will dictate the next question. Hopefully that makes sense from my model and TODO comments.
This gives you the radio buttons with the same name attribute, but different ID attributes.
I can't say how much this might help you, but just found a solution to something similar problem which I faced. In the Pivot-
This would refine the data. Then, I had just copy and pasted this data in a new tab wherein I had applied the filters to my Total column with values greater than certain percentage.
This did work in my case and hope it helps you too.
I couldn't used android:anyDensity="true" because objects in my game would be positioned completely different... seems this also does the trick:
// creating locale Locale locale2 = new Locale(loc); Locale.setDefault(locale2); Configuration config2 = new Configuration(); config2.locale = locale2; // updating locale mContext.getResources().updateConfiguration(config2, null);
For your first method change ws.Range("A")
to ws.Range("A:A")
which will search the entirety of column a, like so:
Sub Find_Bingo()
Dim wb As Workbook
Dim ws As Worksheet
Dim FoundCell As Range
Set wb = ActiveWorkbook
Set ws = ActiveSheet
Const WHAT_TO_FIND As String = "Bingo"
Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
If Not FoundCell Is Nothing Then
MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
Else
MsgBox (WHAT_TO_FIND & " not found")
End If
End Sub
For your second method, you are using Bingo
as a variable instead of a string literal. This is a good example of why I add Option Explicit
to the top of all of my code modules, as when you try to run the code it will direct you to this "variable" which is undefined and not intended to be a variable at all.
Additionally, when you are using With...End With
you need a period .
before you reference Cells
, so Cells
should be .Cells
. This mimics the normal qualifying behavior (i.e. Sheet1.Cells.Find..)
Change Bingo
to "Bingo"
and change Cells
to .Cells
With Sheet1
Set FoundCell = .Cells.Find(What:="Bingo", After:=.Cells(1, 1), _
LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
End With
If Not FoundCell Is Nothing Then
MsgBox ("""Bingo"" found in row " & FoundCell.Row)
Else
MsgBox ("Bingo not found")
End If
In my
With Sheet1
.....
End With
The Sheet1
refers to a worksheet's code name, not the name of the worksheet itself. For example, say I open a new blank Excel workbook. The default worksheet is just Sheet1
. I can refer to that in code either with the code name of Sheet1
or I can refer to it with the index of Sheets("Sheet1")
. The advantage to using a codename is that it does not change if you change the name of the worksheet.
Continuing this example, let's say I renamed Sheet1
to Data
. Using Sheet1
would continue to work, as the code name doesn't change, but now using Sheets("Sheet1")
would return an error and that syntax must be updated to the new name of the sheet, so it would need to be Sheets("Data")
.
In the VB Editor you would see something like this:
Notice how, even though I changed the name to Data
, there is still a Sheet1
to the left. That is what I mean by codename.
The Data
worksheet can be referenced in two ways:
Debug.Print Sheet1.Name
Debug.Print Sheets("Data").Name
Both should return Data
More discussion on worksheet code names can be found here.
Try to reinstall cygwin with selected package:gcc-g++ : gnu compiler collection c++ (from devel category), openssh server and client program (net), make: the gnu version (devel), ncurses terminal (utils), enhanced vim editors (editors), an ANSI common lisp implementation (math) and libncurses-devel (lib).
This library files should be under cygwin\usr\include
Regards.
Use the following regex
^(\+91[\-\s]?)?[0]?(91)?[789]\d{9}$
This will support the following formats:
set @r = 0;
select
case when mod(c,2)=0 then round(sum(lat_N),4)
else round(sum(lat_N)/2,4)
end as Med
from
(select lat_N, @r := @r+1, @r as id from station order by lat_N) A
cross join
(select (count(1)+1)/2 as c from station) B
where id >= floor(c) and id <=ceil(c)
I added a ticket to add an option of some sort here:
https://github.com/pydata/pandas/issues/1450
In the meantime, result.fillna('')
should do what you want
EDIT: in the development version (to be 0.8.0 final) if you specify an empty list of na_values
, empty strings will stay empty strings in the result
If you just use round then the two end numbers (1 and 9) will occur less frequently, to get an even distribution of integers between 1 and 9 then:
SELECT MOD(Round(DBMS_RANDOM.Value(1, 99)), 9) + 1 FROM DUAL
Most people have correctly explained the "What" of this question but no one explained "How" correctly.
So here's a simple illustration:
String s = new String("Hello");
if (s instanceof String) System.out.println("s is instance of String"); // True
if (s instanceof Object) System.out.println("s is instance of Object"); // True
//if (s instanceof StringBuffer) System.out.println("s is instance of StringBuffer"); // Compile error
Object o = (Object)s;
if (o instanceof StringBuffer) System.out.println("o is instance of StringBuffer"); //No error, returns False
else System.out.println("Not an instance of StringBuffer"); //
if (o instanceof String) System.out.println("o is instance of String"); //True
Outputs:
s is instance of String
s is instance of Object
Not an instance of StringBuffer
o is instance of String
The reason for compiler error when comparing s
with StringBuffer is well explained in docs:
You can use it to test if an object is an instance of a class, an instance of a subclass, or an instance of a class that implements a particular interface.
which implies the LHS must either be an instance of RHS or of a Class that either implements RHS or extends RHS.
How to use use instanceof then?
Since every Class extends Object, type-casting LHS to object will always work in your favour:
String s = new String("Hello");
if ((Object)s instanceof StringBuffer) System.out.println("Instance of StringBuffer"); //No compiler error now :)
else System.out.println("Not an instance of StringBuffer");
Outputs:
Not an instance of StringBuffer
Here is the complete example for previewing image before it gets upload.
HTML :
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://goo.gl/r57ze"></script>
<![endif]-->
</head>
<body>
<input type='file' onchange="readURL(this);" />
<img id="blah" src="#" alt="your image" />
</body>
</html>
JavaScript :
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah')
.attr('src', e.target.result)
.width(150)
.height(200);
};
reader.readAsDataURL(input.files[0]);
}
}
You can do it by making form and displaying it using ShowDialogBox....
Form.ShowDialog Method
- Shows the form as a modal dialog box.
Example:
public void ShowMyDialogBox()
{
Form2 testDialog = new Form2();
// Show testDialog as a modal dialog and determine if DialogResult = OK.
if (testDialog.ShowDialog(this) == DialogResult.OK)
{
// Read the contents of testDialog's TextBox.
this.txtResult.Text = testDialog.TextBox1.Text;
}
else
{
this.txtResult.Text = "Cancelled";
}
testDialog.Dispose();
}
Copy should be used for NSString. If it's Mutable, then it gets copied. If it's not, then it just gets retained. Exactly the semantics that you want in an app (let the type do what's best).
save() method can be used to insert new record and update existing record and generally used for saving instance of single record(row in mysql) in database.
update() is not used to insert records and can be used to update multiple records(rows in mysql) in database.
Not sure if this can be an answer but as I see what others have said for someone it may look like you need two separate abstractions for both of these concepts so that one of them (Future
) is just a read-only view of the other (Promise
) ... but actually this is not needed.
For example take a look at how promises are defined in javascript:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise
The focus is on the composability using the then
method like:
asyncOp1()
.then(function(op1Result){
// do something
return asyncOp2();
})
.then(function(op2Result){
// do something more
return asyncOp3();
})
.then(function(op3Result){
// do something even more
return syncOp4(op3Result);
})
...
.then(function(result){
console.log(result);
})
.catch(function(error){
console.log(error);
})
which makes asynchronous computation to look like synchronous:
try {
op1Result = syncOp1();
// do something
op1Result = syncOp2();
// do something more
op3Result = syncOp3();
// do something even more
syncOp4(op3Result);
...
console.log(result);
} catch(error) {
console.log(error);
}
which is pretty cool. (Not as cool as async-await but async-await just removes the boilerplate ....then(function(result) {.... from it).
And actually their abstraction is pretty good as the promise constructor
new Promise( function(resolve, reject) { /* do it */ } );
allows you to provide two callbacks which can be used to either complete the Promise
successfully or with an error. So that only the code that constructs the Promise
can complete it and the code that receives an already constructed Promise
object has the read-only view.
With inheritance the above can be achieved if resolve and reject are protected methods.
Ned Rockson basically answers this question. However there is a fatal flaw within his solution. When the targeted element is closer to the bottom of the page than the viewport-height, the function doesn't reach its exit statement and traps the user on the bottom of the page. This is simply solved by limiting the iteration count.
var smoothScroll = function(elementId) {
var MIN_PIXELS_PER_STEP = 16;
var MAX_SCROLL_STEPS = 30;
var target = document.getElementById(elementId);
var scrollContainer = target;
do {
scrollContainer = scrollContainer.parentNode;
if (!scrollContainer) return;
scrollContainer.scrollTop += 1;
} while (scrollContainer.scrollTop == 0);
var targetY = 0;
do {
if (target == scrollContainer) break;
targetY += target.offsetTop;
} while (target = target.offsetParent);
var pixelsPerStep = Math.max(MIN_PIXELS_PER_STEP,
(targetY - scrollContainer.scrollTop) / MAX_SCROLL_STEPS);
var iterations = 0;
var stepFunc = function() {
if(iterations > MAX_SCROLL_STEPS){
return;
}
scrollContainer.scrollTop =
Math.min(targetY, pixelsPerStep + scrollContainer.scrollTop);
if (scrollContainer.scrollTop >= targetY) {
return;
}
window.requestAnimationFrame(stepFunc);
};
window.requestAnimationFrame(stepFunc);
}
You don't necessarily need to have the parameters inside the URL.
For instance, with:
$stateProvider
.state('home', {
url: '/',
views: {
'': {
templateUrl: 'home.html',
controller: 'MainRootCtrl'
},
},
params: {
foo: null,
bar: null
}
})
You will be able to send parameters to the state, using either:
$state.go('home', {foo: true, bar: 1});
// or
<a ui-sref="home({foo: true, bar: 1})">Go!</a>
Of course, if you reload the page once on the home
state, you will loose the state parameters, as they are not stored anywhere.
A full description of this behavior is documented here, under the params
row in the state(name, stateConfig)
section.
Yes there is, since setState
works in an asynchronous
way. That means after calling setState
the this.state
variable is not immediately changed. so if you want to perform an action immediately after setting state on a state variable and then return a result, a callback will be useful
Consider the example below
....
changeTitle: function changeTitle (event) {
this.setState({ title: event.target.value });
this.validateTitle();
},
validateTitle: function validateTitle () {
if (this.state.title.length === 0) {
this.setState({ titleError: "Title can't be blank" });
}
},
....
The above code may not work as expected since the title
variable may not have mutated before validation is performed on it. Now you may wonder that we can perform the validation in the render()
function itself but it would be better and a cleaner way if we can handle this in the changeTitle function itself since that would make your code more organised and understandable
In this case callback is useful
....
changeTitle: function changeTitle (event) {
this.setState({ title: event.target.value }, function() {
this.validateTitle();
});
},
validateTitle: function validateTitle () {
if (this.state.title.length === 0) {
this.setState({ titleError: "Title can't be blank" });
}
},
....
Another example will be when you want to dispatch
and action when the state changed. you will want to do it in a callback and not the render()
as it will be called everytime rerendering occurs and hence many such scenarios are possible where you will need callback.
Another case is a API Call
A case may arise when you need to make an API call based on a particular state change, if you do that in the render method, it will be called on every render onState
change or because some Prop passed down to the Child Component
changed.
In this case you would want to use a setState callback
to pass the updated state value to the API call
....
changeTitle: function (event) {
this.setState({ title: event.target.value }, () => this.APICallFunction());
},
APICallFunction: function () {
// Call API with the updated value
}
....
Use:
document.location.href = "http://yoursite.com" + document.getElementById('somefield');
That would get the value of some text field or hidden field, and add it to your site URL to get a new URL (href). You can modify this to suit your needs.
You should use "r"
for opening text files. Different operating systems have slightly different ways of storing text, and this will perform the correct translations so that you don't need to know about the idiosyncracies of the local operating system. For example, you will know that newlines will always appear as a simple "\n"
, regardless of where the code runs.
You should use "rb"
if you're opening non-text files, because in this case, the translations are not appropriate.
If I don't know the size up front, I use an arraylist instead of an array.
$al = New-Object System.Collections.ArrayList
for($i=0; $i -lt 5; $i++)
{
$al.Add($i)
}
span.middle {
margin: 0 10px 0 10px; /*top right bottom left */
}
<span>text</span> <span class="middle">text</span> <span>text</span>
You can return an object of a Class in Java.
If you are returning more than 1 value that are related, then it makes sense to encapsulate them into a class and then return an object of that class.
If you want to return unrelated values, then you can use Java's built-in container classes like Map, List, Set etc. Check the java.util package's JavaDoc for more details.
Instead of using a ServletContextListener, use a HttpSessionListener
.
In the sessionCreated()
method, you can set the session timeout programmatically:
public class MyHttpSessionListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent event){
event.getSession().setMaxInactiveInterval(15 * 60); // in seconds
}
public void sessionDestroyed(HttpSessionEvent event) {}
}
And don't forget to define the listener in the deployment descriptor:
<webapp>
...
<listener>
<listener-class>com.example.MyHttpSessionListener</listener-class>
</listener>
</webapp>
(or since Servlet version 3.0 you can use @WebListener
annotation instead).
Still, I would recommend creating different web.xml files for each application and defining the session timeout there:
<webapp>
...
<session-config>
<session-timeout>15</session-timeout> <!-- in minutes -->
</session-config>
</webapp>
This has been answered in a separate question and resolved the problem for me. Be sure to vote up the original person's answer.
ASP.Net error: "The type 'foo' exists in both "temp1.dll" and "temp2.dll"
Add the batch="false" attribute to the "compilation" element of the web.config file.
This problem occurs because of the way in which ASP.NET 2.0 uses the application references and the folder structure of the application to compile the application. If the batch property of the element in the web.config file for the application is set to true, ASP.NET 2.0 compiles each folder in the application into a separate assembly.
http://www.sellsbrothers.com/news/showTopic.aspx?ixTopic=1995
Supposing your date is today. Hope this helps you.
DateTime dt = DateTime.Today;
string thisMonth= dt.ToString("MMMM");
Console.WriteLine(thisMonth);
Add an :order parameter to the query
Alternatively:
Save current changes to a temp stash:
$ git stash
Create a new branch based on this stash, and switch to the new branch:
$ git stash branch <new-branch> stash@{0}
Tip: use tab key to reduce typing the stash name.
This solution uses a RandomAccessFile
to only cache the portion of the file subsequent to the string to remove. It scans until it finds the String
you want to remove. Then it copies all of the data after the found string, then writes it over the found string, and everything after. Last, it truncates the file size to remove the excess data.
public static long scanForString(String text, File file) throws IOException {
if (text.isEmpty())
return file.exists() ? 0 : -1;
// First of all, get a byte array off of this string:
byte[] bytes = text.getBytes(/* StandardCharsets.your_charset */);
// Next, search the file for the byte array.
try (DataInputStream dis = new DataInputStream(new FileInputStream(file))) {
List<Integer> matches = new LinkedList<>();
for (long pos = 0; pos < file.length(); pos++) {
byte bite = dis.readByte();
for (int i = 0; i < matches.size(); i++) {
Integer m = matches.get(i);
if (bytes[m] != bite)
matches.remove(i--);
else if (++m == bytes.length)
return pos - m + 1;
else
matches.set(i, m);
}
if (bytes[0] == bite)
matches.add(1);
}
}
return -1;
}
public static void remove(String text, File file) throws IOException {
try (RandomAccessFile rafile = new RandomAccessFile(file, "rw");) {
long scanForString = scanForString(text, file);
if (scanForString == -1) {
System.out.println("String not found.");
return;
}
long remainderStartPos = scanForString + text.getBytes().length;
rafile.seek(remainderStartPos);
int remainderSize = (int) (rafile.length() - rafile.getFilePointer());
byte[] bytes = new byte[remainderSize];
rafile.read(bytes);
rafile.seek(scanForString);
rafile.write(bytes);
rafile.setLength(rafile.length() - (text.length()));
}
}
File Contents: ABCDEFGHIJKLMNOPQRSTUVWXYZ
Method Call: remove("ABC", new File("Drive:/Path/File.extension"));
Resulting Contents: DEFGHIJKLMNOPQRSTUVWXYZ
This solution could easily be modified to remove with a certain, specifiable cacheSize
, if memory is a concern. This would just involve iterating over the rest of the file to continually replace portions of size, cacheSize
. Regardless, this solution is generally much better than caching an entire file in memory, or copying it to a temporary directory, etc.
Now in Android Studio v1.1.0 should be:
Run
> Run <your app>
<your app>\build\outputs\apk
To those who are wondering if they should or not use event.which
in vanilla JS or Angular : It's now deprecated so prefer using event.buttons
instead.
Note : With this method and (mousedown) event:
and (mouseup) event will NOT return the same numbers but 0 instead.
Source : https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons
A pt is 1/72th of an inch and is a useless measure for anything that is rendered on a device which doesn't calculate the DPI correctly. This makes it a reasonable choice for printing and a dreadful choice for use on screen.
A px is a pixel, which will map on to a screen pixel in most cases.
CSS provides a bunch of other units, and which one you should choose depends on what you are setting the size of.
A pixel is great if you need to size something to match an image, or if you want a thin border.
Percentages are great for font sizes as, if you use them consistently, you get font sizes proportional to the user's preference.
Ems are great when you want an element to size itself based on the font size (so a paragraph might get wider if the font size is larger)
… and so on.
Since you are using Visual Studio 11 Beta, you will want to use the latest and greatest. The new Web API contains classes for this.
See HttpClient: http://wcf.codeplex.com/wikipage?title=WCF%20HTTP
This is short, yet efficient and proven approach:
location ~ (patternOne|patternTwo){ #rules etc. }
So one can easily have multiple patterns with simple pipe syntax pointing to the same location block / rules.
Focus doesn't work on divs by default. But, according to this, you can make it work:
The focus event is sent to an element when it gains focus. This event is implicitly applicable to a limited set of elements, such as form elements (
<input>
,<select>
, etc.) and links (<a href>
). In recent browser versions, the event can be extended to include all element types by explicitly setting the element's tabindex property. An element can gain focus via keyboard commands, such as the Tab key, or by mouse clicks on the element.
this.getClass().getClassLoader().getResource("").getPath()
echo are you sure?
read x
if [ "$x" = "yes" ]
then
# do the dangerous stuff
fi
Fiddle with 3 working solutions in action.
Given an external JSON:
myurl = 'http://wikidata.org/w/api.php?action=wbgetentities&sites=frwiki&titles=France&languages=zh-hans|zh-hant|fr&props=sitelinks|labels|aliases|descriptions&format=json'
Solution 1: $.ajax() + jsonp:
$.ajax({
dataType: "jsonp",
url: myurl ,
}).done(function ( data ) {
// do my stuff
});
Solution 2: $.ajax()+json+&calback=?:
$.ajax({
dataType: "json",
url: myurl + '&callback=?',
}).done(function ( data ) {
// do my stuff
});
Solution 3: $.getJSON()+calback=?:
$.getJSON( myurl + '&callback=?', function(data) {
// do my stuff
});
Documentations: http://api.jquery.com/jQuery.ajax/ , http://api.jquery.com/jQuery.getJSON/
If you have a colleague working with you:
1) ask him to rename the file causing problems and commit
2) you update
(now you see the file with invalid checksum with different name)
3) rename it back to its original name
4) commit
(and ask you colleague to update
to get back the file name in its initial state)
This solved the problem for me.
Note that if you only need one column from the table then using 'lists' is quite nice. In my case i am retrieving a user's favourite articles but i only want the article id's:
$favourites = $user->favourites->lists('id');
Returns an array of ids, eg:
Array
(
[0] => 3
[1] => 7
[2] => 8
)
With Git 2.22 (Q2 2019), you will have a simpler approach: git branch --show-current
.
See commit 0ecb1fc (25 Oct 2018) by Daniels Umanovskis (umanovskis
).
(Merged by Junio C Hamano -- gitster
-- in commit 3710f60, 07 Mar 2019)
branch
: introduce--show-current
display option
When called with
--show-current
,git branch
will print the current branch name and terminate.
Only the actual name gets printed, withoutrefs/heads
.
In detached HEAD state, nothing is output.
Intended both for scripting and interactive/informative use.
Unlikegit branch --list
, no filtering is needed to just get the branch name.
See the original discussion on the Git mailing list in Oct. 2018, and the actual pathc.
You are trying to access the struct statically with a .
instead of ::
, nor are its members static
. Either instantiate ReducedForm
:
ReducedForm rf;
rf.iSimplifiedNumerator = 5;
or change the members to static
like this:
struct ReducedForm
{
static int iSimplifiedNumerator;
static int iSimplifiedDenominator;
};
In the latter case, you must access the members with ::
instead of .
I highly doubt however that the latter is what you are going for ;)
If you are using Android Lollipop i.e. SDK 21, then:
CookieManager.getInstance().setAcceptCookie(true);
won't work. You need to use:
CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);
I ran into same issue and the above line worked as a charm.
As Inian suggested, you should alias python to point to python 3. It is very easy to do, and very easy to switchback, personally i have an alias setup for p2=python2 and p3=python3 as well to save on keystrokes. Read here for more information: How do I create a Bash alias?
Here is an example of doing so for python:
alias python=python3
Like so:
$ python --version
Python 2.7.6
$ python3 --version
Python 3.4.3
$ alias python=python3
$ python --version
Python 3.4.3
See here for the original: https://askubuntu.com/questions/320996/how-to-make-python-program-command-execute-python-3
Remove it from the adapter and then notify the arrayadapter that data set has changed.
m_adapter.remove(o);
m_adapter.notifyDataSetChanged();
Your assignment has an extra $
:
export PATH=$PATH:${PWD}:/foo/bar
<% %>
Executes the ruby code within the brackets.
<%= %>
Prints something into erb file.
<%== %>
Equivalent to <%= raw %>
. Prints something verbatim (i.e. w/o escaping) into erb file. (Taken from Ruby on Rails Guides.)
<% -%>
Avoids line break after expression.
<%# %>
Comments out code within brackets; not sent to client (as opposed to HTML comments).
Visit Ruby Doc for more infos about ERB.
var query = from a in d.tbl_Usuarios
from b in d.tblComidaPreferidas
from c in d.tblLugarNacimientoes
select new
{
_nombre = a.Nombre,
_comida = b.ComidaPreferida,
_lNacimiento = c.Ciudad
};
foreach (var i in query)
{
Console.WriteLine($"{i._nombre } le gusta {i._comida} y nació en {i._lNacimiento}");
}
A secure random API was just added to dart:math
new Random.secure()
dart:math
Random
added asecure
constructor returning a cryptographically secure random generator which reads from the entropy source provided by the embedder for every generated random value.
which delegates to window.crypto.getRandomValues()
in the browser and to the OS (like urandom
on the server)
They do different things. exec
replaces the current process with the new process and never returns. system
invokes another process and returns its exit value to the current process. Using backticks invokes another process and returns the output of that process to the current process.
An empty border is transparent. You need to specify a Line Border or some other visible border when you set the border in order to see it.
Based on Edit to question:
The painting does not honor the border. Add this line of code to your test and you will see the border:
jboard.setBorder(BorderFactory.createEmptyBorder(0,10,10,10));
jboard.add(new JButton("Test")); //Add this line
frame.add(jboard);
An HttpOnly
cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly
attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly
.
Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly
by just XSS and still have access to the cookie via JS and thus make the HttpOnly
on your cookie completely useless.
To the first part of your question - yes, browsers cache css files (if this is not disabled by browser's configuration). Many browsers have key combination to reload a page without a cache. If you made changes to css and want users to see them immediately instead of waiting next time when browser reloads the files without caching, you can change the way CSS ir served by adding some parameters to the url like this:
/style.css?modified=20012009
In the cell you want your result to appear, use the following formula:
=COUNTIF(A1:A200,"<>")
That will count all cells which have a value and ignore all empty cells in the range of A1 to A200.
wp_trim_words()
This function trims text to a certain number of words and returns the trimmed text.
$excerpt = wp_trim_words( get_the_content(), 40, '<a href="'.get_the_permalink().'">More Link</a>');
Get truncated string with specified width using mb_strimwidth()
php function.
$excerpt = mb_strimwidth( strip_tags(get_the_content()), 0, 100, '...' );
Using add_filter()
method of WordPress on the_content
filter hook.
add_filter( "the_content", "limit_content_chr" );
function limit_content_chr( $content ){
if ( 'post' == get_post_type() ) {
return mb_strimwidth( strip_tags($content), 0, 100, '...' );
} else {
return $content;
}
}
Using custom php function to limit content characters.
function limit_content_chr( $content, $limit=100 ) {
return mb_strimwidth( strip_tags($content), 0, $limit, '...' );
}
// using above function in template tags
echo limit_content_chr( get_the_content(), 50 );
Updating the 'phones' function in Justen's answer using AngularJS 1.1.5 syntax.
Original:
phones: function($q, Phone) {
var deferred = $q.defer();
Phone.query(function(phones) {
deferred.resolve(phones);
});
return deferred.promise;
}
Updated:
phones: function(Phone) {
return Phone.query().$promise;
}
Much shorter thanks to the Angular team and contributors. :)
This is also the answer of Maximilian Hoffmann. Apparently that commit made it into 1.1.5.
You can disable constraints in Oracle but not indexes. There's a command to make an index ununsable but you have to rebuild the index anyway, so I'd probably just write a script to drop and rebuild the indexes. You can use the user_indexes and user_ind_columns to get all the indexes for a schema or use dbms_metadata:
select dbms_metadata.get_ddl('INDEX', u.index_name) from user_indexes u;
Use application/javascript
as content type instead of text/javascript
text/javascript
is mentioned obsolete. See reference docs.
http://www.iana.org/assignments/media-types/application
Also see this question on SO.
UPDATE:
I have tried executing the code you have given and the below didn't work.
res.setHeader('content-type', 'text/javascript');
res.send(JS_Script);
This is what worked for me.
res.setHeader('content-type', 'text/javascript');
res.end(JS_Script);
As robertklep has suggested, please refer to the node http docs, there is no response.send()
there.
Just FYI, @
and its numpy equivalents dot
and matmul
are all equally fast. (Plot created with perfplot, a project of mine.)
Code to reproduce the plot:
import perfplot
import numpy
def setup(n):
A = numpy.random.rand(n, n)
x = numpy.random.rand(n)
return A, x
def at(data):
A, x = data
return A @ x
def numpy_dot(data):
A, x = data
return numpy.dot(A, x)
def numpy_matmul(data):
A, x = data
return numpy.matmul(A, x)
perfplot.show(
setup=setup,
kernels=[at, numpy_dot, numpy_matmul],
n_range=[2 ** k for k in range(15)],
)
In the hope it might help a little, here's a simple example I used to understand the difference between a variable declared inside a class, and a variable declared inside an __init__
function:
class MyClass(object):
i = 123
def __init__(self):
self.i = 345
a = MyClass()
print(a.i)
print(MyClass.i)
Output:
345
123
You could use a static lookup table:
public enum Suit {
spades, hearts, diamonds, clubs;
private static final Map<Integer, Suit> lookup = new HashMap<Integer, Suit>();
static{
int ordinal = 0;
for (Suit suit : EnumSet.allOf(Suit.class)) {
lookup.put(ordinal, suit);
ordinal+= 1;
}
}
public Suit fromOrdinal(int ordinal) {
return lookup.get(ordinal);
}
}
A better idea,
if you want to put the error message just beneath the text field, you can do like this
.row.spacer20top
.col-sm-6.form-group
= f.label :first_name, "*Your First Name:"
= f.text_field :first_name, :required => true, class: "form-control"
= f.error_message_for(:first_name)
What is error_message_for
?
--> Well, this is a beautiful hack to do some cool stuff
# Author Shiva Bhusal
# Aug 2016
# in config/initializers/modify_rails_form_builder.rb
# This will add a new method in the `f` object available in Rails forms
class ActionView::Helpers::FormBuilder
def error_message_for(field_name)
if self.object.errors[field_name].present?
model_name = self.object.class.name.downcase
id_of_element = "error_#{model_name}_#{field_name}"
target_elem_id = "#{model_name}_#{field_name}"
class_name = 'signup-error alert alert-danger'
error_declaration_class = 'has-signup-error'
"<div id=\"#{id_of_element}\" for=\"#{target_elem_id}\" class=\"#{class_name}\">"\
"#{self.object.errors[field_name].join(', ')}"\
"</div>"\
"<!-- Later JavaScript to add class to the parent element -->"\
"<script>"\
"document.onreadystatechange = function(){"\
"$('##{id_of_element}').parent()"\
".addClass('#{error_declaration_class}');"\
"}"\
"</script>".html_safe
end
rescue
nil
end
end
Markup Generated after error
<div id="error_user_email" for="user_email" class="signup-error alert alert-danger">has already been taken</div>
<script>document.onreadystatechange = function(){$('#error_user_email').parent().addClass('has-signup-error');}</script>
Corresponding SCSS
.has-signup-error{
.signup-error{
background: transparent;
color: $brand-danger;
border: none;
}
input, select{
background-color: $bg-danger;
border-color: $brand-danger;
color: $gray-base;
font-weight: 500;
}
&.checkbox{
label{
&:before{
background-color: $bg-danger;
border-color: $brand-danger;
}
}
}
Note: Bootstrap variables used here
If you work with Visual Studio then it is pretty easy to get persistable settings. Right click on the project in Solution Explorer and choose Properties. Select the Settings tab and click on the hyperlink if settings doesn't exist.
Use the Settings tab to create application settings. Visual Studio creates the files Settings.settings
and Settings.Designer.settings
that contain the singleton class Settings
inherited from ApplicationSettingsBase. You can access this class from your code to read/write application settings:
Properties.Settings.Default["SomeProperty"] = "Some Value";
Properties.Settings.Default.Save(); // Saves settings in application configuration file
This technique is applicable both for console, Windows Forms, and other project types.
Note that you need to set the scope property of your settings. If you select Application scope then Settings.Default.<your property> will be read-only.
Reference: How To: Write User Settings at Run Time with C# - Microsoft Docs
If you need this in derived classes, you can put that code in the base class:
protected string GetThisClassName() { return this.GetType().Name; }
Then, you can reach the name in the derived class. Returns derived class name. Of course, when using the new keyword "nameof", there will be no need like this variety acts.
Besides you can define this:
public static class Extension
{
public static string NameOf(this object o)
{
return o.GetType().Name;
}
}
And then use like this:
public class MyProgram
{
string thisClassName;
public MyProgram()
{
this.thisClassName = this.NameOf();
}
}
For a permanent solution I found the following worked:
[Environment]::SetEnvironmentVariable("Path", "$env:Path;C:\Python 3.5")
On the data dictionary side there are a lot of tools you can use to such as Schema Spy
To look at what queries are running look at views sys.v_$sql and sys.v_$sqltext. You will also need access to sys.all_users
One thing to note that queries that use parameters will show up once with entries like
and TABLETYPE=’:b16’
while others that dont will show up multiple times such as:
and TABLETYPE=’MT’
An example of these tables in action is the following SQL to find the top 20 diskread hogs. You could change this by removing the WHERE rownum <= 20 and maybe add ORDER BY module. You often find the module will give you a bog clue as to what software is running the query (eg: "TOAD 9.0.1.8", "JDBC Thin Client", "runcbl@somebox (TNS V1-V3)" etc)
SELECT
module,
sql_text,
username,
disk_reads_per_exec,
buffer_gets,
disk_reads,
parse_calls,
sorts,
executions,
rows_processed,
hit_ratio,
first_load_time,
sharable_mem,
persistent_mem,
runtime_mem,
cpu_time,
elapsed_time,
address,
hash_value
FROM
(SELECT
module,
sql_text ,
u.username ,
round((s.disk_reads/decode(s.executions,0,1, s.executions)),2) disk_reads_per_exec,
s.disk_reads ,
s.buffer_gets ,
s.parse_calls ,
s.sorts ,
s.executions ,
s.rows_processed ,
100 - round(100 * s.disk_reads/greatest(s.buffer_gets,1),2) hit_ratio,
s.first_load_time ,
sharable_mem ,
persistent_mem ,
runtime_mem,
cpu_time,
elapsed_time,
address,
hash_value
FROM
sys.v_$sql s,
sys.all_users u
WHERE
s.parsing_user_id=u.user_id
and UPPER(u.username) not in ('SYS','SYSTEM')
ORDER BY
4 desc)
WHERE
rownum <= 20;
Note that if the query is long .. you will have to query v_$sqltext. This stores the whole query. You will have to look up the ADDRESS and HASH_VALUE and pick up all the pieces. Eg:
SELECT
*
FROM
sys.v_$sqltext
WHERE
address = 'C0000000372B3C28'
and hash_value = '1272580459'
ORDER BY
address, hash_value, command_type, piece
;
With the course of : TestMyCode Programming assignment evaluator, that one of the exercises was this kind of issue, I wrote this answer:
import java.util.Scanner;
public class LeapYear {
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("Type a year: ");
int year = Integer.parseInt(reader.nextLine());
if (year % 400 == 0 && year % 100 == 0 && year % 4 == 0) {
System.out.println("The year is a leap year");
} else
if (year % 4 == 0 && year%100!=0 ) {
System.out.println("The year is a leap year");
} else
{
System.out.println("The year is not a leap year");
}
}
}
Another reason> someone changed the password for the default SQL user
this happened to me a couple of minutes ago by switching to a new domain controller ...
The most efficient and safest way to determine if a row exists is by using a FOR-LOOP... You won't even have a difficult time if you are looking to insert a row or do something based on the row NOT being there but, this will certainly help you if you need to determine if a row exists. See example code below for the ins and outs...
If you are only interested in knowing that 1 record exists in your potential multiple return set, than you can exit your loop after it hits it for the first time.
The loop will not be entered into at all if no record exists. You will not get any complaints from Oracle or such if the row does not exist but you are bound to find out if it does regardless. Its what I use 90% of the time (of course dependent on my needs)...
EXAMPLE:
DECLARE
v_exist varchar2(20);
BEGIN
FOR rec IN
(SELECT LOT, COMPONENT
FROM TABLE
WHERE REF_DES = (SELECT REF_DES FROM TABLE2 WHERE ORDER = '1234')
AND ORDER = '1234')
LOOP
v_exist := "IT_EXISTS"
INSERT INTO EAT_SOME_SOUP_TABLE (LOT, COMPONENT)
VALUES (rec.LOT, rec.COMPONENT);**
--Since I don't want to do this for more than one iteration (just in case there may have been more than one record returned, I will EXIT;
EXIT;
END LOOP;
IF v_exist IS NULL
THEN
--do this
END IF;
END;
--This is outside the loop right here The IF-CHECK just above will run regardless, but then you will know if your variable is null or not right!?. If there was NO records returned, it will skip the loop and just go here to the code you would have next... If (in our case above), 4 records were returned, I would exit after the first iteration due to my EXIT;... If that wasn't there, the 4 records would iterate through and do an insert on all of them. Or at least try too.
By the way, I'm not saying this is the only way you should consider doing this... You can
SELECT COUNT(*) INTO v_counter WHERE ******* etc...
Then check it like
if v_counter > 0
THEN
--code goes here
END IF;
There are more ways... Just determine it when your need arises. Keep performance in mind, and safety.
Just add to a variable encode('utf-8')
agent_contact.encode('utf-8')
You can actually do what Chris Chalmers does in his answer, but you must make sure that HAML doesn't parse the JavaScript. This approach is actually useful when you need to use a different type than text/javascript
, which is was I needed to do for MathJax
.
You can use the plain
filter to keep HAML from parsing the script and throwing an illegal nesting error:
%script{type: "text/x-mathjax-config"}
:plain
MathJax.Hub.Config({
tex2jax: {
inlineMath: [["$","$"],["\\(","\\)"]]
}
});
For what it is worth, mine was fixed after I went to target->Build Phases->Link Binary With Libraries, deleted the libstdc++.tbd reference, then added a reference to libstdc++.6.0.9.tbd.
if you are calling from static
method, use :
TestGameTable.class.getClassLoader().getResource("dice.jpg");
If your app is a system app,you can use PowerManager.goToSleep() to turn screen off,you requires a special permission
before you use goToSleep(), you need use reflection just like:
public static void goToSleep(Context context) {
PowerManager powerManager= (PowerManager)context.getSystemService(Context.POWER_SERVICE);
try {
powerManager.getClass().getMethod("goToSleep", new Class[]{long.class}).invoke(powerManager, SystemClock.uptimeMillis());
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
Now,you can use goToSleep() to turn screen off.
This is what happens when the power key is pressed to turn off the screen.
You have by default the static
endpoint for static files. Also Flask
application has the following arguments:
static_url_path
: can be used to specify a different path for the static files on the web. Defaults to the name of the static_folder
folder.
static_folder
: the folder with static files that should be served at static_url_path
. Defaults to the 'static' folder in the root path of the application.
It means that the filename
argument will take a relative path to your file in static_folder
and convert it to a relative path combined with static_url_default
:
url_for('static', filename='path/to/file')
will convert the file path from static_folder/path/to/file
to the url path static_url_default/path/to/file
.
So if you want to get files from the static/bootstrap
folder you use this code:
<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='bootstrap/bootstrap.min.css') }}">
Which will be converted to (using default settings):
<link rel="stylesheet" type="text/css" href="static/bootstrap/bootstrap.min.css">
Also look at url_for
documentation.
Try this
var store = dtpDateTimePicker.Value.Date;
store can be anything entity object etc.
Yes, and it seems to have (more or less) the same API.
import multiprocessing
def worker(lnk):
....
def start_process():
.....
....
if(PROCESS):
pool = multiprocessing.Pool(processes=POOL_SIZE, initializer=start_process)
else:
pool = multiprocessing.pool.ThreadPool(processes=POOL_SIZE,
initializer=start_process)
pool.map(worker, inputs)
....
I used:
recode UTF-16..UTF-8 <filename>
to get rid of zeroes in file.
It is a Generic Type Parameter.
A generic type parameter allows you to specify an arbitrary type T to a method at compile-time, without specifying a concrete type in the method or class declaration.
For example:
public T[] Reverse<T>(T[] array)
{
var result = new T[array.Length];
int j=0;
for(int i=array.Length - 1; i>= 0; i--)
{
result[j] = array[i];
j++;
}
return result;
}
reverses the elements in an array. The key point here is that the array elements can be of any type, and the function will still work. You specify the type in the method call; type safety is still guaranteed.
So, to reverse an array of strings:
string[] array = new string[] { "1", "2", "3", "4", "5" };
var result = reverse(array);
Will produce a string array in result
of { "5", "4", "3", "2", "1" }
This has the same effect as if you had called an ordinary (non-generic) method that looks like this:
public string[] Reverse(string[] array)
{
var result = new string[array.Length];
int j=0;
for(int i=array.Length - 1; i >= 0; i--)
{
result[j] = array[i];
j++;
}
return result;
}
The compiler sees that array
contains strings, so it returns an array of strings. Type string
is substituted for the T
type parameter.
Generic type parameters can also be used to create generic classes. In the example you gave of a SampleCollection<T>
, the T
is a placeholder for an arbitrary type; it means that SampleCollection
can represent a collection of objects, the type of which you specify when you create the collection.
So:
var collection = new SampleCollection<string>();
creates a collection that can hold strings. The Reverse
method illustrated above, in a somewhat different form, can be used to reverse the collection's members.
How about a regex?
function getNum(str) {
return /[-+]?[0-9]*\.?[0-9]+/.test(str)?parseFloat(str):0;
}
The code below will ignore NaN to allow a calculation of properly entered numbers
function getNum(str) {_x000D_
return /[-+]?[0-9]*\.?[0-9]+/.test(str)?parseFloat(str):0;_x000D_
}_x000D_
var inputsArray = document.getElementsByTagName('input');_x000D_
_x000D_
function computeTotal() {_x000D_
var tot = 0;_x000D_
tot += getNum(inputsArray[0].value);_x000D_
tot += getNum(inputsArray[1].value);_x000D_
tot += getNum(inputsArray[2].value);_x000D_
inputsArray[3].value = tot;_x000D_
}
_x000D_
<input type="text"></input>_x000D_
<input type="text"></input>_x000D_
<input type="text"></input>_x000D_
<input type="text" disabled></input>_x000D_
<button type="button" onclick="computeTotal()">Calculate</button>
_x000D_
printf("%.*s\n",n,(char *) memset(buffer,c,n));
n
<= sizeof(buffer)
[ maybe also n < 2^16]
However the optimizer may change it to puts(buffer)
and then the lack of EoS will .....
And the assumption is that memset is an assembler instruction (but still a loop be it on chip).
Strictly seen there is no solution given you precondition 'No loop'.
POD is the official way to do multi line comments in Perl,
From faq.perl.org[perlfaq7]
The quick-and-dirty way to comment out more than one line of Perl is to surround those lines with Pod directives. You have to put these directives at the beginning of the line and somewhere where Perl expects a new statement (so not in the middle of statements like the # comments). You end the comment with
=cut
, ending the Pod section:
=pod
my $object = NotGonnaHappen->new();
ignored_sub();
$wont_be_assigned = 37;
=cut
The quick-and-dirty method only works well when you don't plan to leave the commented code in the source. If a Pod parser comes along, your multiline comment is going to show up in the Pod translation. A better way hides it from Pod parsers as well.
The
=begin
directive can mark a section for a particular purpose. If the Pod parser doesn't want to handle it, it just ignores it. Label the comments withcomment
. End the comment using=end
with the same label. You still need the=cut
to go back to Perl code from the Pod comment:
=begin comment
my $object = NotGonnaHappen->new();
ignored_sub();
$wont_be_assigned = 37;
=end comment
=cut
Just (array)
is missing in your code before the simplexml object:
...
$xml = simplexml_load_string($string, 'SimpleXMLElement', LIBXML_NOCDATA);
$array = json_decode(json_encode((array)$xml), TRUE);
^^^^^^^
...
I have tried everything, and finally deleting the -vm
options worked for me.
I tried a certain sequence that seems to work as you can see below:
ThisWorkbook.Saved = True
Application.Quit
Application.ActiveWindow.Close SaveChanges:=False
ActiveWorkbook.Close SaveChanges:=False
Remove that <p>
tag and add the button inside a <div class="form-actions">
like this:
<div class="form-actions">
<button type="submit" class="btn">Confirm</button>
</div>
an then augment the CSS class with:
.form-actions {
margin: 0;
background-color: transparent;
text-align: center;
}
Here's a JS Bin demo: http://jsbin.com/ijozof/2
Look for form-actions
at the Bootstrap
doc here:
Using this object --> TinyDB--Android-Shared-Preferences-Turbo its very simple. you can save most of the commonly used objects with it like arrays, integer, strings lists etc
In Bootstrap 3 they do not have separate classes for different styles of labels.
http://getbootstrap.com/components/
However, you can customize bootstrap classes that way. In your css file
.lb-sm {
font-size: 12px;
}
.lb-md {
font-size: 16px;
}
.lb-lg {
font-size: 20px;
}
Alternatively, you can use header tags to change the sizes. For example, here is a medium sized label and a small-sized label
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<h3>Example heading <span class="label label-default">New</span></h3>_x000D_
<h6>Example heading <span class="label label-default">New</span></h6>
_x000D_
They might add size classes for labels in future Bootstrap versions.
Simple Explanation.
If you want to convert your PC (running Windows) into Mac, you can do either of these:
(1) You can simply install a Mac theme on your Windows. So, your PC feels more like Mac, but you can't actually run any Mac programs.
(SIMULATION)
(or)
(2) You can program your PC to run like Mac (I'm not sure if this is possible :P ). Now you can even run Mac programs successfully and expect the same output as on Mac.
(EMULATION)
In the first case, you can experience Mac, but you can't expect the same output as on Mac.
In the second case, you can expect the same output as on Mac, but still the fact remains that it is only a PC.
I set the .InnerHtml of a <p>
bracket for my web project to the user's computer name doing the following:
HTML:
<div class="col-md-4">
<h2>Your Computer Name Is</h2>
<p id="pcname" runat="server"></p>
<p>
<a class="btn btn-default" href="#">Learn more »</a>
</p>
</div>
C#:
using System;
using System.Web.UI;
namespace GetPCName {
public partial class _Default : Page {
protected void Page_Load(object sender, EventArgs e) {
pcname.InnerHtml = Environment.MachineName;
}
}
}
I found the best solution for this problem by using ON with $(document).
$(document).on('click', '#yourid', function() { alert("hello"); });
for id start with see below:
$(document).on('click', 'div[id^="start"]', function() {
alert ('hello'); });
finally after 1 week I not need to add onclick triger. I hope this will help many people
A workaround for this I used was to include the data as a js file, that implements a function returning the raw data as a string:
<!DOCTYPE html>
<html>
<head>
<script src="script.js"></script>
<script type="text/javascript">
function loadData() {
// getData() will return the string of data...
document.getElementById('data').innerHTML = getData().replace('\n', '<br>');
}
</script>
</head>
<body onload='loadData()'>
<h1>check out the data!</h1>
<div id='data'></div>
</body>
</html>
// function wrapper, just return the string of data (csv etc)
function getData () {
return 'look at this line of data\n\
oh, look at this line'
}
See it in action here- http://plnkr.co/edit/EllyY7nsEjhLMIZ4clyv?p=preview
The downside is you have to do some preprocessing on the file to support multilines (append each line in the string with '\n\'
).
You can pass an object as argument to the Thread.Start
and use it as a shared data storage between the current thread and the initiating thread.
You can also just directly access (with the appropriate locking of course) your data members, if you started the thread using the instance form of the ThreadStart
delegate.
You can't use attributes to create shared data between threads. You can use the attribute instances attached to your class as a data storage, but I fail to see how that is better than using static or instance data members.
This piece of vba worked for me:
Sub connect()
Dim Password As String
Dim SQLStr As String
'OMIT Dim Cn statement
Dim Server_Name As String
Dim User_ID As String
Dim Database_Name As String
'OMIT Dim rs statement
Set rs = CreateObject("ADODB.Recordset") 'EBGen-Daily
Server_Name = Range("b2").Value
Database_name = Range("b3").Value ' Name of database
User_ID = Range("b4").Value 'id user or username
Password = Range("b5").Value 'Password
SQLStr = "SELECT * FROM ComputingNotesTable"
Set Cn = CreateObject("ADODB.Connection") 'NEW STATEMENT
Cn.Open "Driver={MySQL ODBC 5.2.2 Driver};Server=" & _
Server_Name & ";Database=" & Database_Name & _
";Uid=" & User_ID & ";Pwd=" & Password & ";"
rs.Open SQLStr, Cn, adOpenStatic
Dim myArray()
myArray = rs.GetRows()
kolumner = UBound(myArray, 1)
rader = UBound(myArray, 2)
For K = 0 To kolumner ' Using For loop data are displayed
Range("a5").Offset(0, K).Value = rs.Fields(K).Name
For R = 0 To rader
Range("A5").Offset(R + 1, K).Value = myArray(K, R)
Next
Next
rs.Close
Set rs = Nothing
Cn.Close
Set Cn = Nothing
End Sub
Query String: ?strID=XXXX&strName=yyyy&strDate=zzzzz
before you redirect:
string queryString = Request.QueryString.ToString();
Response.Redirect("page.aspx?"+queryString);
This can be done with pure CSS and does not even require media queries.
To make the images flexible, simply add
max-width:100%
andheight:auto
. Imagemax-width:100%
andheight:auto
works in IE7, but not in IE8 (yes, another weird IE bug). To fix this, you need to addwidth:auto\9
for IE8.source: http://webdesignerwall.com/tutorials/responsive-design-with-css3-media-queries
CSS:
img {
max-width: 100%;
height: auto;
width: auto\9; /* ie8 */
}
And if you want to enforce a fixed max width of the image, just place it inside a container, for example:
<div style="max-width:500px;">
<img src="..." />
</div>
JSFiddle example here. No JavaScript required. Works in latest versions of Chrome, Firefox and IE (which is all I've tested).
If you want to learn your data summary (df)
provides the min, 1st quantile, median and mean, 3rd quantile and max of numerical columns and the frequency of the top levels of the factor columns.
You need to "seed" the generator. Check out this short video, it will clear things up.
It seems like Github has changed their layout since you posted this question. I just created a repository and it used to give you instructions on screen. It appears they have changed that approach.
Here is the information they used to give on repo creation:
Button btn=(Button)findViewById(R.id.btn);
String btnText=btn.getText().toString();
Later this btnText
can be used .
For example:
if(btnText == "Text for comparison")
If you want the string use -
DateTime.ToString("dd/MM/yyyy")
Didn't feel like doing it by hand as in bobince's answer, so I just completely ripped off jQuery's plugin options pattern.
Here's the constructor:
//default constructor for Preset 'class'
function Preset(params) {
var properties = $.extend({
//these are the defaults
id: null,
name: null,
inItems: [],
outItems: [],
}, params);
console.log('Preset instantiated');
this.id = properties.id;
this.name = properties.name;
this.inItems = properties.inItems;
this.outItems = properties.outItems;
}
Here's different ways of instantiation:
presetNoParams = new Preset();
presetEmptyParams = new Preset({});
presetSomeParams = new Preset({id: 666, inItems:['item_1', 'item_2']});
presetAllParams = new Preset({id: 666, name: 'SOpreset', inItems: ['item_1', 'item_2'], outItems: ['item_3', 'item_4']});
And here's what that made:
presetNoParams
Preset {id: null, name: null, inItems: Array[0], outItems: Array[0]}
presetEmptyParams
Preset {id: null, name: null, inItems: Array[0], outItems: Array[0]}
presetSomeParams
Preset {id: 666, name: null, inItems: Array[2], outItems: Array[0]}
presetAllParams
Preset {id: 666, name: "SOpreset", inItems: Array[2], outItems: Array[2]}
I rename in code
echo off
setlocal EnableDelayedExpansion
for %%a in (*.txt) do (
REM echo %%a
set x=%%a
set mes=!x:~17,3!
if !mes!==JAN (
set mes=01
)
if !mes!==ENE (
set mes=01
)
if !mes!==FEB (
set mes=02
)
if !mes!==MAR (
set mes=03
)
if !mes!==APR (
set mes=04
)
if !mes!==MAY (
set mes=05
)
if !mes!==JUN (
set mes=06
)
if !mes!==JUL (
set mes=07
)
if !mes!==AUG (
set mes=08
)
if !mes!==SEP (
set mes=09
)
if !mes!==OCT (
set mes=10
)
if !mes!==NOV (
set mes=11
)
if !mes!==DEC (
set mes=12
)
ren %%a !x:~20,4!!mes!!x:~15,2!.txt
echo !x:~20,4!!mes!!x:~15,2!.txt
)
Alternatively to Link Library Dependencies
in project properties there is another way to link libraries in Visual Studio.
Add Existing Item...
).Item Type
is Library
This will include the other libraries in X as if you ran
lib /out:X.lib X.lib other1.lib other2.lib
A tiny update for @Terry Young answer, i.e. add IE 10+ support
if (window.navigator.msSaveOrOpenBlob) {
// IE 10+
var blob = new Blob([decodeURIComponent(encodeURI(csvString))], {
type: 'text/csv;charset=' + document.characterSet
});
window.navigator.msSaveBlob(blob, filename);
} else {
// actual real browsers
//Data URI
csvData = 'data:application/csv;charset=utf-8,' + encodeURIComponent(csvData);
$(this).attr({
'download': filename,
'href': csvData,
'target': '_blank'
});
}
The solution above does not work in all InputBox-Cancel cases. Most notably, it does not work if you have to InputBox a Range.
For example, try the following InputBox for defining a custom range ('sRange', type:=8, requires Set + Application.InputBox) and you will get an error upon pressing Cancel:
Sub Cancel_Handler_WRONG()
Set sRange = Application.InputBox("Input custom range", _
"Cancel-press test", Selection.Address, Type:=8)
If StrPtr(sRange) = 0 Then 'I also tried with sRange.address and vbNullString
MsgBox ("Cancel pressed!")
Exit Sub
End If
MsgBox ("Your custom range is " & sRange.Address)
End Sub
The only thing that works, in this case, is an "On Error GoTo ErrorHandler" statement before the InputBox + ErrorHandler at the end:
Sub Cancel_Handler_OK()
On Error GoTo ErrorHandler
Set sRange = Application.InputBox("Input custom range", _
"Cancel-press test", Selection.Address, Type:=8)
MsgBox ("Your custom range is " & sRange.Address)
Exit Sub
ErrorHandler:
MsgBox ("Cancel pressed")
End Sub
So, the question is how to detect either an error or StrPtr()=0 with an If statement?
There is an option in Postman if you download it from https://www.getpostman.com instead of the chrome store (most probably it has been introduced in the new versions and the chrome one will be updated later) not sure about the old ones.
In the settings, turn off the SSL certificate verification option
Be sure to remember to reactivate it afterwards, this is a security feature.
If you really want to use the chrome app, you could always add an exception to chrome for the url: Enter the url you would like to open in the chrome browser, you'll get a warning with a link at the bottom of the page to add an exception, which if you do, it will also allow postman to access your url. But the first option of using the postman stand-alone app is much better.
I hope this can help.
I think that you should use a connection pool instead of share a single connection. A connection pool would provide a much better performance, as you can check here.
As stated in the library documentation, it occurs because the MySQL protocol is sequential (this means that you need multiple connections to execute queries in parallel).
break
would stop the foreach
loop completely, continue
would skip to the next DataRow
.
I usually manually set the port that I am listening on in the app.js
file (assuming you are using express.js
var server = app.listen(8080, function() {
console.log('Ready on port %d', server.address().port);
});
This will log Ready on port 8080
to your console.
You have three alternatives:
This is a simple library for keeping iFrames sized to their content. It uses the PostMessage and MutationObserver APIs, with fall backs for IE8-10. It also has options for the content page to request the containing iFrame is a certain size and can also close the iFrame when your done with it.
https://github.com/davidjbradshaw/iframe-resizer
Easy XDM uses a collection of tricks for enabling cross-domain communication between different windows in a number of browsers, and there are examples for using it for iframe resizing:
http://easyxdm.net/wp/2010/03/17/resize-iframe-based-on-content/
http://kinsey.no/blog/index.php/2010/02/19/resizing-iframes-using-easyxdm/
Easy XDM works by using PostMessage on modern browsers and a Flash based solution as fallback for older browsers.
See also this thread on Stackoverflow (there are also others, this is a commonly asked question). Also, Facebook would seem to use a similar approach.
Another option would be to send the iframe height to your server and then poll from that server from the parent web page with JSONP (or use a long poll if possible).
how about using limit 0,1
for mysql optimisation
and about your code:
$DBH = new PDO( "connection string goes here" );
$STH - $DBH -> prepare( "select figure from table1" );
$STH -> execute();
$result = $STH ->fetch(PDO::FETCH_ASSOC)
echo $result["figure"];
$DBH = null;
The quickest way to check is just to write "inetmgr" at run (By pressing Win + R) as a command, if a manager window is appeared then it's installed otherwise it isn't.
Say the data are in file data.txt
, you can use the colClasses
argument of read.table()
to skip columns. Here the data in the first 7 columns are "integer"
and we set the remaining 6 columns to "NULL"
indicating they should be skipped
> read.table("data.txt", colClasses = c(rep("integer", 7), rep("NULL", 6)),
+ header = TRUE)
Year Jan Feb Mar Apr May Jun
1 2009 -41 -27 -25 -31 -31 -39
2 2010 -41 -27 -25 -31 -31 -39
3 2011 -21 -27 -2 -6 -10 -32
Change "integer"
to one of the accepted types as detailed in ?read.table
depending on the real type of data.
data.txt
looks like this:
$ cat data.txt
"Year" "Jan" "Feb" "Mar" "Apr" "May" "Jun" "Jul" "Aug" "Sep" "Oct" "Nov" "Dec"
2009 -41 -27 -25 -31 -31 -39 -25 -15 -30 -27 -21 -25
2010 -41 -27 -25 -31 -31 -39 -25 -15 -30 -27 -21 -25
2011 -21 -27 -2 -6 -10 -32 -13 -12 -27 -30 -38 -29
and was created by using
write.table(dat, file = "data.txt", row.names = FALSE)
where dat
is
dat <- structure(list(Year = 2009:2011, Jan = c(-41L, -41L, -21L), Feb = c(-27L,
-27L, -27L), Mar = c(-25L, -25L, -2L), Apr = c(-31L, -31L, -6L
), May = c(-31L, -31L, -10L), Jun = c(-39L, -39L, -32L), Jul = c(-25L,
-25L, -13L), Aug = c(-15L, -15L, -12L), Sep = c(-30L, -30L, -27L
), Oct = c(-27L, -27L, -30L), Nov = c(-21L, -21L, -38L), Dec = c(-25L,
-25L, -29L)), .Names = c("Year", "Jan", "Feb", "Mar", "Apr",
"May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"), class = "data.frame",
row.names = c(NA, -3L))
If the number of columns is not known beforehand, the utility function count.fields
will read through the file and count the number of fields in each line.
## returns a vector equal to the number of lines in the file
count.fields("data.txt", sep = "\t")
## returns the maximum to set colClasses
max(count.fields("data.txt", sep = "\t"))
Clearly you aren't sending the data with ObjectOutputStream:
you are just writing the bytes.
readObject()
you must write with writeObject().
readUTF()
you must write with writeUTF().
readXXX()
you must write with writeXXX(),
for most values of XXX.An alternative way using filter and arrow functions
arrOne.length === arrTwo.length && arrOne.filter((currVal, idx) => currVal !== arrTwo[idx]).length === 0
explode() might be the function you are looking for
$array = explode(' ',$str);
There are two ways of storing a color with alpha. The first is exactly as you see it, with each component as-is. The second is to use pre-multiplied alpha, where the color values are multiplied by the alpha after converting it to the range 0.0-1.0; this is done to make compositing easier. Ordinarily you shouldn't notice or care which way is implemented by any particular engine, but there are corner cases where you might, for example if you tried to increase the opacity of the color. If you use rgba(0, 0, 0, 0)
you are less likely to to see a difference between the two approaches.
A clustered index alters the way that the rows are stored. When you create a clustered index on a column (or a number of columns), SQL server sorts the table’s rows by that column(s). It is like a dictionary, where all words are sorted in alphabetical order in the entire book.
A non-clustered index, on the other hand, does not alter the way the rows are stored in the table. It creates a completely different object within the table that contains the column(s) selected for indexing and a pointer back to the table’s rows containing the data. It is like an index in the last pages of a book, where keywords are sorted and contain the page number to the material of the book for faster reference.
I had to load webpage from local disk "file:///C:/test/htmlpage.html", call "http://localhost/getxml.php" url, and do this in IE8+ and Firefox12+ browsers, use jQuery v1.7.2 lib to minimize boilerplate code. After reading dozens of articles finally figured it out. Here is my summary.
Here is an example jQuery ajax call with some debug sysouts.
jQuery.support.cors = true;
$.ajax({
url: "http://localhost/getxml.php",
data: { "id":"doc1", "rows":"100" },
type: "GET",
timeout: 30000,
dataType: "text", // "xml", "json"
success: function(data) {
// show text reply as-is (debug)
alert(data);
// show xml field values (debug)
//alert( $(data).find("title").text() );
// loop JSON array (debug)
//var str="";
//$.each(data.items, function(i,item) {
// str += item.title + "\n";
//});
//alert(str);
},
error: function(jqXHR, textStatus, ex) {
alert(textStatus + "," + ex + "," + jqXHR.responseText);
}
});
After you edited your question it's cler you're using ASP.NET. Things are pretty different there (because in that case a roundtrip to server is pretty discouraged). You can do same things with JavaScript (but to handle globalization with toUpperCase()
may be a pain) or you can use CSS classes (relying on browsers implementation). Simply declare this CSS rule:
.upper-case
{
text-transform: uppercase
}
And add upper-case class to your text-box:
<asp:TextBox ID="TextBox1" CssClass="upper-case" runat="server"/>
but it capitalize characters after pressing Enter key.
It depends where you put that code. If you put it in, for example, TextChanged
event it'll make upper case as you type.
You have a property that do exactly what you need: CharacterCasing
:
TextBox1.CharacterCasing = CharacterCasing.Upper;
It works more or less but it doesn't handle locales very well. For example in German language ß is SS when converted in upper case (Institut für Deutsche Sprache) and this property doesn't handle that.
You may mimic CharacterCasing
property adding this code in KeyPress
event handler:
e.KeyChar = Char.ToUpper(e.KeyChar);
Unfortunately .NET framework doesn't handle this properly and upper case of sharp s character is returned unchanged. An upper case version of ß exists and it's ? and it may create some confusion, for example a word containing "ss" and another word containing "ß" can't be distinguished if you convert in upper case using "SS"). Don't forget that:
However, in 2010 the use of the capital sharp s became mandatory in official documentation when writing geographical names in all-caps.
There isn't much you can do unless you add proper code for support this (and others) subtle bugs in .NET localization. Best advice I can give you is to use a custom dictionary per each culture you need to support.
Finally don't forget that this transformation may be confusing for your users: in Turkey, for example, there are two different versions of i upper case letter.
If text processing is important in your application you can solve many issues using specialized DLLs for each locale you support like Word Processors do.
What I usually do is to do not use standard .NET functions for strings when I have to deal with culture specific issues (I keep them only for text in invariant culture). I create a Unicode class with static methods for everything I need (character counting, conversions, comparison) and many specialized derived classes for each supported language. At run-time that static methods will user current thread culture name to pick proper implementation from a dictionary and to delegate work to that. A skeleton may be something like this:
abstract class Unicode
{
public static string ToUpper(string text)
{
return GetConcreteClass().ToUpperCore(text);
}
protected virtual string ToUpperCore(string text)
{
// Default implementation, overridden in derived classes if needed
return text.ToUpper();
}
private Dictionary<string, Unicode> _implementations;
private Unicode GetConcreteClass()
{
string cultureName = Thread.Current.CurrentCulture.Name;
// Check if concrete class has been loaded and put in dictionary
...
return _implementations[cultureName];
}
}
I'll then have an implementation specific for German language:
sealed class German : Unicode
{
protected override string ToUpperCore(string text)
{
// Very naive implementation, just to provide an example
return text.ToUpper().Replace("ß", "?");
}
}
True implementation may be pretty more complicate (not all OSes supports upper case ?) but take as a proof of concept. See also this post for other details about Unicode issues on .NET.
this works. thanks. I am injecting custom html and compile it using angular in the controller.
var tableContent= '<div>Search: <input ng-model="searchText"></div>'
+'<div class="table-heading">'
+ '<div class="table-col">Customer ID</div>'
+ ' <div class="table-col" ng-click="vm.openDialog(c.CustomerId)">{{c.CustomerId}}</div>';
$timeout(function () {
var linkingFunction = $compile(tableContent);
var elem = linkingFunction($scope);
// You can then use the DOM element like normal.
jQuery(tablePanel).append(elem);
console.log("timeout");
},100);
This is what I do when I need to add months or years and don't want to import more libraries. Just create a datetime.date() object, call add_month(date) to add a month and add_year(date) to add a year.
import datetime
__author__ = 'Daniel Margarido'
# Check if the int given year is a leap year
# return true if leap year or false otherwise
def is_leap_year(year):
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
return True
else:
return False
else:
return True
else:
return False
THIRTY_DAYS_MONTHS = [4, 6, 9, 11]
THIRTYONE_DAYS_MONTHS = [1, 3, 5, 7, 8, 10, 12]
# Inputs -> month, year Booth integers
# Return the number of days of the given month
def get_month_days(month, year):
if month in THIRTY_DAYS_MONTHS: # April, June, September, November
return 30
elif month in THIRTYONE_DAYS_MONTHS: # January, March, May, July, August, October, December
return 31
else: # February
if is_leap_year(year):
return 29
else:
return 28
# Checks the month of the given date
# Selects the number of days it needs to add one month
# return the date with one month added
def add_month(date):
current_month_days = get_month_days(date.month, date.year)
next_month_days = get_month_days(date.month + 1, date.year)
delta = datetime.timedelta(days=current_month_days)
if date.day > next_month_days:
delta = delta - datetime.timedelta(days=(date.day - next_month_days) - 1)
return date + delta
def add_year(date):
if is_leap_year(date.year):
delta = datetime.timedelta(days=366)
else:
delta = datetime.timedelta(days=365)
return date + delta
# Validates if the expected_value is equal to the given value
def test_equal(expected_value, value):
if expected_value == value:
print "Test Passed"
return True
print "Test Failed : " + str(expected_value) + " is not equal to " str(value)
return False
# Test leap year
print "---------- Test leap year ----------"
test_equal(True, is_leap_year(2012))
test_equal(True, is_leap_year(2000))
test_equal(False, is_leap_year(1900))
test_equal(False, is_leap_year(2002))
test_equal(False, is_leap_year(2100))
test_equal(True, is_leap_year(2400))
test_equal(True, is_leap_year(2016))
# Test add month
print "---------- Test add month ----------"
test_equal(datetime.date(2016, 2, 1), add_month(datetime.date(2016, 1, 1)))
test_equal(datetime.date(2016, 6, 16), add_month(datetime.date(2016, 5, 16)))
test_equal(datetime.date(2016, 3, 15), add_month(datetime.date(2016, 2, 15)))
test_equal(datetime.date(2017, 1, 12), add_month(datetime.date(2016, 12, 12)))
test_equal(datetime.date(2016, 3, 1), add_month(datetime.date(2016, 1, 31)))
test_equal(datetime.date(2015, 3, 1), add_month(datetime.date(2015, 1, 31)))
test_equal(datetime.date(2016, 3, 1), add_month(datetime.date(2016, 1, 30)))
test_equal(datetime.date(2016, 4, 30), add_month(datetime.date(2016, 3, 30)))
test_equal(datetime.date(2016, 5, 1), add_month(datetime.date(2016, 3, 31)))
# Test add year
print "---------- Test add year ----------"
test_equal(datetime.date(2016, 2, 2), add_year(datetime.date(2015, 2, 2)))
test_equal(datetime.date(2001, 2, 2), add_year(datetime.date(2000, 2, 2)))
test_equal(datetime.date(2100, 2, 2), add_year(datetime.date(2099, 2, 2)))
test_equal(datetime.date(2101, 2, 2), add_year(datetime.date(2100, 2, 2)))
test_equal(datetime.date(2401, 2, 2), add_year(datetime.date(2400, 2, 2)))
I have used below command to remove white space in Oracle
My Table Name is - NG_CAP_SENDER_INFO_MTR
My Column Name is - SENINFO_FROM
UPDATE NG_CAP_SENDER_INFO_MTR SET SENINFO_FROM = TRIM(SENINFO_FROM);
Already Answer on StackOverflow LTRIM RTRIM
And its working fine
You can't, Doctrine 2 doesn't allow for raw queries. It may seem like you can but if you try something like this:
$sql = "SELECT DATE_FORMAT(whatever.createdAt, '%Y-%m-%d') FORM whatever...";
$em = $this->getDoctrine()->getManager();
$em->getConnection()->exec($sql);
Doctrine will spit an error saying that DATE_FORMAT is an unknown function.
But my database (mysql) does know that function, so basically what is hapening is Doctrine is parsing that query behind the scenes (and behind your back) and finding an expression that it doesn't understand, considering the query to be invalid.
So if like me you want to be able to simply send a string to the database and let it deal with it (and let the developer take full responsibility for security), forget it.
Of course you could code an extension to allow that in some way or another, but you just as well off using mysqli to do it and leave Doctrine to it's ORM buisness.
You need to use OPENROWSET
Check this question: import-excel-spreadsheet-columns-into-sql-server-database
Considering that you have
$replaced = array('1' => 'value1', '4' => 'value4');
$replacement = array('4' => 'value2', '6' => 'value3');
Doing $merge = $replacement + $replaced;
will output:
Array('4' => 'value2', '6' => 'value3', '1' => 'value1');
The first array from sum will have values in the final output.
Doing $merge = $replaced + $replacement;
will output:
Array('1' => 'value1', '4' => 'value4', '6' => 'value3');
This is easy. You just need to put inside .form-control
this:
.form-control{
-webkit-appearance:none;
-moz-appearance: none;
-ms-appearance: none;
-o-appearance: none;
appearance: none;
}
This will remove browser's appearance and allow your CSS.
Step 1: See all your databases:
show dbs
Step 2: Select the database
use your_database_name
Step 3: Show the collections
show collections
This will list all the collections in your selected database.
Step 4: See all the data
db.collection_name.find()
or
db.collection_name.find().pretty()
Not gonna happen with CSS only
Inline javascript
<a href='index.html'
onmouseover='this.style.textDecoration="none"'
onmouseout='this.style.textDecoration="underline"'>
Click Me
</a>
In a working draft of the CSS2 spec it was declared that you could use pseudo-classes inline like this:
<a href="http://www.w3.org/Style/CSS"
style="{color: blue; background: white} /* a+=0 b+=0 c+=0 */
:visited {color: green} /* a+=0 b+=1 c+=0 */
:hover {background: yellow} /* a+=0 b+=1 c+=0 */
:visited:hover {color: purple} /* a+=0 b+=2 c+=0 */
">
</a>
but it was never implemented in the release of the spec as far as I know.
http://www.w3.org/TR/2002/WD-css-style-attr-20020515#pseudo-rules
This works well. It's a manager I've made to handle hold events. Has events for hold, and for when you let go.
function onUserHold(element, func, hold, clearfunc) {
//var holdTime = 0;
var holdTimeout;
element.addEventListener('mousedown', function(e) {
holdTimeout = setTimeout(function() {
func();
clearTimeout(holdTimeout);
holdTime = 0;
}, hold);
//alert('UU');
});
element.addEventListener('mouseup', clearTime);
element.addEventListener('mouseout', clearTime);
function clearTime() {
clearTimeout(holdTimeout);
holdTime = 0;
if(clearfunc) {
clearfunc();
}
}
}
The element parameter is the one which you hold. The func parameter fires when it holds for a number of milliseconds specified by the parameter hold. The clearfunc param is optional and if it is given, it will get fired if the user lets go or leaves the element. You can also do some work-arounds to get the features you want. Enjoy! :)
You can use the way like @Florin Ghita has suggested. But remember dbms_lob.substr has a limit of 4000 characters in the function For example :
dbms_lob.substr(clob_value_column,4000,1)
Otherwise you will find ORA-22835 (buffer too small)
You can also use the other sql way :
SELECT * FROM your_table WHERE clob_value_column LIKE '%your string%';
Note : There are performance problems associated with both the above ways like causing Full Table Scans, so please consider about Oracle Text Indexes as well:
https://docs.oracle.com/en/database/oracle/oracle-database/12.2/ccapp/indexing-with-oracle-text.html
You could do something along these lines (which worked in both Python v2.7.17 and v3.8.1 when I tested it/them):
def hi():
# other code...
hi.bye = 42 # Create function attribute.
sigh = 10
hi()
print(hi.bye) # -> 42
Functions are objects in Python and can have arbitrary attributes assigned to them.
If you're going to be doing this kind of thing often, you could implement something more generic by creating a function decorator that adds a this
argument to each call to the decorated function.
This additional argument will give functions a way to reference themselves without needing to explicitly embed (hardcode) their name into the rest of the definition and is similar to the instance argument that class methods automatically receive as their first argument which is usually named self
— I picked something different to avoid confusion, but like the self
argument, it can be named whatever you wish.
Here's an example of that approach:
def add_this_arg(func):
def wrapped(*args, **kwargs):
return func(wrapped, *args, **kwargs)
return wrapped
@add_this_arg
def hi(this, that):
# other code...
this.bye = 2 * that # Create function attribute.
sigh = 10
hi(21)
print(hi.bye) # -> 42
This doesn't work for class methods. Just use the self
argument already passed being passed to instead of the method name. You can reference class-level attributes through type(self)
. See Function's attributes when in a class.
for i in arr1:
if i in arr2:
return 1
return 0
arr1=[1,2,5]
arr2=[2,4,15]
q=checkarrayequalornot(arr1,arr2)
print(q)
>>0
No. I don't see any advantage. Second one is more straitforward.
btw: Second style is found in every corners of JDK source.
So if you want something unique to the device itself, TM.getDeviceId()
should be sufficient.
Here is the code which shows how to get Telephony manager ID. The android Device ID that you are using can change on factory settings and also some manufacturers have issue in giving unique id.
TelephonyManager tm =
(TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
String androidId = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID);
Log.d("ID", "Android ID: " + androidId);
Log.d("ID", "Device ID : " + tm.getDeviceId());
Be sure to take permissions for TelephonyManager
by using
<uses-permission android:name="android.permission.READ_PHONE_STATE" />