PUT
$data = array('username'=>'dog','password'=>'tall');
$data_json = json_encode($data);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
POST
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
GET See @Dan H answer
DELETE
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);
You CAN add css clases, and any type of attributes you need to blade template, try this:
{{ Form::open(array('url' => '/', 'method' => 'PUT', 'class'=>'col-md-12')) }}
.... wathever code here
{{ Form::close() }}
If you dont want to go the blade way you can add a hidden input. This is the form Laravel does, any way:
Note: Since HTML forms only support POST and GET, PUT and DELETE methods will be spoofed by automatically adding a _method hidden field to your form. (Laravel docs)
<form class="col-md-12" action="<?php echo URL::to('/');?>/post/<?=$post->postID?>" method="POST">
<!-- Rendered blade HTML form use this hidden. Dont forget to put the form method to POST -->
<input name="_method" type="hidden" value="PUT">
<div class="form-group">
<textarea type="text" class="form-control input-lg" placeholder="Text Here" name="post"><?=$post->post?></textarea>
</div>
<div class="form-group">
<button class="btn btn-primary btn-lg btn-block" type="submit" value="Edit">Edit</button>
</div>
</form>
You have mixed 2 standard.
The error is in $header = "Content-Type: multipart/form-data; boundary='123456f'";
The function http_build_query($filedata)
is only for "Content-Type: application/x-www-form-urlencoded", or none.
Overall:
Both PUT and POST can be used for creating.
You have to ask, "what are you performing the action upon?", to distinguish what you should be using. Let's assume you're designing an API for asking questions. If you want to use POST, then you would do that to a list of questions. If you want to use PUT, then you would do that to a particular question.
Great, both can be used, so which one should I use in my RESTful design:
You do not need to support both PUT and POST.
Which you use is up to you. But just remember to use the right one depending on what object you are referencing in the request.
Some considerations:
An example:
I wrote the following as part of another answer on SO regarding this:
POST:
Used to modify and update a resource
POST /questions/<existing_question> HTTP/1.1 Host: www.example.com/
Note that the following is an error:
POST /questions/<new_question> HTTP/1.1 Host: www.example.com/
If the URL is not yet created, you should not be using POST to create it while specifying the name. This should result in a 'resource not found' error because
<new_question>
does not exist yet. You should PUT the<new_question>
resource on the server first.You could though do something like this to create a resources using POST:
POST /questions HTTP/1.1 Host: www.example.com/
Note that in this case the resource name is not specified, the new objects URL path would be returned to you.
PUT:
Used to create a resource, or overwrite it. While you specify the resources new URL.
For a new resource:
PUT /questions/<new_question> HTTP/1.1 Host: www.example.com/
To overwrite an existing resource:
PUT /questions/<existing_question> HTTP/1.1 Host: www.example.com/
Additionally, and a bit more concisely, RFC 7231 Section 4.3.4 PUT states (emphasis added),
4.3.4. PUT
The PUT method requests that the state of the target resource be
created
orreplaced
with the state defined by the representation enclosed in the request message payload.
I just found the solution, kind of answering to my own question in case anyone else stumbles upon it.
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://url/url/url" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1 );
curl_setopt($ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_POSTFIELDS, "body goes here" );
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/plain'));
$result=curl_exec ($ch);
Create a new immutable map:
scala> val m1 = Map("k0" -> "v0")
m1: scala.collection.immutable.Map[String,String] = Map(k0 -> v0)
Add a new key/value pair to the above map (and create a new map, since they're both immutable):
scala> val m2 = m1 + ("k1" -> "v1")
m2: scala.collection.immutable.Map[String,String] = Map(k0 -> v0, k1 -> v1)
I used RESTful API in my services, and here is my opinion:
First we must get to a common view: PUT
is used to update an resource not create or get.
I defined resources with: Stateless resource
and Stateful resource
:
Stateless resources For these resources, just return the HttpCode with empty body, it's enough.
Stateful resources For example: the resource's version. For this kind of resources, you must provide the version when you want to change it, so return the full resource or return the version to the client, so the client need't to send a get request after the update action.
But, for a service or system, keep it simple
, clearly
, easy to use and maintain
is the most important thing.
This is how it worked for me:
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("DELETE");
int responseCode = connection.getResponseCode();
If you want to stay within the standard library, you can subclass urllib2.Request
:
import urllib2
class RequestWithMethod(urllib2.Request):
def __init__(self, *args, **kwargs):
self._method = kwargs.pop('method', None)
urllib2.Request.__init__(self, *args, **kwargs)
def get_method(self):
return self._method if self._method else super(RequestWithMethod, self).get_method()
def put_request(url, data):
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = RequestWithMethod(url, method='PUT', data=data)
return opener.open(request)
As far as i know, PUT is mostly used for update the records.
POST - To create document or any other resource
PUT - To update the created document or any other resource.
But to be clear on that PUT usually 'Replaces' the existing record if it is there and creates if it not there..
One additional information I just one to add is that a PATCH request use less bandwidth compared to a PUT request since just a part of the data is sent not the whole entity. So just use a PATCH request for updates of specific records like (1-3 records) while PUT request for updating a larger amount of data. That is it, don't think too much or worry about it too much.
For brevity:
$.delete = function(url, data, callback, type){
if ( $.isFunction(data) ){
type = type || callback,
callback = data,
data = {}
}
return $.ajax({
url: url,
type: 'DELETE',
success: callback,
data: data,
contentType: type
});
}
Here is how I created Http POST request with swift that needs parameters with Json encoding and with headers.
Created API Client BKCAPIClient as a shared instance which will include all types of requests such as POST, GET, PUT, DELETE etc.
func postRequest(url:String, params:Parameters?, headers:HTTPHeaders?, completion:@escaping (_ responseData:Result<Any>?, _ error:Error?)->Void){
Alamofire.request(url, method: .post, parameters: params, encoding: JSONEncoding.default, headers: headers).responseJSON {
response in
guard response.result.isSuccess,
(response.result.value != nil) else {
debugPrint("Error while fetching data: \(String(describing: response.result.error))")
completion(nil,response.result.error)
return
}
completion(response.result,nil)
}
}
Created Operation class that contains all data needed for particular request and also contains parsing logic inside completion block.
func requestAccountOperation(completion: @escaping ( (_ result:Any?, _ error:Error?) -> Void)){
BKCApiClient.shared.postRequest(url: BKCConstants().bkcUrl, params: self.parametrs(), headers: self.headers()) { (result, error) in
if(error != nil){
//Parse and save to DB/Singletons.
}
completion(result, error)
}
}
func parametrs()->Parameters{
return ["userid”:”xnmtyrdx”,”bcode":"HDF"] as Parameters
}
func headers()->HTTPHeaders{
return ["Authorization": "Basic bXl1c2VyOm15cGFzcw",
"Content-Type": "application/json"] as HTTPHeaders
}
Call API In any View Controller where we need this data
func callToAPIOperation(){
let accOperation: AccountRequestOperation = AccountRequestOperation()
accOperation.requestAccountOperation{(result, error) in
}}
In my opinion the best tool for such testing is curl. Its --upload-file
option uploads a file by PUT
, which is exactly what you want (and it can do much more, like modifying HTTP headers, in case you need it):
curl http://myservice --upload-file file.txt
PUT and PATCH methods are similar in nature, but there is a key difference.
PUT - in PUT request, the enclosed entity would be considered as the modified version of a resource which residing on server and it would be replaced by this modified entity.
PATCH - in PATCH request, enclosed entity contains the set of instructions that how the entity which residing on server, would be modified to produce a newer version.
EDITED TO ADD: The following code is outdated and won't work in PHP 7. See the note towards the bottom of the answer for more details.
Assuming a table structure of an integer ID and a blob DATA column, and assuming MySQL functions are being used to interface with the database, you could probably do something like this:
$result = mysql_query 'INSERT INTO table (
data
) VALUES (
\'' . mysql_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf')) . '\'
);';
A word of warning though, storing blobs in databases is generally not considered to be the best idea as it can cause table bloat and has a number of other problems associated with it. A better approach would be to move the file somewhere in the filesystem where it can be retrieved, and store the path to the file in the database instead of the file itself.
Also, using mysql_* function calls is discouraged as those methods are effectively deprecated and aren't really built with versions of MySQL newer than 4.x in mind. You should switch to mysqli or PDO instead.
UPDATE: mysql_* functions are deprecated in PHP 5.x and are REMOVED COMPLETELY IN PHP 7! You now have no choice but to switch to a more modern Database Abstraction (MySQLI, PDO). I've decided to leave the original answer above intact for historical reasons but don't actually use it
Here's how to do it with mysqli in procedural mode:
$result = mysqli_query ($db, 'INSERT INTO table (
data
) VALUES (
\'' . mysqli_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf'), $db) . '\'
);');
The ideal way of doing it is with MySQLI/PDO prepared statements.
Ha... I wish I had found this first! My response was to this post... script to convert mysql dump sql file into format that can be imported into sqlite3 db
Combining the two would be exactly what I needed:
When the sqlite3 database is going to be used with ruby you may want to change:
tinyint([0-9]*)
to:
sed 's/ tinyint(1*) / boolean/g ' |
sed 's/ tinyint([0|2-9]*) / integer /g' |
alas, this only half works because even though you are inserting 1's and 0's into a field marked boolean, sqlite3 stores them as 1's and 0's so you have to go through and do something like:
Table.find(:all, :conditions => {:column => 1 }).each { |t| t.column = true }.each(&:save)
Table.find(:all, :conditions => {:column => 0 }).each { |t| t.column = false}.each(&:save)
but it was helpful to have the sql file to look at to find all the booleans.
Given that they're simply fonts, then you should be able to style them as fonts:
#elementID {
color: #fff;
text-shadow: 1px 1px 1px #ccc;
font-size: 1.5em;
}
answers above are good enough to show how to build the library, but how to collect the headers are still tricky. here I share the little script I use to copy the necessary headers.
SOURCE
is the first param, which is the tensorflow source(build) direcoty;
DST
is the second param, which is the include directory
holds the collected headers. (eg. in cmake, include_directories(./collected_headers_here)
).
#!/bin/bash
SOURCE=$1
DST=$2
echo "-- target dir is $DST"
echo "-- source dir is $SOURCE"
if [[ -e $DST ]];then
echo "clean $DST"
rm -rf $DST
mkdir $DST
fi
# 1. copy the source code c++ api needs
mkdir -p $DST/tensorflow
cp -r $SOURCE/tensorflow/core $DST/tensorflow
cp -r $SOURCE/tensorflow/cc $DST/tensorflow
cp -r $SOURCE/tensorflow/c $DST/tensorflow
# 2. copy the generated code, put them back to
# the right directories along side the source code
if [[ -e $SOURCE/bazel-genfiles/tensorflow ]];then
prefix="$SOURCE/bazel-genfiles/tensorflow"
from=$(expr $(echo -n $prefix | wc -m) + 1)
# eg. compiled protobuf files
find $SOURCE/bazel-genfiles/tensorflow -type f | while read line;do
#echo "procese file --> $line"
line_len=$(echo -n $line | wc -m)
filename=$(echo $line | rev | cut -d'/' -f1 | rev )
filename_len=$(echo -n $filename | wc -m)
to=$(expr $line_len - $filename_len)
target_dir=$(echo $line | cut -c$from-$to)
#echo "[$filename] copy $line $DST/tensorflow/$target_dir"
cp $line $DST/tensorflow/$target_dir
done
fi
# 3. copy third party files. Why?
# In the tf source code, you can see #include "third_party/...", so you need it
cp -r $SOURCE/third_party $DST
# 4. these headers are enough for me now.
# if your compiler complains missing headers, maybe you can find it in bazel-tensorflow/external
cp -RLf $SOURCE/bazel-tensorflow/external/eigen_archive/Eigen $DST
cp -RLf $SOURCE/bazel-tensorflow/external/eigen_archive/unsupported $DST
cp -RLf $SOURCE/bazel-tensorflow/external/protobuf_archive/src/google $DST
cp -RLf $SOURCE/bazel-tensorflow/external/com_google_absl/absl $DST
That is how I prevented direct access from URL to my ini files. Paste the following code in .htaccess
file on root. (no need to create extra folder)
<Files ~ "\.ini$">
Order allow,deny
Deny from all
</Files>
my settings.ini
file is on the root, and without this code is accessible www.mydomain.com/settings.ini
I solved the issue by simply deleting my whole /build folder and rebuilding (menu Build > rebuild project).
you can't access your drawables via a path, so if you want a human readable interface with your drawables that you can build programatically.
declare a HashMap somewhere in your class:
private static HashMap<String, Integer> images = null;
//Then initialize it in your constructor:
public myClass() {
if (images == null) {
images = new HashMap<String, Integer>();
images.put("Human1Arm", R.drawable.human_one_arm);
// for all your images - don't worry, this is really fast and will only happen once
}
}
Now for access -
String drawable = "wrench";
// fill in this value however you want, but in the end you want Human1Arm etc
// access is fast and easy:
Bitmap wrench = BitmapFactory.decodeResource(getResources(), images.get(drawable));
canvas.drawColor(Color .BLACK);
Log.d("OLOLOLO",Integer.toString(wrench.getHeight()));
canvas.drawBitmap(wrench, left, top, null);
If your object is not polymorphic (and a stack implementation likely isn't), then as per other answers here, what you want is the copy constructor. Please note that there are differences between copy construction and assignment in C++; if you want both behaviors (and the default versions don't fit your needs), you'll have to implement both functions.
If your object is polymorphic, then slicing can be an issue and you might need to jump through some extra hoops to do proper copying. Sometimes people use as virtual method called clone() as a helper for polymorphic copying.
Finally, note that getting copying and assignment right, if you need to replace the default versions, is actually quite difficult. It is usually better to set up your objects (via RAII) in such a way that the default versions of copy/assign do what you want them to do. I highly recommend you look at Meyer's Effective C++, especially at items 10,11,12.
<div id="header" style="display: table-cell; vertical-align:middle;">
...
or CSS
.someClass
{
display: table-cell;
vertical-align:middle;
}
Yes, although Internet Explorer 9 will compile your Javascript on a separate thread in preparation for execution on the main thread. This doesn't change anything for you as a programmer, though.
lastInsertId() only work after the INSERT query.
Correct:
$stmt = $this->conn->prepare("INSERT INTO users(userName,userEmail,userPass)
VALUES(?,?,?);");
$sonuc = $stmt->execute([$username,$email,$pass]);
$LAST_ID = $this->conn->lastInsertId();
Incorrect:
$stmt = $this->conn->prepare("SELECT * FROM users");
$sonuc = $stmt->execute();
$LAST_ID = $this->conn->lastInsertId(); //always return string(1)=0
Have a look at the System.Diagnostics
namespace. Lots of goodies in there!
System.Diagnostics.StackTrace t = new System.Diagnostics.StackTrace();
This is really good to have a poke around in to learn whats going on under the hood.
I'd recommend that you have a look into logging solutions (Such as NLog, log4net or the Microsoft patterns and practices Enterprise Library) which may achieve your purposes and then some. Good luck mate!
Use %.6f
.
This will print 6 decimals.
I have tested your example, and while Request.QueryString is not convertible to a string neither implicit nor explicit still the .ToString() method returns the correct result.
Further more when concatenating with a string using the "+" operator as in your example it will also return the correct result (because this behaves as if .ToString() was called).
As such there is nothing wrong with your code, and I would suggest that your issue was because of a typo in your code writing "Querystring" instead of "QueryString".
And this makes more sense with your error message since if the problem is that QueryString is a collection and not a string it would have to give another error message.
int *p=(int *)0x1234 = 10; //0x1234 is the memory address and value 10 is assigned in that address
unsigned int *ptr=(unsigned int *)0x903jf = 20;//0x903j is memory address and value 20 is assigned
Basically in Embedded platform we are using directly addresses instead of names
Add the Access-Control-Allow-Origin header from the server
Access-Control-Allow-Origin: https://www.mysite.com
There is some option to achieve the same, Follow the below points.
1) Open Macro explorer:
2) Create new macro:
3) Name it "OutlineRegions" (Or whatever you want)
4) Right Click on the "OutlineRegions" (Showing on Macro Explorer) select the "Edit" option and paste the following VB code into it:
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE90a
Imports EnvDTE100
Imports System.Diagnostics
Imports System.Collections
Public Module OutlineRegions
Sub OutlineRegions()
Dim selection As EnvDTE.TextSelection = DTE.ActiveDocument.Selection
Const REGION_START As String = "//#region"
Const REGION_END As String = "//#endregion"
selection.SelectAll()
Dim text As String = selection.Text
selection.StartOfDocument(True)
Dim startIndex As Integer
Dim endIndex As Integer
Dim lastIndex As Integer = 0
Dim startRegions As Stack = New Stack()
Do
startIndex = text.IndexOf(REGION_START, lastIndex)
endIndex = text.IndexOf(REGION_END, lastIndex)
If startIndex = -1 AndAlso endIndex = -1 Then
Exit Do
End If
If startIndex <> -1 AndAlso startIndex < endIndex Then
startRegions.Push(startIndex)
lastIndex = startIndex + 1
Else
' Outline region ...
selection.MoveToLineAndOffset(CalcLineNumber(text, CInt(startRegions.Pop())), 1)
selection.MoveToLineAndOffset(CalcLineNumber(text, endIndex) + 1, 1, True)
selection.OutlineSection()
lastIndex = endIndex + 1
End If
Loop
selection.StartOfDocument()
End Sub
Private Function CalcLineNumber(ByVal text As String, ByVal index As Integer)
Dim lineNumber As Integer = 1
Dim i As Integer = 0
While i < index
If text.Chars(i) = vbCr Then
lineNumber += 1
i += 1
End If
i += 1
End While
Return lineNumber
End Function
End Module
5) Save the macro and close the editor.
6) Now let's assign shortcut to the macro. Go to Tools->Options->Environment->Keyboard and search for your macro in "show commands containing" textbox (Type: Macro into the text box, it will suggest the macros name, choose yours one.)
7) now in textbox under the "Press shortcut keys" you can enter the desired shortcut. I use Ctrl+M+N.
Use:
return
{
//Properties
//#region
Name:null,
Address:null
//#endregion
}
8) Press the saved shortcut key
See below result:
Here is one way of doing it (Thanks to Android Documentation though!):
Add the following into a file (say customshape.xml) and then place it in (res/drawable/customshape.xml)
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<gradient
android:startColor="#SomeGradientBeginColor"
android:endColor="#SomeGradientEndColor"
android:angle="270"/>
<corners
android:bottomRightRadius="7dp"
android:bottomLeftRadius="7dp"
android:topLeftRadius="7dp"
android:topRightRadius="7dp"/>
</shape>
Once you are done with creating this file, just set the background in one of the following ways:
Through Code:
listView.setBackgroundResource(R.drawable.customshape);
Through XML, just add the following attribute to the container (ex: LinearLayout or to any fields):
android:background="@drawable/customshape"
Hope someone finds it useful...
One more better approach could be,
import pandas as pd
myList = [1, 2, 3, 1, 2, 5, 6, 7, 8]
cleanList = pd.Series(myList).drop_duplicates().tolist()
print(cleanList)
#> [1, 2, 3, 5, 6, 7, 8]
and the order remains preserved.
I recommend parsecsv-for-php to get around a number any issues with nested newlines and quotes.
SharpCompress is in my opinion one of the smartest compression libraries out there. It supports LZMA (7-zip), is easy to use and under active development.
As it has LZMA streaming support already, at the time of writing it unfortunately only supports 7-zip archive reading. BUT archive writing is on their todo list (see readme). For future readers: Check to get the current status here: https://github.com/adamhathcock/sharpcompress/blob/master/FORMATS.md
I see some errors in your code.
Your probably meant the mathematical term
90 <= angle <= 180, meaning angle in range 90-180.
if (angle >= 90 && angle <= 180) {
// do action
}
Thanks for the pointers guys - the Value vs Value2 argument got me a different set of search results which helped me realise what the answer is. Incidentally, the Value property is a parametrized property, which must be accessed through an accessor in C#. These are called get_Value and set_Value, and take an optional enum value. If anyone's interested, this explains it nicely.
It's possible to make the assignment via the Value2 property however, which is preferable as the interop documentation recommends against the use use of the get_Value and set_Value methods, for reasons beyond my understanding.
The key seems to be the dimension of the array of objects. For the call to work the array must be declared as two-dimensional, even if you're only assigning one-dimensional data.
I declared my data array as an object[NumberofRows,1]
and the assignment call worked.
Let's break it down:
So the GAC must be a place to store code libraries so they're accessible to all applications running on the machine.
Programmatically using D3:
body = d3.select('body')
svg = body.append('svg').attr('height', 600).attr('width', 200)
rect = svg.append('rect').transition().duration(500).attr('width', 150)
.attr('height', 100)
.attr('x', 40)
.attr('y', 100)
.style('fill', 'white')
.attr('stroke', 'black')
text = svg.append('text').text('This is some information about whatever')
.attr('x', 50)
.attr('y', 150)
.attr('fill', 'black')
Given your specifications (plus additional info in the comments),
The query below does not need a sequential scan of the big table, only an index scan.
First, get estimates for the main query:
SELECT count(*) AS ct -- optional
, min(id) AS min_id
, max(id) AS max_id
, max(id) - min(id) AS id_span
FROM big;
The only possibly expensive part is the count(*)
(for huge tables). Given above specifications, you don't need it. An estimate will do just fine, available at almost no cost (detailed explanation here):
SELECT reltuples AS ct FROM pg_class WHERE oid = 'schema_name.big'::regclass;
As long as ct
isn't much smaller than id_span
, the query will outperform other approaches.
WITH params AS (
SELECT 1 AS min_id -- minimum id <= current min id
, 5100000 AS id_span -- rounded up. (max_id - min_id + buffer)
)
SELECT *
FROM (
SELECT p.min_id + trunc(random() * p.id_span)::integer AS id
FROM params p
,generate_series(1, 1100) g -- 1000 + buffer
GROUP BY 1 -- trim duplicates
) r
JOIN big USING (id)
LIMIT 1000; -- trim surplus
Generate random numbers in the id
space. You have "few gaps", so add 10 % (enough to easily cover the blanks) to the number of rows to retrieve.
Each id
can be picked multiple times by chance (though very unlikely with a big id space), so group the generated numbers (or use DISTINCT
).
Join the id
s to the big table. This should be very fast with the index in place.
Finally trim surplus id
s that have not been eaten by dupes and gaps. Every row has a completely equal chance to be picked.
You can simplify this query. The CTE in the query above is just for educational purposes:
SELECT *
FROM (
SELECT DISTINCT 1 + trunc(random() * 5100000)::integer AS id
FROM generate_series(1, 1100) g
) r
JOIN big USING (id)
LIMIT 1000;
Especially if you are not so sure about gaps and estimates.
WITH RECURSIVE random_pick AS (
SELECT *
FROM (
SELECT 1 + trunc(random() * 5100000)::int AS id
FROM generate_series(1, 1030) -- 1000 + few percent - adapt to your needs
LIMIT 1030 -- hint for query planner
) r
JOIN big b USING (id) -- eliminate miss
UNION -- eliminate dupe
SELECT b.*
FROM (
SELECT 1 + trunc(random() * 5100000)::int AS id
FROM random_pick r -- plus 3 percent - adapt to your needs
LIMIT 999 -- less than 1000, hint for query planner
) r
JOIN big b USING (id) -- eliminate miss
)
SELECT *
FROM random_pick
LIMIT 1000; -- actual limit
We can work with a smaller surplus in the base query. If there are too many gaps so we don't find enough rows in the first iteration, the rCTE continues to iterate with the recursive term. We still need relatively few gaps in the ID space or the recursion may run dry before the limit is reached - or we have to start with a large enough buffer which defies the purpose of optimizing performance.
Duplicates are eliminated by the UNION
in the rCTE.
The outer LIMIT
makes the CTE stop as soon as we have enough rows.
This query is carefully drafted to use the available index, generate actually random rows and not stop until we fulfill the limit (unless the recursion runs dry). There are a number of pitfalls here if you are going to rewrite it.
For repeated use with varying parameters:
CREATE OR REPLACE FUNCTION f_random_sample(_limit int = 1000, _gaps real = 1.03)
RETURNS SETOF big AS
$func$
DECLARE
_surplus int := _limit * _gaps;
_estimate int := ( -- get current estimate from system
SELECT c.reltuples * _gaps
FROM pg_class c
WHERE c.oid = 'big'::regclass);
BEGIN
RETURN QUERY
WITH RECURSIVE random_pick AS (
SELECT *
FROM (
SELECT 1 + trunc(random() * _estimate)::int
FROM generate_series(1, _surplus) g
LIMIT _surplus -- hint for query planner
) r (id)
JOIN big USING (id) -- eliminate misses
UNION -- eliminate dupes
SELECT *
FROM (
SELECT 1 + trunc(random() * _estimate)::int
FROM random_pick -- just to make it recursive
LIMIT _limit -- hint for query planner
) r (id)
JOIN big USING (id) -- eliminate misses
)
SELECT *
FROM random_pick
LIMIT _limit;
END
$func$ LANGUAGE plpgsql VOLATILE ROWS 1000;
Call:
SELECT * FROM f_random_sample();
SELECT * FROM f_random_sample(500, 1.05);
You could even make this generic to work for any table: Take the name of the PK column and the table as polymorphic type and use EXECUTE
... But that's beyond the scope of this question. See:
IF your requirements allow identical sets for repeated calls (and we are talking about repeated calls) I would consider a materialized view. Execute above query once and write the result to a table. Users get a quasi random selection at lightening speed. Refresh your random pick at intervals or events of your choosing.
TABLESAMPLE SYSTEM (n)
Where n
is a percentage. The manual:
The
BERNOULLI
andSYSTEM
sampling methods each accept a single argument which is the fraction of the table to sample, expressed as a percentage between 0 and 100. This argument can be anyreal
-valued expression.
Bold emphasis mine. It's very fast, but the result is not exactly random. The manual again:
The
SYSTEM
method is significantly faster than theBERNOULLI
method when small sampling percentages are specified, but it may return a less-random sample of the table as a result of clustering effects.
The number of rows returned can vary wildly. For our example, to get roughly 1000 rows:
SELECT * FROM big TABLESAMPLE SYSTEM ((1000 * 100) / 5100000.0);
Related:
Or install the additional module tsm_system_rows to get the number of requested rows exactly (if there are enough) and allow for the more convenient syntax:
SELECT * FROM big TABLESAMPLE SYSTEM_ROWS(1000);
See Evan's answer for details.
But that's still not exactly random.
Here is here I solved mine https://stackoverflow.com/questions/17219916/64923728 .. The JSON file has to be in UTF-8 Encoding mine was in UTF-8 with BOM which was adding a weird &65279; to the json string output causing json_decode()
to return null
You can't mix tab and spaces for identation. Best practice is to convert all tabs to spaces.
How to fix this? Well just delete all the spaces/tabs before each line and convert them uniformly either to tabs OR spaces, but don't mix. Best solution: enable in your Editor the option to convert automagically any tabs to spaces.
Also be aware that your actual problem may lie in the lines before this block, and python throws the error here, because of a leading invalid indentation which doesn't match the following identations!
The below also happens to answer the Original Poster's question without, the "ugly" conditional code that some commenters have mentioned.
CONTIGUOUS NON-PRINTING Ruby Code
This will work in any mixed language Rails View file, e.g, *.html.erb, *.js.erb, *.rhtml
, etc.
This should also work with STD OUT/printing code, e.g. <%#= f.label :title %>
DETAILS:
Rather than use rails brackets on each line and commenting in front of each starting bracket as we usually do like this:
<%# if flash[:myErrors] %>
<%# if flash[:myErrors].any? %>
<%# if @post.id.nil? %>
<%# if @myPost!=-1 %>
<%# @post = @myPost %>
<%# else %>
<%# @post = Post.new %>
<%# end %>
<%# end %>
<%# end %>
<%# end %>
YOU CAN INSTEAD add only one comment (hashmark/poundsign) to the first open Rails bracket if you write your code as one large block... LIKE THIS:
<%#
if flash[:myErrors] then
if flash[:myErrors].any? then
if @post.id.nil? then
if @myPost!=-1 then
@post = @myPost
else
@post = Post.new
end
end
end
end
%>
The following functions are available to obtain the current date and/or time in PostgreSQL:
CURRENT_TIME
CURRENT_DATE
CURRENT_TIMESTAMP
Example
SELECT CURRENT_TIME;
08:05:18.864750+05:30
SELECT CURRENT_DATE;
2020-05-14
SELECT CURRENT_TIMESTAMP;
2020-05-14 08:04:51.290498+05:30
After reading this post some time ago I was wondering if it was safe to use domains for exception handling on an api / function level. I wanted to use them to simplify exception handling code in each async function I wrote. My concern was that using a new domain for each function would introduce significant overhead. My homework seems to indicate that there is minimal overhead and that performance is actually better with domains than with try catch in some situations.
http://www.lighthouselogic.com/#/using-a-new-domain-for-each-async-function-in-node/
On the solution explorer, right click on the project title and select the 'Properties' on the context menu to open the 'Project Property' form. In the 'Application' tab, on the 'Resources' group box there is a entry field where you can select the icon file you want for your application.
Well, you can't check if it's down after the event, but you can check if it's Up... If it's up.. it means that no longer is down :P lol
So the user presses the button down (onMouseDown event) ... and after that, you check if is up (onMouseUp). While it's not up, you can do what you need.
I needed to get the element as a string.
jQuery("#bob").get(0).outerHTML;
Which will give you something like:
<input type="text" id="bob" value="hello world" />
...as a string rather than a DOM element.
It's an excellent question, I had the same question yesterday. I thought about this problem, specifically SEARCHED if existed something like "ON UPDATE CASCADE" and fortunately the designers of SQL had also thought about that. I agree with Ted.strauss, and I also commented Noran's case.
When did I use it? Like Ted pointed out, when you are treating several databases at one time, and the modification in one of them, in one table, has any kind of reproduction in what Ted calls "satellite database", can't be kept with the very original ID, and for any reason you have to create a new one, in case you can't update the data on the old one (for example due to permissions, or in case you are searching for fastness in a case that is so ephemeral that doesn't deserve the absolute and utter respect for the total rules of normalization, simply because will be a very short-lived utility)
So, I agree in two points:
(A.) Yes, in many times a better design can avoid it; BUT
(B.) In cases of migrations, replicating databases, or solving emergencies, it's a GREAT TOOL that fortunately was there when I went to search if it existed.
You can export the secret keys to as environment variables on the ~/.bashrc
or ~/.bash_profile
of your server:
export SECRET_KEY_BASE = "YOUR_SECRET_KEY"
And then, you can source your .bashrc
or .bash_profile
:
source ~/.bashrc
source ~/.bash_profile
Never commit your secrets.yml
per the Selenium API, you really should call browser.quit()
as this method will close all windows and kills the process. You should still use browser.quit()
.
However: At my workplace, we've noticed a huge problem when trying to execute chromedriver tests in the Java platform, where the chromedriver.exe actually still exists even after using browser.quit()
. To counter this, we created a batch file similar to this one below, that just forces closed the processes.
kill_chromedriver.bat
@echo off
rem just kills stray local chromedriver.exe instances.
rem useful if you are trying to clean your project, and your ide is complaining.
taskkill /im chromedriver.exe /f
Since chromedriver.exe is not a huge program and does not consume much memory, you shouldn't have to run this every time, but only when it presents a problem. For example when running Project->Clean in Eclipse.
I just had this problem and wrapping each cell with the CLEAN
function fixed it for me. That should be relatively easy to do by doing =CLEAN(
, selecting your cell, and then autofilling the rest of the column. After I did this, pastes into Notepad or any other program no longer had duplicate quotes.
It also works if you change the content type
<form method="POST"
action="http://localhost:8080/cms/customer/create_customer"
id="frmRegister" name="frmRegister"
enctype="application/x-www-form-urlencoded">
In the controller also add the header value as follows:
@RequestMapping(value = "/create_customer", method = RequestMethod.POST, headers = "Content-Type=application/x-www-form-urlencoded")
As of pandas 1.0.0, you no longer need to use numpy to create null values in your dataframe. Instead you can just use pandas.NA (which is of type pandas._libs.missing.NAType), so it will be treated as null within the dataframe but will not be null outside dataframe context.
A .NET Framework v4.5+ solution that improves on tdbeckett's answer:
using System.Collections.ObjectModel;
// ...
public ReadOnlyCollection<string> Titles { get; } = new ReadOnlyCollection<string>(
new string[] { "German", "Spanish", "Corrects", "Wrongs" }
);
Note: Given that the collection is conceptually constant, it may make sense to make it static
to declare it at the class level.
The above:
Initializes the property's implicit backing field once with the array.
Note that { get; }
- i.e., declaring only a property getter - is what makes the property itself implicitly read-only (trying to combine readonly
with { get; }
is actually a syntax error).
Alternatively, you could just omit the { get; }
and add readonly
to create a field instead of a property, as in the question, but exposing public data members as properties rather than fields is a good habit to form.
Creates an array-like structure (allowing indexed access) that is truly and robustly read-only (conceptually constant, once created), both with respect to:
IReadOnlyList<T>
solution, where a (string[])
cast can be used to gain write access to the elements, as shown in mjepsen's helpful answer.IReadOnlyCollection<T>
interface, which, despite the similarity in name to class ReadOnlyCollection
, does not even support indexed access, making it fundamentally unsuitable for providing array-like access.)If you will change the ID then Toggle will not working same problem was with me i just change
<div class="collapse navbar-collapse" id="defaultNavbar1">
<ul class="nav navbar-nav">
id="defaultNavbar1" then toggle is working
After wrestling with this problem today my opinion is this: BEGIN...END brackets code just like {....} does in C languages, e.g. code blocks for if...else and loops
GO is (must be) used when succeeding statements rely on an object defined by a previous statement. USE database is a good example above, but the following will also bite you:
alter table foo add bar varchar(8);
-- if you don't put GO here then the following line will error as it doesn't know what bar is.
update foo set bar = 'bacon';
-- need a GO here to tell the interpreter to execute this statement, otherwise the Parser will lump it together with all successive statements.
It seems to me the problem is this: the SQL Server SQL Parser, unlike the Oracle one, is unable to realise that you're defining a new symbol on the first line and that it's ok to reference in the following lines. It doesn't "see" the symbol until it encounters a GO token which tells it to execute the preceding SQL since the last GO, at which point the symbol is applied to the database and becomes visible to the parser.
Why it doesn't just treat the semi-colon as a semantic break and apply statements individually I don't know and wish it would. Only bonus I can see is that you can put a print() statement just before the GO and if any of the statements fail the print won't execute. Lot of trouble for a minor gain though.
Copy conditionally formatted cells into Word (using CTRL+C, CTRL+V). Copy them back into Excel, keeping the source formatting. Now the conditional formatting is lost but you still have the colors and can check the RGB choosing Home > Fill color (or Font color) > More colors.
However many years late this response may be, anyone coming across this might just want to try
li {
display: flex;
flex-direction: row;
align-items: center;
}
Browser support for flexbox is far better than it was when @scottjoudry posted his response above, but you may still want to consider prefixing or other options if you're trying to support much older browsers. caniuse: flex
You can have great success and great performance either way. MSDN runs off of ASP.NET so you know it can perform well. PHP runs a lot of the top websites in the world. The same can be said of the databases as well. You really need to choose based upon your skills, the skills of your team, possible specific features that you need/want that one does better than the other, and even the servers that you want to run this site.
If I were building it, I would lean towards PHP because probably everything you want to do has been done before (with code examples how) and because hosting is so much easier to get (and cheaper because you don't have the licensing issues to deal with compared to Windows hosting). For the same reason, I would choose MySQL as well. It is a great database platform and the price is right.
Firstly, you probably want to add a return false; to the bottom of your Submit() method in JavaScript (so it stops the submit, since you're handling it in AJAX).
You're connecting to the complete event, not the success event - there's a significant difference and that's why your debugging results aren't as expected. Also, I've never made the signature methods match yours, and I've always provided a contentType and dataType. For example:
$.ajax({
type: "POST",
url: "Default.aspx/OnSubmit",
data: dataValue,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
},
success: function (result) {
alert("We returned: " + result);
}
});
Sorry, but all the answers are difficult to understand for me as a beginner in graphics...
After some fiddling, this is working for me and it is easy to reason about.
@Override
public void draw(Graphics2D g) {
AffineTransform tr = new AffineTransform();
// X and Y are the coordinates of the image
tr.translate((int)getX(), (int)getY());
tr.rotate(
Math.toRadians(this.rotationAngle),
img.getWidth() / 2,
img.getHeight() / 2
);
// img is a BufferedImage instance
g.drawImage(img, tr, null);
}
I suppose that if you want to rotate a rectangular image this method wont work and will cut the image, but I thing you should create square png images and rotate that.
A URL must not contain a literal space. It must either be encoded using the percent-encoding or a different encoding that uses URL-safe characters (like application/x-www-form-urlencoded that uses +
instead of %20
for spaces).
But whether the statement is right or wrong depends on the interpretation: Syntactically, a URI must not contain a literal space and it must be encoded; semantically, a %20
is not a space (obviously) but it represents a space.
I was able to call my callback function at minimum of 250ms using audio tag and handling its ontimeupdate event. Its called 3-4 times in a second. Its better than one second lagging setTimeout
You can do this:
add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010
and most of it will work (although MS support will tell you that doing this is not supported because it bypasses RBAC).
I've seen issues with some cmdlets (specifically enable/disable UMmailbox) not working with just the snapin loaded.
In Exchange 2010, they basically don't support using Powershell outside of the the implicit remoting environment of an actual EMS shell.
String[] token=s.split("[.-]");
The real answer has to include keyCode:
var e = jQuery.Event("keydown");
e.which = 50; // # Some key code value
e.keyCode = 50
$("input").trigger(e);
Even though jQuery's website says that which and keyCode are normalized they are very badly mistaken. It's always safest to do the standard cross-browser checks for e.which and e.keyCode and in this case just define both.
Depending on your needs, like if you want to allow the data to eventually expire or set limitations on how many records to store, you could also look at https://github.com/jmdobry/angular-cache which allows you to define if the cache sits in memory, localStorage, or sessionStorage.
The answers seem a bit dated, they don't work for me. What did work was
\begin{align}
1+1=2 \tag{xyz}
\end{align}
public string nullToString(string value)
{
return value == null ?string.Empty: value;
}
In Solution Explorer, please select files you want to copied to output directory and assign two properties: - Build action = Content - Copy to Output Directory = Copy Always
This will do the trick.
There is a simple way available in Kotlin
var lst: List<Object> = ...
listOFStrings: ArrayList<String> = (lst!!.map { it.name })
On python 3.6 with django 2.0, decode on a byte literal does not works as expected. Yeah i get the right result when i print it, but the b'value' is still there even if you print it right.
This is what im encoding
uid': urlsafe_base64_encode(force_bytes(user.pk)),
This is what im decoding:
uid = force_text(urlsafe_base64_decode(uidb64))
This is what django 2.0 says :
urlsafe_base64_encode(s)[source]
Encodes a bytestring in base64 for use in URLs, stripping any trailing equal signs.
urlsafe_base64_decode(s)[source]
Decodes a base64 encoded string, adding back any trailing equal signs that might have been stripped.
This is my account_activation_email_test.html file
{% autoescape off %}
Hi {{ user.username }},
Please click on the link below to confirm your registration:
http://{{ domain }}{% url 'accounts:activate' uidb64=uid token=token %}
{% endautoescape %}
This is my console response:
Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: Activate Your MySite Account From: webmaster@localhost To: [email protected] Date: Fri, 20 Apr 2018 06:26:46 -0000 Message-ID: <152420560682.16725.4597194169307598579@Dash-U>
Hi testuser,
Please click on the link below to confirm your registration:
http://127.0.0.1:8000/activate/b'MjU'/4vi-fasdtRf2db2989413ba/
as you can see uid = b'MjU'
expected uid = MjU
test in console:
$ python
Python 3.6.4 (default, Apr 7 2018, 00:45:33)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode
>>> from django.utils.encoding import force_bytes, force_text
>>> var1=urlsafe_base64_encode(force_bytes(3))
>>> print(var1)
b'Mw'
>>> print(var1.decode())
Mw
>>>
After investigating it seems like its related to python 3. My workaround was quite simple:
'uid': user.pk,
i receive it as uidb64 on my activate function:
user = User.objects.get(pk=uidb64)
and voila:
Content-Transfer-Encoding: 7bit
Subject: Activate Your MySite Account
From: webmaster@localhost
To: [email protected]
Date: Fri, 20 Apr 2018 20:44:46 -0000
Message-ID: <152425708646.11228.13738465662759110946@Dash-U>
Hi testuser,
Please click on the link below to confirm your registration:
http://127.0.0.1:8000/activate/45/4vi-3895fbb6b74016ad1882/
now it works fine. :)
Imagine an 8 digit padding function that transforms:
We can used the padded strings to help us sort '19asd' to appear before '123asd'.
Use the regular expression /\d+/g
to help find all the numbers that need to be padded:
str.replace(/\d+/g, pad)
The following demonstrates sorting using this technique:
var list = [_x000D_
'123asd',_x000D_
'19asd',_x000D_
'12345asd',_x000D_
'asd123',_x000D_
'asd12'_x000D_
];_x000D_
_x000D_
function pad(n) { return ("00000000" + n).substr(-8); }_x000D_
function natural_expand(a) { return a.replace(/\d+/g, pad) };_x000D_
function natural_compare(a, b) {_x000D_
return natural_expand(a).localeCompare(natural_expand(b));_x000D_
}_x000D_
_x000D_
console.log(list.map(natural_expand).sort()); // intermediate values_x000D_
console.log(list.sort(natural_compare)); // result
_x000D_
The intermediate results show what the natural_expand() routine does and gives you an understanding of how the subsequent natural_compare routine will work:
[
"00000019asd",
"00000123asd",
"00012345asd",
"asd00000012",
"asd00000123"
]
Outputs:
[
"19asd",
"123asd",
"12345asd",
"asd12",
"asd123"
]
If it's too late at night and your table is already innoDB and you still don't see the link, maybe is due to the fact that now it's placed above the structure of the table, like in the picture is shown
I suggest using one of the exchange
methods that accepts an HttpEntity
for which you can also set the HttpHeaders
. (You can also specify the HTTP method you want to use.)
For example,
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<>("body", headers);
restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
I prefer this solution because it's strongly typed, ie. exchange
expects an HttpEntity
.
However, you can also pass that HttpEntity
as a request
argument to postForObject
.
HttpEntity<String> entity = new HttpEntity<>("body", headers);
restTemplate.postForObject(url, entity, String.class);
This is mentioned in the RestTemplate#postForObject
Javadoc.
The
request
parameter can be aHttpEntity
in order to add additional HTTP headers to the request.
You can create table variables:
DECLARE @result1 TABLE (a INT, b INT, c INT)
INSERT INTO @result1
SELECT a, b, c
FROM table1
SELECT a AS val FROM @result1
UNION
SELECT b AS val FROM @result1
UNION
SELECT c AS val FROM @result1
This should be fine for what you need.
While the answer provided by BalusC works for this case, it will break when the file path contains spaces because in a URL, these are being converted to %20 which is not a valid file name. If you construct the File object using a URI rather than a String, whitespaces will be handled correctly:
URL url = getClass().getResource("ListStopWords.txt");
File file = new File(url.toURI());
This solved my case:
In my case, I was getting the exception below (note that my application class was causing the exception, not my activity):
ClassNotFoundException: Didn't find class "com.example.MyApplication" on path: DexPathList
I was getting this exception only on devices equal or below API 19, the reason was that I was extending MultiDexApplication()
class and overriding attachBaseContext
at the same time! When I removed attachBaseContext
everything got on track.
class MyApplication : MultiDexApplication() {
override fun onCreate() {
super.onCreate()
// ...
}
override fun attachBaseContext(base: Context?) {
super.attachBaseContext(base)
MultiDex.install(this)
}
So if you happen to have such case as I had (Which isn't likely), there is no need to extend MultiDexApplication()
and override attachBaseContext
at the same time, doing one of these actions is enough.
This behavior is explicitly documented in String.split(String regex)
(emphasis mine):
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
If you want those trailing empty strings included, you need to use String.split(String regex, int limit)
with a negative value for the second parameter (limit
):
String[] array = values.split("\\|", -1);
Just use
<input type="number" id="foo" runat="server" />
It'll work on all modern browsers except IE +10. Here is a full list:
If you want to use class, you can do this.
Helper.js
function x(){}
function y(){}
export default class Helper{
static x(){ x(); }
static y(){ y(); }
}
App.js
import Helper from 'helper.js';
/****/
Helper.x
If you really just have lock-step iteration over a range, you can do it one of several ways:
for i in range(x):
j = i
…
# or
for i, j in enumerate(range(x)):
…
# or
for i, j in ((i,i) for i in range(x)):
…
All of the above are equivalent to for i, j in zip(range(x), range(y))
if x <= y
.
If you want a nested loop and you only have two iterables, just use a nested loop:
for i in range(x):
for i in range(y):
…
If you have more than two iterables, use itertools.product
.
Finally, if you want lock-step iteration up to x
and then to continue to y
, you have to decide what the rest of the x
values should be.
for i, j in itertools.zip_longest(range(x), range(y), fillvalue=float('nan')):
…
# or
for i in range(min(x,y)):
j = i
…
for i in range(min(x,y), max(x,y)):
j = float('nan')
…
If you are using webjars. You need to add this in your configure
method:
http.authorizeRequests().antMatchers("/webjars/**").permitAll();
Make sure this is the first statement. For example:
@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests().antMatchers("/webjars/**").permitAll();
http.authorizeRequests().anyRequest().authenticated();
http.formLogin()
.loginPage("/login")
.failureUrl("/login?error")
.usernameParameter("email")
.permitAll()
.and()
.logout()
.logoutUrl("/logout")
.deleteCookies("remember-me")
.logoutSuccessUrl("/")
.permitAll()
.and()
.rememberMe();
}
You will also need to have this in order to have webjars enabled:
@Configuration
public class MvcConfig extends WebMvcConfigurerAdapter {
...
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
}
...
}
I am having a similar problem. I can get the screen to stay on, but if I use a partial wake lock and the screen is turned off, my onFinish function isn't called until the screen is turned on.
You can check your wake lock using mWakeLock.isHeld(), first of all, to make sure you're getting it. Easiest way is to add that to the code, set a breakpoint on it in the debugger, and then check it.
In my case, I'm getting it, but the partial wake lock doesn't seem to be doing anything. Here's my working code for the screen dim lock.
protected void setScreenLock(boolean on){
if(mWakeLock == null){
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK |
PowerManager.ON_AFTER_RELEASE, TAG);
}
if(on){
mWakeLock.acquire();
}else{
if(mWakeLock.isHeld()){
mWakeLock.release();
}
mWakeLock = null;
}
}
ADDENDUM:
Droid Eris and DROID users are reporting to me that this DOES NOT work on their devices, though it works fine on my G1. What device are you testing on? I think this may be an Android bug.
var lat = homeMarker.getPosition().lat();
var lng = homeMarker.getPosition().lng();
See the google.maps.LatLng docs and google.maps.Marker getPosition()
.
Recent I have met several times of stop abnormal. Although shutdown.sh provides some information, The situations are:
ps -ef| grep java
is Null.ps -ef| grep java
is not null. My opinion is just kill the process of Catalina and remove the pid file (In your situation is /opt/tomcat/work/catalina.pid.)
The result seems not so seriously to influence others.
class Sort
{
public static void main(String[] args)
{
System.out.println("Enter the range");
java.util.Scanner sc=new java.util.Scanner(System.in);
int n=sc.nextInt();
int arr[]=new int[n];
System.out.println("Enter the array values");
for(int i=0;i<=n-1;i++)
{
arr[i]=sc.nextInt();
}
System.out.println("Before sorting array values are");
for(int i=0;i<=n-1;i++)
{
System.out.println(arr[i]);
}
System.out.println();
for(int pass=1;pass<=n;pass++)
{
for(int i=0;i<=n-1;i++)
{
if(i==n-1)
{
break;
}
int temp;
if(arr[i]>arr[i+1])
{
temp=arr[i];
arr[i]=arr[i+1];
arr[i+1]=temp;
}
}
}
System.out.println("After sorting array values are");
for(int i=0;i<=n-1;i++)
{
System.out.println(arr[i]);
}
}
}
From psql's help (\?
):
\o [FILE] send all query results to file or |pipe
The sequence of commands will look like this:
[wist@scifres ~]$ psql db
Welcome to psql 8.3.6, the PostgreSQL interactive terminal
db=>\o out.txt
db=>\dt
db=>\q
Apple is abstracting the system fonts going forward. This facility uses new generic family name -apple-system. So something like below should get you what you want.
body
{
font-family: -apple-system, "Helvetica Neue", "Lucida Grande";
}
You certainly want to hack the header to have a proper Ajax Request :
headers = {'X_REQUESTED_WITH' :'XMLHttpRequest',
'ACCEPT': 'application/json, text/javascript, */*; q=0.01',}
request = urllib2.Request(path, data, headers)
response = urllib2.urlopen(request).read()
And to json.loads the POST on the server-side.
Edit : By the way, you have to urllib.urlencode(mydata_dict)
before sending them. If you don't, the POST won't be what the server expect
I would not do that. I would keep the profileID
as primary key of the table Profile
A foreign key is just a referential constraint between two tables
One could argue that a primary key is necessary as the target of any foreign keys which refer to it from other tables. A foreign key is a set of one or more columns in any table (not necessarily a candidate key, let alone the primary key, of that table) which may hold the value(s) found in the primary key column(s) of some other table. So we must have a primary key to match the foreign key. Or must we? The only purpose of the primary key in the primary key/foreign key pair is to provide an unambiguous join - to maintain referential integrity with respect to the "foreign" table which holds the referenced primary key. This insures that the value to which the foreign key refers will always be valid (or null, if allowed).
In my case 415 Unsupported Media Types was received since I used new FormData()
and sent it with axios.post(...)
but did not set headers: {content-type: 'multipart/form-data'}
. I also had to do the same on the server side:
[Consumes("multipart/form-data")]
public async Task<IActionResult> FileUpload([FromForm] IFormFile formFile) { ... }
According to this article application/xml is preferred.
EDIT
I did a little follow-up on the article.
The author claims that the encoding declared in XML processing instructions, like:
<?xml version="1.0" encoding="UTF-8"?>
can be ignored when text/xml
media type is used.
They support the thesis with the definition of text/*
MIME type family specification in RFC 2046, specifically the following fragment:
4.1.2. Charset Parameter
A critical parameter that may be specified in the Content-Type field
for "text/plain" data is the character set. This is specified with a
"charset" parameter, as in:
Content-type: text/plain; charset=iso-8859-1
Unlike some other parameter values, the values of the charset
parameter are NOT case sensitive. The default character set, which
must be assumed in the absence of a charset parameter, is US-ASCII.
The specification for any future subtypes of "text" must specify
whether or not they will also utilize a "charset" parameter, and may
possibly restrict its values as well. For other subtypes of "text"
than "text/plain", the semantics of the "charset" parameter should be
defined to be identical to those specified here for "text/plain",
i.e., the body consists entirely of characters in the given charset.
In particular, definers of future "text" subtypes should pay close
attention to the implications of multioctet character sets for their
subtype definitions.
According to them, such difficulties can be avoided when using application/xml
MIME type. Whether it's true or not, I wouldn't go as far as to avoid text/xml
. IMHO, it's best just to follow the semantics of human-readability(non-readability) and always remember to specify the charset.
In SQL server 2005 new datatypes were introduced: varchar(max)
and nvarchar(max)
They have the advantages of the old text type: they can contain op to 2GB of data, but they also have most of the advantages of varchar
and nvarchar
. Among these advantages are the ability to use string manipulation functions such as substring().
Also, varchar(max) is stored in the table's (disk/memory) space while the size is below 8Kb. Only when you place more data in the field, it's is stored out of the table's space. Data stored in the table's space is (usually) retrieved quicker.
In short, never use Text, as there is a better alternative: (n)varchar(max). And only use varchar(max) when a regular varchar is not big enough, ie if you expect teh string that you're going to store will exceed 8000 characters.
As was noted, you can use SUBSTRING on the TEXT datatype,but only as long the TEXT fields contains less than 8000 characters.
There is a very simple way in which you can do this. It involves injecting a javascript code to a label control from code behind. here is sample code:
<head runat="server">
<title>Calling javascript function from code behind example</title>
<script type="text/javascript">
function showDialogue() {
alert("this dialogue has been invoked through codebehind.");
}
</script>
</head>
..........
lblJavaScript.Text = "<script type='text/javascript'>showDialogue();</script>";
Check out the full code here: http://softmate-technologies.com/javascript-from-CodeBehind.htm (dead)
Link from Internet Archive: https://web.archive.org/web/20120608053720/http://softmate-technologies.com/javascript-from-CodeBehind.htm
I think apache provides a better util class which provides a function to get the string
ReflectionToStringBuilder.toString(object)
You can create a setTimeout
loop using recursion:
function timeout() {
setTimeout(function () {
// Do Something Here
// Then recall the parent function to
// create a recursive loop.
timeout();
}, 1000);
}
The problem with setInterval()
and setTimeout()
is that there is no guarantee your code will run in the specified time. By using setTimeout()
and calling it recursively, you're ensuring that all previous operations inside the timeout are complete before the next iteration of the code begins.
You can negate a time.Duration
:
then := now.Add(- dur)
You can even compare a time.Duration
against 0
:
if dur > 0 {
dur = - dur
}
then := now.Add(dur)
You can see a working example at http://play.golang.org/p/ml7svlL4eW
Check MediaQuery
class
For example, to learn the size of the current media (e.g., the window containing your app), you can read the
MediaQueryData.size
property from theMediaQueryData
returned byMediaQuery.of
:MediaQuery.of(context).size
.
So you can do the following:
new Container(
height: MediaQuery.of(context).size.height/2,
.. )
Messages have content. Content can be text, html, a DataHandler or a Multipart, and there can only be one content. Multiparts only have BodyParts but can have more than one. BodyParts, like Messages, can have content which has already been described.
A message with HTML, text and an a attachment can be viewed hierarchically like this:
message
mainMultipart (content for message, subType="mixed")
->htmlAndTextBodyPart (bodyPart1 for mainMultipart)
->htmlAndTextMultipart (content for htmlAndTextBodyPart, subType="alternative")
->textBodyPart (bodyPart2 for the htmlAndTextMultipart)
->text (content for textBodyPart)
->htmlBodyPart (bodyPart1 for htmlAndTextMultipart)
->html (content for htmlBodyPart)
->fileBodyPart1 (bodyPart2 for the mainMultipart)
->FileDataHandler (content for fileBodyPart1 )
And the code to build such a message:
// the parent or main part if you will
Multipart mainMultipart = new MimeMultipart("mixed");
// this will hold text and html and tells the client there are 2 versions of the message (html and text). presumably text
// being the alternative to html
Multipart htmlAndTextMultipart = new MimeMultipart("alternative");
// set text
MimeBodyPart textBodyPart = new MimeBodyPart();
textBodyPart.setText(text);
htmlAndTextMultipart.addBodyPart(textBodyPart);
// set html (set this last per rfc1341 which states last = best)
MimeBodyPart htmlBodyPart = new MimeBodyPart();
htmlBodyPart.setContent(html, "text/html; charset=utf-8");
htmlAndTextMultipart.addBodyPart(htmlBodyPart);
// stuff the multipart into a bodypart and add the bodyPart to the mainMultipart
MimeBodyPart htmlAndTextBodyPart = new MimeBodyPart();
htmlAndTextBodyPart.setContent(htmlAndTextMultipart);
mainMultipart.addBodyPart(htmlAndTextBodyPart);
// attach file body parts directly to the mainMultipart
MimeBodyPart filePart = new MimeBodyPart();
FileDataSource fds = new FileDataSource("/path/to/some/file.txt");
filePart.setDataHandler(new DataHandler(fds));
filePart.setFileName(fds.getName());
mainMultipart.addBodyPart(filePart);
// set message content
message.setContent(mainMultipart);
git reset --hard origin/master
says: throw away all my staged and unstaged changes, forget everything on my current local branch and make it exactly the same as origin/master
.
You probably wanted to ask this before you ran the command. The destructive nature is hinted at by using the same words as in "hard reset".
FILE *fp;
char* str = "string";
int x = 10;
fp=fopen("test.txt", "w");
if(fp == NULL)
exit(-1);
fprintf(fp, "This is a string which is written to a file\n");
fprintf(fp, "The string has %d words and keyword %s\n", x, str);
fclose(fp);
Accessing a single row
//Result as an Object
$result = $this->db->select('age')->from('my_users_table')->where('id', '3')->limit(1)->get()->row();
echo $result->age;
//Result as an Array
$result = $this->db->select('age')->from('my_users_table')->where('id', '3')->limit(1)->get()->row_array();
echo $result['age'];
All versions of Git since v1.7.8 understand git fetch
with a refspec, whereas since v1.9.0 the --tags
option overrides the --prune
option. For a general purpose solution, try this:
$ git --version
git version 2.1.3
$ git fetch --prune origin "+refs/tags/*:refs/tags/*"
From ssh://xxx
x [deleted] (none) -> rel_test
For further reading on how the "--tags" with "--prune" behavior changed in Git v1.9.0, see: https://github.com/git/git/commit/e66ef7ae6f31f246dead62f574cc2acb75fd001c
Using attr() pointing to an external domain may trigger an error like this in Chrome: "Refused to display document because display forbidden by X-Frame-Options". The workaround to this can be to move the whole iframe HTML code into the script (eg. using .html() in jQuery).
Example:
var divMapLoaded = false;
$("#container").scroll(function() {
if ((!divMapLoaded) && ($("#map").position().left <= $("#map").width())) {
$("#map-iframe").html("<iframe id=\"map-iframe\" " +
"width=\"100%\" height=\"100%\" frameborder=\"0\" scrolling=\"no\" " +
"marginheight=\"0\" marginwidth=\"0\" " +
"src=\"http://www.google.it/maps?t=m&cid=0x3e589d98063177ab&ie=UTF8&iwloc=A&brcurrent=5,0,1&ll=41.123115,16.853177&spn=0.005617,0.009943&output=embed\"" +
"></iframe>");
divMapLoaded = true;
}
var http = require('http');
var url = require('url');
var fs = require('fs');
var neededstats = [];
http.createServer(function(req, res) {
if (req.url == '/index.html' || req.url == '/') {
fs.readFile('./index.html', function(err, data) {
res.end(data);
});
} else {
var p = __dirname + '/' + req.params.filepath;
fs.stat(p, function(err, stats) {
if (err) {
throw err;
}
neededstats.push(stats.mtime);
neededstats.push(stats.size);
res.send(neededstats);
});
}
}).listen(8080, '0.0.0.0');
console.log('Server running.');
I have not tested your code but other things works
If you want to get the path info from request url
var url_parts = url.parse(req.url);
console.log(url_parts);
console.log(url_parts.pathname);
1.If you are getting the URL parameters still not able to read the file just correct your file path in my example. If you place index.html in same directory as server code it would work...
2.if you have big folder structure that you want to host using node then I would advise you to use some framework like expressjs
If you want raw solution to file path
var http = require("http");
var url = require("url");
function start() {
function onRequest(request, response) {
var pathname = url.parse(request.url).pathname;
console.log("Request for " + pathname + " received.");
response.writeHead(200, {"Content-Type": "text/plain"});
response.write("Hello World");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("Server has started.");
}
exports.start = start;
source : http://www.nodebeginner.org/
This is what I get from console on Windows 10:
C:\>find /?
Searches for a text string in a file or files.
FIND [/V] [/C] [/N] [/I] [/OFF[LINE]] "string" [[drive:][path]filename[ ...]]
/V Displays all lines NOT containing the specified string.
/C Displays only the count of lines containing the string.
/N Displays line numbers with the displayed lines.
/I Ignores the case of characters when searching for the string.
/OFF[LINE] Do not skip files with offline attribute set.
"string" Specifies the text string to find.
[drive:][path]filename
Specifies a file or files to search.
If a path is not specified, FIND searches the text typed at the prompt
or piped from another command.
Yes, that is normal behavior. You basically read to the end of the file the first time (you can sort of picture it as reading a tape), so you can't read any more from it unless you reset it, by either using f.seek(0)
to reposition to the start of the file, or to close it and then open it again which will start from the beginning of the file.
If you prefer you can use the with
syntax instead which will automatically close the file for you.
e.g.,
with open('baby1990.html', 'rU') as f:
for line in f:
print line
once this block is finished executing, the file is automatically closed for you, so you could execute this block repeatedly without explicitly closing the file yourself and read the file this way over again.
Process: program under execution is known as process
Thread: Thread is a functionality which is executed with the other part of the program based on the concept of "one with other"so thread is a part of process..
The simplest way is this:
while (cursor.moveToNext()) {
...
}
The cursor starts before the first result row, so on the first iteration this moves to the first result if it exists. If the cursor is empty, or the last row has already been processed, then the loop exits neatly.
Of course, don't forget to close the cursor once you're done with it, preferably in a finally
clause.
Cursor cursor = db.rawQuery(...);
try {
while (cursor.moveToNext()) {
...
}
} finally {
cursor.close();
}
If you target API 19+, you can use try-with-resources.
try (Cursor cursor = db.rawQuery(...)) {
while (cursor.moveToNext()) {
...
}
}
Just my 2 cents. The below command should do the trick, as answered earlier
curl -vs google.com 2>&1
However if need to get the output to a file,
curl -vs google.com > out.txt 2>&1
should work.
You can add your Script Manager tags just below the <Form>
tag of your page. Here is how you can place your Script Manager tag.
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
If you are using Master Pages, its recommended to use your Script Manager in your Master page so that you do not have to write it again and again on every page that contains AJAX controls.
This is much simple and easy way.
import pandas
df = pandas.read_excel(open('your_xls_xlsx_filename','rb'), sheetname='Sheet 1')
# or using sheet index starting 0
df = pandas.read_excel(open('your_xls_xlsx_filename','rb'), sheetname=2)
check out documentation full details http://pandas.pydata.org/pandas-docs/version/0.17.1/generated/pandas.read_excel.html
FutureWarning: The sheetname
keyword is deprecated for newer Pandas versions, use sheet_name
instead.
If you're looking for a nice library to prettify json on a web page...
Prism.js is pretty good.
I found using JSON.stringify(obj, undefined, 2) to get the indentation, and then using prism to add a theme was a good approach.
If you're loading in JSON via an ajax call, then you can run one of Prism's utility methods to prettify
For example:
Prism.highlightAll()
Note: Note to Win32 Users In order to enable this module (cURL) on a Windows environment, libeay32.dll and ssleay32.dll must be present in your PATH. You don't need libcurl.dll from the cURL site.
This note solved my problem. Thought of sharing. libeay32.dll & ssleay.dll you will find in your php installation folder.
I was getting a similar error after moving my dev machine from Win7 32bit to Win7 64bit. Error message:
...\Web\Views\Login.cshtml: ASP.net runtime error: [A]System.Web.WebPages.Razor.Configuration.HostSection cannot be cast to [B]System.Web.WebPages.Razor.Configuration.HostSection. Type A originates from System.Web.WebPages.Razor, Version=1.0.0.0 ... Type B originates from ... Version=2.0.0.0
Turns out I had both versions in the GAC. The View web.config
referenced v1 but the app was referencing v2. Removed the referenced assemblies and re-added v1. of System.Web.WebPages.Razor
, etc.
Switch the order of the functions or do a forward declaration of the writefiles function and it will work I think.
So while this is answered and accepted it still came up as a top search result and the answers though laid out (after lots of research) left me scratching my head and digging a lot further. So here's a quick layout of how I resolved the issue.
Assuming my server is myserver.myhome.com and my static IP address is 192.168.1.150:
Edit the hosts file
$ sudo nano -w /etc/hosts
127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4
127.0.0.1 myserver.myhome.com myserver
192.168.1.150 myserver.myhome.com myserver
::1 localhost localhost.localdomain localhost6 localhost6.localdomain6
::1 myserver.myhome.com myserver
Edit httpd.conf
$ sudo nano -w /etc/apache2/httpd.conf
ServerName myserver.myhome.com
Edit network
$ sudo nano -w /etc/sysconfig/network HOSTNAME=myserver.myhome.com
Verify
$ hostname
(output) myserver.myhome.com
$ hostname -f
(output) myserver.myhome.com
Restart Apache
$ sudo /etc/init.d/apache2 restart
It appeared the difference was including myserver.myhome.com
to both the 127.0.0.1 as well as the static IP address 192.168.1.150 in the hosts file. The same on Ubuntu Server and CentOS.
This method worked for me:
if ("username" in localStorage) {
alert('yes');
} else {
alert('no');
}
you could try in this way: get the integer value of the double, subtract this from the original double value, define a rounding range and tests if the absolute number of the new double value(without the integer part) is larger or smaller than your defined range. if it is smaller you can intend it it is an integer value. Example:
public final double testRange = 0.2;
public static boolean doubleIsInteger(double d){
int i = (int)d;
double abs = Math.abs(d-i);
return abs <= testRange;
}
If you assign to d the value 33.15 the method return true. To have better results you can assign lower values to testRange (as 0.0002) at your discretion.
This worked at least in matplotlib version 2.2.2:
plt.axis([None, None, 0, 100])
Probably this is a nice way to set up for example xmin and ymax only, etc.
why isn't this one of the answers yet?:
$("#manual2").click(function() {
$.fancybox([
'http://farm5.static.flickr.com/4044/4286199901_33844563eb.jpg',
'http://farm3.static.flickr.com/2687/4220681515_cc4f42d6b9.jpg',
{
'href' : 'http://farm5.static.flickr.com/4005/4213562882_851e92f326.jpg',
'title' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit'
}
], {
'padding' : 0,
'transitionIn' : 'none',
'transitionOut' : 'none',
'type' : 'image',
'changeFade' : 0
});
});
now just trigger your link!!
got this from the Fancybox homepage
In PostgreSQL, the default limit is 63 characters. Because index names must be unique it's nice to have a little convention. I use (I tweaked the example to explain more complex constructions):
def change
add_index :studies, [:professor_id, :user_id], name: :idx_study_professor_user
end
The normal index would have been:
:index_studies_on_professor_id_and_user_id
The logic would be:
index
becomes idx
_id
Which usually does the job.
A slight generalization to Peter's answer -- you can specify a range over the original array's shape if you want to go beyond three dimensional arrays.
e.g. to flatten all but the last two dimensions:
arr = numpy.zeros((3, 4, 5, 6))
new_arr = arr.reshape(-1, *arr.shape[-2:])
new_arr.shape
# (12, 5, 6)
EDIT: A slight generalization to my earlier answer -- you can, of course, also specify a range at the beginning of the of the reshape too:
arr = numpy.zeros((3, 4, 5, 6, 7, 8))
new_arr = arr.reshape(*arr.shape[:2], -1, *arr.shape[-2:])
new_arr.shape
# (3, 4, 30, 7, 8)
I know this is too late for sure, but, this could help someone as well.
In my case, i found that the source file is being used by another process which was restricting from copying to the destination. I found that by using command prompt ( just copy paste the post build command to the command prompt and executed gave me the error info).
Make sure that you can copy from the command prompt,
Multiple SQL statements must be executed with the mysqli_multi_query()
function.
Example (MySQLi Object-oriented):
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO names (firstname, lastname)
VALUES ('inpute value here', 'inpute value here');";
$sql .= "INSERT INTO phones (landphone, mobile)
VALUES ('inpute value here', 'inpute value here');";
if ($conn->multi_query($sql) === TRUE) {
echo "New records created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
clear project and then run. it will work
You can't do it at all, let alone quickly. Arrays in Java are fixed size. Two things you could do are:
You can use System.arraycopy
for either of these. Both of these are O(n), since they copy all but 1 element.
If you will be removing the first element often, consider using LinkedList
instead. You can use LinkedList.remove
, which is from the Queue
interface, for convenience. With LinkedList
, removing the first element is O(1). In fact, removing any element is O(1) once you have a ListIterator
to that position. However, accessing an arbitrary element by index is O(n).
May be the browser will do it for you if you do something like:
Copy the div
and its attributes and insert it before the old one, then move the content from the old to the new and delete the old?
If anyone is using angular and material design with sidenav. This will send you to to the top of the page:
let ele = document.getElementsByClassName('md-sidenav-content');
let eleArray = <Element[]>Array.prototype.slice.call(ele);
eleArray.map( val => {
val.scrollTop = document.documentElement.scrollTop = 0;
});
Think of a class as a description of the members of a set of things. All of the members of that set have common characteristics (methods and properties).
A subclass is a class that describes the members of a particular subset of the original set. They share many of characteristics of the main class, but may have properties or methods that are unique to members of the subclass.
You declare that one class is subclass of another via the "extends" keyword in Java.
public class B extends A
{
...
}
B is a subclass of A. Instances of class B will automatically exhibit many of the same properties as instances of class A.
This is the main concept of inheritance in Object-Oriented programming.
It's also possible that in persistence.xml, EmbeddedDriver was used while the jdbc url was pointing to Derby server. In this case just change the url to pointing a path of database.
You have another server_name ec2-xx-xx-xxx-xxx.us-west-1.compute.amazonaws.com
somewhere in the config.
If you need Hex color desperately in your application, there is one simple step you can follow:
2. Get your RGB values.
3. In flutter, you have an simple option to use RGB color:
Color.fromRGBO(r_value, g_value, b_value, opacity)
will do the job for you.
4. Go ahead and tweek O_value to get the color you want.
Run this in project folder:
$ git log --pretty=format:"%C(yellow)%h %ar %C(auto)%d %Creset %s , %Cblue%cn" --graph --all
And if you like, add this line to your ~/.gitconfig:
[alias]
...
list = log --pretty=format:\"%C(yellow)%h %ar %C(auto)%d %Creset %s, %Cblue%cn\" --graph --all
There are many ways to do this, one way is:
sqlite3 auction.db
Followed by:
sqlite> .read create.sql
In general, the SQLite project has really fantastic documentation! I know we often reach for Google before the docs, but in SQLite's case, the docs really are technical writing at its best. It's clean, clear, and concise.
Have you checked the docstring of write()
? It says:
write(str) -> None. Write string str to file.
Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written.
So you need to convert y
to str
first.
Also note that the string will be written at the current position which will be at the end of the file, because you'll already have read the old value. Use f.seek(0)
to get to the beginning of the file.`
Edit: As for the IOError
, this issue seems related. A cite from there:
For the modes where both read and writing (or appending) are allowed (those which include a "+" sign), the stream should be flushed (fflush) or repositioned (fseek, fsetpos, rewind) between either a reading operation followed by a writing operation or a writing operation followed by a reading operation.
So, I suggest you try f.seek(0)
and maybe the problem goes away.
SELECT A.ABC_ID, A.VAL FROM A WHERE NOT EXISTS
(SELECT * FROM B WHERE B.ABC_ID = A.ABC_ID AND B.VAL = A.VAL)
or
SELECT A.ABC_ID, A.VAL FROM A WHERE VAL NOT IN
(SELECT VAL FROM B WHERE B.ABC_ID = A.ABC_ID)
or
SELECT A.ABC_ID, A.VAL LEFT OUTER JOIN B
ON A.ABC_ID = B.ABC_ID AND A.VAL = B.VAL FROM A WHERE B.VAL IS NULL
Please note that these queries do not require that ABC_ID be in table B at all. I think that does what you want.
There are (at least) two things you can do here–you can reclone the remote repo, or you can reset --hard
to the common ancestor and then do a pull, which will fast-forward to the latest commit on the remote master.
To be concrete, here's a simple extension of Nevik Rehnel's original answer:
git reset --hard origin/master
git pull origin master
NOTE: using git reset --hard
will discard any uncommitted changes, and it can be easy to confuse yourself with this command if you're new to git, so make sure you have a sense of what it is going to do before proceeding.
this works for me...
using System.IO;
private long GetTotalFreeSpace(string driveName)
{
foreach (DriveInfo drive in DriveInfo.GetDrives())
{
if (drive.IsReady && drive.Name == driveName)
{
return drive.TotalFreeSpace;
}
}
return -1;
}
good luck!
For default exports you should use:
import * as fs from 'fs';
Or in case the module has named exports:
import {fs} from 'fs';
Example:
//module1.js
export function function1() {
console.log('f1')
}
export function function2() {
console.log('f2')
}
export default function1;
And then:
import defaultExport, { function1, function2 } from './module1'
defaultExport(); // This calls function1
function1();
function2();
Additionally, you should use Webpack or something similar to be able to use ES6 import
first.py:
a=5
second.py:
import first
print(first.a)
The result will be 5.
use css :
p { margin:0 }
Try this wonderful plugin http://www.getfirebug.com :)
EDIT: Firebug is now closed as a project, it was migrated to https://www.mozilla.org/en-US/firefox/developer
max
function is used to get the maximum out of an iterable
.
The iterators may be lists, tuples, dict objects, etc. Or even custom objects as in the example you provided.
max(iterable[, key=func]) -> value
max(a, b, c, ...[, key=func]) -> value
With a single iterable argument, return its largest item.
With two or more arguments, return the largest argument.
So, the key=func
basically allows us to pass an optional argument key
to the function on whose basis is the given iterator/arguments are sorted & the maximum is returned.
lambda
is a python keyword that acts as a pseudo function. So, when you pass player
object to it, it will return player.totalScore
. Thus, the iterable passed over to function max
will sort according to the key
totalScore of the player
objects given to it & will return the player
who has maximum totalScore
.
If no key
argument is provided, the maximum is returned according to default Python orderings.
Examples -
max(1, 3, 5, 7)
>>>7
max([1, 3, 5, 7])
>>>7
people = [('Barack', 'Obama'), ('Oprah', 'Winfrey'), ('Mahatma', 'Gandhi')]
max(people, key=lambda x: x[1])
>>>('Oprah', 'Winfrey')
In case anybody else falls onto this page, you can also solve this by using the Ip address in the URL request instead of the domain:
NSURL *myURL = [NSURL URLWithString:@"http://10.0.0.2/mypage.php"];
Then you specify the Host manually:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:myURL];
[request setAllHTTPHeaderFields:[NSDictionary dictionaryWithObjectAndKeys:@"myserver",@"Host"]];
As far as the server is concerned, it will behave the exact same way as if you had used http://myserver/mypage.php
, except that the iPhone will not have to do a DNS lookup.
100% Public API.
Use This Code
@echo off
:: Get the current directory
for /f "tokens=* delims=/" %%A in ('cd') do set CURRENT_DIR=%%A
echo CURRENT_DIR%%A
(echo this To confirm this code works fine)
#outerDiv{_x000D_
width: 500px;_x000D_
height: 500px;_x000D_
position:relative;_x000D_
_x000D_
background-color: lightgrey; _x000D_
}_x000D_
_x000D_
#innerDiv{_x000D_
width: 284px;_x000D_
height: 290px;_x000D_
_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
transform: translate(-50%, -50%);_x000D_
-ms-transform: translate(-50%, -50%); /* IE 9 */_x000D_
-webkit-transform: translate(-50%, -50%); /* Chrome, Safari, Opera */ _x000D_
_x000D_
background-color: grey;_x000D_
}
_x000D_
<div id="outerDiv">_x000D_
<div id="innerDiv"></div>_x000D_
</div>
_x000D_
If you want a specific date in next month, you can do this:
// Calculate the timestamp
$expire = strtotime('first day of +1 month');
// Format the timestamp as a string
echo date('m/d/Y', $expire);
Note that this actually works more reliably where +1 month
can be confusing. For example...
Current Day | first day of +1 month | +1 month
---------------------------------------------------------------------------
2015-01-01 | 2015-02-01 | 2015-02-01
2015-01-30 | 2015-02-01 | 2015-03-02 (skips Feb)
2015-01-31 | 2015-02-01 | 2015-03-03 (skips Feb)
2015-03-31 | 2015-04-01 | 2015-05-01 (skips April)
2015-12-31 | 2016-01-01 | 2016-01-31
The whole code if somebody need it.
void alarm(Context context, Calendar calendar) {
AlarmManager alarmManager = (AlarmManager)context.getSystemService(ALARM_SERVICE);
final String SOME_ACTION = "com.android.mytabs.MytabsActivity.AlarmReceiver";
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);
AlarmReceiver mReceiver = new AlarmReceiver();
context.registerReceiver(mReceiver, intentFilter);
Intent anotherIntent = new Intent(SOME_ACTION);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, anotherIntent, 0);
alramManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
Toast.makeText(context, "Added", Toast.LENGTH_LONG).show();
}
class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent arg1) {
Toast.makeText(context, "Started", Toast.LENGTH_LONG).show();
}
}
All these solutions are outdated. It's really easy now in Android Studio:
File > New Module...
The next screen looks weird, like you are selecting some widget or something but keep it on the first picture and below scroll and find "Import JAR or .AAR Package"
Then take Project Structure
from File menu.Select app
from the opened window then select dependencies
,then press green plus button
,select module dependency
then select module you imported then press OK
In C++
Any variable at file scope and that is not nested inside a class or function, is visible throughout all translation units in a program. This is called external linkage because at link time the name is visible to the linker everywhere, external to that translation unit.
Global variables and ordinary functions have external linkage.
Static object or function name at file scope is local to translation unit. That is called as Internal Linkage
Linkage refers only to elements that have addresses at link/load time; thus, class declarations and local variables have no linkage.
Alternately, you could do a Text to Columns with space as the delimiter.
You can use the Enumerable.SequenceEqual() in the System.Linq to compare the contents in the array
bool isEqual = Enumerable.SequenceEqual(target1, target2);
Above of all, I found this library right here. Works out of the box perfectly on a Bootstrap-3 environment.
CSS
<link rel="stylesheet" type="text/css" href="dist/bootstrap-clockpicker.min.css">
HTML
<div class="input-group clockpicker">
<input type="text" class="form-control" value="09:30">
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
JAVASCRIPT
<script type="text/javascript" src="dist/bootstrap-clockpicker.min.js"></script>
<script type="text/javascript">
$('.clockpicker').clockpicker();
</script>
As simple as that! Find more examples on the link above.
If you are using Bootstrap-4, the most popular time/date picker library available right now is Tempus Dominus. It is not fancy looking, but much responsive and modern.
From what I have found, your query is mostly correct. Just change "select r" to "select r.Text" is all and that should solve the problem. This is how MSDN documented how it should work.
Ex:
var query = (from r in table1 orderby r.Text select r.Text).distinct();
If you run VMware Player or Workstation (or maybe VirtualBox, I'm not sure if it supports Mac OS X, but may), and then Mac OS X Server (Client can't legally be virtualized). Of course, in this case you are running XCode on OS X, but your host machine could be linux.
In my case image path
was wrong! So firstly, you might want to check if image path is correct :)
Telerik have a Control called the RadWatermarkTextBox
specifically to solve this issue. If you are using Telerik controls, simply use in the following manner
<telerik:RadWatermarkTextBox
Text="{Binding Path=MyTextBoxText}"
WatermarkContent="Please enter some text" />
You should use reflect.DeepEqual()
DeepEqual is a recursive relaxation of Go's == operator.
DeepEqual reports whether x and y are “deeply equal,” defined as follows. Two values of identical type are deeply equal if one of the following cases applies. Values of distinct types are never deeply equal.
Array values are deeply equal when their corresponding elements are deeply equal.
Struct values are deeply equal if their corresponding fields, both exported and unexported, are deeply equal.
Func values are deeply equal if both are nil; otherwise they are not deeply equal.
Interface values are deeply equal if they hold deeply equal concrete values.
Map values are deeply equal if they are the same map object or if they have the same length and their corresponding keys (matched using Go equality) map to deeply equal values.
Pointer values are deeply equal if they are equal using Go's == operator or if they point to deeply equal values.
Slice values are deeply equal when all of the following are true: they are both nil or both non-nil, they have the same length, and either they point to the same initial entry of the same underlying array (that is, &x[0] == &y[0]) or their corresponding elements (up to length) are deeply equal. Note that a non-nil empty slice and a nil slice (for example, []byte{} and []byte(nil)) are not deeply equal.
Other values - numbers, bools, strings, and channels - are deeply equal if they are equal using Go's == operator.
I had the exact same problem, unfortunately, adding the primary key doesn't solve the issue. So here's how I solve mine:
primary key
on the table so I alter my table and add a primary key.Delete the ADO.NET Entity Data Model
(edmx file) where I use to map and connect with my database.Add again a new file of ADO.NET Entity Data Model
to connect with my database and for mapping my model properties.Clean and rebuild the solution.
Problem solved.
Object.equals is null safe, however be aware that if two objects are null, object.equals will return true so be sure to check that the objects you are comparing aren't null (or hold null values) before using object.equals for comparison.
String firstname = null;
String lastname = null;
if(Objects.equals(firstname, lastname)){
System.out.println("equal!");
} else {
System.out.println("not equal!");
}
Example snippet above will return equal!
As an alternative to using UsedRange or providing an explicit range address, the AutoFilter.Range property can also specify the affected range.
ActiveSheet.AutoFilter.Range.Offset(1,0).Rows.SpecialCells(xlCellTypeVisible).Delete(xlShiftUp)
As used here, Offset causes the first row after the AutoFilter range to also be deleted. In order to avoid that, I would try using .Resize() after .Offset().
in viewDidLoad add this line
yourUiTextField.becomeFirstResponder()
I followed https://www.mysysadmintips.com/windows/clients/761-move-android-studio-avd-folder-to-a-new-location.
Start copying a folder "C:\Users\user\.android\avd" to "D:\Android\.android\avd" (or something else).
Close Android Studio and running emulators.
Press Win + Break
and open Advanced System Settings
. Then press Environment Variables
. Add a user variable ANDROID_SDK_HOME
. (I didn't experiment with ANDROID_AVD_HOME
.) In Variable value
field write D:\Android
. If you also moved SDK to another folder, change ANDROID_HOME
(I forgot to change it and some emulators didn't launch, see https://stackoverflow.com/a/57408085/2914140).
Wait until the folder will finish copying and start Android Studio.
Open Android Virtual Device Manager
and see a list of emulators. If you don't see emulators and they existed, then probably you entered wrong path into user variable value in step 3. In this case close AS, change the variable and open AS again.
Start any emulator. It will try to restore it's state, but it sometimes fails. A black screen can appear instead of Android wallpaper.
In this case you can:
a. Restart your emulator. To do this close running emulator, then in AVD Manager click Cold Boot Now
.
b. If this didn't help, open emulator settings, found in file "D:\Android\.android\avd\Pixel_API_27.ini".
Change a path to a new AVD folder. Restart the emulator.
If what you're really doing is manipulating a CSV file itself, Nelson's answer makes sense. However, my suspicion is that the CSV is simply an artifact of the problem you're solving. In C++, that probably means you have something like this as your data model:
struct Customer {
int id;
std::string first_name;
std::string last_name;
struct {
std::string street;
std::string unit;
} address;
char state[2];
int zip;
};
Thus, when you're working with a collection of data, it makes sense to have std::vector<Customer>
or std::set<Customer>
.
With that in mind, think of your CSV handling as two operations:
// if you wanted to go nuts, you could use a forward iterator concept for both of these
class CSVReader {
public:
CSVReader(const std::string &inputFile);
bool hasNextLine();
void readNextLine(std::vector<std::string> &fields);
private:
/* secrets */
};
class CSVWriter {
public:
CSVWriter(const std::string &outputFile);
void writeNextLine(const std::vector<std::string> &fields);
private:
/* more secrets */
};
void readCustomers(CSVReader &reader, std::vector<Customer> &customers);
void writeCustomers(CSVWriter &writer, const std::vector<Customer> &customers);
Read and write a single row at a time, rather than keeping a complete in-memory representation of the file itself. There are a few obvious benefits:
<table>
rendering.sizeof(Customer)
vs. the number of bytes in a single row).CSVReader
and CSVWriter
can be reused as the basis for an in-memory model (such as Nelson's) without loss of performance or functionality. The converse is not true.a = ['1', '2', '3', '4']
print len(a) - 1
3
You can also type "top" and look at the list of running processes.
One way to solve this problem is by turning the warnings off.
SET ANSI_WARNINGS OFF;
GO
I'm on Windows 10 x64 and Visual Studio 2017. I copied and pasted rc.exe and rcdll.dll from:
C:\Program Files (x86)\Windows Kits\8.1\bin\x86
to
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\bin\amd64
it's works with: ( qt creator 5.7.1)
I had this issue also and I simply found out that if you simply remove the "#" the issue goes off. Like this :
<a href="" class="disabled" ng-click="doSomething(object)">Do something</a>
I had this problem and tried various solutions to solve it including many of those listed above (config file, debug ssh etc). In the end, I resolved it by including the -u switch in the git push, per the github instructions when creating a new repository onsite - Github new Repository
If you need a free and simple API for converting one currency to another, try free.currencyconverterapi.com.
Disclaimer, I'm the author of the website and I use it for one of my other websites.
The service is free to use even for commercial applications but offers no warranty. For performance reasons, the values are only updated every hour.
A sample conversion URL is: http://free.currencyconverterapi.com/api/v6/convert?q=EUR_PHP&compact=ultra&apiKey=sample-api-key which will return a json-formatted value, e.g. {"EUR_PHP":60.849184}
I found "npm config edit" to be more useful to update the entries for https-proxy, proxy, registry
I did something like this
Exact same thing, just omit the -c
option. Apache's docs on it here.
htpasswd /etc/apache2/.htpasswd newuser
Also, htpasswd
typically isn't run as root. It's typically owned by either the web server, or the owner of the files being served. If you're using root to edit it instead of logging in as one of those users, that's acceptable (I suppose), but you'll want to be careful to make sure you don't accidentally create a file as root (and thus have root own it and no one else be able to edit it).
The answer provided by Joe Stefanelli is already correct.
SELECT name FROM (SELECT name FROM agentinformation) as a
We need to make an alias of the subquery because a query needs a table object which we will get from making an alias for the subquery. Conceptually, the subquery results are substituted into the outer query. As we need a table object in the outer query, we need to make an alias of the inner query.
Statements that include a subquery usually take one of these forms:
Check for more subquery rules and subquery types.
More examples of Nested Subqueries.
IN / NOT IN – This operator takes the output of the inner query after the inner query gets executed which can be zero or more values and sends it to the outer query. The outer query then fetches all the matching [IN operator] or non matching [NOT IN operator] rows.
ANY – [>ANY or ANY operator takes the list of values produced by the inner query and fetches all the values which are greater than the minimum value of the list. The
e.g. >ANY(100,200,300), the ANY operator will fetch all the values greater than 100.
e.g. >ALL(100,200,300), the ALL operator will fetch all the values greater than 300.
This is made from the other solutions above.
$(document).ready(function(){
$("button").click(function(event){
$(".area").toggle();
event.stopPropagation(); //stops the click event to go "throu" the button an hit the document
});
$(document).click(function() {
$(".area").hide();
});
$(".interface").click(function(event) {
event.stopPropagation();
return false;
});
});
<div>
<div>
<button> Press here for content</button>
<div class="area">
<div class="interface"> Content</div>
</div>
</div>
</div>
That is ill-formatted. You have one JSON object per line, but they are not contained in a larger data structure (ie an array). You'll either need to reformat it so that it begins with [
and ends with ]
with a comma at the end of each line, or parse it line by line as separate dictionaries.
Let's say you have two entities Album
and Photo
. Album contains many photos, so it's a one to many relationship.
Album class
@Entity
public class Album {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
Integer albumId;
String albumName;
@OneToMany(targetEntity=Photo.class,mappedBy="album",cascade={CascadeType.ALL},orphanRemoval=true)
Set<Photo> photos = new HashSet<Photo>();
}
Photo class
@Entity
public class Photo{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
Integer photo_id;
String photoName;
@ManyToOne(targetEntity=Album.class)
@JoinColumn(name="album_id")
Album album;
}
What you have to do before persist or merge is to set the Album reference in each photos.
Album myAlbum = new Album();
Photo photo1 = new Photo();
Photo photo2 = new Photo();
photo1.setAlbum(myAlbum);
photo2.setAlbum(myAlbum);
That is how to attach the related entity before you persist or merge.
Based on your comment to Issun:
Thanks for the explanation. In my case, The object is declared and created prior to the If condition. So, How do I use If condition to check for < No Variables> ? In other words, I do not want to execute My_Object.Compute if My_Object has < No Variables>
You need to check one of the properties of the object. Without telling us what the object is, we cannot help you.
I did test several common objects and found that an instantiated Collection
with no items added shows <No Variables>
in the watch window. If your object is indeed a collection, you can check for the <No Variables>
condition using the .Count
property:
Sub TestObj()
Dim Obj As Object
Set Obj = New Collection
If Obj Is Nothing Then
Debug.Print "Object not instantiated"
Else
If Obj.Count = 0 Then
Debug.Print "<No Variables> (ie, no items added to the collection)"
Else
Debug.Print "Object instantiated and at least one item added"
End If
End If
End Sub
It is also worth noting that if you declare any object As New
then the Is Nothing
check becomes useless. The reason is that when you declare an object As New
then it gets created automatically when it is first called, even if the first time you call it is to see if it exists!
Dim MyObject As New Collection
If MyObject Is Nothing Then ' <--- This check always returns False
This does not seem to be the cause of your specific problem. But, since others may find this question through a Google search, I wanted to include it because it is a common beginner mistake.
This solution work for td
's that need both border
and padding
for styling.
(Tested on Chrome 32, IE 11, Firefox 25)
CSS:
table {border-collapse: separate; border-spacing:0; } /* separate needed */
td { display: inline-block; width: 33% } /* Firefox need inline-block + width */
td { position: relative } /* needed to make td move */
td { left: 10px; } /* push all 10px */
td:first-child { left: 0px; } /* move back first 10px */
td:nth-child(3) { left: 20px; } /* push 3:rd another extra 10px */
/* to support older browsers we need a class on the td's we want to push
td.col1 { left: 0px; }
td.col2 { left: 10px; }
td.col3 { left: 20px; }
*/
HTML:
<table>
<tr>
<td class='col1'>Player</td>
<td class='col2'>Result</td>
<td class='col3'>Average</td>
</tr>
</table>
Updated 2016
Firefox now support it without inline-block
and a set width
table {border-collapse: separate; border-spacing:0; }_x000D_
td { position: relative; padding: 5px; }_x000D_
td { left: 10px; }_x000D_
td:first-child { left: 0px; }_x000D_
td:nth-child(3) { left: 20px; }_x000D_
td { border: 1px solid gray; }_x000D_
_x000D_
_x000D_
/* CSS table */_x000D_
.table {display: table; }_x000D_
.tr { display: table-row; }_x000D_
.td { display: table-cell; }_x000D_
_x000D_
.table { border-collapse: separate; border-spacing:0; }_x000D_
.td { position: relative; padding: 5px; }_x000D_
.td { left: 10px; }_x000D_
.td:first-child { left: 0px; }_x000D_
.td:nth-child(3) { left: 20px; }_x000D_
.td { border: 1px solid gray; }
_x000D_
<table>_x000D_
<tr>_x000D_
<td>Player</td>_x000D_
<td>Result</td>_x000D_
<td>Average</td>_x000D_
</tr>_x000D_
</table>_x000D_
_x000D_
<div class="table">_x000D_
<div class="tr">_x000D_
<div class="td">Player</div>_x000D_
<div class="td">Result</div>_x000D_
<div class="td">Average</div>_x000D_
</div>_x000D_
</div>
_x000D_
I think this is solved by Tillito:
Entity Framework and SQL Server View
I'll quote his entry below:
We had the same problem and this is the solution:
To force entity framework to use a column as a primary key, use ISNULL.
To force entity framework not to use a column as a primary key, use NULLIF.
An easy way to apply this is to wrap the select statement of your view in another select.
Example:
SELECT
ISNULL(MyPrimaryID,-999) MyPrimaryID,
NULLIF(AnotherProperty,'') AnotherProperty
FROM ( ... ) AS temp
answered Apr 26 '10 at 17:00 by Tillito
nput from a terminal never really "ends" (unless the device is disconnected), but it is useful to enter more than one "file" into a terminal, so a key sequence is reserved to indicate end of input. In UNIX the translation of the keystroke to EOF is performed by the terminal driver, so a program does not need to distinguish terminals from other input files. By default, the driver converts a Control-D character at the start of a line into an end-of-file indicator. To insert an actual Control-D (ASCII 04) character into the input stream, the user precedes it with a "quote" command character (usually Control-V). AmigaDOS is similar but uses Control-\ instead of Control-D.
In Microsoft's DOS and Windows (and in CP/M and many DEC operating systems), reading from the terminal will never produce an EOF. Instead, programs recognize that the source is a terminal (or other "character device") and interpret a given reserved character or sequence as an end-of-file indicator; most commonly this is an ASCII Control-Z, code 26. Some MS-DOS programs, including parts of the Microsoft MS-DOS shell (COMMAND.COM) and operating-system utility programs (such as EDLIN), treat a Control-Z in a text file as marking the end of meaningful data, and/or append a Control-Z to the end when writing a text file. This was done for two reasons:
Backward compatibility with CP/M. The CP/M file system only recorded the lengths of files in multiples of 128-byte "records", so by convention a Control-Z character was used to mark the end of meaningful data if it ended in the middle of a record. The MS-DOS filesystem has always recorded the exact byte-length of files, so this was never necessary on MS-DOS.
It allows programs to use the same code to read input from both a terminal and a text file.
As I answered here, you can remove spines from all your plots through style settings (style sheet or rcParams):
import matplotlib as mpl
mpl.rcParams['axes.spines.left'] = False
mpl.rcParams['axes.spines.right'] = False
mpl.rcParams['axes.spines.top'] = False
mpl.rcParams['axes.spines.bottom'] = False
Use jQuery dialog to show image, try this code
<html>
<head>
</head>
<body>
<div id="divid">
<img>
</div>
<body>
</html>
<script>
$(document).ready(function(){
$("btn").click(function(){
$("divid").dialog();
});
});
</script>
`
first you have to include jQuery UI at your Page.
Set the style of each ListViewItem to have Focusable set to false.
<ListView ItemsSource="{Binding Test}" >
<ListView.ItemContainerStyle>
<Style TargetType="{x:Type ListViewItem}">
<Setter Property="Focusable" Value="False"/>
</Style>
</ListView.ItemContainerStyle>
</ListView>
your compilation option -c makes your compiling just compilation and assembly, but no link.
Firstly checked the list of installed Python packages by:
pip list | grep -i keras
If there is keras shown then install it by:
pip install keras --upgrade --log ./pip-keras.log
now check the log, if there is any pending dependencies are present, it will affect your installation. So remove dependencies and then again install it.
I finally got to solve the problem: UNINSTALL Gallio
Gallio seems to have quite some many rough edges and it's better to not use MbUnit 3.0 but use the MbUnit 2.0 framework but use the gallio runner, that you are running without installing from the installer (which also installed a visual studio plugin).
Incidentally, I had the issue even after "disabling" he Gallio plugin. Only the uninstall solved the problem.
PS. Edited by nightcoder:
In my case disabling TypeMock Isolator (mocking framework) finally helped! Edit & Continue now works!!!
Here is the answer from TypeMock support:
After looking further into the edit and continue issue, and conversing about it with Microsoft, we reached the conclusion it cannot be resolved for Isolator. Isolator implements a CLR profiler, and according to our research, once a CLR profiler is enabled and attached, edit and continue is automatically disabled. I'm sorry to say this is no longer considered a bug, but rather a limitation of Isolator.
Please see this.
Text inside a CDATA section will be ignored by the parser.
http://www.w3schools.com/xml/dom_cdatasection.asp
This is will help you to understand the basics about XML
I tried Dave Ward's solution. The data part was not being sent from the browser in the payload part of the post request as the contentType is set to "application/json"
. Once I removed this line everything worked great.
var markers = [{ "position": "128.3657142857143", "markerPosition": "7" },
{ "position": "235.1944023323615", "markerPosition": "19" },
{ "position": "42.5978231292517", "markerPosition": "-3" }];
$.ajax({
type: "POST",
url: "/webservices/PodcastService.asmx/CreateMarkers",
// The key needs to match your method's input parameter (case-sensitive).
data: JSON.stringify({ Markers: markers }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){alert(data);},
failure: function(errMsg) {
alert(errMsg);
}
});
maybe it is from the connection I changed the connection from Ethernet to wireless the it worked without doing anything else
I think this is what we like to do very much.
--Step 1: (create a new user)
create LOGIN hello WITH PASSWORD='foo', CHECK_POLICY = OFF;
-- Step 2:(deny view to any database)
USE master;
GO
DENY VIEW ANY DATABASE TO hello;
-- step 3 (then authorized the user for that specific database , you have to use the master by doing use master as below)
USE master;
GO
ALTER AUTHORIZATION ON DATABASE::yourDB TO hello;
GO
If you already created a user and assigned to that database before by doing
USE [yourDB]
CREATE USER hello FOR LOGIN hello WITH DEFAULT_SCHEMA=[dbo]
GO
then kindly delete it by doing below and follow the steps
USE yourDB;
GO
DROP USER newlogin;
GO
For more information please follow the links:
Hiding databases for a login on Microsoft Sql Server 2008R2 and above
I was finding same but lastly i found an answer. I hope this answer help you so much.
when your array is empty then you can send empty array just like
if(!empty($result))
{
echo json_encode($result);
}
else
{
echo json_encode(array('data'=>''));
}
Thank you
Say you have a DIV
you want centred horizontally:
<div id="foo">Lorem ipsum</div>
In the CSS you'd style it with this:
#foo
{
margin:0 auto;
width:30%;
}
Which states that you have a top and bottom margin of zero pixels, and on either left or right, automatically work out how much is needed to be even.
Doesn't really matter what you put in for the width, as long as it's there and isn't 100%. Otherwise you wouldn't be setting the centre on anything.
But if you float it, left or right, then the bets are off since that pulls it out of the normal flow of elements on the page and the auto margin setting won't work.
gnu/stubs-32.h
is not directed included in programms. It's a back-end type header file of gnu/stubs.h
, just like gnu/stubs-64.h
. You can install the multilib
package to add both.
I mostly use following code to scroll down
$('html, body').animate({ scrollTop: $(SELECTOR).offset().top - 50 }, 'slow');
To easily understand the problem, imagine we wrote this code:
static void Main(string[] args)
{
string[] test = new string[3];
test[0]= "hello1";
test[1]= "hello2";
test[2]= "hello3";
for (int i = 0; i <= 3; i++)
{
Console.WriteLine(test[i].ToString());
}
}
Result will be:
hello1
hello2
hello3
Unhandled Exception: System.IndexOutOfRangeException: Index was outside the bounds of the array.
Size of array is 3 (indices 0, 1 and 2), but the for-loop loops 4 times (0, 1, 2 and 3).
So when it tries to access outside the bounds with (3) it throws the exception.
I recommend another option. jQuery UI has a new position feature that allows you to position elements relative to each other. For complete documentation and demo see: http://jqueryui.com/demos/position/#option-offset.
Here's one way to position your elements using the position feature:
var options = {
"my": "top left",
"at": "top left",
"of": ".layer1"
};
$(".layer2").position(options);
Or use this for an English (or mix it up for custom) format:
StringFormat='{}{0:dd/MM/yyyy}'
$(":input").bind('keyup change click', function (e) {
if (! $(this).data("previousValue") ||
$(this).data("previousValue") != $(this).val()
)
{
console.log("changed");
$(this).data("previousValue", $(this).val());
}
});
$(":input").each(function () {
$(this).data("previousValue", $(this).val());
});?
This is a little bit ghetto, but this way you can use the "click" event to capture the event that runs when you use the mouse to increment/decrement via the little arrows on the input. You can see how I've built in a little manual "change check" routine that makes sure your logic won't fire unless the value actually changed (to prevent false positives from simple clicks on the field).
For a long time, DOM3 mutation events were the best available solution, but they have been deprecated for performance reasons. DOM4 Mutation Observers are the replacement for deprecated DOM3 mutation events. They are currently implemented in modern browsers as MutationObserver
(or as the vendor-prefixed WebKitMutationObserver
in old versions of Chrome):
MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var observer = new MutationObserver(function(mutations, observer) {
// fired when a mutation occurs
console.log(mutations, observer);
// ...
});
// define what element should be observed by the observer
// and what types of mutations trigger the callback
observer.observe(document, {
subtree: true,
attributes: true
//...
});
This example listens for DOM changes on document
and its entire subtree, and it will fire on changes to element attributes as well as structural changes. The draft spec has a full list of valid mutation listener properties:
childList
- Set to
true
if mutations to target's children are to be observed.attributes
- Set to
true
if mutations to target's attributes are to be observed.characterData
- Set to
true
if mutations to target's data are to be observed.subtree
- Set to
true
if mutations to not just target, but also target's descendants are to be observed.attributeOldValue
- Set to
true
ifattributes
is set to true and target's attribute value before the mutation needs to be recorded.characterDataOldValue
- Set to
true
ifcharacterData
is set to true and target's data before the mutation needs to be recorded.attributeFilter
- Set to a list of attribute local names (without namespace) if not all attribute mutations need to be observed.
(This list is current as of April 2014; you may check the specification for any changes.)
I was facing the same issue. Everything was fine but in
bootstrap/cache/config.php
always had the incomplete password. Upon digging further, realized that the password had '#' character in it and that was getting dropped. As '#' is used to mark a line as a comment.
You should extend the scope of the component-scan e.g. <context:component-scan base-package="at.naviclean" />
since you placed the entities in package at.naviclean.domain;
This should help you to get rid the exeption: Not an managed type: class at.naviclean.domain.Kassa
For further debugging you could try to dump the application context (see javadoc) to explore which classes have been detected by the component-scan if some are still no recognized check their annotation (@Service, @Component etc.)
EDIT:
You also need to add the classes to your persistence.xml
<persistence-unit>
<class>at.naviclean.domain.Kassa</class>
...
</persistence-unit>
Use json_decode
to convert the JSON string to a PHP array, then use normal PHP array functions on it.
$json = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$data = json_decode($json);
var_dump($data[0]['var1']); // outputs '9'
Short answer: Yes. Use Python's urllib to pull the historical data pages for the stocks you want. Go with Yahoo! Finance; Google is both less reliable, has less data coverage, and is more restrictive in how you can use it once you have it. Also, I believe Google specifically prohibits you from scraping the data in their ToS.
Longer answer: This is the script I use to pull all the historical data on a particular company. It pulls the historical data page for a particular ticker symbol, then saves it to a csv file named by that symbol. You'll have to provide your own list of ticker symbols that you want to pull.
import urllib
base_url = "http://ichart.finance.yahoo.com/table.csv?s="
def make_url(ticker_symbol):
return base_url + ticker_symbol
output_path = "C:/path/to/output/directory"
def make_filename(ticker_symbol, directory="S&P"):
return output_path + "/" + directory + "/" + ticker_symbol + ".csv"
def pull_historical_data(ticker_symbol, directory="S&P"):
try:
urllib.urlretrieve(make_url(ticker_symbol), make_filename(ticker_symbol, directory))
except urllib.ContentTooShortError as e:
outfile = open(make_filename(ticker_symbol, directory), "w")
outfile.write(e.content)
outfile.close()
<?php
$post = ['batch_id'=> "2"];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://example.com/student_list.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
$result = json_decode($response);
curl_close($ch); // Close the connection
$new= $result->status;
if( $new =="1")
{
echo "<script>alert('Student list')</script>";
}
else
{
echo "<script>alert('Not Removed')</script>";
}
?>
A subtle alternative to MaxNoe's answer where you aren't explicitly setting the ticks but instead setting the cadence.
import matplotlib.pyplot as plt
from matplotlib.ticker import (AutoMinorLocator, MultipleLocator)
fig, ax = plt.subplots(figsize=(10, 8))
# Set axis ranges; by default this will put major ticks every 25.
ax.set_xlim(0, 200)
ax.set_ylim(0, 200)
# Change major ticks to show every 20.
ax.xaxis.set_major_locator(MultipleLocator(20))
ax.yaxis.set_major_locator(MultipleLocator(20))
# Change minor ticks to show every 5. (20/4 = 5)
ax.xaxis.set_minor_locator(AutoMinorLocator(4))
ax.yaxis.set_minor_locator(AutoMinorLocator(4))
# Turn grid on for both major and minor ticks and style minor slightly
# differently.
ax.grid(which='major', color='#CCCCCC', linestyle='--')
ax.grid(which='minor', color='#CCCCCC', linestyle=':')
I noticed one error in Dave Ward's answer (perhaps a recent change?):
The query string paramaters are in request.query
, not request.params
. (See https://stackoverflow.com/a/6913287/166530 )
request.params
by default is filled with the value of any "component matches" in routes, i.e.
app.get('/user/:id', function(request, response){
response.send('user ' + request.params.id);
});
and, if you have configured express to use its bodyparser (app.use(express.bodyParser());
) also with POST'ed formdata. (See How to retrieve POST query parameters? )