For a more aesthetic appearance :) can be:
left:-9999em;
top:-9999em;
position for .sNv2 .nav UL
can be replaced by z-index:-1
and z-index:1
for .sNv2 .nav LI:Hover UL
move
struct body bodies[n];
to after
struct body
{
double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double mass;
};
Rest all looks fine.
This code can distinguish between click and movement (drag, scroll). In onTouchEvent set a flag isOnClick, and initial X, Y coordinates on ACTION_DOWN. Clear the flag on ACTION_MOVE (minding that unintentional movement is often detected which can be solved with a THRESHOLD const).
private float mDownX;
private float mDownY;
private final float SCROLL_THRESHOLD = 10;
private boolean isOnClick;
@Override
public boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mDownX = ev.getX();
mDownY = ev.getY();
isOnClick = true;
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (isOnClick) {
Log.i(LOG_TAG, "onClick ");
//TODO onClick code
}
break;
case MotionEvent.ACTION_MOVE:
if (isOnClick && (Math.abs(mDownX - ev.getX()) > SCROLL_THRESHOLD || Math.abs(mDownY - ev.getY()) > SCROLL_THRESHOLD)) {
Log.i(LOG_TAG, "movement detected");
isOnClick = false;
}
break;
default:
break;
}
return true;
}
For LongPress as suggested above, GestureDetector is the way to go. Check this Q&A:
This is a self contained project so that you can see everything in context.
Create a layout like the following with a UIView
and a UIButton
. The UIView
will be the container in which we will play our video.
If you need a sample video to practice with, you can get one from sample-videos.com. I'm using an mp4 format video in this example. Drag and drop the video file into your project. I also had to add it explicitly into the bundle resources (go to Build Phases > Copy Bundle Resources, see this answer for more).
Here is the complete code for the project.
import UIKit
import AVFoundation
class ViewController: UIViewController {
var player: AVPlayer?
@IBOutlet weak var videoViewContainer: UIView!
override func viewDidLoad() {
super.viewDidLoad()
initializeVideoPlayerWithVideo()
}
func initializeVideoPlayerWithVideo() {
// get the path string for the video from assets
let videoString:String? = Bundle.main.path(forResource: "SampleVideo_360x240_1mb", ofType: "mp4")
guard let unwrappedVideoPath = videoString else {return}
// convert the path string to a url
let videoUrl = URL(fileURLWithPath: unwrappedVideoPath)
// initialize the video player with the url
self.player = AVPlayer(url: videoUrl)
// create a video layer for the player
let layer: AVPlayerLayer = AVPlayerLayer(player: player)
// make the layer the same size as the container view
layer.frame = videoViewContainer.bounds
// make the video fill the layer as much as possible while keeping its aspect size
layer.videoGravity = AVLayerVideoGravity.resizeAspectFill
// add the layer to the container view
videoViewContainer.layer.addSublayer(layer)
}
@IBAction func playVideoButtonTapped(_ sender: UIButton) {
// play the video if the player is initialized
player?.play()
}
}
Notes
AVPlayerItem
.AVFoundation
and AVPlayer
, then you have to build all of your own controls. If you want full screen video playback, you can use AVPlayerViewController
. You will need to import AVKit
for that. It comes with a full set of controls for pause, fast forward, rewind, stop, etc. Here and here are some video tutorials.MPMoviePlayerController
that you may have seen in other answers is deprecated.The project should look like this now.
If you just want an outer border, the easiest way is to put it in a Border control:
<Border BorderBrush="Black" BorderThickness="2">
<Grid>
<!-- Grid contents here -->
</Grid>
</Border>
The reason you're seeing the border completely fill your control is that, by default, it's HorizontalAlignment and VerticalAlignment are set to Stretch. Try the following:
<Grid>
<Border HorizontalAlignment="Left" VerticalAlignment="Top" BorderBrush="Black" BorderThickness="2">
<Grid Height="166" HorizontalAlignment="Left" Margin="12,12,0,0" Name="grid1" VerticalAlignment="Top" Width="479" Background="#FFF2F2F2" />
</Border>
</Grid>
This should get you what you're after (though you may want to put a margin on all 4 sides, not just 2...)
Spaces are horrible in filenames or directory names.
The correct syntax for this is to include every directory name that includes spaces, in double quotes
cmd /c C:\"Program Files"\"Microsoft Visual Studio 9.0"\Common7\IDE\devenv.com mysolution.sln /build "release|win32"
The jar file is missing. You can download the jar file and add it as external libraries in your project . You can download this from
http://www.findjar.com/jar/com/googlecode/json-simple/json-simple/1.1/json-simple-1.1.jar.html
It is pretty old thread but recently i had a similar issue. I was calling a downstream soap service, from a rest service, and I needed to return the xml response coming from the downstream server as is.
So, i ended up adding a SoapMessageContext handler to get the XML response. Then i injected the response xml into servlet context as an attribute.
public boolean handleMessage(SOAPMessageContext context) {
// Get xml response
try {
ServletContext servletContext =
((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getServletContext();
SOAPMessage msg = context.getMessage();
ByteArrayOutputStream out = new ByteArrayOutputStream();
msg.writeTo(out);
String strMsg = new String(out.toByteArray());
servletContext.setAttribute("responseXml", strMsg);
return true;
} catch (Exception e) {
return false;
}
}
Then I have retrieved the xml response string in the service layer.
ServletContext servletContext =
((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getServletContext();
String msg = (String) servletContext.getAttribute("responseXml");
Didn't have chance to test it yet but this approach must be thread safe since it is using the servlet context.
select * from table where fiels1 NOT LIKE 'x' AND field2 NOT LIKE 'y'
//this work in case insensitive manner
Step-by-Step way to do this:
I've made a Python script for exporting Visual Studio Code settings into a single ZIP file:
https://gist.github.com/wonderbeyond/661c686b64cb0cabb77a43b49b16b26e
You can upload the ZIP file to external storage.
$ vsc-settings.py export
Exporting vsc settings:
created a temporary dump dir /tmp/tmpf88wo142
generating extensions list
copying /home/wonder/.config/Code/User/settings.json
copying /home/wonder/.config/Code/User/keybindings.json
copying /home/wonder/.config/Code/User/projects.json
copying /home/wonder/.config/Code/User/snippets
adding: snippets/ (stored 0%)
adding: snippets/go.json (deflated 56%)
adding: projects.json (deflated 67%)
adding: extensions.txt (deflated 40%)
adding: keybindings.json (deflated 81%)
adding: settings.json (deflated 59%)
VSC settings exported into /home/wonder/vsc-settings-2019-02-25-171337.zip
$ unzip -l /home/wonder/vsc-settings-2019-02-25-171337.zip
Archive: /home/wonder/vsc-settings-2019-02-25-171337.zip
Length Date Time Name
--------- ---------- ----- ----
0 2019-02-25 17:13 snippets/
942 2019-02-25 17:13 snippets/go.json
519 2019-02-25 17:13 projects.json
471 2019-02-25 17:13 extensions.txt
2429 2019-02-25 17:13 keybindings.json
2224 2019-02-25 17:13 settings.json
--------- -------
6585 6 files
PS: You may implement the vsc-settings.py import
subcommand for me.
You do not need to install or update any software for the JUnit. it is the part of Java Development tools and comes with almost most of the latest versions in Eclipse.
Go to your project. Right click onto that->Select buildpath->add library->select JUnit from the list ->select the version you want to work with-> done
build you project again to see the errors gone:)
Escaping characters is different for tags and attributes.
For tags:
< <
> > (only for compatibility, read below)
& &
For attributes:
" "
' '
From Character Data and Markup:
The ampersand character (&) and the left angle bracket (<) must not appear in their literal form, except when used as markup delimiters, or within a comment, a processing instruction, or a CDATA section. If they are needed elsewhere, they must be escaped using either numeric character references or the strings " & " and " < " respectively. The right angle bracket (>) may be represented using the string " > ", and must, for compatibility, be escaped using either " > " or a character reference when it appears in the string " ]]> " in content, when that string is not marking the end of a CDATA section.
To allow attribute values to contain both single and double quotes, the apostrophe or single-quote character (') may be represented as " ' ", and the double-quote character (") as " " ".
Similar to this question.
In essence it means that the method Bar
will not modify non mutable member variables of Foo
.
Try this
typeof(IFoo).IsAssignableFrom(typeof(BarClass));
This will tell you whether BarClass(Derived)
implements IFoo(SomeType)
or not
import numpy as np
a=np.array([[21,20,19,18,17],[16,15,14,13,12],[11,10,9,8,7],[6,5,4,3,2]])
y=np.argsort(a[:,2],kind='mergesort')# a[:,2]=[19,14,9,4]
a=a[y]
print(a)
Desired output is [[6,5,4,3,2],[11,10,9,8,7],[16,15,14,13,12],[21,20,19,18,17]]
note that argsort(numArray)
returns the indices of an numArray
as it was supposed to be arranged in a sorted manner.
example
x=np.array([8,1,5])
z=np.argsort(x) #[1,3,0] are the **indices of the predicted sorted array**
print(x[z]) #boolean indexing which sorts the array on basis of indices saved in z
answer would be [1,5,8]
I wrote a library for solving this problem, everything happens in compiling time, except for getting the message.
Use macro DEF_MSG
to define a macro and message pair:
DEF_MSG(CODE_OK, "OK!")
DEF_MSG(CODE_FAIL, "Fail!")
CODE_OK
is the macro to use, and "OK!"
is the corresponding message.
Use get_message()
or just gm()
to get the message:
get_message(CODE_FAIL); // will return "Fail!"
gm(CODE_FAIL); // works exactly the same as above
Use MSG_NUM
to find out how many macros have been defined. This will automatically increse, you don't need to do anything.
Predefined messages:
MSG_OK: OK
MSG_BOTTOM: Message bottom
Project: libcodemsg
The library doesn't create extra data. Everything happens in compiling time. In message_def.h
, it generates an enum
called MSG_CODE
; in message_def.c
, it generates a variable holds all the strings in static const char* _g_messages[]
.
In such case, the library is limited to create one enum
only. This is ideal for return values, for example:
MSG_CODE foo(void) {
return MSG_OK; // or something else
}
MSG_CODE ret = foo();
if (MSG_OK != ret) {
printf("%s\n", gm(ret););
}
Another thing I like this design is you can manage message definitions in different files.
I found the solution to this question looks much better.
You should probably do some validations before you actually execute your function :
function trim(str) {
if(typeof str !== 'string') {
throw new Error('only string parameter supported!');
}
return str.replace(/^\s+|\s+$/g,'');
}
That is because you pass string to the function. Just remove quotes and pass real values:
<a href=# onclick="return ReAssign(valuationId, user)">Re-Assign</a>
Guess the ReAssign function should return true
or false
.
if you want to scroll within a particular view/frame (WebElement), what you only need to do is to replace "body" with a particular element that you intend to scroll within. i get that element via "getElementById" in the example below:
self.driver.execute_script('window.scrollTo(0, document.getElementById("page-manager").scrollHeight);')
this is the case on YouTube, for example...
url="https://myserver/post_service"
data["name"] = "joe"
data["age"] = "20"
data_encoded = urllib2.urlencode(data)
print urllib2.urlopen(url + "?" + data_encoded).read()
May be this can help
Your "application/xrds+xml"
was giving me issues, I was receiving a Content-Length of 0 (no response).
After removing that, you can access the response using response.GetResponseStream()
.
HttpWebRequest request = WebRequest.Create("http://google.com") as HttpWebRequest;
//request.Accept = "application/xrds+xml";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
WebHeaderCollection header = response.Headers;
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
string responseText = reader.ReadToEnd();
}
I have the same problem here, then I reinstalled mysql
and it worked.
sudo apt-get install mysql-server mysql-common mysql-client
import java.util.*; public class Mult {
public static int[][] C;
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("Enter Row of Matrix A");
int Rowa = s.nextInt();
System.out.println("Enter Column of Matrix A");
int Cola = s.nextInt();
System.out.println("Enter Row of Matrix B");
int Rowb = s.nextInt();
System.out.println("Enter Column of Matrix B");
int Colb = s.nextInt();
int[][] A = new int[Rowa][Cola];
int[][] B = new int[Rowb][Colb];
C= new int[Rowa][Colb];
//int[][] C = new int;
System.out.println("Enter Values of Matrix A");
for(int i =0 ; i< A.length ; i++) {
for(int j = 0 ; j<A.length;j++) {
A[i][j] = s.nextInt();
}
}
System.out.println("Enter Values of Matrix B");
for(int i =0 ; i< B.length ; i++) {
for(int j = 0 ; j<B.length;j++) {
B[i][j] = s.nextInt();
}
}
if(Cola==Rowb) {
for(int i = 0;i < A.length;i++){
for(int j = 0;j < A.length;j++){
C[i][j]=0;
for(int k = 0;k < B.length;k++){
C[i][j] += A[i][k] * B[k][j];
}
}
}
}
else {
System.out.println("Cannot multiply");
}
// Printing matrix A
/*
for(int i =0 ; i< A.length ; i++) {
for(int j = 0 ; j<A.length;j++) {
System.out.print(A[i][j]+ "\t");
}
System.out.println();
}
*/
for(int i =0 ; i< A.length ; i++) {
for(int j = 0 ; j<A.length;j++) {
System.out.print(C[i][j]+ "\t");
}
System.out.println();
}
}
}
std::string::data
would seem to be sufficient and most efficient. If you want to have non-const memory to manipulate (strange for encryption) you can copy the data to a buffer using memcpy:
unsigned char buffer[mystring.length()];
memcpy(buffer, mystring.data(), mystring.length());
STL fanboys would encourage you to use std::copy instead:
std::copy(mystring.begin(), mystring.end(), buffer);
but there really isn't much of an upside to this. If you need null termination use std::string::c_str()
and the various string duplication techniques others have provided, but I'd generally avoid that and just query for the length
. Particularly with cryptography you just know somebody is going to try to break it by shoving nulls in to it, and using std::string::data()
discourages you from lazily making assumptions about the underlying bits in the string.
Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.
As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:
var clone = _.clone(data, true);
data[1].values.d = 'x';
_.isEqual(data, clone) === false
_.isEqual(data, clone) === true
I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.
Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).
Can you use unix commands? I think using head -1
and tail -n 1
are probably the most efficient methods. Alternatively, you could use a simple fid.readline()
to get the first line and fid.readlines()[-1]
, but that may take too much memory.
You could try updating the table to get rid of these characters:
UPDATE dbo.[audit]
SET UserID = REPLACE(UserID, CHAR(0), '')
WHERE CHARINDEX(CHAR(0), UserID) > 0;
But then you'll also need to fix whatever is putting this bad data into the table in the first place. In the meantime perhaps try:
SELECT CONVERT(INT, REPLACE(UserID, CHAR(0), ''))
FROM dbo.[audit];
But that is not a long term solution. Fix the data (and the data type while you're at it). If you can't fix the data type immediately, then you can quickly find the culprit by adding a check constraint:
ALTER TABLE dbo.[audit]
ADD CONSTRAINT do_not_allow_stupid_data
CHECK (CHARINDEX(CHAR(0), UserID) = 0);
EDIT
Ok, so that is definitely a 4-digit integer followed by six instances of CHAR(0). And the workaround I posted definitely works for me:
DECLARE @foo TABLE(UserID VARCHAR(32));
INSERT @foo SELECT 0x31353831000000000000;
-- this succeeds:
SELECT CONVERT(INT, REPLACE(UserID, CHAR(0), '')) FROM @foo;
-- this fails:
SELECT CONVERT(INT, UserID) FROM @foo;
Please confirm that this code on its own (well, the first SELECT
, anyway) works for you. If it does then the error you are getting is from a different non-numeric character in a different row (and if it doesn't then perhaps you have a build where a particular bug hasn't been fixed). To try and narrow it down you can take random values from the following query and then loop through the characters:
SELECT UserID, CONVERT(VARBINARY(32), UserID)
FROM dbo.[audit]
WHERE UserID LIKE '%[^0-9]%';
So take a random row, and then paste the output into a query like this:
DECLARE @x VARCHAR(32), @i INT;
SET @x = CONVERT(VARCHAR(32), 0x...); -- paste the value here
SET @i = 1;
WHILE @i <= LEN(@x)
BEGIN
PRINT RTRIM(@i) + ' = ' + RTRIM(ASCII(SUBSTRING(@x, @i, 1)))
SET @i = @i + 1;
END
This may take some trial and error before you encounter a row that fails for some other reason than CHAR(0)
- since you can't really filter out the rows that contain CHAR(0)
because they could contain CHAR(0)
and CHAR(something else)
. For all we know you have values in the table like:
SELECT '15' + CHAR(9) + '23' + CHAR(0);
...which also can't be converted to an integer, whether you've replaced CHAR(0)
or not.
I know you don't want to hear it, but I am really glad this is painful for people, because now they have more war stories to push back when people make very poor decisions about data types.
C++ references naturally can't be null, you don't need the check. The function can only be called by passing a reference to an existing object.
I did a small benchmark on this topic. While many of the other posters have made good points about compatibility, my experience has been that PyPy isn't that much faster for just moving around bits. For many uses of Python, it really only exists to translate bits between two or more services. For example, not many web applications are performing CPU intensive analysis of datasets. Instead, they take some bytes from a client, store them in some sort of database, and later return them to other clients. Sometimes the format of the data is changed.
The BDFL and the CPython developers are a remarkably intelligent group of people and have a managed to help CPython perform excellent in such a scenario. Here's a shameless blog plug: http://www.hydrogen18.com/blog/unpickling-buffers.html . I'm using Stackless, which is derived from CPython and retains the full C module interface. I didn't find any advantage to using PyPy in that case.
$(document).ready(function() {
$('ul.art-vmenu li').live("click", function() {
alert($(this).text());
});
});
jsfiddle: http://jsfiddle.net/ZpYSC/
jquery documentation on live(): http://api.jquery.com/live/
Description: Attach a handler to the event for all elements which match the current selector, now and in the future.
I guess the below should work (instead of the writer part from your example). I'm unfortunately with no build environment so It's from memory but I hope it helps
using (var fs = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite)))
{
var destinationReader = StreamReader(fs);
var writer = StreamWriter(fs);
while ((line = reader.ReadLine()) != null)
{
if (line_number == line_to_edit)
{
writer.WriteLine(lineToWrite);
}
else
{
destinationReader .ReadLine();
}
line_number++;
}
}
I believe this error message is due to a "zombie transaction".
Look for possible areas where the transacton is being committed twice (or rolled back twice, or rolled back and committed, etc.). Does the .Net code commit the transaction after the SP has already committed it? Does the .Net code roll it back on encountering an error, then attempt to roll it back again in a catch (or finally) clause?
It's possible an error condition was never being hit on the old server, and thus the faulty "double rollback" code was never hit. Maybe now you have a situation where there is some configuration error on the new server, and now the faulty code is getting hit via exception handling.
Can you debug into the error code? Do you have a stack trace?
I deactivated my "Arno's Iptables Firewall" for testing, and then the messages are gone
Try this:
$('#select_all').click(function() {
$('#countries option').prop('selected', true);
});
And here's a live demo.
It is absolutely possible that all other answers work for people but for me this path worked:
Leave your JDK path under JAVA_HOME
System Variable as it is given here. Do not append bin or another path. It worked for me.
C:\Program Files\Java\jdk1.8.0_11\
Otherwise I am getting this error:
Installing Android Studio, does not point to a valid JVM installation error
Do it like so
all: program1 program2
program1: program1.c
gcc -o program1 program1.c
program2: program2.c
gcc -o program2 program2.c
You said you don't want advanced stuff, but you could also shorten it like this based on some default rules.
all: program1 program2
program1: program1.c
program2: program2.c
If you are replacing by an index value specified in variable 'n', then try the below:
def missing_char(str, n):
str=str.replace(str[n],":")
return str
var variable1 = "Hello, World!";
var variable2 = "Testing...";
var variable3 = 42;
is more readable than:
var variable1 = "Hello, World!",
variable2 = "Testing...",
variable3 = 42;
But they do the same thing.
compiler changes checks your source code for errors and changes it into object code.this is the code that operating system runs.
You often don't write a whole program in single file so linker links all your object code files.
your program wont get executed unless it is in main memory
To build on @Michelle Tilley's answer, I sometimes want to scroll if the user's selection changes, so I trigger the scroll on componentDidUpdate
. I also did some math to figure out how far to scroll and whether scrolling was needed, which for me looks like the following:
componentDidUpdate() {_x000D_
let panel, node;_x000D_
if (this.refs.selectedSection && this.refs.selectedItem) {_x000D_
// This is the container you want to scroll. _x000D_
panel = this.refs.listPanel;_x000D_
// This is the element you want to make visible w/i the container_x000D_
// Note: You can nest refs here if you want an item w/i the selected item _x000D_
node = ReactDOM.findDOMNode(this.refs.selectedItem);_x000D_
}_x000D_
_x000D_
if (panel && node &&_x000D_
(node.offsetTop > panel.scrollTop + panel.offsetHeight || node.offsetTop < panel.scrollTop)) {_x000D_
panel.scrollTop = node.offsetTop - panel.offsetTop;_x000D_
}_x000D_
}
_x000D_
This is a complete solution that uses the mouseover and mouseleave events and some screen width checking.
This was built with desktop and mobile in mind. Fell free to change the BREAK_POINT variable to suit your needs :D.
jQuery
var WINDOW_WIDTH;
var BREAK_POINT = 991;
(function ($) {
/** Set window width onload */
WINDOW_WIDTH = $(window).width(); // Returns width of browser viewport
/** Set window width if the browser is resized */
$(window).resize(function () {
WINDOW_WIDTH = $(window).width(); // Returns width of browser viewport
});
/** Dropdown menu on mouseenter */
$(".nav-item.dropdown").on('mouseenter', function () {
console.log("mouseenter");
if (WINDOW_WIDTH >= BREAK_POINT) {
// Open up the dropdown
$(this).addClass('show'); // add the class show to the li parent
$(this).children('.nav-link').removeAttr('data-toggle'); // remove the data-toggle attribute so we can click and follow link
$(this).children('.dropdown-menu').addClass('show'); // add the class show to the dropdown div sibling
}
});
/** Dropdown menu on mouseleave */
$(".nav-item.dropdown").on('mouseleave', function () {
console.log("mouseleave");
if (WINDOW_WIDTH >= BREAK_POINT) {
// Open up the dropdown
$(this).removeClass('show'); // add the class show to the li parent
$(this).children('.nav-link').attr('data-toggle', 'dropdown'); // remove the data-toggle attribute so we can click and follow link
$(this).children('.dropdown-menu').removeClass('show'); // add the class show to the dropdown div sibling
}
});
});
@media(min-width: 768px) {
.dropdown-menu {
margin-top: 0; // fixes closing on slow mouse transition
}
}
You might also be interested in go-libucl, a set of Go bindings for UCL, the Universal Configuration Language. UCL is a bit like JSON, but with better support for humans: it supports comments and human-readable constructs like SI multipliers (10k, 40M, etc.) and has a little bit less boilerplate (e.g., quotes around keys). It's actually pretty close to the nginx configuration file format, if you're already familiar with that.
This is a simple way.
<div class="row">
<div class="col-md-6 mx-auto">
<p>My text</p>
</div>
</div>
The number 6 controls the width of the column.
// Java 8
int vInt = Integer.parseUnsignedInt("4294967295");
System.out.println(vInt); // -1
String sInt = Integer.toUnsignedString(vInt);
System.out.println(sInt); // 4294967295
long vLong = Long.parseUnsignedLong("18446744073709551615");
System.out.println(vLong); // -1
String sLong = Long.toUnsignedString(vLong);
System.out.println(sLong); // 18446744073709551615
// Guava 18.0
int vIntGu = UnsignedInts.parseUnsignedInt(UnsignedInteger.MAX_VALUE.toString());
System.out.println(vIntGu); // -1
String sIntGu = UnsignedInts.toString(vIntGu);
System.out.println(sIntGu); // 4294967295
long vLongGu = UnsignedLongs.parseUnsignedLong("18446744073709551615");
System.out.println(vLongGu); // -1
String sLongGu = UnsignedLongs.toString(vLongGu);
System.out.println(sLongGu); // 18446744073709551615
/**
Integer - Max range
Signed: From -2,147,483,648 to 2,147,483,647, from -(2^31) to 2^31 – 1
Unsigned: From 0 to 4,294,967,295 which equals 2^32 - 1
Long - Max range
Signed: From -9,223,372,036,854,775,808 to 9,223,372,036,854,775,807, from -(2^63) to 2^63 - 1
Unsigned: From 0 to 18,446,744,073,709,551,615 which equals 2^64 – 1
*/
As an alternative to @Mark Byers' approach, you can use while True
:
guess = 50 # this should be outside the loop, I think
while True: # infinite loop
n = raw_input("\n\nTrue, False or Correct?: ")
if n == "Correct":
break # stops the loop
elif n == "True":
# etc.
Here's another dodge that I came up with for my base repository class where I needed to order by an arbitrary number of columns:
public function findAll(array $where = [], array $with = [], array $orderBy = [], int $limit = 10)
{
$result = $this->model->with($with);
$dataSet = $result->where($where)
// Conditionally use $orderBy if not empty
->when(!empty($orderBy), function ($query) use ($orderBy) {
// Break $orderBy into pairs
$pairs = array_chunk($orderBy, 2);
// Iterate over the pairs
foreach ($pairs as $pair) {
// Use the 'splat' to turn the pair into two arguments
$query->orderBy(...$pair);
}
})
->paginate($limit)
->appends(Input::except('page'));
return $dataSet;
}
Now, you can make your call like this:
$allUsers = $userRepository->findAll([], [], ['name', 'DESC', 'email', 'ASC'], 100);
I am part of a team investigating the use of Evolutionary Computation (EC) to automatically fix bugs in existing programs. We have successfully repaired a number of real bugs in real world software projects (see this project's homepage).
We have two applications of this EC repair technique.
The first (code and reproduction information available through the project page) evolves the abstract syntax trees parsed from existing C programs and is implemented in Ocaml using our own custom EC engine.
The second (code and reproduction information available through the project page), my personal contribution to the project, evolves the x86 assembly or Java byte code compiled from programs written in a number of programming languages. This application is implemented in Clojure and also uses its own custom built EC engine.
One nice aspect of Evolutionary Computation is the simplicity of the technique makes it possible to write your own custom implementations without too much difficulty. For a good freely available introductory text on Genetic Programming see the Field Guide to Genetic Programming.
Another answer to the OP's exact question is to set the consumes
content type to "text/plain"
and then declare a @RequestBody String
input parameter. This will pass the text of the POST data in as the declared String
variable (postPayload
in the following example).
Of course, this presumes your POST payload is text data (as the OP stated was the case).
Example:
@RequestMapping(value = "/your/url/here", method = RequestMethod.POST, consumes = "text/plain")
public ModelAndView someMethod(@RequestBody String postPayload) {
// ...
}
Yes. 'Z' stands for Zulu time, which is also GMT and UTC.
From http://en.wikipedia.org/wiki/Coordinated_Universal_Time:
The UTC time zone is sometimes denoted by the letter Z—a reference to the equivalent nautical time zone (GMT), which has been denoted by a Z since about 1950. The letter also refers to the "zone description" of zero hours, which has been used since 1920 (see time zone history). Since the NATO phonetic alphabet and amateur radio word for Z is "Zulu", UTC is sometimes known as Zulu time.
Technically, because the definition of nautical time zones is based on longitudinal position, the Z time is not exactly identical to the actual GMT time 'zone'. However, since it is primarily used as a reference time, it doesn't matter what area of Earth it applies to as long as everyone uses the same reference.
From wikipedia again, http://en.wikipedia.org/wiki/Nautical_time:
Around 1950, a letter suffix was added to the zone description, assigning Z to the zero zone, and A–M (except J) to the east and N–Y to the west (J may be assigned to local time in non-nautical applications; zones M and Y have the same clock time but differ by 24 hours: a full day). These were to be vocalized using a phonetic alphabet which pronounces the letter Z as Zulu, leading sometimes to the use of the term "Zulu Time". The Greenwich time zone runs from 7.5°W to 7.5°E longitude, while zone A runs from 7.5°E to 22.5°E longitude, etc.
For people who are reading byte array into String and trying to convert to object with JAXB, you can add "iso-8859-1" encoding by creating String from byte array like this:
String JAXBallowedString= new String(byte[] input, "iso-8859-1");
This would replace the conflicting byte to single-byte encoding which JAXB can handle. Obviously this solution is only to parse the xml.
Note: this solution and any other "edit the policy.xml" solution disables safety measures against arbitrary code execution vulnerabilities in ImageMagick. If you need to process input that you do not control 100%, you should use a different program (not ImageMagick).
If you're still here, you are trying to edit images that you have complete control over, know are safe, and cannot be edited by users.
There is an /etc/ImageMagick/policy.xml
file that is installed by yum. It disallows almost everything (for security and to protect your system from getting overloaded with ImageMagick calls).
If you're getting a ReadImage
error as above, you can change the line to:
<policy domain="coder" rights="read" pattern="LABEL" />
which should fix the issue.
The file has a bunch of documentation in it, so you should read that. For example, if you need more permissions, you can combine them like:
<policy domain="coder" rights="read|write" pattern="LABEL" />
...which is preferable to removing all permissions checks (i.e., deleting or commenting out the line).
Calling object.paintComponent(g)
is an error.
Instead this method is called automatically when the panel is created. The paintComponent()
method can also be called explicitly by the repaint()
method defined in Component
class.
The effect of calling repaint()
is that Swing automatically clears the graphic on the panel and executes the paintComponent
method to redraw the graphics on this panel.
I know this is an old post but I would like share my solution. I spent several hours trying to make a justified navigation menu. You do not really need to modify anything in bootstrap css. Just need to add the correct class in the html.
<nav class="nav navbar-default navbar-fixed-top">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#collapsable-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#top">Brand Name</a>
</div>
<div class="collapse navbar-collapse" id="collapsable-1">
<ul class="nav nav-justified">
<li><a href="#about-me">About Me</a></li>
<li><a href="#skills">Skills</a></li>
<li><a href="#projects">Projects</a></li>
<li><a href="#contact-me">Contact Me</a></li>
</ul>
</div>
</nav>
This CSS code will simply remove the navbar-brand class when the screen reaches 768px.
media@(min-width: 768px){
.navbar-brand{
display: none;
}
}
Other posts have mentioned flexbox, but if more than one row of items is necessary, flexbox's space-between
property fails (see the end of the post)
To date, the only clean solution for this is with the
Basically the relevant code necessary boils down to this:
ul {
display: grid; /* (1) */
grid-template-columns: repeat(auto-fit, 120px); /* (2) */
grid-gap: 1rem; /* (3) */
justify-content: space-between; /* (4) */
align-content: flex-start; /* (5) */
}
1) Make the container element a grid container
2) Set the grid with an 'auto' amount of columns - as necessary. This is done for responsive layouts. The width of each column will be 120px. (Note the use of auto-fit
(as apposed to auto-fill
) which (for a 1-row layout) collapses empty tracks to 0 - allowing the items to expand to take up the remaining space. (check out this demo to see what I'm talking about) ).
3) Set gaps/gutters for the grid rows and columns - here, since want a 'space-between' layout - the gap will actually be a minimum gap because it will grow as necessary.
4) and 5) - Similar to flexbox.
body {_x000D_
margin: 0;_x000D_
}_x000D_
ul {_x000D_
display: grid;_x000D_
grid-template-columns: repeat(auto-fit, 120px);_x000D_
grid-gap: 1rem;_x000D_
justify-content: space-between;_x000D_
align-content: flex-start;_x000D_
_x000D_
/* boring properties: */_x000D_
list-style: none;_x000D_
width: 90vw;_x000D_
height: 90vh;_x000D_
margin: 2vh auto;_x000D_
border: 5px solid green;_x000D_
padding: 0;_x000D_
overflow: auto;_x000D_
}_x000D_
li {_x000D_
background: tomato;_x000D_
height: 120px;_x000D_
}
_x000D_
<ul>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
</ul>
_x000D_
Currently supported by Chrome (Blink), Firefox, Safari and Edge! ... with partial support from IE (See this post by Rachel Andrew)
Flexbox's space-between
property works great for one row of items, but when applied to a flex container which wraps it's items - (with flex-wrap: wrap
) - fails, because you have no control over the alignment of the last row of items;
the last row will always be justified (usually not what you want)
To demonstrate:
body {_x000D_
margin: 0;_x000D_
}_x000D_
ul {_x000D_
_x000D_
display: flex;_x000D_
justify-content: space-between;_x000D_
flex-wrap: wrap;_x000D_
align-content: flex-start;_x000D_
_x000D_
list-style: none;_x000D_
width: 90vw;_x000D_
height: 90vh;_x000D_
margin: 2vh auto;_x000D_
border: 5px solid green;_x000D_
padding: 0;_x000D_
overflow: auto;_x000D_
_x000D_
}_x000D_
li {_x000D_
background: tomato;_x000D_
width: 110px;_x000D_
height: 80px;_x000D_
margin-bottom: 1rem;_x000D_
}
_x000D_
<ul>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
<li></li>_x000D_
</ul>
_x000D_
Codepen (Resize to see what i'm talking about)
Further reading on CSS grids:
Maybe that can help someone, I had the same problem.
I've already created two tables with the serializer class and the views. So when I wanted to updated, I had this error.
I followed this steps:
.\manage.py makemigrations app
.\manage.py migrate
models.py
1
and 2
.models.py
5
.If you're working with Pycharm, local history is very helpfull.
select name, count(*) from DBS, TBLS
where DBS.DB_ID = TBLS.DB_ID
group by NAME into outfile '/tmp/QueryOut1.csv'
fields terminated by ',' lines terminated by '\n';
for (int i = 0; i < nodeList.getLength(); i++)
change to
for (int i = 0, len = nodeList.getLength(); i < len; i++)
to be more efficient.
The second way of javanna answer may be the best as it tends to use a flatter, predictable memory model.
We can use
Type.GetType()
to get class name and can also create object of it using Activator.CreateInstance(type);
using System;
using System.Reflection;
namespace MyApplication
{
class Application
{
static void Main()
{
Type type = Type.GetType("MyApplication.Action");
if (type == null)
{
throw new Exception("Type not found.");
}
var instance = Activator.CreateInstance(type);
//or
var newClass = System.Reflection.Assembly.GetAssembly(type).CreateInstance("MyApplication.Action");
}
}
public class Action
{
public string key { get; set; }
public string Value { get; set; }
}
}
If you want they to be paragraph, then use it.
<p><label for="id1">label1:</label> <input type="text" id="id1"/></p>
<p><label for="id2">label2:</label> <input type="text" id="id2"/></p>
Both <label>
and <input>
are paragraph and flow content so you can insert as paragraph elements and as block elements.
I'm trying to redirect my current web site to other section on the same page, using JavaScript. This follow code work for me:
location.href='/otherSection'
I think you should first define all your routes and as the last route add
//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res){
res.status(404).send('what???');
});
An example app which does work:
var express = require('express'),
app = express.createServer();
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res){
res.send('hello world');
});
//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res){
res.send('what???', 404);
});
app.listen(3000, '127.0.0.1');
alfred@alfred-laptop:~/node/stackoverflow/6528876$ mkdir public
alfred@alfred-laptop:~/node/stackoverflow/6528876$ find .
alfred@alfred-laptop:~/node/stackoverflow/6528876$ echo "I don't find a function for that... Anyone knows?" > public/README.txt
alfred@alfred-laptop:~/node/stackoverflow/6528876$ cat public/README.txt
.
./app.js
./public
./public/README.txt
alfred@alfred-laptop:~/node/stackoverflow/6528876$ curl http://localhost:3000/
hello world
alfred@alfred-laptop:~/node/stackoverflow/6528876$ curl http://localhost:3000/README.txt
I don't find a function for that... Anyone knows?
First you compile the regex, then you have to use it with match
, find
, or some other method to actually run it against some input.
import os
import re
import shutil
def test():
os.chdir("C:/Users/David/Desktop/Test/MyFiles")
files = os.listdir(".")
os.mkdir("C:/Users/David/Desktop/Test/MyFiles2")
pattern = re.compile(regex_txt, re.IGNORECASE)
for x in (files):
with open((x), 'r') as input_file:
for line in input_file:
if pattern.search(line):
shutil.copy(x, "C:/Users/David/Desktop/Test/MyFiles2")
break
That's depending if userid is a resource identifier or additional parameter. If it is then it's ok to return 404 if not you might return other code like
400 (bad request) - indicates a bad request
or
412 (Precondition Failed) e.g. conflict by performing conditional update
More info in free InfoQ Explores: REST book.
Just a small one to add, you should use the img tag if you want users to be able to 'right click' and 'save-image'/'save-picture', so if you intend to provide the image as a resource for others.
Using background image will (as far as I'm aware on most browsers) disable the option to save the image directly.
The good news is that if you need to make a case-sensitive query, it is very easy to do:
SELECT * FROM `table` WHERE BINARY `column` = 'value'
To fix the ugly look of a divider being too short when the content of one column is taller, add borders to all columns. Give every other column a negative margin to compensate for position differences.
For example, my three column classes:
.border-right {
border-right: 1px solid #ddd;
}
.borders {
border-left: 1px solid #ddd;
border-right: 1px solid #ddd;
margin: -1px;
}
.border-left {
border-left: 1px solid #ddd;
}
And the HTML:
<div class="col-sm-4 border-right">First</div>
<div class="col-sm-4 borders">Second</div>
<div class="col-sm-4 border-left">Third</div>
Make sure you use #ddd if you want the same color as Bootstrap's horizontal dividers.
GROUP BY can be selected from Total row in query design view in MS Access.
If Total row not shown in design view (as in my case). You can go to SQL View and add GROUP By fname etc. Then Total row will automatically show in design view.
You have to select as Expression in this row for calculated fields.
I entirely agree that goto
is poor poor coding, but no one has actually answered the question. There is in fact a goto module for Python (though it was released as an April fool joke and is not recommended to be used, it does work).
Just add <br>
where you would like to make the new line.
$S$: a set of shops
<br>
$I$: a set of items M wants to get
Because jupyter notebook markdown cell is a superset of HTML.
http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Working%20With%20Markdown%20Cells.html
Note that newlines using <br>
does not persist when exporting or saving the notebook to a pdf (using "Download as > PDF via LaTeX"). It is probably treating each <br>
as a space.
If you do run()
in main method, the thread of main method will invoke the run
method instead of the thread you require to run.
The start()
method creates new thread and for which the run()
method has to be done
Try the following:
cv::Mat image = ...do some stuff...;
image.at<cv::Vec3b>(y,x);
gives you the RGB (it might be ordered as BGR) vector of type cv::Vec3b
image.at<cv::Vec3b>(y,x)[0] = newval[0];
image.at<cv::Vec3b>(y,x)[1] = newval[1];
image.at<cv::Vec3b>(y,x)[2] = newval[2];
Is there an easy way to convert jQuery code to regular javascript?
No, especially if:
understanding the examples of javascript solutions written in jQuery [is] hard.
JQuery and all the frameworks tend to make understanding the code easier. If that's difficult to understand, then vanilla javascript will be torture :)
Another nifty way is:
DATEADD(dd, 0, DATEDIFF(dd, 0, [YourDate]))
Which gets the number of days from DAY 0 to YourDate and the adds it to DAY 0 to set the baseline again. This method (or "derivatives" hereof) can be used for a bunch of other date manipulation.
Edit - other date calculations:
First Day of Month:
DATEADD(mm, DATEDIFF(mm, 0, getdate()), 0)
First Day of the Year:
DATEADD(yy, DATEDIFF(yy, 0, getdate()), 0)
First Day of the Quarter:
DATEADD(qq, DATEDIFF(qq, 0, getdate()), 0)
Last Day of Prior Month:
DATEADD(ms, -3, DATEADD(mm, DATEDIFF(mm, 0, getdate()), 0))
Last Day of Current Month:
DATEADD(ms, -3, DATEADD(mm, DATEDIFF(m, 0, getdate()) + 1, 0))
Last Day of Current Year:
DATEADD(ms, -3, DATEADD(yy, DATEDIFF(yy, 0, getdate()) + 1, 0))
First Monday of the Month:
DATEADD(wk, DATEDIFF(wk, 0, DATEADD(dd, 6 - DATEPART(day, getdate()), getdate())), 0)
Edit: True, Joe, it does not add it to DAY 0, it adds 0 (days) to the number of days which basically just converts it back to a datetime.
Put this in C2 and copy down
=IF(ISNA(VLOOKUP(A2,$B$2:$B$65535,1,FALSE)),"not in B","")
Then if the value in A isn't in B the cell in column C will say "not in B".
I like using _.pickBy, because you have full control over what you are removing:
var person = {"name":"bill","age":21,"sex":undefined,"height":null};
var cleanPerson = _.pickBy(person, function(value, key) {
return !(value === undefined || value === null);
});
Source: https://www.codegrepper.com/?search_term=lodash+remove+undefined+values+from+object
I'm not sure what your problem is, but the following seems to work OK:
#include <stdio.h>
int main()
{
const char s0[] = "ABCD";
const char s1[] = { s0[3], s0[2], s0[1], s0[0], 0 };
puts(s0);
puts(s1);
return 0;
}
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 13.10.3077 for 80x86
Copyright (C) Microsoft Corporation 1984-2002. All rights reserved.
cl /Od /D "WIN32" /D "_CONSOLE" /Gm /EHsc /RTC1 /MLd /W3 /c /ZI /TC
.\Tmp.c
Tmp.c
Linking...
Build Time 0:02
C:\Tmp>tmp.exe
ABCD
DCBA
C:\Tmp>
Edit 9 June 2009
If you need global access, you might need something ugly like this:
#include <stdio.h>
const char *GetString(int bMunged)
{
static char s0[5] = "ABCD";
static char s1[5];
if (bMunged) {
if (!s1[0]) {
s1[0] = s0[3];
s1[1] = s0[2];
s1[2] = s0[1];
s1[3] = s0[0];
s1[4] = 0;
}
return s1;
} else {
return s0;
}
}
#define S0 GetString(0)
#define S1 GetString(1)
int main()
{
puts(S0);
puts(S1);
return 0;
}
Below are two ways to generate prime factors of given number efficiently:
from math import sqrt
def prime_factors(num):
'''
This function collectes all prime factors of given number and prints them.
'''
prime_factors_list = []
while num % 2 == 0:
prime_factors_list.append(2)
num /= 2
for i in range(3, int(sqrt(num))+1, 2):
if num % i == 0:
prime_factors_list.append(i)
num /= i
if num > 2:
prime_factors_list.append(int(num))
print(sorted(prime_factors_list))
val = int(input('Enter number:'))
prime_factors(val)
def prime_factors_generator(num):
'''
This function creates a generator for prime factors of given number and generates the factors until user asks for them.
It handles StopIteration if generator exhausted.
'''
while num % 2 == 0:
yield 2
num /= 2
for i in range(3, int(sqrt(num))+1, 2):
if num % i == 0:
yield i
num /= i
if num > 2:
yield int(num)
val = int(input('Enter number:'))
prime_gen = prime_factors_generator(val)
while True:
try:
print(next(prime_gen))
except StopIteration:
print('Generator exhausted...')
break
else:
flag = input('Do you want next prime factor ? "y" or "n":')
if flag == 'y':
continue
elif flag == 'n':
break
else:
print('Please try again and enter a correct choice i.e. either y or n')
You can use date function to format it by using the code below:
echo date("g:i a", strtotime("13:30:30 UTC"));
output: 1:30 pm
If you are using Hibernate version prior to Hibernate5 @GeneratedValue(strategy = GenerationType.IDENTITY)
works like a charm. But post Hibernate5 the following fix is necessary.
@Id
@GeneratedValue(strategy= GenerationType.AUTO,generator="native")
@GenericGenerator(name = "native",strategy = "native")
private Long id;
DDL
`id` BIGINT(20) NOT NULL AUTO_INCREMENT PRIMARY KEY
REASON
Excerpt from hibernate-issue
Currently, if the hibernate.id.new_generator_mappings is set to false, @GeneratedValue(strategy = GenerationType.AUTO) is mapped to native. If this property is true (which is the defult value in 5.x), the @GeneratedValue(strategy = GenerationType.AUTO) is always mapped to SequenceStyleGenerator.
For this reason, on any database that does not support sequences natively (e.g. MySQL) we are going to use the TABLE generator instead of IDENTITY.
However, TABLE generator, although more portable, uses a separate transaction every time a value is being fetched from the database. In fact, even if the IDENTITY disables JDBC batch updates and the TABLE generator uses the pooled optimizer, the IDENTITY still scales better.
SELECT * FROM `permlog` as one
RIGHT JOIN (SELECT MAX(id) as max_id FROM `permlog`) as two
ON one.id = two.max_id
To install GLIBC_2.14 or GLIBC_2.15, download package from /gnu/libc/ index at
Then follow instructions listed by Timo:
For example glibc-2.14.tar.gz in your case.
tar xvfz glibc-2.14.tar.gz
cd glibc-2.14
mkdir build
cd build
../configure --prefix=/opt/glibc-2.14
make
sudo make install
export LD_LIBRARY_PATH=/opt/glibc-2.14/lib:$LD_LIBRARY_PATH
Table variables are just like int or varchar variables.
You don't need to drop them. They have the same scope rules as int or varchar variables
The scope of a variable is the range of Transact-SQL statements that can reference the variable. The scope of a variable lasts from the point it is declared until the end of the batch or stored procedure in which it is declared.
setSize
will resize the component to the specified size.
setPreferredSize
sets the preferred size. The component may not actually be this size depending on the size of the container it's in, or if the user re-sized the component manually.
Specify the maxrecursion option at the end of the query:
...
from EmployeeTree
option (maxrecursion 0)
That allows you to specify how often the CTE can recurse before generating an error. Maxrecursion 0 allows infinite recursion.
if re.search(r"\b(?<=\w)%s\b(?!\w)" % TEXTO, subject, re.IGNORECASE):
This will insert what is in TEXTO into the regex as a string.
I've always thought that DLLs and shared objects are just different terms for the same thing - Windows calls them DLLs, while on UNIX systems they're shared objects, with the general term - dynamically linked library - covering both (even the function to open a .so on UNIX is called dlopen()
after 'dynamic library').
They are indeed only linked at application startup, however your notion of verification against the header file is incorrect. The header file defines prototypes which are required in order to compile the code which uses the library, but at link time the linker looks inside the library itself to make sure the functions it needs are actually there. The linker has to find the function bodies somewhere at link time or it'll raise an error. It ALSO does that at runtime, because as you rightly point out the library itself might have changed since the program was compiled. This is why ABI stability is so important in platform libraries, as the ABI changing is what breaks existing programs compiled against older versions.
Static libraries are just bundles of object files straight out of the compiler, just like the ones that you are building yourself as part of your project's compilation, so they get pulled in and fed to the linker in exactly the same way, and unused bits are dropped in exactly the same way.
Using the map()
and reduce()
built-in functions
def file_to_list(file):
#stuff to parse file to a list
return list
files = [...list of files...]
L = map(file_to_list, files)
flat_L = reduce(lambda x,y:x+y, L)
Minimal "for looping" and elegant coding pattern :)
I can offer you a jquery solution
add this in your <head></head>
tag
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
add this after </ul>
<script> $('ul li:first').remove(); </script>
Radio buttons are meant to be required options... If you want them to be unchecked, use a checkbox, there is no need to complicate things and allow users to uncheck a radio button; removing the JQuery allows you to select from one of them
Try
private void cleanlistbox(object sender, EventArgs e)
{
ListBox1.Items.Clear();
}
The value 3172978990 is greater than 2147483647 – the maximum value for INT
– hence the error. MySQL integer types and their ranges are listed here.
Also note that the (10)
in INT(10)
does not define the "size" of an integer. It specifies the display width of the column. This information is advisory only.
To fix the error, change your datatype to VARCHAR
. Phone and Fax numbers should be stored as strings. See this discussion.
To add to rcs' answer, if you want to use position_dodge() with geom_bar() when x is a POSIX.ct date, you must multiply the width by 86400, e.g.,
ggplot(data=dat, aes(x=Types, y=Number, fill=sample)) +
geom_bar(position = "dodge", stat = 'identity') +
geom_text(aes(label=Number), position=position_dodge(width=0.9*86400), vjust=-0.25)
First, you need to understand that you have two documents: The frame and the container (which contains the frame).
The main obstacle with manipulating the frame from the container is that the frame loads asynchronously. You can't simply access it any time, you must know when it has finished loading. So you need a trick. The usual solution is to use window.parent
in the frame to get "up" (into the document which contains the iframe
tag).
Now you can call any method in the container document. This method can manipulate the frame (for example call some JavaScript in the frame with the parameters you need). To know when to call the method, you have two options:
Call it from body.onload of the frame.
Put a script element as the last thing into the HTML content of the frame where you call the method of the container (left as an exercise for the reader).
So the frame looks like this:
<script>
function init() { window.parent.setUpFrame(); return true; }
function yourMethod(arg) { ... }
</script>
<body onload="init();">...</body>
And the container like this:
<script>
function setUpFrame() {
var frame = window.frames['frame-id'];
frame.yourMethod('hello');
}
</script>
<body><iframe name="frame-id" src="..."></iframe></body>
Most important
Keep in mind that relative URLs are resolved from the URL of your stylesheet.
So it will work if folder images
is inside the stylesheets
folder.
From you description you would need to change it to either
url("../images/plaid.jpg")
or
url("/images/plaid.jpg")
Additional 1
Also you cannot have no selector..
CSS is applied through selectors..
Additional 2
You should use either the shorthand background
to pass multiple values like this
background: url("../images/plaid.jpg") no-repeat;
or the verbose syntax of specifying each property on its own
background-image: url("../images/plaid.jpg");
background-repeat:no-repeat;
Simple solution:
int str_case_ins_cmp(const char* a, const char* b) {
int rc;
while (1) {
rc = tolower((unsigned char)*a) - tolower((unsigned char)*b);
if (rc || !*a) {
break;
}
++a;
++b;
}
return rc;
}
Waking up a dead question here but the answers provided will not work with jdk 7 (I read somewhere that a bug is open for this for Oracle Engineers but not fixed yet). Along with the link that @Ryan provided, you will have to also add :
System.setProperty("jsse.enableSNIExtension", "false");
(Courtesy to many stackoverflow answers combined together to figure this out)
The complete code will look as follows which worked for me (without setting the system property the Client Config did not work for me):
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.client.urlconnection.HTTPSProperties;
public class ClientHelper
{
public static ClientConfig configureClient()
{
System.setProperty("jsse.enableSNIExtension", "false");
TrustManager[] certs = new TrustManager[]
{
new X509TrustManager()
{
@Override
public X509Certificate[] getAcceptedIssuers()
{
return null;
}
@Override
public void checkServerTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
}
@Override
public void checkClientTrusted(X509Certificate[] chain, String authType)
throws CertificateException
{
}
}
};
SSLContext ctx = null;
try
{
ctx = SSLContext.getInstance("SSL");
ctx.init(null, certs, new SecureRandom());
}
catch (java.security.GeneralSecurityException ex)
{
}
HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());
ClientConfig config = new DefaultClientConfig();
try
{
config.getProperties().put(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES, new HTTPSProperties(
new HostnameVerifier()
{
@Override
public boolean verify(String hostname, SSLSession session)
{
return true;
}
},
ctx));
}
catch (Exception e)
{
}
return config;
}
public static Client createClient()
{
return Client.create(ClientHelper.configureClient());
}
Use this, works for me and solve problems with small screen.
<div class="row">
<!-- (fixed content) JUST VISIBLE IN LG SCREEN -->
<div class="col-lg-3 device-lg visible-lg">
<div class="affix">
fixed position
</div>
</div>
<div class="col-lg-9">
<!-- (fixed content) JUST VISIBLE IN NO LG SCREEN -->
<div class="device-sm visible-sm device-xs visible-xs device-md visible-md ">
<div>
NO fixed position
</div>
</div>
Normal data enter code here
</div>
</div>
In case of SSL connections this may be caused by issue in older versions of nginx server that segfault during curl and Safari requests. This bug was fixed around version 1.10 of nginx but there is still a lot of older versions of nginx on the internet.
For nginx admins: adding ssl_session_cache shared:SSL:1m;
to http
block should solve the problem.
I'm aware that OP was asking for non-SSL case but since this is the top page in goole for "empty reply from server" issue, I'm leaving the SSL answer here as I was one of many that was banging my head against the wall with this issue.
I just came up with a general solution, which should work on most websites. I tried this on Chrome only, but this method should work with any other browser, though, as Dev Tools are pretty much the same in them all.
Steps:
.m3u8
extension. There may be many of them, but most likely the first you find is the one you are looking for. It may have any name, e.g. playlist.m3u8
.You can go fullscreen automatically by putting this code in:
var elem = document.documentElement; if (elem.requestFullscreen) { elem.requestFullscreen() }
demo: https://codepen.io/ConfidentCoding/pen/ewLyPX
note: does not always work for security reasons. but it works for me at least. does not work when inspecting and pasting the code.
You can get these parameter list in ControllerContext.RoutValues object as key-value pair.
You can store it in some variable and you make use of that variable in your logic.
the effect that happens when you hit the space bar in a folder of documents, allowing you to preview them in a lightbox fashion
Looks like a classic lightbox plugin is needed. This is my favorite jQuery lightbox plugin: http://colorpowered.com/colorbox/. It's easy to customize, etc.
Get a reference to your input box however you like (eg document.getElementById('mytextbox')
) and set its readonly
property to true
:
myInputBox.readonly = true;
Alternatively you can simply add this property inline (no JavaScript needed):
<input type="text" value="from db" readonly="readonly" />
This just happened to me.
Solution: Pull down my own branch so I get that extra commit. Then push it back to my remote branch.
literally what I did on my branch was:
git pull
git push
You have one DateFormat
, but you need two: one for the input, and another for the output.
You've got one for the output, but I don't see anything that would match your input. When you give the input string to the output format, it's no surprise that you see that exception.
DateFormat inputDateFormat = new SimpleDateFormat("yyyy-MM-ddhh:mm:ss.SSS-Z");
For huge one-liners (prints characters from 1
to 99
):
cut -c 1-99 filename
I recently moved to a new PC all my eclipse projects. I experienced this issue. What i did was:
I respectually disagree with the notion that link extension methods should be side-effect free (not only because they aren't, any delegate can perform side effects).
Consider the following:
public class Element {}
public Enum ProcessType
{
This = 0, That = 1, SomethingElse = 2
}
public class Class1
{
private Dictionary<ProcessType, Action<Element>> actions =
new Dictionary<ProcessType,Action<Element>>();
public Class1()
{
actions.Add( ProcessType.This, DoThis );
actions.Add( ProcessType.That, DoThat );
actions.Add( ProcessType.SomethingElse, DoSomethingElse );
}
// Element actions:
// This example defines 3 distict actions
// that can be applied to individual elements,
// But for the sake of the argument, make
// no assumption about how many distict
// actions there may, and that there could
// possibly be many more.
public void DoThis( Element element )
{
// Do something to element
}
public void DoThat( Element element )
{
// Do something to element
}
public void DoSomethingElse( Element element )
{
// Do something to element
}
public void Apply( ProcessType processType, IEnumerable<Element> elements )
{
Action<Element> action = null;
if( ! actions.TryGetValue( processType, out action ) )
throw new ArgumentException("processType");
foreach( element in elements )
action(element);
}
}
What the example shows is really just a kind of late-binding that allows one invoke one of many possible actions having side-effects on a sequence of elements, without having to write a big switch construct to decode the value that defines the action and translate it into its corresponding method.
As @letitbee said, its best practice to assign primary keys to tables and properly define the relationships to allow for proper ORM querying. That being said...
If you're interested in writing a query along the lines of:
SELECT
user.email,
user.name,
document.name,
documents_permissions.readAllowed,
documents_permissions.writeAllowed
FROM
user, document, documents_permissions
WHERE
user.email = "[email protected]";
Then you should go for something like:
session.query(
User,
Document,
DocumentsPermissions
).filter(
User.email == Document.author
).filter(
Document.name == DocumentsPermissions.document
).filter(
User.email == "[email protected]"
).all()
If instead, you want to do something like:
SELECT 'all the columns'
FROM user
JOIN document ON document.author_id = user.id AND document.author == User.email
JOIN document_permissions ON document_permissions.document_id = document.id AND document_permissions.document = document.name
Then you should do something along the lines of:
session.query(
User
).join(
Document
).join(
DocumentsPermissions
).filter(
User.email == "[email protected]"
).all()
One note about that...
query.join(Address, User.id==Address.user_id) # explicit condition
query.join(User.addresses) # specify relationship from left to right
query.join(Address, User.addresses) # same, with explicit target
query.join('addresses') # same, using a string
For more information, visit the docs.
List.clear
would remove the elements without reducing the capacity of the list.
groovy:000> mylist = [1,2,3,4,5,6,7,8,9,10,11,12]
===> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
groovy:000> mylist.elementData.length
===> 12
groovy:000> mylist.elementData
===> [Ljava.lang.Object;@19d6af
groovy:000> mylist.clear()
===> null
groovy:000> mylist.elementData.length
===> 12
groovy:000> mylist.elementData
===> [Ljava.lang.Object;@19d6af
groovy:000> mylist = new ArrayList();
===> []
groovy:000> mylist.elementData
===> [Ljava.lang.Object;@2bfdff
groovy:000> mylist.elementData.length
===> 10
Here mylist got cleared, the references to the elements held by it got nulled out, but it keeps the same backing array. Then mylist was reinitialized and got a new backing array, the old one got GCed. So one way holds onto memory, the other one throws out its memory and gets reallocated from scratch (with the default capacity). Which is better depends on whether you want to reduce garbage-collection churn or minimize the current amount of unused memory. Whether the list sticks around long enough to be moved out of Eden might be a factor in deciding which is faster (because that might make garbage-collecting it more expensive).
this is how you can parse iCal files with javascript
function calParse(str) {
function parse() {
var obj = {};
while(str.length) {
var p = str.shift().split(":");
var k = p.shift(), p = p.join();
switch(k) {
case "BEGIN":
obj[p] = parse();
break;
case "END":
return obj;
default:
obj[k] = p;
}
}
return obj;
}
str = str.replace(/\n /g, " ").split("\n");
return parse().VCALENDAR;
}
example =
'BEGIN:VCALENDAR\n'+
'VERSION:2.0\n'+
'PRODID:-//hacksw/handcal//NONSGML v1.0//EN\n'+
'BEGIN:VEVENT\n'+
'DTSTART:19970714T170000Z\n'+
'DTEND:19970715T035959Z\n'+
'SUMMARY:Bastille Day Party\n'+
'END:VEVENT\n'+
'END:VCALENDAR\n'
cal = calParse(example);
alert(cal.VEVENT.SUMMARY);
I was getting this error too and the reason ended up being wrong call url. I am leaving this answer here, if someone else happens to mix the urls and getting this error. Took me hours to realize I had wrong URL.
Error I got (HTTP code 400):
{
"error": "unsupported_grant_type",
"error_description": "grant type not supported"
}
I was calling:
https://MY_INSTANCE.lightning.force.com
While the correct URL would have been:
Well, if you really want to return a mapping from _id
to user
, you could always do:
server.get('/usersList', function(req, res) {
User.find({}, function(err, users) {
var userMap = {};
users.forEach(function(user) {
userMap[user._id] = user;
});
res.send(userMap);
});
});
find()
returns all matching documents in an array, so your last code snipped sends that array to the client.
This was driving me bonkers as the .astype()
solution above didn't work for me. But I found another way. Haven't timed it or anything, but might work for others out there:
t1 = pd.to_datetime('1/1/2015 01:00')
t2 = pd.to_datetime('1/1/2015 03:30')
print pd.Timedelta(t2 - t1).seconds / 3600.0
...if you want hours. Or:
print pd.Timedelta(t2 - t1).seconds / 60.0
...if you want minutes.
SELECT TOP 5 Id, Name FROM customerNames
ORDER BY NEWID()
That said, everybody seems to come to this page for the more general answer to your question:
SELECT column FROM table
ORDER BY RAND()
LIMIT 1
SELECT column FROM table
ORDER BY RANDOM()
LIMIT 1
SELECT TOP 1 column FROM table
ORDER BY NEWID()
SELECT column, RAND() as IDX
FROM table
ORDER BY IDX FETCH FIRST 1 ROWS ONLY
SELECT column FROM
( SELECT column FROM table
ORDER BY dbms_random.value )
WHERE rownum = 1
SELECT column FROM table
ORDER BY RANDOM() LIMIT 1
At the time of writing this answer, there was no method to embed which let the user navigate inside folders and view the files without her leaving the website (the method in other answers, makes everything open in a new tab on google drive website), so I made my own tool for it. To embed a drive, paste the iframe code below in your HTML:
<iframe src="https://googledriveembedder.collegefam.com/?key=YOUR_API_KEY&folderid=FOLDER_ID_WHIHCH_IS_PUBLICLY_VIEWABLE" style="border:none;" width="100%"></iframe>
In the above code, you need to have your own API key and the folder ID. You can set the height as per your wish.
To get the API key:
1.) Go to https://console.developers.google.com/ Create a new project.
2.) From the menu button, go to 'APIs and Services' --> 'Dashboard' --> Click on 'Enable APIs and Services'.
3.) Search for 'Google Drive API', enable it. Then go to "credentials' tab, and create credentials. Keep your API key unrestricted.
4.) Copy the newly generated API key.
To get the folder ID:
1.)Go to the google drive folder you want to embed (for example, drive.google.com/drive/u/0/folders/1v7cGug_e3lNT0YjhvtYrwKV7dGY-Nyh5u [this is not a real folder]) Ensure that the folder is publicly shared and visible to anyone.
2.) Copy the part after 'folders/', this is your folder ID.
Now put both the API key and folder id in the above code and embed.
Note: To hide the download button for files, add '&allowdl=no' at the end of the iframe's src URL.
I made the widget keeping mobile users in mind, however it suits both mobile and desktop. If you run into issues, leave a comment here. I have attached some screenshots of the content of the iframe here.
Server side encoding files/Images to base64String ready for client side consumption
public Optional<String> InputStreamToBase64(Optional<InputStream> inputStream) throws IOException{
if (inputStream.isPresent()) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
FileCopyUtils.copy(inputStream.get(), output);
//TODO retrieve content type from file, & replace png below with it
return Optional.ofNullable("data:image/png;base64," + DatatypeConverter.printBase64Binary(output.toByteArray()));
}
return Optional.empty();
}
Server side base64 Image/File decoder
public Optional<InputStream> Base64InputStream(Optional<String> base64String)throws IOException {
if (base64String.isPresent()) {
return Optional.ofNullable(new ByteArrayInputStream(DatatypeConverter.parseBase64Binary(base64String.get())));
}
return Optional.empty();
}
To highlight a few points:
The docs recommend using an install environment: https://conda.io/docs/user-guide/install/download.html#choosing-a-version-of-anaconda-or-miniconda
The version archive is here: https://repo.continuum.io/archive/
The version history is here: https://docs.anaconda.com/anaconda/release-notes
"Anaconda3
then its python 3.x and if it is Anaconda2
then its 2.x" - +1 papbiceps
The version archive is sorted newest at the top, but Anaconda2
ABOVE Anaconda3
.
Wanted to give my contribution, as my regex cover all cases from OP and correctly group all relevant data on the group method (you don't need to post process the string to get each part of the uuid, this regex already get it for you)
([\d\w]{8})-?([\d\w]{4})-?([\d\w]{4})-?([\d\w]{4})-?([\d\w]{12})|[{0x]*([\d\w]{8})[0x, ]{4}([\d\w]{4})[0x, ]{4}([\d\w]{4})[0x, {]{5}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})[0x, ]{4}([\d\w]{2})
Has to be more complex test if you really want to handle just about anything as function argument.
type(a) != type('') and hasattr(a, "__iter__")
Although, usually it's enough to just spell out that a function expects iterable and then check only type(a) != type('')
.
Also it may happen that for a string you have a simple processing path or you are going to be nice and do a split etc., so you don't want to yell at strings and if someone sends you something weird, just let him have an exception.
Push object into your array. Try this:
export class FormComponent implements OnInit {
name: string;
empoloyeeID : number;
empList: Array<{name: string, empoloyeeID: number}> = [];
constructor() {}
ngOnInit() {}
onEmpCreate(){
console.log(this.name,this.empoloyeeID);
this.empList.push({ name: this.name, empoloyeeID: this.empoloyeeID });
this.name = "";
this.empoloyeeID = 0;
}
}
WHERE t.date >= DATE_ADD(CURDATE(), INTERVAL '-3' DAY);
use quotes on the -3 value
using eval function works just have to remove the forward slash at front and back.
var date1 = "/Date(25200000)/"
eval("new " + date1.substring(1, date1.length - 1));
yields Thu Jan 01 1970 00:00:00 GMT-0700 (US Mountain Standard Time)
Within a ServiceWorker
or Worker
, replace window
with self
:
self[method_prefix + method_name](arg1, arg2);
Workers have no access to the DOM, therefore window
is an invalid reference. The equivalent global scope identifier for this purpose is self
.
Check with your firewall expert. They open the firewall for PROD servers so there is no need to use the Proxy.
Thanks your tip helped me solve my problem:
Had to to set the Credentials in two locations to get past the 407 error:
HttpWebRequest webRequest = WebRequest.Create(uirTradeStream) as HttpWebRequest;
webRequest.Proxy = WebRequest.DefaultWebProxy;
webRequest.Credentials = new NetworkCredential("user", "password", "domain");
webRequest.Proxy.Credentials = new NetworkCredential("user", "password", "domain");
and voila!
Go language does not support method overloading, but you can use variadic args just like optional parameters, also you can use interface{} as parameter but it is not a good choice.
The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity
changes.
Instead you could try the following approach. Change your markup to the following:
<div ng-controller="myAppController" style="text-align:center">
<p style="font-size:28px;">Enter Quantity:
<input type="text" ng-model="quantity"/>
</p>
<button ng-click="calculateQuantity()">Calculate</button>
<h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>
Next, update your controller:
myAppModule.controller('myAppController', function($scope,calculateService) {
$scope.quantity=1;
$scope.quantityResult = 0;
$scope.calculateQuantity = function() {
$scope.quantityResult = calculateService.calculate($scope.quantity, 10);
};
});
Here's a JSBin example that demonstrates the above approach.
The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity
changes.
This would involve updating the template to add an ng-change
on the input, and an ng-if
on the result:
<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>
and
<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>
In the controller add:
$scope.showQuantityResult = false;
$scope.calculateQuantity = function() {
$scope.quantityResult = calculateService.calculate($scope.quantity, 10);
$scope.showQuantityResult = true;
};
$scope.hideQuantityResult = function() {
$scope.showQuantityResult = false;
};
These updates can be seen in this JSBin demo.
Had a similar problem (using NHibernate, so the ESCAPE keyword would have been very difficult) and solved it using the bracket characters. So your sample would become
WHERE ... LIKE '%aa[%]bb%'
If you need proof:
create table test (field nvarchar(100))
go
insert test values ('abcdef%hijklm')
insert test values ('abcdefghijklm')
go
select * from test where field like 'abcdef[%]hijklm'
go
You can use HttpServletRequest.getRequestURL and HttpServletRequest.getRequestURI.
StringBuffer url = request.getRequestURL();
String uri = request.getRequestURI();
int idx = (((uri != null) && (uri.length() > 0)) ? url.indexOf(uri) : url.length());
String host = url.substring(0, idx); //base url
idx = host.indexOf("://");
if(idx > 0) {
host = host.substring(idx); //remove scheme if present
}
If you want to parse date from "1996-12-19T16:39:57-08:00", use the following format "yyyy-MM-dd'T'HH:mm:ssZZZZZ":
let RFC3339DateFormatter = DateFormatter()
RFC3339DateFormatter.locale = Locale(identifier: "en_US_POSIX")
RFC3339DateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"
RFC3339DateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
/* 39 minutes and 57 seconds after the 16th hour of December 19th, 1996 with an offset of -08:00 from UTC (Pacific Standard Time) */
let string = "1996-12-19T16:39:57-08:00"
let date = RFC3339DateFormatter.date(from: string)
from Apple https://developer.apple.com/documentation/foundation/dateformatter
You cannot directly use a SQL statement in a PL/SQL expression:
SQL> begin
2 if (select count(*) from dual) >= 1 then
3 null;
4 end if;
5 end;
6 /
if (select count(*) from dual) >= 1 then
*
ERROR at line 2:
ORA-06550: line 2, column 6:
PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:
...
...
You must use a variable instead:
SQL> set serveroutput on
SQL>
SQL> declare
2 v_count number;
3 begin
4 select count(*) into v_count from dual;
5
6 if v_count >= 1 then
7 dbms_output.put_line('Pass');
8 end if;
9 end;
10 /
Pass
PL/SQL procedure successfully completed.
Of course, you may be able to do the whole thing in SQL:
update my_table
set x = y
where (select count(*) from other_table) >= 1;
It's difficult to prove that something is not possible. Other than the simple test case above, you can look at the syntax diagram for the IF
statement; you won't see a SELECT
statement in any of the branches.
As a oneliner guide:
minSdkVersion <= targetSdkVersion <= compileSdkVersion
Ideally:
minSdkVersion (lowest possible) <= targetSdkVersion == compileSdkVersion (latest SDK)
Selenium2Library has get_location():
import Selenium2Library
s = Selenium2Library.Selenium2Library()
url = s.get_location()
Try this:
import cv2
import cv
color_img = cv2.cvtColor(gray_img, cv.CV_GRAY2RGB)
I discovered, while using opencv, that some of the constants are defined in the cv2 module, and other in the cv module.
You can use ng-show on every div element in the loop. Is this what you've wanted: http://jsfiddle.net/pGwRu/2/ ?
<div class="from" ng-show="message.from">From: {{message.from.name}}</div>
Simple fix:
Targets -> Build Settings -> Build Options -> Enable Bitcode -> No
Works on device with iOS 9.3.3
count=0
with open ('filename.txt','rb') as f:
for line in f:
count+=1
print count
Drive letters can be used in the target like
scp some_file user@host:/c/temp
where c
is the drive letter. It's treated like a directory.
Maybe this works on the source, too.
The implicit make rule for compiling a C program is
%.o:%.c
$(CC) $(CPPFLAGS) $(CFLAGS) -c -o $@ $<
where the $()
syntax expands the variables. As both CPPFLAGS
and CFLAGS
are used in the compiler call, which you use to define include paths is a matter of personal taste. For instance if foo.c
is a file in the current directory
make foo.o CPPFLAGS="-I/usr/include"
make foo.o CFLAGS="-I/usr/include"
will both call your compiler in exactly the same way, namely
gcc -I/usr/include -c -o foo.o foo.c
The difference between the two comes into play when you have multiple languages which need the same include path, for instance if you have bar.cpp
then try
make bar.o CPPFLAGS="-I/usr/include"
make bar.o CFLAGS="-I/usr/include"
then the compilations will be
g++ -I/usr/include -c -o bar.o bar.cpp
g++ -c -o bar.o bar.cpp
as the C++ implicit rule also uses the CPPFLAGS
variable.
This difference gives you a good guide for which to use - if you want the flag to be used for all languages put it in CPPFLAGS
, if it's for a specific language put it in CFLAGS
, CXXFLAGS
etc. Examples of the latter type include standard compliance or warning flags - you wouldn't want to pass -std=c99
to your C++ compiler!
You might then end up with something like this in your makefile
CPPFLAGS=-I/usr/include
CFLAGS=-std=c99
CXXFLAGS=-Weffc++
$('#serialize').click(function () {_x000D_
$('#out').text(_x000D_
$('form').serialize()_x000D_
);_x000D_
});_x000D_
_x000D_
$('#exclude').change(function () {_x000D_
if ($(this).is(':checked')) {_x000D_
$('[name=age]').attr('form', 'fake-form-id');_x000D_
} else {_x000D_
$('[name=age]').removeAttr('form'); _x000D_
}_x000D_
_x000D_
$('#serialize').click();_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form action="/">_x000D_
<input type="text" value="John" name="name">_x000D_
<input type="number" value="100" name="age">_x000D_
</form>_x000D_
_x000D_
<input type="button" value="serialize" id="serialize">_x000D_
<label for="exclude"> _x000D_
<input type="checkbox" value="exclude age" id="exclude">_x000D_
exlude age_x000D_
</label>_x000D_
_x000D_
<pre id="out"></pre>
_x000D_
The java standard answer is often:
Before I go on, I have the latest version (v5.0.15) of OS X Server (yes, horrible, I know...however, the web server seems to work A-OK). I searched high and low for days trying to update (or at least get Apache to point to) a new version of PHP. My mcrypt
did not work, along with other extensions and I installed and reinstalled PHP countless times from http://php-osx.liip.ch/ and other tutorials until I finally noticed a tid-bit of information written in a comment in one of the many different .conf
files OS X Server keeps which was that OS X Server loads it's own custom .conf
file before it loads the Apache httpd.conf
(located at /etc/apache2/httpd.conf
). The server file is located:
/Library/Server/Web/Config/apache2/httpd_server_app.conf
When you open this file, you have to comment out this line like so:
#LoadModule php5_module libexec/apache2/libphp5.so
Then add in the correct path (which should already be installed if you have installed via the http://php-osx.liip.ch/ link):
LoadModule php5_module /usr/local/php5/libphp5.so
After this modification, my PHP finally loaded the correct PHP installation. That being said, if things go wonky, it may be because OS X is made to work off the native installation of PHP at the time of OS X installation. To revert, just undo the change above.
Anyway, hopefully this is helpful for anyone else spending countless hours on this.
Adam Luter gave me the idea for this, but it actually turned out to be really simple:
img {
width: 75px;
height: auto;
}
IE6 now scales the image fine and this seems to be what all the other browsers use by default.
Thanks for both the answers though!
You might want to learn vim because you might not be happy with the editors you're already using.
You might want to learn vim because many people say it is cool. Just look how many answers you've got to this question.
I will provide an additional reason for learning vim. It has a reputation for the quality and the completeness of its docs. So you will find most answers to your questions in its help system as soon as you will manage to stick the proper keywords in your help queries.
First, you need to compile your code with appropriate flags, enabling debug into code.
$ gcc -Wall -g -ggdb -o ex1 ex1.c
then just run you code with your favourite debugger
$ gdb ./ex1
show me the code.
(gdb) list
1 #include <stdio.h>
2 int main(void)
3 {
4 int i = 0;
5 for(i=0;i<7;++i)
6 printf("%d\n", i);
7
8 return 0;
9 }
break on lines 5 and looks if i == 5.
(gdb) b 5
Breakpoint 1 at 0x4004fb: file ex1.c, line 5.
(gdb) rwatch i if i==5
Hardware read watchpoint 5: i
checking breakpoints
(gdb) info b
Num Type Disp Enb Address What
1 breakpoint keep y 0x00000000004004fb in main at ex1.c:5
breakpoint already hit 1 time
5 read watchpoint keep y i
stop only if i==5
running the program
(gdb) c
Continuing.
0
1
2
3
4
Hardware read watchpoint 5: i
Value = 5
0x0000000000400523 in main () at ex1.c:5
5 for(i=0;i<7;++i)
m.put(null,null); // here key=null, value=null
m.put(null,a); // here also key=null, and value=a
Duplicate keys are not allowed in hashmap.
However,value can be duplicated.
It would appear as though this event has some clipboardData
property attached to it (it may be nested within the originalEvent
property). The clipboardData
contains an array of items and each one of those items has a getAsString()
function that you can call. This returns the string representation of what is in the item.
Those items also have a getAsFile()
function, as well as some others which are browser specific (e.g. in webkit browsers, there is a webkitGetAsEntry()
function).
For my purposes, I needed the string value of what is being pasted. So, I did something similar to this:
$(element).bind("paste", function (e) {
e.originalEvent.clipboardData.items[0].getAsString(function (pStringRepresentation) {
debugger;
// pStringRepresentation now contains the string representation of what was pasted.
// This does not include HTML or any markup. Essentially jQuery's $(element).text()
// function result.
});
});
You'll want to perform an iteration through the items, keeping a string concatenation result.
The fact that there is an array of items makes me think more work will need to be done, analyzing each item. You'll also want to do some null/value checks.
One risk of using the keyboard shortcut is that it requires using a non-ASCII encoding. That might be fine, but if your source is loaded by different editors in different locales, you might hit trouble somewhere along the line.
It might be safer to use either ’
or ’
(which are equivalent) as both are ASCII.
I have experienced that kind of issue before and now I'm not using header('Location: pageExample.php');
anymore, instead I'm using javascript's document.location
.
Change your:
header('Location: page1.php');
To something like this:
echo "<script type='text/javascript'> document.location = 'page1.php'; </script>";
And what is the purpose of echo $_POST['cancel'];
by the way?, just delete that line if what you want is just the redirection. I've been using that <script>
every time and it doesn't fail me. :-)
As the data you show are factors, it complicates things a little bit. @diliop's Answer approaches the problem by converting to nm
to a character variable. To get back to the original factors a further step is required.
An alternative is to manipulate the levels of the factor in place.
> lev <- with(junk, levels(nm))
> lev[lev == "B"] <- "b"
> junk2 <- within(junk, levels(nm) <- lev)
> junk2
nm val
1 A a
2 b b
3 C c
4 D d
5 A e
6 b f
7 C g
8 D h
9 A i
10 b j
11 C k
12 D l
That is quite simple and I often forget that there is a replacement function for levels()
.
Edit: As noted by @Seth in the comments, this can be done in a one-liner, without loss of clarity:
within(junk, levels(nm)[levels(nm) == "B"] <- "b")
For me, I had side-sync enabled and active. Closing it imediately made the issue go away. It might be worth closing this or any other communication between PC and device
Although this isn't an answer to the OP, I had the exact same error from a completely different root cause; so in case this helps anybody else...
The problem for me was an incorrectly named method parameter which caused WebAPI to route the request unexpectedly. I have the following methods in my ProgrammesController:
[HttpGet]
public Programme GetProgrammeById(int id)
{
...
}
[HttpDelete]
public bool DeleteProgramme(int programmeId)
{
...
}
DELETE requests to .../api/programmes/3 were not getting routed to DeleteProgramme as I expected, but to GetProgrammeById, because DeleteProgramme didn't have a parameter name of id. GetProgrammeById was then of course rejecting the DELETE as it is marked as only accepting GETs.
So the fix was simple:
[HttpDelete]
public bool DeleteProgramme(int id)
{
...
}
And all is well. Silly mistake really but hard to debug.
If you are using Hibernate its not possible to create an Entity without a primary key. This issues can create problem if you are working with an existing database which was created with plain sql/ddl scripts, and no primary key was added
just write in your Custom ArrayAdaper this code:
public void swapItems(ArrayList<Item> arrayList) {
this.clear();
this.addAll(arrayList);
}
In general, multiple inserts will be slower because of the connection overhead. Doing multiple inserts at once will reduce the cost of overhead per insert.
Depending on which language you are using, you can possibly create a batch in your programming/scripting language before going to the db and add each insert to the batch. Then you would be able to execute a large batch using one connect operation. Here's an example in Java.
The below code assumes that the variable 'str' contains your http://.... string. It checks to see if it is https and if true does nothing. However if it is http it replaces http with https.
if (str.indexOf('https') === -1) {
str = str.replace('http', 'https')
}
_x000D_
The difference is that std::make_shared
performs one heap-allocation, whereas calling the std::shared_ptr
constructor performs two.
std::shared_ptr
manages two entities:
std::make_shared
performs a single heap-allocation accounting for the space necessary for both the control block and the data. In the other case, new Obj("foo")
invokes a heap-allocation for the managed data and the std::shared_ptr
constructor performs another one for the control block.
For further information, check out the implementation notes at cppreference.
NOTE (2019/08/30): This is not a problem since C++17, due to the changes in the evaluation order of function arguments. Specifically, each argument to a function is required to fully execute before evaluation of other arguments.
Since the OP seem to be wondering about the exception-safety side of things, I've updated my answer.
Consider this example,
void F(const std::shared_ptr<Lhs> &lhs, const std::shared_ptr<Rhs> &rhs) { /* ... */ }
F(std::shared_ptr<Lhs>(new Lhs("foo")),
std::shared_ptr<Rhs>(new Rhs("bar")));
Because C++ allows arbitrary order of evaluation of subexpressions, one possible ordering is:
new Lhs("foo"))
new Rhs("bar"))
std::shared_ptr<Lhs>
std::shared_ptr<Rhs>
Now, suppose we get an exception thrown at step 2 (e.g., out of memory exception, Rhs
constructor threw some exception). We then lose memory allocated at step 1, since nothing will have had a chance to clean it up. The core of the problem here is that the raw pointer didn't get passed to the std::shared_ptr
constructor immediately.
One way to fix this is to do them on separate lines so that this arbitary ordering cannot occur.
auto lhs = std::shared_ptr<Lhs>(new Lhs("foo"));
auto rhs = std::shared_ptr<Rhs>(new Rhs("bar"));
F(lhs, rhs);
The preferred way to solve this of course is to use std::make_shared
instead.
F(std::make_shared<Lhs>("foo"), std::make_shared<Rhs>("bar"));
std::make_shared
Quoting Casey's comments:
Since there there's only one allocation, the pointee's memory cannot be deallocated until the control block is no longer in use. A
weak_ptr
can keep the control block alive indefinitely.
weak_ptr
s keep the control block alive?There must be a way for weak_ptr
s to determine if the managed object is still valid (eg. for lock
). They do this by checking the number of shared_ptr
s that own the managed object, which is stored in the control block. The result is that the control blocks are alive until the shared_ptr
count and the weak_ptr
count both hit 0.
std::make_shared
Since std::make_shared
makes a single heap-allocation for both the control block and the managed object, there is no way to free the memory for control block and the managed object independently. We must wait until we can free both the control block and the managed object, which happens to be until there are no shared_ptr
s or weak_ptr
s alive.
Suppose we instead performed two heap-allocations for the control block and the managed object via new
and shared_ptr
constructor. Then we free the memory for the managed object (maybe earlier) when there are no shared_ptr
s alive, and free the memory for the control block (maybe later) when there are no weak_ptr
s alive.
In Swift
let alertController = UIAlertController(title:"Title", message: "Message", preferredStyle:.alert)
let Action = UIAlertAction.init(title: "Ok", style: .default) { (UIAlertAction) in
// Write Your code Here
}
alertController.addAction(Action)
self.present(alertController, animated: true, completion: nil)
In Objective C
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"Title" message:@"Message" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *OK = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
{
}];
[alertController addAction:OK];
[self presentViewController:alertController animated:YES completion:nil];
It's because it's already null or undefined. Null or undefined does not have any type. You can check if it's is undefined first. In typescript (null == undefined)
is true.
if (uemail == undefined) {
alert('undefined');
} else {
alert('defined');
}
or
if (uemail == null) {
alert('undefined');
} else {
alert('defined');
}
use jquery : $("#id").css("background","red");
It's simple, you're just not in the right directory.
Go to the C:\Program Files\nodejs\node_modules\npm
and you should be able to run this command properly.
You could match the port numbers from wireshark up to port numbers from, say, netstat which will tell you the PID of a process listening on that port.
If you are using VS Code Insiders:
code-insiders .
If you are using VS Code:
code .
Make sure that st_new.sh does something at the end what you can recognize (like touch /tmp/st_new.tmp when you remove the file first and always start one instance of st_new.sh).
Then make a polling loop. First sleep the normal time you think you should wait,
and wait short time in every loop.
This will result in something like
max_retry=20
retry=0
sleep 10 # Minimum time for st_new.sh to finish
while [ ${retry} -lt ${max_retry} ]; do
if [ -f /tmp/st_new.tmp ]; then
break # call results.sh outside loop
else
(( retry = retry + 1 ))
sleep 1
fi
done
if [ -f /tmp/st_new.tmp ]; then
source ../../results.sh
rm -f /tmp/st_new.tmp
else
echo Something wrong with st_new.sh
fi
By this way you can print it in pretty way for example your dictionary name is yasin
import json
print (json.dumps(yasin, indent=2))
or, safer:
print (json.dumps(yasin, indent=2, default=str))
Click on Wamp icon and open Apache/httpd.conf and search "#LoadModule rewrite_module modules/mod_rewrite.so". Remove # as below and save it
LoadModule rewrite_module modules/mod_rewrite.so
and restart all service.
The clear
property indicates that the left, right or both sides of an element can not be adjacent to earlier floated elements within the same block formatting context. Cleared elements are pushed below the corresponding floated elements. Examples:
clear: none;
Element remains adjacent to floated elementsbody {_x000D_
font-family: monospace;_x000D_
background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
float: left;_x000D_
width: 60px;_x000D_
height: 60px;_x000D_
background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
float: right;_x000D_
width: 60px;_x000D_
height: 60px;_x000D_
background: #CEF;_x000D_
}_x000D_
.clear-none {_x000D_
clear: none;_x000D_
background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-none">clear: none;</div>
_x000D_
clear: left;
Element pushed below left floated elementsbody {_x000D_
font-family: monospace;_x000D_
background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
float: left;_x000D_
width: 60px;_x000D_
height: 60px;_x000D_
background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
float: right;_x000D_
width: 60px;_x000D_
height: 120px;_x000D_
background: #CEF;_x000D_
}_x000D_
.clear-left {_x000D_
clear: left;_x000D_
background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-left">clear: left;</div>
_x000D_
clear: right;
Element pushed below right floated elementsbody {_x000D_
font-family: monospace;_x000D_
background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
float: left;_x000D_
width: 60px;_x000D_
height: 120px;_x000D_
background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
float: right;_x000D_
width: 60px;_x000D_
height: 60px;_x000D_
background: #CEF;_x000D_
}_x000D_
.clear-right {_x000D_
clear: right;_x000D_
background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-right">clear: right;</div>
_x000D_
clear: both;
Element pushed below all floated elementsbody {_x000D_
font-family: monospace;_x000D_
background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
float: left;_x000D_
width: 60px;_x000D_
height: 60px;_x000D_
background: #CEF;_x000D_
}_x000D_
.float-right {_x000D_
float: right;_x000D_
width: 60px;_x000D_
height: 60px;_x000D_
background: #CEF;_x000D_
}_x000D_
.clear-both {_x000D_
clear: both;_x000D_
background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="float-right">float: right;</div>_x000D_
<div class="clear-both">clear: both;</div>
_x000D_
clear
does not affect floats outside the current block formatting contextbody {_x000D_
font-family: monospace;_x000D_
background: #EEE;_x000D_
}_x000D_
.float-left {_x000D_
float: left;_x000D_
width: 60px;_x000D_
height: 120px;_x000D_
background: #CEF;_x000D_
}_x000D_
.inline-block {_x000D_
display: inline-block;_x000D_
background: #BDF;_x000D_
}_x000D_
.inline-block .float-left {_x000D_
height: 60px;_x000D_
}_x000D_
.clear-both {_x000D_
clear: both;_x000D_
background: #FFF;_x000D_
}
_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="inline-block">_x000D_
<div>display: inline-block;</div>_x000D_
<div class="float-left">float: left;</div>_x000D_
<div class="clear-both">clear: both;</div>_x000D_
</div>
_x000D_
Outside of the direct answers here, one should note the other key difference between python 2 and 3. The official python wiki goes into almost all of the major differences and focuses on when you should use either of the versions. This blog post also does a fine job of explaining the current python universe and the somehow unsolved puzzle of moving to python 3.
As far as I can tell, you are beginning to learn the python language. You should consider the aforementioned articles before you continue down the python 3 route. Not only will you have to change some of your syntax, you will also need to think about which packages will be available to you (an advantage of python 2) and potential optimizations that could be made in your code (an advantage of python 3).
since openssl v1.1.0
C:\openssl>openssl version
OpenSSL 1.1.0g 2 Nov 2017
C:\openssl>openssl s_client -proxy 192.168.103.115:3128 -connect www.google.com -CAfile C:\TEMP\internalCA.crt
CONNECTED(00000088)
depth=2 DC = com, DC = xxxx, CN = xxxx CA interne
verify return:1
depth=1 C = FR, L = CROIX, CN = svproxysg1, emailAddress = [email protected]
verify return:1
depth=0 C = US, ST = California, L = Mountain View, O = Google Inc, CN = www.google.com
verify return:1
---
Certificate chain
0 s:/C=US/ST=California/L=Mountain View/O=Google Inc/CN=www.google.com
i:/C=xxxx/L=xxxx/CN=svproxysg1/[email protected]
1 s:/C=xxxx/L=xxxx/CN=svproxysg1/[email protected]
i:/DC=com/DC=xxxxx/CN=xxxxx CA interne
---
Server certificate
-----BEGIN CERTIFICATE-----
MIIDkTCCAnmgAwIBAgIJAIv4/hQAAAAAMA0GCSqGSIb3DQEBCwUAMFIxCzAJBgNV
BAYTAkZSMQ4wDAYDVQQHEwVDUk9JWDETMBEGA1UEAxMKc3Zwcm94eXNnMTEeMBwG
A more-advanced example:
? unlimited arguments.
? exist on file system (either
file
ordirectory
?) or a genericstring
.? specify if is a file
? specify is a directory
? no extensions, would work in legacy scripts!
? minimal code ?
@echo off :loop ::-------------------------- has argument ? if ["%~1"]==[""] ( echo done. goto end ) ::-------------------------- argument exist ? if not exist %~s1 ( echo not exist ) else ( echo exist if exist %~s1\NUL ( echo is a directory ) else ( echo is a file ) ) ::-------------------------- shift goto loop :end pause
? other stuff..?
¦ in %~1
- the ~
removes any wrapping "
or '
.
¦ in %~s1
- the s
makes the path be DOS 8.3 naming
, which is a nice trick to avoid spaces in file-name while checking stuff (and this way no need to wrap the resource with more "
s.
¦ the ["%~1"]==[""]
"can not be sure" if the argument is a file/directory or just a generic string yet, so instead the expression uses brackets and the original unmodified %1
(just without the "
wrapping, if any..)
if there were no arguments of if we've used shift
and the arg-list pointer has passed the last one, the expression will be evaluated to [""]==[""]
.
¦ this is as much specific you can be without using more tricks (it would work even in windows-95's batch-scripts...)
save it as identifier.cmd
it can identify an unlimited arguments (normally you are limited to %1
-%9
), just remember to wrap the arguments with inverted-commas, or use 8.3 naming, or drag&drop them over (it automatically does either of above).
this allows you to run the following commands:
?identifier.cmd c:\windows
and to get
exist is a directory done
?identifier.cmd "c:\Program Files (x86)\Microsoft Office\OFFICE11\WINWORD.EXE"
and to get
exist is a file done
? and multiple arguments (of course this is the whole-deal..)
identifier.cmd c:\windows\system32 c:\hiberfil.sys "c:\pagefile.sys" hello-world
and to get
exist is a directory exist is a file exist is a file not exist done.
naturally it can be a lot more complex, but nice examples should always be simple and minimal. :)
published here:CMD Ninja - Unlimited Arguments Processing, Identifying If Exist In File-System, Identifying If File Or Directory
and here is a working example that takes any amount of APK files (Android apps) and installs them on your device via debug-console (ADB.exe): Make The Previous Post A Mass APK Installer That Does Not Uses ADB Install-Multi Syntax
go to your website via FTP/Cpanel
, find maintenance.flag
and remove
SELECT DISTINCT groups.id,
(SELECT COUNT(*) FROM group_members
WHERE member_id = groups.id) AS memberCount
FROM groups
HTML div
elements, unlike SVG circle
primitives, are always rectangular.
You could use round corners (i.e. CSS border-radius
) to make it look round. On square elements, a value of 50% naturally forms a circle. Use this, or even a SVG inside your HTML:
document.body.innerHTML+='<i></i>'.repeat(4);
_x000D_
i{border-radius:50%;display:inline-block;background:#F48024;}
svg {fill:#F48024;width:60px;height:60px;}
i:nth-of-type(1n){width:30px;height:30px;}
i:nth-of-type(2n){width:60px;height:60px;}
_x000D_
<svg viewBox="0 0 120 120" xmlns="http://www.w3.org/2000/svg">
<circle cx="60" cy="60" r="60"/>
</svg>
_x000D_
I'm going to pile on. I solved this with a simple line of code. My command line arguments look like this:
input--hdfs:/path/to/myData/part-00199.avro output--hdfs:/path/toWrite/Data fileFormat--avro option1--5
This creates an array via Scala's native command line functionality (from either App or a main method):
Array("input--hdfs:/path/to/myData/part-00199.avro", "output--hdfs:/path/toWrite/Data","fileFormat--avro","option1--5")
I can then use this line to parse out the default args array:
val nArgs = args.map(x=>x.split("--")).map(y=>(y(0),y(1))).toMap
Which creates a map with names associated with the command line values:
Map(input -> hdfs:/path/to/myData/part-00199.avro, output -> hdfs:/path/toWrite/Data, fileFormat -> avro, option1 -> 5)
I can then access the values of named parameters in my code and the order they appear on the command line is no longer relevant. I realize this is fairly simple and doesn't have all the advanced functionality mentioned above but seems to be sufficient in most cases, only needs one line of code, and doesn't involve external dependencies.
Atomic means only one thread accesses the variable (static type). Atomic is thread-safe, but it is slow.
Nonatomic means multiple threads access the variable (dynamic type). Nonatomic is thread-unsafe, but it is fast.
The easiest way I've found to do this is to write in markdown right from the start of the line. Press Ctrl+D
(shortcut for opening the markup input dialog) and type markdown. The normal wiki editor doesn't seem to be very good for precise formatting. It doesn't seem to know much about character styles and only knows paragraph styles.
go to tsconfig.json and comment the line the //strict:true this worked for me
For Fiddler to capture traffic from localhost on local IIS, there are 3 steps (It worked on my computer):
@Jason S:
You can use slice! You just have to make sure you know how to use it. Positive #s are relative to the beginning, negative numbers are relative to the end.
js>"12345.00".slice(0,-1) 12345.0
Sorry for my graphomany but post was tagged 'jquery' earlier. So, you can't use slice() inside jQuery because slice() is jQuery method for operations with DOM elements, not substrings ... In other words answer @Jon Erickson suggest really perfect solution.
However, your method will works out of jQuery function, inside simple Javascript. Need to say due to last discussion in comments, that jQuery is very much more often renewable extension of JS than his own parent most known ECMAScript.
Here also exist two methods:
as our:
string.substring(from,to)
as plus if 'to' index nulled returns the rest of string. so:
string.substring(from)
positive or negative ...
and some other - substr() - which provide range of substring and 'length' can be positive only:
string.substr(start,length)
Also some maintainers suggest that last method string.substr(start,length)
do not works or work with error for MSIE.
This works in MySQL all versions and Amazon RDS Aurora:
INSERT INTO my_table SELECT 0,tmp.* FROM tmp;
or
Setting the index column to NULL and then doing the INSERT.
But not in MariaDB, I tested version 10.
I, for example, use fail()
to indicate tests that are not yet finished (it happens); otherwise, they would show as successful.
This is perhaps due to the fact that I am unaware of some sort of incomplete() functionality, which exists in NUnit.
use this URL : "https://twitter.com/(userName)/profile_image?size=original"
If you are using TWitter SDK you can get the user name when logged in, with TWTRAPIClient
, using TWTRAuthSession
.
This is the code snipe for iOS:
if let twitterId = session.userID{
let twitterClient = TWTRAPIClient(userID: twitterId)
twitterClient.loadUser(withID: twitterId) {(user, error) in
if let userName = user?.screenName{
let url = "https://twitter.com/\(userName)/profile_image?size=original")
}
}
}
.cont{_x000D_
height: 100px;_x000D_
overflow-x: hidden;_x000D_
overflow-y: auto;_x000D_
transform: rotate(180deg);_x000D_
direction:rtl;_x000D_
text-align:left;_x000D_
}_x000D_
ul{_x000D_
overflow: hidden;_x000D_
transform: rotate(180deg);_x000D_
}
_x000D_
<div class="cont"> _x000D_
<ul>_x000D_
<li>0</li>_x000D_
<li>1</li>_x000D_
<li>2</li>_x000D_
<li>3</li>_x000D_
<li>4</li>_x000D_
<li>5</li>_x000D_
<li>6</li>_x000D_
<li>7</li>_x000D_
<li>8</li>_x000D_
<li>9</li>_x000D_
<li>10</li> _x000D_
</ul>_x000D_
</div>
_x000D_
Run code snippet
to see the effect. (PS: If Run code snippet
is not working, try this: https://jsfiddle.net/Yeshen/xm2yLksu/3/ )
How it work:
Default overflow is scroll from top to bottom.
transform: rotate(180deg)
can make it scroll or load dynamic block from bottom to top.
Here is my simple code FormData with react-native to post request with string and image.
I have used react-native-image-picker to capture/select photo react-native-image-picker
let photo = { uri: source.uri}
let formdata = new FormData();
formdata.append("product[name]", 'test')
formdata.append("product[price]", 10)
formdata.append("product[category_ids][]", 2)
formdata.append("product[description]", '12dsadadsa')
formdata.append("product[images_attributes[0][file]]", {uri: photo.uri, name: 'image.jpg', type: 'image/jpeg'})
NOTE you can change image/jpeg
to other content type. You can get content type from image picker response.
fetch('http://192.168.1.101:3000/products',{
method: 'post',
headers: {
'Content-Type': 'multipart/form-data',
},
body: formdata
}).then(response => {
console.log("image uploaded")
}).catch(err => {
console.log(err)
})
});
If you get the above problem on windows server 2008 you may need to enable ASP. To do so, follow these steps:
Add an 'Application Server' role:
Then, add a 'Web Server' role:
use 'https-proxy-agent' like this
var HttpsProxyAgent = require('https-proxy-agent');
var proxy = process.env.https_proxy || 'other proxy address';
var agent = new HttpsProxyAgent(proxy);
options = {
//...
agent : agent
}
https.get(options, (res)=>{...});
another way to access a column by number is to use a mapping dictionary where the key is the column name and the value is the column number
dates = pd.date_range('1/1/2000', periods=8)
df = pd.DataFrame(np.random.randn(8, 4),
index=dates, columns=['A', 'B', 'C', 'D'])
print(df)
dct={'A':0,'B':1,'C':2,'D':3}
columns=df.columns
print(df.iloc[:,dct['D']])
DialogFragment has a public getTheme() method that you can over ride for this exact reason. This solution uses less lines of code:
public class MyCustomDialogFragment extends DialogFragment{
...
@Override
public int getTheme() {
return R.style.MyThemeWithCustomAnimation;
}
}
It means that your jQuery library has not been loaded yet.
You can move your code after pulling jQuery library.
or you can use something like this
window.onload = function(){
// Your code here
};
By default is private
. Unless they're nested, classes are internal
.
int i = 100;// explicitly typed
var j = 100; // implicitly typed
You should learn Redux and ReactRedux library.It will structure your states and props in one store and you can access them later in your components .
In application.properties, please add this:
spring.servlet.multipart.max-file-size=128KB
spring.servlet.multipart.max-request-size=128KB
spring.http.multipart.enabled=false
and in your html form, you need an : enctype="multipart/form-data"
.
For example:
<form method="POST" enctype="multipart/form-data" action="/">
Hope this help!
That is a C++ standard library header file for input output streams. It includes functionality to read and write from streams. You only need to include it if you wish to use streams.
You can get the current page, post, or custom post type with the global variable $post
:
echo $post->post_title
Note: In a function or class you'll need to specify global $post;
prior to trying to use $post
.
If you have loops on your page, make sure you end each loop with wp_reset_postdata();
to set $post
back to the default item being displayed (the page).
Note, the 'post_title' variable is also available for any custom loop / query... including menu items and media attachments... everything in WordPress is a 'post'.
Because you're returning from the first method call, the second doesn't execute.
Try something like
OnClientClick="var b = validateView();ShowDiv1(); return b"
or reverse the situation,
OnClientClick="ShowDiv1();return validateView();"
or if there is a dependency of div1 on the validation routine.
OnClientClick="var b = validateView(); if (b) ShowDiv1(); return b"
What might be best is to encapsulate multiple inline statements into a mini function like so, to simplify the call:
// change logic to suit taste
function clicked() {
var b = validateView();
if (b)
ShowDiv1()
return b;
}
and then
OnClientClick="return clicked();"