simply add "classpath 'com.google.gms:google-services:3.0.0'" to android/build.gradle to look like this
buildscript {
repositories {
maven {
url "https://maven.google.com"
}
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
classpath 'com.google.gms:google-services:3.0.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
and also add "apply plugin: 'com.google.gms.google-services'" to the end of file in android/app/build.gradle to look like this
apply plugin: 'com.google.gms.google-services'
In [56]: df = pd.DataFrame(np.abs(randn(3, 4)), index=[1,2,3], columns=['A','B','C','D'])
In [57]: df.divide(df.sum(axis=1), axis=0)
Out[57]:
A B C D
1 0.319124 0.296653 0.138206 0.246017
2 0.376994 0.326481 0.230464 0.066062
3 0.036134 0.192954 0.430341 0.340571
Well, looking at the :help columns, it's not really being made to mess with.
In console, it's usually determined by console setting (i.e. it's detected automatically) ; in GUI, it determines (and is determined by) the width of the gvim windows.
So normally you just let consoles and window managers doing their jobs by commented out the set columns
I am not sure what you mean by "see and anticipate line overflow".
If you want EOL to be inserted roughly column 80, use either set textwidth
or set wrapmargin
; if you just want soft wrap (i.e. line is wrapped, but no actual EOL), then play with set linebreak
and set showbreak
.
With Spring 3.0 you can use the HttpEntity
return object. If you use this, then your controller does not need a HttpServletResponse
object, and therefore it is easier to test.
Except this, this answer is relative equals to the one of Infeligo.
If the return value of your pdf framework is an byte array (read the second part of my answer for other return values) :
@RequestMapping(value = "/files/{fileName}", method = RequestMethod.GET)
public HttpEntity<byte[]> createPdf(
@PathVariable("fileName") String fileName) throws IOException {
byte[] documentBody = this.pdfFramework.createPdf(filename);
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_PDF);
header.set(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=" + fileName.replace(" ", "_"));
header.setContentLength(documentBody.length);
return new HttpEntity<byte[]>(documentBody, header);
}
If the return type of your PDF Framework (documentBbody
) is not already a byte array (and also no ByteArrayInputStream
) then it would been wise NOT to make it a byte array first. Instead it is better to use:
InputStreamResource
,PathResource
(since Spring 4.0) orFileSystemResource
, example with FileSystemResource
:
@RequestMapping(value = "/files/{fileName}", method = RequestMethod.GET)
public HttpEntity<byte[]> createPdf(
@PathVariable("fileName") String fileName) throws IOException {
File document = this.pdfFramework.createPdf(filename);
HttpHeaders header = new HttpHeaders();
header.setContentType(MediaType.APPLICATION_PDF);
header.set(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=" + fileName.replace(" ", "_"));
header.setContentLength(document.length());
return new HttpEntity<byte[]>(new FileSystemResource(document),
header);
}
Wow, there are a lot of examples here. I am providing one that does some error handling. It rebuilds and returns the entire URL with the query-string-param-to-be-removed, removed. It also provides a bonus function that builds the current URL on the fly. Tested, works!
Credit to Mark B for the steps. This is a complete solution to tpow's "strip off this return parameter" original question -- might be handy for beginners, trying to avoid PHP gotchas. :-)
<?php
function currenturl_without_queryparam( $queryparamkey ) {
$current_url = current_url();
$parsed_url = parse_url( $current_url );
if( array_key_exists( 'query', $parsed_url )) {
$query_portion = $parsed_url['query'];
} else {
return $current_url;
}
parse_str( $query_portion, $query_array );
if( array_key_exists( $queryparamkey , $query_array ) ) {
unset( $query_array[$queryparamkey] );
$q = ( count( $query_array ) === 0 ) ? '' : '?';
return $parsed_url['scheme'] . '://' . $parsed_url['host'] . $parsed_url['path'] . $q . http_build_query( $query_array );
} else {
return $current_url;
}
}
function current_url() {
$current_url = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
return $current_url;
}
echo currenturl_without_queryparam( 'key' );
?>
You can notify your users that there is a new version of the current app available to update. Also, if this condition is true, you can block login in the app.
Please see if this provides you the solution.
I used the code snippet from Vijay Singh Rana which basically does the job. But it causes problems if the firstString
does already contain the lastString
. What I wanted was extracting a access_token from a JSON Response (no JSON Parser loaded). My firstString
was \"access_token\": \"
and my lastString
was \"
. I ended up with a little modification
string Between(string str, string firstString, string lastString)
{
int pos1 = str.IndexOf(firstString) + firstString.Length;
int pos2 = str.Substring(pos1).IndexOf(lastString);
return str.Substring(pos1, pos2);
}
I had the same problem. I called my own custom logger in the log4j.properties file from code when using log4j api directly. If you are using the slf4j api calls, you are probably using the default root logger so you must configure that to be associated with an appender in the log4j.properties:
# Set root logger level to DEBUG and its only appender to A1. log4j.rootLogger=DEBUG, A1 # A1 is set to be a ConsoleAppender. log4j.appender.A1=org.apache.log4j.ConsoleAppender
Reader they show at http://www.webqr.com/index.html works like a charm, but literaly, you need the one on the webpage, the github version it's really hard to make it work, however, it is possible. The best way to go is reverse-engineer the example shown at the webpage.
However, to edit and get the full potential out of it, it's not so easy. At some point I may post the stripped-down reverse-engineered QR reader, but in the meantime have some fun hacking the code.
Happy coding.
for windows users download open ssl from google's code repository https://code.google.com/p/openssl-for-windows/downloads/list
After the download, extract the contents to a folder preferably in your c: drive.
Then update your PATH environment variable so you can use the .exe from any location in your command line.
[windows 8] To update your PATH environment variable, click my computer->properties->Advanced System Settings.
Click the Advanced Tab and click the 'Environment Variable' button at the bottom of the dialog then select the Path entry from the 'System Variables' Section by clicking edit.
Paste the path to the bin folder of the extracted openssl download and click ok.
You will need to close and open and command prompt you may have previously launched so that you can load the updated path settings.
Now run this command:
keytool -exportcert -alias androiddebugkey -keystore "C:\Users\Oladipo.android\debug.keystore" | openssl sha1 -binary | openssl base64
You should see the developer key.
Yes, you can delete data from iOS device support by the symbols of the operating system, one for each version for each architecture. It's used for debugging. If you don't need to support those devices any more, you can delete the directory without ill effect
Why is this blocked by Java?
You'd have to ask the Java designers. There might be some subtle grammatical reason for the restriction. Note that some of the array creation / initialization constructs were not in Java 1.0, and (IIRC) were added in Java 1.1.
But "why" is immaterial ... the restriction is there, and you have to live with it.
I know how to work around it, but from time to time it would be simpler.
You can write this:
AClass[] array;
...
array = new AClass[]{object1, object2};
You can convert an object to array simply by using the following:
You can convert the object values to an array:
myObject = { 'a': 1, 'b': 2, 'c': 3 };
let valuesArray = Object.values(myObject);
console.log(valuesArray);
_x000D_
You can convert the object keys to an array:
myObject = { 'a': 1, 'b': 2, 'c': 3 };
let keysArray = Object.keys(myObject);
console.log(keysArray);
_x000D_
Now you can perform normal array operations, including the 'map' function
This will render depending components 3 times (arrays with equal elements aren't equal):
const [msg, setMsg] = useState([""])
setMsg(["test"])
setMsg(["test"])
setMsg(["test"])
I've started my own project, called syncProj. Documentation / download links from here:
https://docs.google.com/document/d/1C1YrbFUVpTBXajbtrC62aXru2om6dy5rClyknBj5zHU/edit# https://sourceforge.net/projects/syncproj/
If you're planning to use Visual studio for development, and currently only C++ is supported.
Main advantage compared to other make systems is that you can actually debug your script, as it's C# based.
If you're not familiar with syncProj, you can just convert your solution / project to .cs script, and continue further development from that point on.
In cmake you will need to write everything from scratch.
/******************
Fit the body to the edges of the screen
******************/
body {
margin:0;
padding:0;
}
header {
background:black;
width:100%;
}
.header {
height:200px;
}
nav {
width:100%;
background:lightseagreen;
}
.nav {
padding:0;
margin:0;
}
.nav a {
padding:10px;
font-family:tahoma;
font-size:12pt;
color:white;
}
/******************
Centered wrapper, all other content divs will go inside this and will never exceed the width of 960px.
******************/
.wrapper {
width:960px;
max-width:100%;
margin:0 auto;
}
<!-------- Start HTML ---------->
<body>
<header>
<div id="header" class="wrapper">
</div>
</header>
<nav>
<div id="nav" class="wrapper">
</div>
</nav>
</body>
In this article, under the title "Using form input for selecting"
http://www.html5rocks.com/en/tutorials/file/dndfiles/
<input type="file" id="files" name="files[]" multiple />
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// files is a FileList of File objects. List some properties.
var output = [];
for (var i = 0, f; f = files[i]; i++) {
// Code to execute for every file selected
}
// Code to execute after that
}
document.getElementById('files').addEventListener('change',
handleFileSelect,
false);
</script>
It adds an event listener to 'change', but I tested it and it triggers even if you choose the same file and not if you cancel.
I've created an example to show how to. Updated state
definition would be:
$stateProvider
.state('home', {
url: '/:foo?bar',
views: {
'': {
templateUrl: 'tpl.home.html',
controller: 'MainRootCtrl'
},
...
}
And this would be the controller:
.controller('MainRootCtrl', function($scope, $state, $stateParams) {
//..
var foo = $stateParams.foo; //getting fooVal
var bar = $stateParams.bar; //getting barVal
//..
$scope.state = $state.current
$scope.params = $stateParams;
})
What we can see is that the state home now has url defined as:
url: '/:foo?bar',
which means, that the params in url are expected as
/fooVal?bar=barValue
These two links will correctly pass arguments into the controller:
<a ui-sref="home({foo: 'fooVal1', bar: 'barVal1'})">
<a ui-sref="home({foo: 'fooVal2', bar: 'barVal2'})">
Also, the controller does consume $stateParams
instead of $stateParam
.
Link to doc:
You can check it here
params : {}
There is also new, more granular setting params : {}
. As we've already seen, we can declare parameters as part of url
. But with params : {}
configuration - we can extend this definition or even introduce paramters which are not part of the url:
.state('other', {
url: '/other/:foo?bar',
params: {
// here we define default value for foo
// we also set squash to false, to force injecting
// even the default value into url
foo: {
value: 'defaultValue',
squash: false,
},
// this parameter is now array
// we can pass more items, and expect them as []
bar : {
array : true,
},
// this param is not part of url
// it could be passed with $state.go or ui-sref
hiddenParam: 'YES',
},
...
Settings available for params are described in the documentation of the $stateProvider
Below is just an extract
We can call these params this way:
// hidden param cannot be passed via url
<a href="#/other/fooVal?bar=1&bar=2">
// default foo is skipped
<a ui-sref="other({bar: [4,5]})">
Check it in action here
Well getheight gets the height, and getwidth gets the width. But you're calling those methods too soon. If you're calling them in oncreate or onresume, the view isn't drawn yet. You have to call it after the view has been drawn.
You need to use Integer.parseInt(String)
private void jTextField2MouseClicked(java.awt.event.MouseEvent evt) {
if(evt.getSource()==jTextField2){
int jml = Integer.parseInt(jTextField3.getText());
jTextField1.setText(numberToWord(jml));
}
}
Say your model is 'Shop'
class Shop(models.Model):
street = models.CharField(max_length=150)
city = models.CharField(max_length=150)
# some of your models may have explicit ordering
class Meta:
ordering = ('city')
Since you may have the Meta
class ordering
attribute set, you can use order_by()
without parameters to clear any ordering when using distinct()
. See the documentation under order_by
()
If you don’t want any ordering to be applied to a query, not even the default ordering, call order_by() with no parameters.
and distinct()
in the note where it discusses issues with using distinct()
with ordering.
To query your DB, you just have to call:
models.Shop.objects.order_by().values('city').distinct()
It returns a dictionnary
or
models.Shop.objects.order_by().values_list('city').distinct()
This one returns a ValuesListQuerySet
which you can cast to a list
.
You can also add flat=True
to values_list
to flatten the results.
See also: Get distinct values of Queryset by field
There is no need to use any plugin, you can do it like this:
var divPosition = $('#divId').offset();
then use this to scroll document to specific DOM:
$('html, body').animate({scrollTop: divPosition.top}, "slow");
Your problem arises from the fact that $i
has a blank value when your statement fails. Always quote your variables when performing comparisons if there is the slightest chance that one of them may be empty, e.g.:
if [ "$i" -ge 2 ] ; then
...
fi
This is because of how the shell treats variables. Assume the original example,
if [ $i -ge 2 ] ; then ...
The first thing that the shell does when executing that particular line of code is substitute the value of $i
, just like your favorite editor's search & replace function would. So assume that $i
is empty or, even more illustrative, assume that $i
is a bunch of spaces! The shell will replace $i
as follows:
if [ -ge 2 ] ; then ...
Now that variable substitutions are done, the shell proceeds with the comparison and.... fails because it cannot see anything intelligible to the left of -gt
. However, quoting $i
:
if [ "$i" -ge 2 ] ; then ...
becomes:
if [ " " -ge 2 ] ; then ...
The shell now sees the double-quotes, and knows that you are actually comparing four blanks to 2 and will skip the if
.
You also have the option of specifying a default value for $i
if $i
is blank, as follows:
if [ "${i:-0}" -ge 2 ] ; then ...
This will substitute the value 0 instead of $i
is $i
is undefined. I still maintain the quotes because, again, if $i
is a bunch of blanks then it does not count as undefined, it will not be replaced with 0, and you will run into the problem once again.
Please read this when you have the time. The shell is treated like a black box by many, but it operates with very few and very simple rules - once you are aware of what those rules are (one of them being how variables work in the shell, as explained above) the shell will have no more secrets for you.
Page Control can be contained in Window Control but vice versa is not possible
You can use Page control within the Window control using NavigationWindow and Frame controls. Window is the root control that must be used to hold/host other controls (e.g. Button) as container. Page is a control which can be hosted in other container controls like NavigationWindow or Frame. Page control has its own goal to serve like other controls (e.g. Button). Page is to create browser like applications. So if you host Page in NavigationWindow, you will get the navigation implementation built-in. Pages are intended for use in Navigation applications (usually with Back and Forward buttons, e.g. Internet Explorer).
WPF provides support for browser style navigation inside standalone application using Page class. User can create multiple pages, navigate between those pages along with data.There are multiple ways available to Navigate through one page to another page.
In our case it was an empty AndroidManifest.xml.
While upgrading Eclispe we ran into the usual trouble, and AndroidManifest.xml must have been checked into SVN by the build script after being clobbered.
Found it by compiling from inside Eclipse, instead of from the command line.
You can perform the following T-SQL command:
SELECT * FROM sys.dm_exec_sessions WHERE status = 'running';
To use unsafe code blocks, open the properties for the project, go to the Build tab and check the Allow unsafe code checkbox, then compile and run.
class myclass
{
public static void Main(string[] args)
{
unsafe
{
int iData = 10;
int* pData = &iData;
Console.WriteLine("Data is " + iData);
Console.WriteLine("Address is " + (int)pData);
}
}
}
Output:
Data is 10
Address is 1831848
I worked quite a long time with Flux and now quite a long time using Redux. As Dan pointed out both architectures are not so different. The thing is that Redux makes the things simpler and cleaner. It teaches you a couple of things on top of Flux. Like for example Flux is a perfect example of one-direction data flow. Separation of concerns where we have data, its manipulations and view layer separated. In Redux we have the same things but we also learn about immutability and pure functions.
Since new Date().toUTCString()
returns a string like "Wed, 11 Oct 2017 09:24:41 GMT"
you can slice the last 3 characters and pass the sliced string to new Date()
:
new Date()
// Wed Oct 11 2017 11:34:33 GMT+0200 (CEST)
new Date(new Date().toUTCString().slice(0, -3))
// Wed Oct 11 2017 09:34:33 GMT+0200 (CEST)
The syntax for creating a new table is
CREATE TABLE new_table
AS
SELECT *
FROM old_table
This will create a new table named new_table
with whatever columns are in old_table
and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.
SELECT INTO
is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.
This error may also be triggered by having the wrong .NET framework version selected as the default in IIS.
Click on the root node under the Connections view (on the left hand side), then select Change .NET Framework Version from the Actions view (on the right hand side), then select the appropriate .NET version from the dropdown list.
You ask two questions; your title says "Displaying a vector of strings", but you're not actually doing that, you actually build a single string composed of all the strings and output that.
Your question body asks "Why doesn't this work".
It doesn't work because your for loop is constrained by "userString.size()" which is 0, and you test your loop variable for being "userString.size() - 1". The condition of a for() loop is tested before permitting execution of the first iteration.
int n = 1;
for (int i = 1; i < n; ++i) {
std::cout << i << endl;
}
will print exactly nothing.
So your loop executes exactly no iterations, leaving userString and sentence empty.
Lastly, your code has absolutely zero reason to use a vector. The fact that you used "decltype(userString.size())" instead of "size_t" or "auto", while claiming to be a rookie, suggests you're either reading a book from back to front or you are setting yourself up to fail a class.
So to answer your question at the end of your post: It doesn't work because you didn't step through it with a debugger and inspect the values as it went. While I say it tongue-in-cheek, I'm going to leave it out there.
I know it's a bit too late, but maybe someone is looking for easy way to access appsettings in .net core app. in API constructor add the following:
public class TargetClassController : ControllerBase
{
private readonly IConfiguration _config;
public TargetClassController(IConfiguration config)
{
_config = config;
}
[HttpGet("{id:int}")]
public async Task<ActionResult<DTOResponse>> Get(int id)
{
var config = _config["YourKeySection:key"];
}
}
I wrote a simple Xcode 6 project that shows how to mix C++, Objective-C and Swift code:
https://github.com/romitagl/shared/tree/master/C-ObjC-Swift/Performance_Console
In particular, the example calls an Objective-C and a C++ function from the Swift.
The key is to create a shared header, Project-Bridging-Header.h, and put the Objective-C headers there.
Please download the project as a complete example.
In C++
using namespace std;
string my_string {"Hello world"};
string element_to_be_found {"Hello"};
if(my_string.find(element_to_be_found)!=string::npos)
std::cout<<"Element Found"<<std::endl;
This is what worked for me (Windows 10) :
Tip : You can pin mysql.exe to Start Menu so you don't always have to search for this folder
You can simply use ORS dynamically like this:
awk '{ORS="" ; print($1" "$2" "$3" "$4" "$5" "); ORS="\n"; print($6-=2*$6)}' file_in > file_out
The PRG pattern can only prevent the resubmission caused by page refreshing. This is not a 100% safe measure.
Usually, I will take actions below to prevent resubmission:
Client Side - Use javascript to prevent duplicate clicks on a button which will trigger form submission. You can just disable the button after the first click.
Server Side - I will calculate a hash on the submitted parameters and save that hash in session or database, so when the duplicated submission was received we can detect the duplication then proper response to the client. However, you can manage to generate a hash at the client side.
In most of the occasions, these measures can help to prevent resubmission.
Sometimes you don't want to use version ranges, because it seems that they are "slow" to resolve your dependencies, especially when there is continuous delivery in place and there are tons of versions - mainly during heavy development.
One workaround would be to use the versions-maven-plugin. For example, you can declare a property:
<properties>
<myname.version>1.1.1</myname.version>
</properties>
and add the versions-maven-plugin to your pom file:
<build>
<plugins>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>versions-maven-plugin</artifactId>
<version>2.3</version>
<configuration>
<properties>
<property>
<name>myname.version</name>
<dependencies>
<dependency>
<groupId>group-id</groupId>
<artifactId>artifact-id</artifactId>
<version>latest</version>
</dependency>
</dependencies>
</property>
</properties>
</configuration>
</plugin>
</plugins>
</build>
Then, in order to update the dependency, you have to execute the goals:
mvn versions:update-properties validate
If there is a version newer than 1.1.1, it will tell you:
[INFO] Updated ${myname.version} from 1.1.1 to 1.3.2
On Windows 7 I had to do the following:
quick way
long way
This likely breaks when you upgrade your JDK installation but you have access to all the command line tools now.
Follow comments above about how to compile the file ("javac MyFile.java" then "java MyFile") https://stackoverflow.com/a/33149828/194872
An alternative way of sending a large number of repeating characters to a text field (for instance to test the maximum number of characters the field will allow) is to type a few characters and then repeatedly copy and paste them:
inputField.sendKeys('0123456789');
for(int i = 0; i < 100; i++) {
inputField.sendKeys(Key.chord(Key.CONTROL, 'a'));
inputField.sendKeys(Key.chord(Key.CONTROL, 'c'));
for(int i = 0; i < 10; i++) {
inputField.sendKeys(Key.chord(Key.CONTROL, 'v'));
}
}
Unfortunately pressing CTRL doesn't seem to work for IE unless REQUIRE_WINDOW_FOCUS
is enabled (which can cause other issues), but it works fine for Firefox and Chrome.
Use a service to achieve this:
MyApp.app.service("xxxSvc", function () {
var _xxx = {};
return {
getXxx: function () {
return _xxx;
},
setXxx: function (value) {
_xxx = value;
}
};
});
Next, inject this service into both controllers.
In Controller1, you would need to set the shared xxx value with a call to the service: xxxSvc.setXxx(xxx)
Finally, in Controller2, add a $watch on this service's getXxx() function like so:
$scope.$watch(function () { return xxxSvc.getXxx(); }, function (newValue, oldValue) {
if (newValue != null) {
//update Controller2's xxx value
$scope.xxx= newValue;
}
}, true);
Moving file using kotlin. App has to have permission to write a file in destination directory.
@Throws(FileNotFoundException::class, IOError::class)
private fun moveTo(source: File, dest: File, destDirectory: File? = null) {
if (destDirectory?.exists() == false) {
destDirectory.mkdir()
}
val fis = FileInputStream(source)
val bufferLength = 1024
val buffer = ByteArray(bufferLength)
val fos = FileOutputStream(dest)
val bos = BufferedOutputStream(fos, bufferLength)
var read = fis.read(buffer, 0, read)
while (read != -1) {
bos.write(buffer, 0, read)
read = fis.read(buffer) // if read value is -1, it escapes loop.
}
fis.close()
bos.flush()
bos.close()
if (!source.delete()) {
HLog.w(TAG, klass, "failed to delete ${source.name}")
}
}
The easiest way to achieve is by applying width to view.
width: '80%'
alternatively you can try this:
<?php echo (new DateTime("now", new DateTimeZone('Asia/Singapore')))->format("Y-m-d H:i:s e"); ?>
this will output :
2017-10-25 17:13:20 Asia/Singapore
you can use this inside the value attribute of a text input box if you only want to display a read-only date.
remove the 'e' if you do not wish to show your region/country.
Not only double quotes, you will be in need for single quote ('
), double quote ("
), backslash (\
) and NUL (the NULL byte).
Use fputcsv()
to write, and fgetcsv()
to read, which will take care of all.
You should give your <tr>
tag an id foo_row
or whatever. And hide that instead
From the comp.compilers FAQ:
"Programming a Personal Computer" by Per Brinch Hansen Prentice-Hall 1982 ISBN 0-13-730283-5
This unfortunately-titled book explains the design and creation of a single-user programming environment for micros, using a Pascal-like language called Edison. The author presents all source code and explanations for the step-by-step implementation of an Edison compiler and simple supporting operating system, all written in Edison itself (except for a small supporting kernel written in a symbolic assembler for PDP 11/23; the complete source can also be ordered for the IBM PC).
The most interesting things about this book are: 1) its ability to demonstrate how to create a complete, self-contained, self-maintaining, useful compiler and operating system, and 2) the interesting discussion of language design and specification problems and trade-offs in Chapter 2.
"Brinch Hansen on Pascal Compilers" by Per Brinch Hansen Prentice-Hall 1985 ISBN 0-13-083098-4
Another light-on-theory heavy-on-pragmatics here's-how-to-code-it book. The author presents the design, implementation, and complete source code for a compiler and p-code interpreter for Pascal- (Pascal "minus"), a Pascal subset with boolean and integer types (but no characters, reals, subranged or enumerated types), constant and variable definitions and array and record types (but no packed, variant, set, pointer, nameless, renamed, or file types), expressions, assignment statements, nested procedure definitions with value and variable parameters, if statements, while statements, and begin-end blocks (but no function definitions, procedural parameters, goto statements and labels, case statements, repeat statements, for statements, and with statements).
The compiler and interpreter are written in Pascal* (Pascal "star"), a Pascal subset extended with some Edison-style features for creating software development systems. A Pascal* compiler for the IBM PC is sold by the author, but it's easy to port the book's Pascal- compiler to any convenient Pascal platform.
This book makes the design and implementation of a compiler look easy. I particularly like the way the author is concerned with quality, reliability, and testing. The compiler and interpreter can easily be used as the basis for a more involved language or compiler project, especially if you're pressed to quickly get something up and running.
Even though answers to this question are long overdue, but I'm still posting a nice solution that I came with some time ago and makes it really simple to send complex JSON to Asp.net MVC controller actions so they are model bound to whatever strong type parameters.
This plugin supports dates just as well, so they get converted to their DateTime
counterpart without a problem.
You can find all the details in my blog post where I examine the problem and provide code necessary to accomplish this.
All you have to do is to use this plugin on the client side. An Ajax request would look like this:
$.ajax({
type: "POST",
url: "SomeURL",
data: $.toDictionary(yourComplexJSONobject),
success: function() { ... },
error: function() { ... }
});
But this is just part of the whole problem. Now we are able to post complex JSON back to server, but since it will be model bound to a complex type that may have validation attributes on properties things may fail at that point. I've got a solution for it as well. My solution takes advantage of jQuery Ajax functionality where results can be successful or erroneous (just as shown in the upper code). So when validation would fail, error
function would get called as it's supposed to be.
What you want to do is to make an interface which handles this code and all your classes implement the interface.
class IEventListener{
public:
void OnEvent(int x) = 0; // renamed Callback to OnEvent removed the instance, you can add it back if you want.
};
class MyClass :public IEventListener
{
...
void OnEvent(int x); //typically such a function is NOT static. This wont work if it is static.
};
class YourClass :public IEventListener
{
Note that for this to work the "Callback" function is non static which i believe is an improvement. If you want it to be static, you need to do it as JaredC suggests with templates.
You can also do this progamatically, rather than through xml, but it's a bit more "hackish". But give a man no options and you leave him no choice :p.. Here's the code:
TableLayout table = new TableLayout(this);
TableRow tr = new TableRow(this);
tr.setBackgroundColor(Color.BLACK);
tr.setPadding(0, 0, 0, 2); //Border between rows
TableRow.LayoutParams llp = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
llp.setMargins(0, 0, 2, 0);//2px right-margin
//New Cell
LinearLayout cell = new LinearLayout(this);
cell.setBackgroundColor(Color.WHITE);
cell.setLayoutParams(llp);//2px border on the right for the cell
TextView tv = new TextView(this);
tv.setText("Some Text");
tv.setPadding(0, 0, 4, 3);
cell.addView(tv);
tr.addView(cell);
//add as many cells you want to a row, using the same approach
table.addView(tr);
.communicate()
writes input (there is no input in this case so it just closes subprocess' stdin to indicate to the subprocess that there is no more input), reads all output, and waits for the subprocess to exit.
The exception EOFError is raised in the child process by raw_input()
(it expected data but got EOF (no data)).
p.stdout.read()
hangs forever because it tries to read all output from the child at the same time as the child waits for input (raw_input()
) that causes a deadlock.
To avoid the deadlock you need to read/write asynchronously (e.g., by using threads or select) or to know exactly when and how much to read/write, for example:
from subprocess import PIPE, Popen
p = Popen(["python", "-u", "1st.py"], stdin=PIPE, stdout=PIPE, bufsize=1)
print p.stdout.readline(), # read the first line
for i in range(10): # repeat several times to show that it works
print >>p.stdin, i # write input
p.stdin.flush() # not necessary in this case
print p.stdout.readline(), # read output
print p.communicate("n\n")[0], # signal the child to exit,
# read the rest of the output,
# wait for the child to exit
Note: it is a very fragile code if read/write are not in sync; it deadlocks.
Beware of block-buffering issue (here it is solved by using "-u" flag that turns off buffering for stdin, stdout in the child).
In this case you might want to use the functions np.hstack and np.vstack
arr = np.array([])
arr = np.hstack((arr, np.array([1,2,3])))
# arr is now [1,2,3]
arr = np.vstack((arr, np.array([4,5,6])))
# arr is now [[1,2,3],[4,5,6]]
You also can use the np.concatenate function.
Cheers
This is an old question, but the accepted answer has a serious flaw. If the Spring Environment
object contains any overriding values (as described in Externalized Configuration), there is no guarantee that the map of property values it produces will match those returned from the Environment
object. I found that simply iterating through the PropertySource
s of the Environment
did not, in fact, give any overriding values. Instead it produced the original value, the one that should have been overridden.
Here is a better solution. This uses the EnumerablePropertySource
s of the Environment
to iterate through the known property names, but then reads the actual value out of the real Spring environment. This guarantees that the value is the one actually resolved by Spring, including any overriding values.
Properties props = new Properties();
MutablePropertySources propSrcs = ((AbstractEnvironment) springEnv).getPropertySources();
StreamSupport.stream(propSrcs.spliterator(), false)
.filter(ps -> ps instanceof EnumerablePropertySource)
.map(ps -> ((EnumerablePropertySource) ps).getPropertyNames())
.flatMap(Arrays::<String>stream)
.forEach(propName -> props.setProperty(propName, springEnv.getProperty(propName)));
I faced same error but in a different way.
When you curl a page with a specific SSL protocol.
curl --sslv3 https://example.com
If --sslv3 is not supported by the target server then the error will be
curl: (35) TCP connection reset by peer
With the supported protocol, error will be gone.
curl --tlsv1.2 https://example.com
People already mentioned that
Task.Run(A);
Is equivalent to
Task.Factory.StartNew(A, CancellationToken.None, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default);
But no one mentioned that
Task.Factory.StartNew(A);
Is equivalent to:
Task.Factory.StartNew(A, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Current);
As you can see two parameters are different for Task.Run
and Task.Factory.StartNew
:
TaskCreationOptions
- Task.Run
uses TaskCreationOptions.DenyChildAttach
which means that children tasks can not be attached to the parent, consider this:
var parentTask = Task.Run(() =>
{
var childTask = new Task(() =>
{
Thread.Sleep(10000);
Console.WriteLine("Child task finished.");
}, TaskCreationOptions.AttachedToParent);
childTask.Start();
Console.WriteLine("Parent task finished.");
});
parentTask.Wait();
Console.WriteLine("Main thread finished.");
When we invoke parentTask.Wait()
, childTask
will not be awaited, even though we specified TaskCreationOptions.AttachedToParent
for it, this is because TaskCreationOptions.DenyChildAttach
forbids children to attach to it. If you run the same code with Task.Factory.StartNew
instead of Task.Run
, parentTask.Wait()
will wait for childTask
because Task.Factory.StartNew
uses TaskCreationOptions.None
TaskScheduler
- Task.Run
uses TaskScheduler.Default
which means that the default task scheduler (the one that runs tasks on Thread Pool) will always be used to run tasks. Task.Factory.StartNew
on the other hand uses TaskScheduler.Current
which means scheduler of the current thread, it might be TaskScheduler.Default
but not always. In fact when developing Winforms
or WPF
applications it is required to update UI from the current thread, to do this people use TaskScheduler.FromCurrentSynchronizationContext()
task scheduler, if you unintentionally create another long running task inside task that used TaskScheduler.FromCurrentSynchronizationContext()
scheduler the UI will be frozen. A more detailed explanation of this can be found here
So generally if you are not using nested children task and always want your tasks to be executed on Thread Pool it is better to use Task.Run
, unless you have some more complex scenarios.
Both methods are used to prevent thread execution. But specifically, sleep(): purpose:if a thread don't want to perform any operation for particular amount of time then we should go for sleep().for e.x. slide show . yield(): purpose:if a thread wants to pause it's execution to give chance of execution to another waiting threads of same priority.thread which requires more execution time should call yield() in between execution.
Note:some platform may not provide proper support for yield() . because underlying system may not provide support for preemptive scheduling.moreover yield() is native method.
Or
$dataProvider->setSort([
'defaultOrder' => ['topic_order'=>SORT_DESC],
'attributes' => [...
What I have found is that TensorFlow 2.0 (I am using 2.0.0-alpha0) is not compatible with the latest version of Numpy i.e. v1.17.0 (and possibly v1.16.5+). As soon as TF2 is imported, it throws a huge list of FutureWarning, that looks something like this:
FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
_np_qint8 = np.dtype([("qint8", np.int8, 1)])
/anaconda3/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:541: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
_np_qint8 = np.dtype([("qint8", np.int8, 1)])
/anaconda3/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:542: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
_np_quint8 = np.dtype([("quint8", np.uint8, 1)])
/anaconda3/lib/python3.6/site-packages/tensorboard/compat/tensorflow_stub/dtypes.py:543: FutureWarning: Passing (type, 1) or '1type' as a synonym of type is deprecated; in a future version of numpy, it will be understood as (type, (1,)) / '(1,)type'.
This also resulted in the allow_pickle error when tried to load imdb dataset from keras
I tried to use the following solution which worked just fine, but I had to do it every single project where I was importing TF2 or tf.keras.
np.load = lambda *a,**k: np_load_old(*a, allow_pickle=True, **k)
The easiest solution I found was to either install numpy 1.16.1 globally, or use compatible versions of tensorflow and numpy in a virtual environment.
My goal with this answer is to point out that its not just a problem with imdb.load_data, but a larger problem vaused by incompatibility of TF2 and Numpy versions and may result in many other hidden bugs or issues.
You can simply open the phpmyadmin page from your browser, then open any existing database -> go to Privileges tab, click on your root user and then a popup window will appear, you can set your password there.. Hope this Helps.
I believe PowerShell now trumps the "sc" command in terms of simplicity:
Restart-Service "servicename"
Check your browser version and do the following.
1. Download the Firefox/Chrome webdriver from Google
2. Put the webdriver in Chrome's directory.
For Rails 4 and above version:
You can try something like this If you want first oldest entry
YourModel.order(id: :asc).limit(5).each do |d|
You can try something like this if you want last latest entries..
YourModel.order(id: :desc).limit(5).each do |d|
this part :
"Your new price is: $"(float(price)
asks python to call this string:
"Your new price is: $"
just like you would a function:
function( some_args)
which will ALWAYS trigger the error:
TypeError: 'str' object is not callable
Use Mark Longair's answer, but make sure to use the HTTPS link to the repository:
git remote set-url origin https://github.com/my_user_name/my_repo.git
You can use then git push origin master
.
Although in most general cases the error is quite clearly that file handles have not been closed, I just encountered an instance with JDK7 on Linux that well... is sufficiently ****ed up to explain here.
The program opened a FileOutputStream (fos), a BufferedOutputStream (bos) and a DataOutputStream (dos). After writing to the dataoutputstream, the dos was closed and I thought everything went fine.
Internally however, the dos, tried to flush the bos, which returned a Disk Full error. That exception was eaten by the DataOutputStream, and as a consequence the underlying bos was not closed, hence the fos was still open.
At a later stage that file was then renamed from (something with a .tmp) to its real name. Thereby, the java file descriptor trackers lost track of the original .tmp, yet it was still open !
To solve this, I had to first flush the DataOutputStream myself, retrieve the IOException and close the FileOutputStream myself.
I hope this helps someone.
Ruby version: 2.7.1 gem version: 3.1.3
You need to check the extension that could not be installed, and find the reasons.
Read the mkmf.log file showed at the installation error under "To see why this extension failed to compile, please check the mkmf.log which can be found here" , perhaps there is a missing lib ( sometimes iconv ), and you must install it.
You can search the extension with your package manager(apt, yum, pacman...) too.
gem install rails
Showed me:
To see why this extension failed to compile, please check the mkmf.log which can be found here: /home/user/.gem/ruby/2.7.0/extensions/x86_64-linux/2.7.0/nokogiri-1.10.9/mkmf.log
Go to: https://aur.archlinux.org/packages/ruby-nokogiri/
make
installedgit clone
the packagecd
to packagemakepkg
the packageHope to help!
I think most people who answered are a bit clueless and have found a solution by trial and error. I too had this issue recently and looked at the various solutions in this thread and they did not make much sense. I looked in to my project's makefile (it is handmade by my project lead) and I found -j11 in there. I replaced that with -j1 and it fixed the problem. The hunch was that make was probably doing a bad job at running multiple jobs (threads) i.e. while one thread was working on a file, another thread was trying to use it.
For those who use an IDE to compile your code, you need to look for a build property where you can set the number of jobs and then try compiling your code with the number of jobs set to 1. You might also have to close and restart the IDE (it all depends on how the IDEs are programmed).
I understand that this might hinder the performance of your builds but there is probably no alternative to this until either make fixes this bug (if there is one, I haven't bothered to dig in) or the makefile generators become smart enough to prevent this situation.
The most simple and straightforward C/C++ implementation that I found is in a link at the bottom of this page:
Web Page: http://www.barrgroup.com/Embedded-Systems/How-To/CRC-Calculation-C-Code
Code Download Link: https://barrgroup.com/code/crc.zip
It is a simple standalone implementation with one .h and one .c file. There is support for CRC32, CRC16 and CRC_CCITT thru the use of a define. Also, the code lets the user change parameter settings like the CRC polynomial, initial/final XOR value, and reflection options if you so desire.
The license is not explicitly defined ala LGPL or similar. However the site does say that they are placing the code in the public domain for any use. The actual code files also say this.
Hope it helps!
Here is an example if you want to use the primes number to go a lot faster. These lists are easy to find on the internet. I added comments in the code.
# http://primes.utm.edu/lists/small/10000.txt
# First 10000 primes
_PRIMES = (2, 3, 5, 7, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
73, 79, 83, 89, 97, 101, 103, 107, 109, 113,
127, 131, 137, 139, 149, 151, 157, 163, 167, 173,
179, 181, 191, 193, 197, 199, 211, 223, 227, 229,
233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
283, 293, 307, 311, 313, 317, 331, 337, 347, 349,
353, 359, 367, 373, 379, 383, 389, 397, 401, 409,
419, 421, 431, 433, 439, 443, 449, 457, 461, 463,
467, 479, 487, 491, 499, 503, 509, 521, 523, 541,
547, 557, 563, 569, 571, 577, 587, 593, 599, 601,
607, 613, 617, 619, 631, 641, 643, 647, 653, 659,
661, 673, 677, 683, 691, 701, 709, 719, 727, 733,
739, 743, 751, 757, 761, 769, 773, 787, 797, 809,
811, 821, 823, 827, 829, 839, 853, 857, 859, 863,
877, 881, 883, 887, 907, 911, 919, 929, 937, 941,
947, 953, 967, 971, 977, 983, 991, 997, 1009, 1013,
# Mising a lot of primes for the purpose of the example
)
from bisect import bisect_left as _bisect_left
from math import sqrt as _sqrt
def get_factors(n):
assert isinstance(n, int), "n must be an integer."
assert n > 0, "n must be greather than zero."
limit = pow(_PRIMES[-1], 2)
assert n <= limit, "n is greather then the limit of {0}".format(limit)
result = set((1, n))
root = int(_sqrt(n))
primes = [t for t in get_primes_smaller_than(root + 1) if not n % t]
result.update(primes) # Add all the primes factors less or equal to root square
for t in primes:
result.update(get_factors(n/t)) # Add all the factors associted for the primes by using the same process
return sorted(result)
def get_primes_smaller_than(n):
return _PRIMES[:_bisect_left(_PRIMES, n)]
I also had a similar question, sharing the below example if it helps.
My Controller:
@RequestMapping(value = {"/batchDeleteIndex"}, method = RequestMethod.POST)
@ResponseBody
public BaseResponse batchDeleteIndex(@RequestBody List<String> datasetQnames)
Postman: Set the Body type to raw and add header Content-Type: application/json
["aaa","bbb","ccc"]
You use a compound key (a key with more than one attribute) whenever you want to ensure the uniqueness of a combination of several attributes. A single attribute key would not achieve the same thing.
Use cbind
e.g.
df <- data.frame(b = runif(6), c = rnorm(6))
cbind(a = 0, df)
giving:
> cbind(a = 0, df)
a b c
1 0 0.5437436 -0.1374967
2 0 0.5634469 -1.0777253
3 0 0.9018029 -0.8749269
4 0 0.1649184 -0.4720979
5 0 0.6992595 0.6219001
6 0 0.6907937 -1.7416569
Alternate form of the answer by @rumpel
with open(filename, 'w'): pass
This isn't exactly what the user asked, but another way to create a long string that spans multiple lines is by incrementally building it up, like so:
$ greeting="Hello"
$ greeting="$greeting, World"
$ echo $greeting
Hello, World
Obviously in this case it would have been simpler to build it one go, but this style can be very lightweight and understandable when dealing with longer strings.
This is called trimming. If you can use Boost, I'd recommend it.
Otherwise, use find_first_not_of
to get the index of the first non-whitespace character, then find_last_not_of
to get the index from the end that isn't whitespace. With these, use substr
to get the sub-string with no surrounding whitespace.
In response to your edit, I don't know the term but I'd guess something along the lines of "reduce", so that's what I called it. :) (Note, I've changed the white-space to be a parameter, for flexibility)
#include <iostream>
#include <string>
std::string trim(const std::string& str,
const std::string& whitespace = " \t")
{
const auto strBegin = str.find_first_not_of(whitespace);
if (strBegin == std::string::npos)
return ""; // no content
const auto strEnd = str.find_last_not_of(whitespace);
const auto strRange = strEnd - strBegin + 1;
return str.substr(strBegin, strRange);
}
std::string reduce(const std::string& str,
const std::string& fill = " ",
const std::string& whitespace = " \t")
{
// trim first
auto result = trim(str, whitespace);
// replace sub ranges
auto beginSpace = result.find_first_of(whitespace);
while (beginSpace != std::string::npos)
{
const auto endSpace = result.find_first_not_of(whitespace, beginSpace);
const auto range = endSpace - beginSpace;
result.replace(beginSpace, range, fill);
const auto newStart = beginSpace + fill.length();
beginSpace = result.find_first_of(whitespace, newStart);
}
return result;
}
int main(void)
{
const std::string foo = " too much\t \tspace\t\t\t ";
const std::string bar = "one\ntwo";
std::cout << "[" << trim(foo) << "]" << std::endl;
std::cout << "[" << reduce(foo) << "]" << std::endl;
std::cout << "[" << reduce(foo, "-") << "]" << std::endl;
std::cout << "[" << trim(bar) << "]" << std::endl;
}
Result:
[too much space]
[too much space]
[too-much-space]
[one
two]
If you read error message, "icuuc36.dll" is missing. The problem is that you don't have the PHP dir in your PATH, or you can copy all "intl" files from php directory to apache\bin directory. They are : icudt36.dll icuin36.dll icuio36.dll icule36.dll iculx36.dll icutu36.dll icuuc36.dll
Try:
.Formula = "='" & strProjectName & "'!" & Cells(2, 7).Address
If your worksheet name (strProjectName
) has spaces, you need to include the single quotes in the formula string.
If this does not resolve it, please provide more information about the specific error or failure.
Update
In comments you indicate you're replacing spaces with underscores. Perhaps you are doing something like:
strProjectName = Replace(strProjectName," ", "_")
But if you're not also pushing that change to the Worksheet.Name
property, you can expect these to happen:
#REF
errorThe reason for both is that you are passing a reference to a worksheet that doesn't exist, which is why you get the #REF error. The file dialog is an attempt to let you correct that reference, by pointing to a file wherein that sheet name does exist. When you cancel out, the #REF error is expected.
So you need to do:
Worksheets(strProjectName).Name = Replace(strProjectName," ", "_")
strProjectName = Replace(strProjectName," ", "_")
Then, your formula should work.
The second form (creating an HTTP server yourself, instead of having Express create one for you) is useful if you want to reuse the HTTP server, for example to run socket.io
within the same HTTP server instance:
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
...
server.listen(1234);
However, app.listen()
also returns the HTTP server instance, so with a bit of rewriting you can achieve something similar without creating an HTTP server yourself:
var express = require('express');
var app = express();
// app.use/routes/etc...
var server = app.listen(3033);
var io = require('socket.io').listen(server);
io.sockets.on('connection', function (socket) {
...
});
The following code:
echo "hello world" | ( test=($(< /dev/stdin)); echo test=$test )
will work too, but it will open another new sub-shell after the pipe, where
echo "hello world" | { test=($(< /dev/stdin)); echo test=$test; }
won't.
I had to disable job control to make use of chepnars' method (I was running this command from terminal):
set +m;shopt -s lastpipe
echo "hello world" | read test; echo test=$test
echo "hello world" | test="$(</dev/stdin)"; echo test=$test
lastpipe
If set, and job control is not active, the shell runs the last command of a pipeline not executed in the background in the current shell environment.
Note: job control is turned off by default in a non-interactive shell and thus you don't need the set +m
inside a script.
First, you declared $db outside the function. If you want to use it inside the function, you should put this at the begining of your function code:
global $db;
And I guess, when you wrote:
if($result->num_rows){
return (mysqli_result($query, 0) == 1) ? true : false;
what you really wanted was:
if ($result->num_rows==1) { return true; } else { return false; }
Because the dot is inside character class (square brackets []
).
Take a look at http://www.regular-expressions.info/reference.html, it says (under char class section):
Any character except ^-]\ add that character to the possible matches for the character class.
seeing how the rules are fairly complicated, I'd suggest the following:
/^[a-z](\w*)[a-z0-9]$/i
match the whole string and capture intermediate characters. Then either with the string functions or the following regex:
/__/
check if the captured part has two underscores in a row. For example in Python it would look like this:
>>> import re
>>> def valid(s):
match = re.match(r'^[a-z](\w*)[a-z0-9]$', s, re.I)
if match is not None:
return match.group(1).count('__') == 0
return False
For future Googlers, If you get an error similar below after you trigger click for a polygon
"Uncaught TypeError: Cannot read property 'vertex' of undefined"
then try the code below
google.maps.event.trigger(polygon, "click", {});
Just encompass the iframe in a div set the width to the width of button, set overflow to hidden i.e.
<div style="width:52px;overflow:hidden;">
<fb:like layout="button_count"></fb:like>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: 'YOUR_APP_ID',
status: true,
cookie: true,
xfbml: true
});
};
(function() {
var e = document.createElement('script');
e.type = 'text/javascript';
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
</div>
Empty strings are falsey, so you can just write:
if ($a) {
echo 'text';
}
Although if you're asking if a particular substring exists in that string, you can use strpos()
to do that:
if (strpos($a, 'some text') !== false) {
echo 'text';
}
You could use the INDIRECT function. This takes a string and converts it into a range
More info here
=INDIRECT("K"&A2)
But it's preferable to use INDEX as it is less volatile.
=INDEX(K:K,A2)
This returns a value or the reference to a value from within a table or range
More info here
Put either function into cell B2 and fill down.
when LD_PRELOAD is used that file will be loaded before any other
$export LD_PRELOAD=/path/lib
lib to be pre loaded, even this can be used in programs too
If you use Bootstrap 3, you can use one of it's mixins:
.rotate(degrees);
Example:
.rotate(-90deg);
Try this: getActivity().runOnUiThread(new Runnable...
It's because:
1) the implicit this in your call to runOnUiThread is referring to AsyncTask, not your fragment.
2) Fragment doesn't have runOnUiThread.
However, Activity does.
Note that Activity just executes the Runnable if you're already on the main thread, otherwise it uses a Handler. You can implement a Handler in your fragment if you don't want to worry about the context of this, it's actually very easy:
// A class instance
private Handler mHandler = new Handler(Looper.getMainLooper());
// anywhere else in your code
mHandler.post(<your runnable>);
// ^ this will always be run on the next run loop on the main thread.
The best way is ViewOverlay , You can add any drawable as overlay to any view as its overlay since Android JellyBeanMR2(Api 18).
Add mMyDrawable
to mMyView
as its overlay:
mMyDrawable.setBounds(0, 0, mMyView.getMeasuredWidth(), mMyView.getMeasuredHeight())
mMyView.getOverlay().add(mMyDrawable)
Assuming you have something like so:
public class MyFirstClass {
...
public ArrayList<Integer> myNumbers() {
ArrayList<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(11);
numbers.add(3);
return(numbers);
}
...
}
You can call that method like so:
public class MySecondClass {
...
MyFirstClass m1 = new MyFirstClass();
List<Integer> myList = m1.myNumbers();
...
}
Since the method you are trying to call is not static, you will have to create an instance of the class which provides this method. Once you create the instance, you will then have access to the method.
Note, that in the code example above, I used this line: List<Integer> myList = m1.myNumbers();
. This can be changed by the following: ArrayList<Integer> myList = m1.myNumbers();
. However, it is usually recommended to program to an interface, and not to a concrete implementation, so my suggestion for the method you are using would be to do something like so:
public List<Integer> myNumbers() {
List<Integer> numbers = new ArrayList<Integer>();
numbers.add(5);
numbers.add(11);
numbers.add(3);
return(numbers);
}
This will allow you to assign the contents of that list to whatever implements the List
interface.
Try the following idea:
var firstBornDate = People.GroupBy(p => p.DateOfBirth).Min(g => g.Key).FirstOrDefault();
Do you want to insert one dictionary into the other, as one of its elements, or do you want to reference the values of one dictionary from the keys of another?
Previous answers have already covered the first case, where you are creating a dictionary within another dictionary.
To re-reference the values of one dictionary into another, you can use dict.update
:
>>> d1 = {1: [1]}
>>> d2 = {2: [2]}
>>> d1.update(d2)
>>> d1
{1: [1], 2: [2]}
A change to a value that's present in both dictionaries will be visible in both:
>>> d1[2].append('appended')
>>> d1
{1: [1], 2: [2, 'appended']}
>>> d2
{2: [2, 'appended']}
This is the same as copying the value over or making a new dictionary with it, i.e.
>>> d3 = {1: d1[1]}
>>> d3[1].append('appended from d3')
>>> d1[1]
[1, 'appended from d3']
As others have noted, "SKU" stands for stock keeping unit. Here's what I find currently (3 February 2017) in the Apple documentation regarding the "SKU Number:"
SKU Number
A unique ID for your app in the Apple system that is not seen by users. You can use letters, numbers, hyphens, periods, and underscores. The SKU can’t
start with a hyphen, period, or underscore. Use a value that is meaningful to your organization. Can’t be edited after saving the iTunes Connect record.
(internet archive link:) iTunes Connect Properties
MySQL v5.5.3 and greater:
Just add three lines only in the [mysqld] section:
[mysqld]
character-set-server = utf8
collation-server = utf8_unicode_ci
skip-character-set-client-handshake
Note: Including skip-character-set-client-handshake
here obviates the need to include both init-connect
in [mysqld]
and default-character-set
in the [client]
and [mysql]
sections.
Just activate the sheet where the chart is:
Sheets(1).Activate
and your problem disappears.
I had the same problem and none of the things you mentioned in question worked for me until I just activated sheet. The accepted answer didn't work for me neither.
Alternatively you can make:
ActiveCell.Activate
I often ended up doing things like this. Therefore I tried to write a simple function that 'snips' out the unwanted elements in an easy way. This turns matlab logic a bit upside down, but looks good:
b = snip(a,'0')
you can find the function file at: http://www.mathworks.co.uk/matlabcentral/fileexchange/41941-snip-m-snip-elements-out-of-vectorsmatrices
It also works with all other 'x', nan or whatever elements.
There are a few great examples:
This has also been covered before in this Stack Overflow question.
NuGet Google reCAPTCHA V2 for MVC 4 and 5
You can use the .charAt(int) function with Strings to retrieve the char value at any index. If you want to convert the String to a char array, try calling .toCharArray() on the String.
String g = "line";
char c = g.charAt(0); // returns 'l'
char[] c_arr = g.toCharArray(); // returns a length 4 char array ['l','i','n','e']
You should use
<input type="submit" value="submit" />
inside your form
.
and add action
into your form
tag for example:
<form action="booking.php" method="post">
It's post your form into action which you choose.
From php you can get this value by
$_POST['booking-check'];
Example based on ASP.NET CheckBoxList
<asp:CheckBoxList ID="checkBoxList1" runat="server">
<asp:ListItem>abc</asp:ListItem>
<asp:ListItem>def</asp:ListItem>
</asp:CheckBoxList>
private void SelectCheckBoxList(string valueToSelect)
{
ListItem listItem = this.checkBoxList1.Items.FindByText(valueToSelect);
if(listItem != null) listItem.Selected = true;
}
protected void Page_Load(object sender, EventArgs e)
{
SelectCheckBoxList("abc");
}
Since the return value has changed, $("#datetimepicker1").data("DateTimePicker").date()
actually returns a moment object as Alexandre Bourlier stated:
It seems the doc evolved.
One should now use : $("#datetimepicker1").data("DateTimePicker").date().
NB : Doing so return a Moment object, not a Date object
Therefore, we must use .toDate() to change this statement to a date as such:
$("#datetimepicker1").data("DateTimePicker").date().toDate();
I know this is an older post, but I ran into the ERROR! MySQL server PID file could not be found!
when trying to start MySQL after making an update to my.cnf
file. I did the following to resolve the issue:
Deleted my experimental update to my.cnf
Deleted the .net.pid
and .net.err
files.
delete /usr/local/var/mysql/**<YourUserName>**-MBP.airstreamcomm.net.*
ps -ax | grep mysql
kill **<process id>**
mysql.server start
I see two things missing from the other answers:
canvas.toBlob
(when available) is more performant than canvas.toDataURL
, and also async.The following script deals with both points:
// From https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob, needed for Safari:
if (!HTMLCanvasElement.prototype.toBlob) {
Object.defineProperty(HTMLCanvasElement.prototype, 'toBlob', {
value: function(callback, type, quality) {
var binStr = atob(this.toDataURL(type, quality).split(',')[1]),
len = binStr.length,
arr = new Uint8Array(len);
for (var i = 0; i < len; i++) {
arr[i] = binStr.charCodeAt(i);
}
callback(new Blob([arr], {type: type || 'image/png'}));
}
});
}
window.URL = window.URL || window.webkitURL;
// Modified from https://stackoverflow.com/a/32490603, cc by-sa 3.0
// -2 = not jpeg, -1 = no data, 1..8 = orientations
function getExifOrientation(file, callback) {
// Suggestion from http://code.flickr.net/2012/06/01/parsing-exif-client-side-using-javascript-2/:
if (file.slice) {
file = file.slice(0, 131072);
} else if (file.webkitSlice) {
file = file.webkitSlice(0, 131072);
}
var reader = new FileReader();
reader.onload = function(e) {
var view = new DataView(e.target.result);
if (view.getUint16(0, false) != 0xFFD8) {
callback(-2);
return;
}
var length = view.byteLength, offset = 2;
while (offset < length) {
var marker = view.getUint16(offset, false);
offset += 2;
if (marker == 0xFFE1) {
if (view.getUint32(offset += 2, false) != 0x45786966) {
callback(-1);
return;
}
var little = view.getUint16(offset += 6, false) == 0x4949;
offset += view.getUint32(offset + 4, little);
var tags = view.getUint16(offset, little);
offset += 2;
for (var i = 0; i < tags; i++)
if (view.getUint16(offset + (i * 12), little) == 0x0112) {
callback(view.getUint16(offset + (i * 12) + 8, little));
return;
}
}
else if ((marker & 0xFF00) != 0xFF00) break;
else offset += view.getUint16(offset, false);
}
callback(-1);
};
reader.readAsArrayBuffer(file);
}
// Derived from https://stackoverflow.com/a/40867559, cc by-sa
function imgToCanvasWithOrientation(img, rawWidth, rawHeight, orientation) {
var canvas = document.createElement('canvas');
if (orientation > 4) {
canvas.width = rawHeight;
canvas.height = rawWidth;
} else {
canvas.width = rawWidth;
canvas.height = rawHeight;
}
if (orientation > 1) {
console.log("EXIF orientation = " + orientation + ", rotating picture");
}
var ctx = canvas.getContext('2d');
switch (orientation) {
case 2: ctx.transform(-1, 0, 0, 1, rawWidth, 0); break;
case 3: ctx.transform(-1, 0, 0, -1, rawWidth, rawHeight); break;
case 4: ctx.transform(1, 0, 0, -1, 0, rawHeight); break;
case 5: ctx.transform(0, 1, 1, 0, 0, 0); break;
case 6: ctx.transform(0, 1, -1, 0, rawHeight, 0); break;
case 7: ctx.transform(0, -1, -1, 0, rawHeight, rawWidth); break;
case 8: ctx.transform(0, -1, 1, 0, 0, rawWidth); break;
}
ctx.drawImage(img, 0, 0, rawWidth, rawHeight);
return canvas;
}
function reduceFileSize(file, acceptFileSize, maxWidth, maxHeight, quality, callback) {
if (file.size <= acceptFileSize) {
callback(file);
return;
}
var img = new Image();
img.onerror = function() {
URL.revokeObjectURL(this.src);
callback(file);
};
img.onload = function() {
URL.revokeObjectURL(this.src);
getExifOrientation(file, function(orientation) {
var w = img.width, h = img.height;
var scale = (orientation > 4 ?
Math.min(maxHeight / w, maxWidth / h, 1) :
Math.min(maxWidth / w, maxHeight / h, 1));
h = Math.round(h * scale);
w = Math.round(w * scale);
var canvas = imgToCanvasWithOrientation(img, w, h, orientation);
canvas.toBlob(function(blob) {
console.log("Resized image to " + w + "x" + h + ", " + (blob.size >> 10) + "kB");
callback(blob);
}, 'image/jpeg', quality);
});
};
img.src = URL.createObjectURL(file);
}
Example usage:
inputfile.onchange = function() {
// If file size > 500kB, resize such that width <= 1000, quality = 0.9
reduceFileSize(this.files[0], 500*1024, 1000, Infinity, 0.9, blob => {
let body = new FormData();
body.set('file', blob, blob.name || "file.jpg");
fetch('/upload-image', {method: 'POST', body}).then(...);
});
};
What I did:
return to clients:
byte[] result = ****encrypted data****;
String str = Base64.encodeBase64String(result);
return str;
receive from clients:
byte[] bytes = Base64.decodeBase64(str);
your data will be transferred in this format:
OpfyN9paAouZ2Pw+gDgGsDWzjIphmaZbUyFx5oRIN1kkQ1tDbgoi84dRfklf1OZVdpAV7TonlTDHBOr93EXIEBoY1vuQnKXaG+CJyIfrCWbEENJ0gOVBr9W3OlFcGsZW5Cf9uirSmx/JLLxTrejZzbgq3lpToYc3vkyPy5Y/oFWYljy/3OcC/S458uZFOc/FfDqWGtT9pTUdxLDOwQ6EMe0oJBlMXm8J2tGnRja4F/aVHfQddha2nUMi6zlvAm8i9KnsWmQG//ok25EHDbrFBP2Ia/6Bx/SGS4skk/0couKwcPVXtTq8qpNh/aYK1mclg7TBKHfF+DHppwd30VULpA==
You just need to use these commands
sudo rm -rf /Library/Java/*
sudo rm -rf /Library/PreferencePanes/Java*
sudo rm -rf /Library/Internet\ Plug-Ins/Java*
If you write android:extractNativeLibs="false"
in AndroidManifest file. then change it to android:extractNativeLibs="true"
As of Python 3.5, you can merge two dicts with:
merged = {**dictA, **dictB}
(https://www.python.org/dev/peps/pep-0448/)
So:
jsonMerged = {**json.loads(jsonStringA), **json.loads(jsonStringB)}
asString = json.dumps(jsonMerged)
etc.
The following commands (modified after those found here) worked for me on my WSL install of Ubuntu after hours of trial and error:
sudo service mysql stop
sudo mysqld --skip-grant-tables &
mysql -u root mysql
UPDATE mysql.user SET authentication_string=null WHERE User='root';
flush privileges;
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'your_new_password_here';
flush privileges;
exit;
If you use "=", a replica is created for the original arraylist in the second one, but the reference is same so if you change in one list , the other one will also get modified. Use this instead of "="
List_Of_Array1.addAll(List_Of_Array);
The best way to do it I think is:
if(val != true){
//do something
}
This will be true if val is false, NaN, or undefined.
Also consider that if you click a button, the target of the event listener is not necessaily the button itself, but whatever content inside the button you clicked on. You can reference the element to which you assigned the listener using the currentTarget property. Here is a pretty solution in modern ES using a single statement:
document.querySelectorAll(".myClassName").forEach(i => i.addEventListener(
"click",
e => {
alert(e.currentTarget.dataset.myDataContent);
}));
The ultimate curl php function:
function getURL($url,$fields=null,$method=null,$file=null){
// author = Ighor Toth <[email protected]>
// required:
// url = include http or https
// optionals:
// fields = must be array (e.g.: 'field1' => $field1, ...)
// method = "GET", "POST"
// file = if want to download a file, declare store location and file name (e.g.: /var/www/img.jpg, ...)
// please crete 'cookies' dir to store local cookies if neeeded
// do not modify below
$useragent = 'Mozilla/5.0 (Windows NT 6.3; Trident/7.0; rv:11.0) like Gecko';
$timeout= 240;
$dir = dirname(__FILE__);
$_SERVER["REMOTE_ADDR"] = $_SERVER["REMOTE_ADDR"] ?? '127.0.0.1';
$cookie_file = $dir . '/cookies/' . md5($_SERVER['REMOTE_ADDR']) . '.txt';
$ch = curl_init($url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_FAILONERROR, true);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file);
curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie_file);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true );
curl_setopt($ch, CURLOPT_ENCODING, "" );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt($ch, CURLOPT_AUTOREFERER, true );
curl_setopt($ch, CURLOPT_MAXREDIRS, 10 );
curl_setopt($ch, CURLOPT_USERAGENT, $useragent);
curl_setopt($ch, CURLOPT_REFERER, 'http://www.google.com/');
if($file!=null){
if (!curl_setopt($ch, CURLOPT_FILE, $file)){ // Handle error
die("curl setopt bit the dust: " . curl_error($ch));
}
//curl_setopt($ch, CURLOPT_FILE, $file);
$timeout= 3600;
}
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout );
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout );
if($fields!=null){
$postvars = http_build_query($fields); // build the urlencoded data
if($method=="POST"){
// set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $postvars);
}
if($method=="GET"){
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
$url = $url.'?'.$postvars;
}
}
curl_setopt($ch, CURLOPT_URL, $url);
$content = curl_exec($ch);
if (!$content){
$error = curl_error($ch);
$info = curl_getinfo($ch);
die("cURL request failed, error = {$error}; info = " . print_r($info, true));
}
if(curl_errno($ch)){
echo 'error:' . curl_error($ch);
} else {
return $content;
}
curl_close($ch);
}
This function, based on the work by Laurenz Albe at https://www.cybertec-postgresql.com/en/index-your-foreign-key/, list all the foreign keys with missing indexes. The size of the table is shown, as for small tables the scanning performance could be superior to the index one.
--
-- function: fkeys_missing_indexes
-- purpose: list all foreing keys in the database without and index in the source table.
-- author: Laurenz Albe
-- see: https://www.cybertec-postgresql.com/en/index-your-foreign-key/
--
create or replace function oftool_fkey_missing_indexes ()
returns table (
src_table regclass,
fk_columns varchar,
table_size varchar,
fk_constraint name,
dst_table regclass
)
as $$
select
-- source table having ta foreign key declaration
tc.conrelid::regclass as src_table,
-- ordered list of foreign key columns
string_agg(ta.attname, ',' order by tx.n) as fk_columns,
-- source table size
pg_catalog.pg_size_pretty (
pg_catalog.pg_relation_size(tc.conrelid)
) as table_size,
-- name of the foreign key constraint
tc.conname as fk_constraint,
-- name of the target or destination table
tc.confrelid::regclass as dst_table
from pg_catalog.pg_constraint tc
-- enumerated key column numbers per foreign key
cross join lateral unnest(tc.conkey) with ordinality as tx(attnum, n)
-- name for each key column
join pg_catalog.pg_attribute ta on ta.attnum = tx.attnum and ta.attrelid = tc.conrelid
where not exists (
-- is there ta matching index for the constraint?
select 1 from pg_catalog.pg_index i
where
i.indrelid = tc.conrelid and
-- the first index columns must be the same as the key columns, but order doesn't matter
(i.indkey::smallint[])[0:cardinality(tc.conkey)-1] @> tc.conkey) and
tc.contype = 'f'
group by
tc.conrelid,
tc.conname,
tc.confrelid
order by
pg_catalog.pg_relation_size(tc.conrelid) desc;
$$ language sql;
test it this way,
select * from oftool_fkey_missing_indexes();
you'll see a list like this.
fk_columns |table_size|fk_constraint |dst_table |
----------------------|----------|----------------------------------|-----------------|
id_group |0 bytes |fk_customer__group |im_group |
id_product |0 bytes |fk_cart_item__product |im_store_product |
id_tax |0 bytes |fk_order_tax_resume__tax |im_tax |
id_product |0 bytes |fk_order_item__product |im_store_product |
id_tax |0 bytes |fk_invoice_tax_resume__tax |im_tax |
id_product |0 bytes |fk_invoice_item__product |im_store_product |
id_article,locale_code|0 bytes |im_article_comment_id_article_fkey|im_article_locale|
The pattern rules for glob are not regular expressions. Instead, they follow standard Unix path expansion rules. There are only a few special characters: two different wild-cards, and character ranges are supported [from pymotw: glob – Filename pattern matching].
So you can exclude some files with patterns.
For example to exclude manifests files (files starting with _
) with glob, you can use:
files = glob.glob('files_path/[!_]*')
pip install module_name will work or If you are using a file that you were previously working on than just do shift+enter to reload and will do the job
Two things:
Coding a linked list is, no doubt, a bit more work than using an array and he wondered what would justify the additional effort.
Never code a linked list when using C++. Just use the STL. How hard it is to implement should never be a reason to choose one data structure over another because most are already implemented out there.
As for the actual differences between an array and a linked list, the big thing for me is how you plan on using the structure. I'll use the term vector since that's the term for a resizable array in C++.
Indexing into a linked list is slow because you have to traverse the list to get to the given index, while a vector is contiguous in memory and you can get there using pointer math.
Appending onto the end or the beginning of a linked list is easy, since you only have to update one link, where in a vector you may have to resize and copy the contents over.
Removing an item from a list is easy, since you just have to break a pair of links and then attach them back together. Removing an item from a vector can be either faster or slower, depending if you care about order. Swapping in the last item over top the item you want to remove is faster, while shifting everything after it down is slower but retains ordering.
You guessed right, HTTP Headers are not part of the URL.
And when you type a URL in the browser the request will be issued with standard headers. Anyway REST Apis are not meant to be consumed by typing the endpoint in the address bar of a browser.
The most common scenario is that your server consumes a third party REST Api.
To do so your server-side code forges a proper GET (/PUT/POST/DELETE) request pointing to a given endpoint (URL) setting (when needed, like your case) some headers and finally (maybe) sending some data (as typically occurrs in a POST request for example).
The code to forge the request, send it and finally get the response back depends on your server side language.
If you want to test a REST Api you may use curl
tool from the command line.
curl
makes a request and outputs the response to stdout (unless otherwise instructed).
In your case the test request would be issued like this:
$curl -H "Accept: application/json" 'http://localhost:8080/otp/routers/default/plan?fromPlace=52.5895,13.2836&toPlace=52.5461,13.3588&date=2017/04/04&time=12:00:00'
The H
or --header
directive sets a header and its value.
Add your MAVEN_HOME
environment variable, edit your Path to include %MAVEN_HOME%/bin
then try creating the project manually with Maven:
mvn archetype:generate -DgroupId=com.program -DartifactId=Program -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
Then import the existing Maven project to Eclipse.
In pyspark,SparkSql syntax:
where column_n like 'xyz%'
might not work.
Use:
where column_n RLIKE '^xyz'
This works perfectly fine.
Although $date
is a part of MongoDB Extended JSON and that's what you get as default with mongoexport
I don't think you can really use it as a part of the query.
If try exact search with $date
like below:
db.foo.find({dt: {"$date": "2012-01-01T15:00:00.000Z"}})
you'll get error:
error: { "$err" : "invalid operator: $date", "code" : 10068 }
Try this:
db.mycollection.find({
"dt" : {"$gte": new Date("2013-10-01T00:00:00.000Z")}
})
or (following comments by @user3805045):
db.mycollection.find({
"dt" : {"$gte": ISODate("2013-10-01T00:00:00.000Z")}
})
ISODate
may be also required to compare dates without time (noted by @MattMolnar).
According to Data Types in the mongo Shell both should be equivalent:
The mongo shell provides various methods to return the date, either as a string or as a Date object:
- Date() method which returns the current date as a string.
- new Date() constructor which returns a Date object using the ISODate() wrapper.
- ISODate() constructor which returns a Date object using the ISODate() wrapper.
and using ISODate
should still return a Date object.
{"$date": "ISO-8601 string"}
can be used when strict JSON representation is required. One possible example is Hadoop connector.
I stumbled on this post while trying to change the display format for dates in sql-developer. Just wanted to add to this what I found out:
But a lot of times, I just want to retain the DEFAULT_FORMAT while modifying the format only during a bunch of related queries. That's when I would change the format of the session with the following:
alter SESSION set NLS_DATE_FORMAT = 'my_required_date_format'
Eg:
alter SESSION set NLS_DATE_FORMAT = 'DD-MM-YYYY HH24:MI:SS'
Dependent on how the API is created, normally with a 201 (created) you would return the resource which was created. For example if it was creating a user account you would do something like:
return {"data": {"username": "test","id":"fdsf345"}}, 201
Note the postfixed number is the status code returned.
Alternatively, you may want to send a message to the client such as:
return {"msg": "Created Successfully"}, 201
Caution: This answer provides a solution that was relevant at that time, before the new features of MongoDB 2.2 and up were introduced. See the other answers if you are using a more recent version of MongoDB.
The field selector parameter is limited to complete properties. It cannot be used to select part of an array, only the entire array. I tried using the $ positional operator, but that didn't work.
The easiest way is to just filter the shapes in the client.
If you really need the correct output directly from MongoDB, you can use a map-reduce to filter the shapes.
function map() {
filteredShapes = [];
this.shapes.forEach(function (s) {
if (s.color === "red") {
filteredShapes.push(s);
}
});
emit(this._id, { shapes: filteredShapes });
}
function reduce(key, values) {
return values[0];
}
res = db.test.mapReduce(map, reduce, { query: { "shapes.color": "red" } })
db[res.result].find()
code {_x000D_
background: black;_x000D_
color: white;_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
}
_x000D_
<p>Some text <code>A<br />B<br />C<br />D</code> continues afterward.</p>
_x000D_
Tested and works in Safari 5 and IE6+.
If you want to convert a python datetime to seconds since epoch you should do it explicitly:
>>> import datetime
>>> datetime.datetime(2012, 04, 01, 0, 0).strftime('%s')
'1333234800'
>>> (datetime.datetime(2012, 04, 01, 0, 0) - datetime.datetime(1970, 1, 1)).total_seconds()
1333238400.0
In Python 3.3+ you can use timestamp()
instead:
>>> import datetime
>>> datetime.datetime(2012, 4, 1, 0, 0).timestamp()
1333234800.0
The solution is:
$('body').scroll(function(e){
console.log(e);
});
You asked how to escape an Apostrophe character (')
in SQL Server. All the answers above do an excellent job of explaining that.
However, depending on the situation, the Right single quotation mark character (’)
might be appropriate.
(No escape characters needed)
-- Direct insert
INSERT INTO Table1 (Column1) VALUES ('John’s')
• Apostrophe (U+0027)
• Right single quotation mark (U+2019)
php artisan dump-autoload
was deprecated on Laravel 5, so you need to use composer dump-autoload
Self-closing tags are valid in HTML5, but not required.
<br>
and <br />
are both fine.
Using DISTINCT should do it:
SELECT DISTINCT id, uname, tel
FROM YourTable
Though you could really do with having a primary key on that table, a way to uniquely identify each record. I'd be considering sticking an IDENTITY column on the table
Assuming that your original dataset is similar to the one you created (i.e. with NA
as character
. You could specify na.strings
while reading the data using read.table
. But, I guess NAs would be detected automatically.
The price
column is factor
which needs to be converted to numeric
class. When you use as.numeric
, all the non-numeric elements (i.e. "NA"
, FALSE) gets coerced to NA
) with a warning.
library(dplyr)
df %>%
mutate(price=as.numeric(as.character(price))) %>%
group_by(company, year, product) %>%
summarise(total.count=n(),
count=sum(is.na(price)),
avg.price=mean(price,na.rm=TRUE),
max.price=max(price, na.rm=TRUE))
I am using the same dataset
(except the ...
row) that was showed.
df = tbl_df(data.frame(company=c("Acme", "Meca", "Emca", "Acme", "Meca","Emca"),
year=c("2011", "2010", "2009", "2011", "2010", "2013"), product=c("Wrench", "Hammer",
"Sonic Screwdriver", "Fairy Dust", "Kindness", "Helping Hand"), price=c("5.67",
"7.12", "12.99", "10.99", "NA",FALSE)))
accept
can continuously provide new client connections. However, note that it, and other socket calls are usually blocking. Therefore you have a few options at this point:
First of all you should get JdK 8.
if you have Jdk installed.
you should set its path using cmd prompt or system variables.
sometimes it can happen that the path is not set due to which eclipse is unable to get the properties for jdk.
Installing latest ecipse luna can solve your problem.
i have indigo and luna. i can set 1.8 in luna but 1.7 in indigo.Eclipse luna
You can check the eclipse site. it says that the eclipse luna was certainly to associate the properties for jdk 8.
Update pandas 0.17.0
@7stud's answer for the newest pandas version would require to just call
s.plot(
kind='bar',
color=my_colors,
)
instead of
pd.Series.plot(
s,
kind='bar',
color=my_colors,
)
The plotting functions have become members of the Series, DataFrame objects and in fact calling pd.Series.plot
with a color
argument gives an error
Never saw such simple way at official docs or at stack overflow, but i was amazed when found this:
# jinja2.__version__ == 2.8
from jinja2 import Template
def calcName(n, i):
return ' '.join([n] * i)
template = Template("Hello {{ calcName('Gandalf', 2) }}")
template.render(calcName=calcName)
# or
template.render({'calcName': calcName})
Angular 10
You should now edit the tsconfig.app.json
(notice the "app" in the name) file instead.
There you'll find the compilerOptions
, and you simply add resolveJsonModule: true
.
So, for example, the file in a brand new project should look like this:
/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
"extends": "./tsconfig.base.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": [],
"resolveJsonModule": true
},
"files": [
"src/main.ts",
"src/polyfills.ts"
],
"include": [
"src/**/*.d.ts"
]
}
You can use:
if [ 1 -eq 0 ]; then
echo "The code that you want commented out goes here."
echo "This echo statement will not be called."
fi
If the number of your messages is limited then the following may help. I used jQuery for the following example, but it works with plain js too.
The innerHtml property did not work for me. So I experimented with ...
<div id=successAndErrorMessages-1>100% OK</div>
<div id=successAndErrorMessages-2>This is an error mssg!</div>
and toggled one of the two on/off ...
$("#successAndErrorMessages-1").css('display', 'none')
$("#successAndErrorMessages-2").css('display', '')
For some reason I had to fiddle around with the ordering before it worked in all types of browsers.
In case of a 2D array (matrix), you can use:
[val, idx] = max(A, [], 2);
The idx part will contain the column number of containing the max element of each row.
my solution is
navigationText: ["", ""]
full code is below:
var owl1 = $("#main-demo");
owl1.owlCarousel({
navigation: true, // Show next and prev buttons
slideSpeed: 300,
pagination:false,
singleItem: true, transitionStyle: "fade",
navigationText: ["", ""]
});// Custom Navigation Events
owl1.trigger('owl.play', 4500);
private void button1_Click( object sender, EventArgs e )
{
string s = @"p1=6&p2=7&p3=8";
NameValueCollection nvc = new NameValueCollection();
foreach ( string vp in Regex.Split( s, "&" ) )
{
string[] singlePair = Regex.Split( vp, "=" );
if ( singlePair.Length == 2 )
{
nvc.Add( singlePair[ 0 ], singlePair[ 1 ] );
}
}
}
If you prefer binding your events outside the html-markup (in the javascript) you could do it like this:
document.getElementById("curtainInput").addEventListener(_x000D_
"click",_x000D_
function(event) {_x000D_
if (event.target.value === "Open Curtain") {_x000D_
event.target.value = "Close Curtain";_x000D_
} else {_x000D_
event.target.value = "Open Curtain";_x000D_
}_x000D_
},_x000D_
false_x000D_
);
_x000D_
<!doctype html>_x000D_
<html>_x000D_
<body>_x000D_
<input _x000D_
id="curtainInput" _x000D_
type="button" _x000D_
value="Open Curtain" />_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
If this is C#, it won't work: enums are value types, and can't be null
.
The normal options are to add a None
member:
public enum Color
{
None,
Red,
Green,
Yellow
}
Color color = Color.None;
...or to use Nullable
:
Color? color = null;
In this post I'll provide you with three different methods of doing what you ask for. I actually recommend using the last snippet, since it's easiest to comprehend as well as being quite neat in code.
There is a function dedicated for just this purpose, preg_grep
. It will take a regular expression as first parameter, and an array as the second.
See the below example:
$haystack = array (
'say hello',
'hello stackoverflow',
'hello world',
'foo bar bas'
);
$matches = preg_grep ('/^hello (\w+)/i', $haystack);
print_r ($matches);
output
Array
(
[1] => hello stackoverflow
[2] => hello world
)
array_reduce
with preg_match
can solve this issue in clean manner; see the snippet below.
$haystack = array (
'say hello',
'hello stackoverflow',
'hello world',
'foo bar bas'
);
function _matcher ($m, $str) {
if (preg_match ('/^hello (\w+)/i', $str, $matches))
$m[] = $matches[1];
return $m;
}
// N O T E :
// ------------------------------------------------------------------------------
// you could specify '_matcher' as an anonymous function directly to
// array_reduce though that kind of decreases readability and is therefore
// not recommended, but it is possible.
$matches = array_reduce ($haystack, '_matcher', array ());
print_r ($matches);
output
Array
(
[0] => stackoverflow
[1] => world
)
Documentation
array_reduce
seems tedious, isn't there another way?Yes, and this one is actually cleaner though it doesn't involve using any pre-existing array_*
or preg_*
function.
Wrap it in a function if you are going to use this method more than once.
$matches = array ();
foreach ($haystack as $str)
if (preg_match ('/^hello (\w+)/i', $str, $m))
$matches[] = $m[1];
Documentation
jbernadas already mentioned the Aho-Corasick-Algorithm in order to reduce complexity.
Here is one way to use it in Python:
Download aho_corasick.py from here
Put it in the same directory as your main Python file and name it aho_corasick.py
Try the alrorithm with the following code:
from aho_corasick import aho_corasick #(string, keywords)
print(aho_corasick(string, ["keyword1", "keyword2"]))
Note that the search is case-sensitive
JSON does not allow real line-breaks. You need to replace all the line breaks with \n
.
eg:
"first line
second line"
can saved with:
"first line\nsecond line"
Note:
for Python
, this should be written as:
"first line\\nsecond line"
where \\
is for escaping the backslash, otherwise python will treat \n
as
the control character "new line"
You can do that using Python 2.
request
from urllib2 import urlopen
You cannot have request
in Python 2, you need to have Python 3 or above.
MaterialApp( debugShowCheckedModeBanner: false, )
The correct result for me with SQL Server 2017:
USE <DATABASE>;
EXEC sp_configure 'clr enabled' ,1
GO
RECONFIGURE
GO
EXEC sp_configure 'clr enabled' -- make sure it took
GO
USE <DATABASE>
GO
EXEC sp_changedbowner 'sa'
USE <DATABASE>
GO
ALTER DATABASE <DATABASE> SET TRUSTWORTHY ON;
From An error occurred in the Microsoft .NET Framework while trying to load assembly id 65675
input = {"A":"a", "B":"b", "C":"c"}
output = {k:v for (k,v) in input.items() if key_satifies_condition(k)}
Follow the following steps if you are using proxy server:
Hope this helps.
Excel 2007 has a feature for doing this under the "Data" tab that works pretty nicely.
As of Angular Material v9, it now has a clipboard CDK
It can be used as simply as
<button [cdkCopyToClipboard]="This goes to Clipboard">Copy this</button>
I am installing pyfuzzy
but is is not in PyPI; it returns the message: No matching distribution found for pyfuzzy
.
I tried the accepted answer
pip install --no-index --find-links=file:///Users/victor/Downloads/pyfuzzy-0.1.0 pyfuzzy
But it does not work either and returns the following error:
Ignoring indexes: https://pypi.python.org/simple Collecting pyfuzzy Could not find a version that satisfies the requirement pyfuzzy (from versions: ) No matching distribution found for pyfuzzy
At last , I have found a simple good way there: https://pip.pypa.io/en/latest/reference/pip_install.html
Install a particular source archive file.
$ pip install ./downloads/SomePackage-1.0.4.tar.gz
$ pip install http://my.package.repo/SomePackage-1.0.4.zip
So the following command worked for me:
pip install ../pyfuzzy-0.1.0.tar.gz.
Hope it can help you.
Try this:
df = spark.createDataFrame([('2018-07-27 10:30:00',)], ['Date_col'])
df.select(from_unixtime(unix_timestamp(df.Date_col, 'yyyy-MM-dd HH:mm:ss')).alias('dt_col'))
df.show()
+-------------------+
| Date_col|
+-------------------+
|2018-07-27 10:30:00|
+-------------------+
Sets pattern validation error key if the ngModel $viewValue does not match a RegExp found by evaluating the Angular expression given in the attribute value. If the expression evaluates to a RegExp object, then this is used directly. If the expression evaluates to a string, then it will be converted to a RegExp after wrapping it in ^ and $ characters.
It seems that a most voted answer in this question should be updated, because when i try it, it does not apply test
function and validation not working.
Example from Angular docs works good for me:
Modifying built-in validators
html
<form name="form" class="css-form" novalidate>
<div>
Overwritten Email:
<input type="email" ng-model="myEmail" overwrite-email name="overwrittenEmail" />
<span ng-show="form.overwrittenEmail.$error.email">This email format is invalid!</span><br>
Model: {{myEmail}}
</div>
</form>
js
var app = angular.module('form-example-modify-validators', []);
app.directive('overwriteEmail', function() {
var EMAIL_REGEXP = /^[a-z0-9!#$%&'*+/=?^_`{|}~.-]+@example\.com$/i;
return {
require: 'ngModel',
restrict: '',
link: function(scope, elm, attrs, ctrl) {
// only apply the validator if ngModel is present and Angular has added the email validator
if (ctrl && ctrl.$validators.email) {
// this will overwrite the default Angular email validator
ctrl.$validators.email = function(modelValue) {
return ctrl.$isEmpty(modelValue) || EMAIL_REGEXP.test(modelValue);
};
}
}
};
});
try this.....it work in mine.... code:
<div class="container">
<br>
<div id="myCarousel" class="carousel slide" data-ride="carousel">
<!-- Indicators -->
<ol class="carousel-indicators">
<li data-target="#myCarousel" data-slide-to="0" class="active"></li>
<li data-target="#myCarousel" data-slide-to="1"></li>
<li data-target="#myCarousel" data-slide-to="2"></li>
<li data-target="#myCarousel" data-slide-to="3"></li>
</ol>
<!-- Wrapper for slides -->
<div class="carousel-inner" role="listbox">
<div class="item active">
<div class="span4" style="padding-left: 18px;">
<img src="http://placehold.it/290x180" class="img-thumbnail">
<img src="http://placehold.it/290x180" class="img-thumbnail">
<img src="http://placehold.it/290x180" class="img-thumbnail">
</div>
</div>
<div class="item">
<div class="span4" style="padding-left: 18px;">
<img src="http://placehold.it/290x180" class="img-thumbnail">
<img src="http://placehold.it/290x180" class="img-thumbnail">
<img src="http://placehold.it/290x180" class="img-thumbnail">
</div>
</div>
</div>
<a class="right carousel-control" href="#myCarousel" role="button" data-slide="next">
<span class="glyphicon glyphicon-chevron-right" aria-hidden="true"></span>
<span class="sr-only">Next</span>
</a>
</div>
</div>
It is just this:
if 'errormessage' in kwargs:
print("yeah it's here")
You need to check, if the key is in the dictionary. The syntax for that is some_key in some_dict
(where some_key
is something hashable, not necessarily a string).
The ideas you have linked (these ideas) contained examples for checking if specific key existed in dictionaries returned by locals()
and globals()
. Your example is similar, because you are checking existence of specific key in kwargs
dictionary (the dictionary containing keyword arguments).
if you want to get the index values, you can simply do:
dataframe.index
this will output a pandas.core.index
You can use recursion to solve this.
first get the length of an integer number by using following recursive function.
int Length(int num,int count){
if(num==0){
return count;
}
else{
count++;
return Lenght(num/10,count);
}
}
and then you can simply multiply remainder of a number by 10^(Length of integer - 1).
int ReturnReverse(int num,int Length,int reverse){
if(Length!=0){
reverse = reverse + ((num%10) * (int)(Math.pow(10,Length-1)));
return ReturnReverse(num/10,Length-1,reverse);
}
return reverse;
}
The whole Source Code :
import java.util.Scanner;
public class ReverseNumbers {
int Length(int num, int count) {
if (num == 0) {
return count;
} else {
return Length(num / 10, count + 1);
}
}
int ReturnReverse(int num, int Length, int reverse) {
if (Length != 0) {
reverse = reverse + ((num % 10) * (int) (Math.pow(10, Length - 1)));
return ReturnReverse(num / 10, Length - 1, reverse);
}
return reverse;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
ReverseNumbers reverseNumbers = new ReverseNumbers();
reverseNumbers.ReturnReverse(N, reverseNumbers.Length(N, 0), reverseNumbers.ReturnReverse(N, reverseNumbers.Length(N, 0), 0));
scanner.close();
}
}
When you create a flex container various default flex rules come into play.
Two of these default rules are flex-direction: row
and align-items: stretch
. This means that flex items will automatically align in a single row, and each item will fill the height of the container.
If you don't want flex items to stretch – i.e., like you wrote:
make its height the minimum required for holding its content
... then simply override the default with align-items: flex-start
.
#a {_x000D_
display: flex;_x000D_
align-items: flex-start; /* NEW */_x000D_
}_x000D_
#a > div {_x000D_
background-color: red;_x000D_
padding: 5px;_x000D_
margin: 2px;_x000D_
}_x000D_
#b {_x000D_
height: auto;_x000D_
}
_x000D_
<div id="a">_x000D_
<div id="b">left</div>_x000D_
<div>_x000D_
right<br>right<br>right<br>right<br>right<br>_x000D_
</div>_x000D_
</div>
_x000D_
Here's an illustration from the flexbox spec that highlights the five values for align-items
and how they position flex items within the container. As mentioned before, stretch
is the default value.
Source: W3C
What bout this query (based on the description from manual)?
SELECT table_name
FROM information_schema.tables
WHERE table_schema='public'
AND table_type='BASE TABLE';
See link here. You find your solution. And try:
Creating a Custom Toast View
If a simple text message isn't enough, you can create a customized layout for your toast notification. To create a custom layout, define a View layout, in XML or in your application code, and pass the root View object to the setView (View) method.
For example, you can create the layout for the toast visible in the screenshot to the right with the following XML (saved as toast_layout.xml):
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toast_layout_root"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:background="#DAAA"
>
<ImageView android:id="@+id/image"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_marginRight="10dp"
/>
<TextView android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:textColor="#FFF"
/>
</LinearLayout>
Notice that the ID of the LinearLayout element is "toast_layout". You must use this ID to inflate the layout from the XML, as shown here:
LayoutInflater inflater = getLayoutInflater();
View layout = inflater.inflate(R.layout.toast_layout,
(ViewGroup) findViewById(R.id.toast_layout_root));
ImageView image = (ImageView) layout.findViewById(R.id.image);
image.setImageResource(R.drawable.android);
TextView text = (TextView) layout.findViewById(R.id.text);
text.setText("Hello! This is a custom toast!");
Toast toast = new Toast(getApplicationContext());
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.setDuration(Toast.LENGTH_LONG);
toast.setView(layout);
toast.show();
First, retrieve the LayoutInflater with getLayoutInflater() (or getSystemService()), and then inflate the layout from XML using inflate(int, ViewGroup). The first parameter is the layout resource ID and the second is the root View. You can use this inflated layout to find more View objects in the layout, so now capture and define the content for the ImageView and TextView elements. Finally, create a new Toast with Toast(Context) and set some properties of the toast, such as the gravity and duration. Then call setView(View) and pass it the inflated layout. You can now display the toast with your custom layout by calling show().
Note: Do not use the public constructor for a Toast unless you are going to define the layout with setView(View). If you do not have a custom layout to use, you must use makeText(Context, int, int) to create the Toast.
You can execute shell script in two ways,either by using cron job or by writing a shell script
Lets assume your script name is "yourscript.sh"
First check the user permission of the script. use below command to check user permission of the script
ll script.sh
If the script is in root,then use below command
sudo crontab -e
Second if the script holds the user "ubuntu", then use below command
crontab -e
Add the following line in your crontab:-
55 23 * * * /path/to/yourscript.sh
Another way of doing this is to write a script and run it in the backgroud
Here is the script where you have to put your script name(eg:- youscript.sh) which is going to run at 23:55pm everyday
#!/bin/bash
while true
do
/home/modassir/yourscript.sh
sleep 1d
done
save it in a file (lets name it "every-day.sh")
sleep 1d - means it waits for one day and then it runs again.
now give the permission to your script.use below command:-
chmod +x every-day.sh
now, execute this shell script in the background by using "nohup". This will keep executing the script even after you logout from your session.
use below command to execute the script.
nohup ./every-day.sh &
Note:- to run "yourscript.sh" at 23:55pm everyday,you have to execute "every-day.sh" script at exactly 23:55pm.
There is an Apple style Gallery Slider over at http://www.jqueryfordesigners.com/slider-gallery/ which uses jQuery and the UI.
Flushing the session forces Hibernate to synchronize the in-memory state of the Session
with the database (i.e. to write changes to the database). By default, Hibernate will flush changes automatically for you:
Allowing to explicitly flush the Session
gives finer control that may be required in some circumstances (to get an ID assigned, to control the size of the Session,...).
Since you are the only user:
git reset --hard HEAD@{1}
git push -f
git reset --hard HEAD@{1}
( basically, go back one commit, force push to the repo, then go back again - remove the last step if you don't care about the commit )
Without doing any changes to your local repo, you can also do something like:
git push -f origin <sha_of_previous_commit>:master
Generally, in published repos, it is safer to do git revert
and then git push
If you stick to HTML structure and proper selectors according to the Bootstrap convention, you should be alright.
<div class="panel-group" id="accordion">
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse1">Collapsible Group 1</a>
</h4>
</div>
<div id="collapse1" class="panel-collapse collapse in">
<div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse2">Collapsible Group 2</a>
</h4>
</div>
<div id="collapse2" class="panel-collapse collapse">
<div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>
</div>
</div>
<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a data-toggle="collapse" data-parent="#accordion" href="#collapse3">Collapsible Group 3</a>
</h4>
</div>
<div id="collapse3" class="panel-collapse collapse">
<div class="panel-body">Lorem ipsum dolor sit amet, consectetur adipisicing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.</div>
</div>
</div>
</div>
Thanks to Ging3r i got solution:
follow these steps:
don't use in dependency tag. Use following in dependencies tag in pom.xml file::
<dependency>
<groupId>com.netsuite.suitetalk.proxy.v2019_1</groupId>
<artifactId>suitetalk-axis-proxy-v2019_1</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.netsuite.suitetalk.client.v2019_1</groupId>
<artifactId>suitetalk-client-v2019_1</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>com.netsuite.suitetalk.client.common</groupId>
<artifactId>suitetalk-client-common</artifactId>
<version>1.0.0</version>
</dependency>
use following code in plugins tag in pom.xml file:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
<executions>
<execution>
<id>suitetalk-proxy</id>
<phase>clean</phase>
<configuration>
<file>${basedir}/lib/suitetalk-axis-proxy-v2019_1-1.0.0.jar</file>
<repositoryLayout>default</repositoryLayout>
<groupId>com.netsuite.suitetalk.proxy.v2019_1</groupId>
<artifactId>suitetalk-axis-proxy-v2019_1</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<generatePom>true</generatePom>
</configuration>
<goals>
<goal>install-file</goal>
</goals>
</execution>
<execution>
<id>suitetalk-client</id>
<phase>clean</phase>
<configuration>
<file>${basedir}/lib/suitetalk-client-v2019_1-2.0.0.jar</file>
<repositoryLayout>default</repositoryLayout>
<groupId>com.netsuite.suitetalk.client.v2019_1</groupId>
<artifactId>suitetalk-client-v2019_1</artifactId>
<version>2.0.0</version>
<packaging>jar</packaging>
<generatePom>true</generatePom>
</configuration>
<goals>
<goal>install-file</goal>
</goals>
</execution>
<execution>
<id>suitetalk-client-common</id>
<phase>clean</phase>
<configuration>
<file>${basedir}/lib/suitetalk-client-common-1.0.0.jar</file>
<repositoryLayout>default</repositoryLayout>
<groupId>com.netsuite.suitetalk.client.common</groupId>
<artifactId>suitetalk-client-common</artifactId>
<version>1.0.0</version>
<packaging>jar</packaging>
<generatePom>true</generatePom>
</configuration>
<goals>
<goal>install-file</goal>
</goals>
</execution>
</executions>
</plugin>
I am including 3 jars from lib folder:
Finally, use mvn clean
and then mvn install
or 'mvn clean install' and just run jar file from target folder or the path where install(see mvn install
log):
java -jar abc.jar
note: Remember one thing if you are working at jenkins then first use mvn clean
and then mvn clean install
command work for you because with previous code mvn clean install
command store cache for dependency.
In recent versions of Gradle (ie. 5+), if you run your build with the --scan
flag, it tells you all kinds of useful information, including dependencies, in a browser where you can click around.
gradlew --scan clean build
It will analyze the crap out of what's going on in that build. It's pretty neat.
You cannot shrink a transaction log smaller than its initially created size.
Directory Services/LDAP lookups can be used to serve this purpose. It involves some changes at infrastructure level, but most production environments have such provision
public void scheduleAtFixedRate(TimerTask task,
long delay,
long period)
Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals, separated by the specified period.
In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).
Fixed-rate execution is appropriate for recurring activities that are sensitive to absolute time, such as ringing a chime every hour on the hour, or running scheduled maintenance every day at a particular time. It is also appropriate for recurring activities where the total time to perform a fixed number of executions is important, such as a countdown timer that ticks once every second for ten seconds. Finally, fixed-rate execution is appropriate for scheduling multiple repeating timer tasks that must remain synchronized with respect to one another.
Parameters:
Throws:
To sort by MULTIPLE COLUMN (Sort by column_1
, and then sort by column_2
)
with open('unsorted.csv',newline='') as csvfile:
spamreader = csv.DictReader(csvfile, delimiter=";")
sortedlist = sorted(spamreader, key=lambda row:(row['column_1'],row['column_2']), reverse=False)
with open('sorted.csv', 'w') as f:
fieldnames = ['column_1', 'column_2', column_3]
writer = csv.DictWriter(f, fieldnames=fieldnames)
writer.writeheader()
for row in sortedlist:
writer.writerow(row)
If you need to download only text file into String
you can use this simple way, Swift 5:
let list = try? String(contentsOf: URL(string: "https://example.com/file.txt")!)
In case you want non optional result or error handling:
do {
let list = try String(contentsOf: URL(string: "https://example.com/file.txt")!)
}
catch {
// Handle error here
}
You should know that network operations may take some time, to prevent it from running in main thread and locking your UI, you may want to execute the code asynchronously, for example:
DispatchQueue.global().async {
let list = try? String(contentsOf: URL(string: "https://example.com/file.txt")!)
}
You are trying to run a Python 2 codebase with Python 3. xrange()
was renamed to range()
in Python 3.
Run the game with Python 2 instead. Don't try to port it unless you know what you are doing, most likely there will be more problems beyond xrange()
vs. range()
.
For the record, what you are seeing is not a syntax error but a runtime exception instead.
If you do know what your are doing and are actively making a Python 2 codebase compatible with Python 3, you can bridge the code by adding the global name to your module as an alias for range
. (Take into account that you may have to update any existing range()
use in the Python 2 codebase with list(range(...))
to ensure you still get a list object in Python 3):
try:
# Python 2
xrange
except NameError:
# Python 3, xrange is now named range
xrange = range
# Python 2 code that uses xrange(...) unchanged, and any
# range(...) replaced with list(range(...))
or replace all uses of xrange(...)
with range(...)
in the codebase and then use a different shim to make the Python 3 syntax compatible with Python 2:
try:
# Python 2 forward compatibility
range = xrange
except NameError:
pass
# Python 2 code transformed from range(...) -> list(range(...)) and
# xrange(...) -> range(...).
The latter is preferable for codebases that want to aim to be Python 3 compatible only in the long run, it is easier to then just use Python 3 syntax whenever possible.
The correct way of use forms now in Angular2 is:
<form (ngSubmit)="onSubmit()">
<label>Username:</label>
<input type="text" class="form-control" [(ngModel)]="user.username" name="username" #username="ngModel" required />
<label>Contraseña:</label>
<input type="password" class="form-control" [(ngModel)]="user.password" name="password" #password="ngModel" required />
<input type="submit" value="Entrar" class="btn btn-primary"/>
</form>
The old way doesn't works anymore
You can use git gui
to delete multiple branches at once.
From Command Prompt/Bash -> git gui
-> Remote -> Delete branch ... -> select remote branches you want to remove -> Delete.
Used in Angular 4 - it's working. Best way to format a date is a pipe.
Create your custom pipe like this:
import { Pipe, PipeTransform} from '@angular/core';
import { DatePipe } from '@angular/common';
@Pipe({
name: 'dateFormat'
})
export class DateFormatPipe extends DatePipe implements PipeTransform {
transform(value: any, args?: any): any {
///MMM/dd/yyyy
return super.transform(value, "MMM/dd/yyyy");
}
}
and it's used in a TypeScript class like this:
////my class////
export class MyComponent
{
constructor(private _dateFormatPipe:DateFormatPipe)
{
}
formatHereDate()
{
let myDate = this._dateFormatPipe.transform(new Date())//formatting current ///date here
//you can pass any date type variable
}
}
This is the most flexible/reusable way to reset all select boxes in your form.
var $form = $('form') // Replace with your form selector
$('select', $form).each(function() {
$(this).val($(this).prop('defaultSelected'));
});
The behavior depends on which version your repository has. Subversion 1.5 allows 4 types of merge:
Subversion before 1.5 only allowed the first 2 formats.
Technically you can perform all merges with the first two methods, but the last two enable subversion 1.5's merge tracking.
TortoiseSVN's options merge a range or revisions maps to method 3 when your repository is 1.5+ or to method one when your repository is older.
When merging features over to a release/maintenance branch you should use the 'Merge a range of revisions' command.
Only when you want to merge all features of a branch back to a parent branch (commonly trunk) you should look into using 'Reintegrate a branch'.
And the last command -Merge two different trees- is only usefull when you want to step outside the normal branching behavior. (E.g. Comparing different releases and then merging the differenct to yet another branch)
I had the same issue as you, I figured it out. Facebook now roles some features as plugins. In the left hand side select Products and add product. Then select Facbook Login. Pretty straight forward from there, you'll see all the Oauth options show up.
Well I fond this post because I got a similar error. So I added the top line like in your controller respond_to :html, :json
then I got a different error(see below)
The controller-level respond_to' feature has been extracted to the
responders` gem. Add it to your Gemfile to continue using this feature: gem 'responders', '~> 2.0' Consult the Rails upgrade guide for details.
But that had nothing to do with it.
Imagine if one went into a store and asked for a device with a power switch. You didn't say whether you wanted a copier, television, vacuum cleaner, desk lamp, waffle maker, or anything. You asked for a device with a power switch. Would you expect the clerk to offer you something that could only be described as "a device with a power switch"?
A typical interface would be analogous to the description "a device with a power switch". Knowing that a piece of equipment is " a device with a power switch" would allow one to do some operations with it (i.e. turn it on and off), and one might plausibly want a list of e.g. "devices with power switches that will need to be turned off at the end of the day", without the devices having to share any characteristic beyond having a power switch, but such situations generally only apply when applying some common operation to devices that were created for some more specific purpose. When creating something from scratch, one would more likely wand a "copier", "television", "vacuum cleaner", or other particular type of device, than some random "device with a power switch".
There are some circumstances where one may want a vaguely-defined object, and really not care about what exactly it is. "Give me your cheapest device that can boil water". It would be nice if one could specify that when someone asks for an arbitrary object with "water boiling" ability, they should be offered an Acme 359 Electric Teakettle, and indeed when using classes it's possible to do that. Note, however, that someone who asks for a "device to boil water" would not be given a "device to boil water", but an "Acme 359 Electric Teakettle".
Same as WorksheetFunction.EncodeUrl
with UTF-8 support:
Public Function EncodeURL(url As String) As String
Dim buffer As String, i As Long, c As Long, n As Long
buffer = String$(Len(url) * 12, "%")
For i = 1 To Len(url)
c = AscW(Mid$(url, i, 1)) And 65535
Select Case c
Case 48 To 57, 65 To 90, 97 To 122, 45, 46, 95 ' Unescaped 0-9A-Za-z-._ '
n = n + 1
Mid$(buffer, n) = ChrW(c)
Case Is <= 127 ' Escaped UTF-8 1 bytes U+0000 to U+007F '
n = n + 3
Mid$(buffer, n - 1) = Right$(Hex$(256 + c), 2)
Case Is <= 2047 ' Escaped UTF-8 2 bytes U+0080 to U+07FF '
n = n + 6
Mid$(buffer, n - 4) = Hex$(192 + (c \ 64))
Mid$(buffer, n - 1) = Hex$(128 + (c Mod 64))
Case 55296 To 57343 ' Escaped UTF-8 4 bytes U+010000 to U+10FFFF '
i = i + 1
c = 65536 + (c Mod 1024) * 1024 + (AscW(Mid$(url, i, 1)) And 1023)
n = n + 12
Mid$(buffer, n - 10) = Hex$(240 + (c \ 262144))
Mid$(buffer, n - 7) = Hex$(128 + ((c \ 4096) Mod 64))
Mid$(buffer, n - 4) = Hex$(128 + ((c \ 64) Mod 64))
Mid$(buffer, n - 1) = Hex$(128 + (c Mod 64))
Case Else ' Escaped UTF-8 3 bytes U+0800 to U+FFFF '
n = n + 9
Mid$(buffer, n - 7) = Hex$(224 + (c \ 4096))
Mid$(buffer, n - 4) = Hex$(128 + ((c \ 64) Mod 64))
Mid$(buffer, n - 1) = Hex$(128 + (c Mod 64))
End Select
Next
EncodeURL = Left$(buffer, n)
End Function
this works nicely
width:40%; // the width of the content div
right:0;
margin-right:30%; // 1/2 the remaining space
This resizes nicely with adaptive layouts also..
CSS example would be:
.centered-div {
position:fixed;
background-color:#fff;
text-align:center;
width:40%;
right:0;
margin-right:30%;
}
In case if you were to pass the image as part of JSON along with other attributes, you can use the below snippet.
client.py
import base64
import json
import requests
api = 'http://localhost:8080/test'
image_file = 'sample_image.png'
with open(image_file, "rb") as f:
im_bytes = f.read()
im_b64 = base64.b64encode(im_bytes).decode("utf8")
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
payload = json.dumps({"image": im_b64, "other_key": "value"})
response = requests.post(api, data=payload, headers=headers)
try:
data = response.json()
print(data)
except requests.exceptions.RequestException:
print(response.text)
server.py
import io
import json
import base64
import logging
import numpy as np
from PIL import Image
from flask import Flask, request, jsonify, abort
app = Flask(__name__)
app.logger.setLevel(logging.DEBUG)
@app.route("/test", methods=['POST'])
def test_method():
# print(request.json)
if not request.json or 'image' not in request.json:
abort(400)
# get the base64 encoded string
im_b64 = request.json['image']
# convert it into bytes
img_bytes = base64.b64decode(im_b64.encode('utf-8'))
# convert bytes data to PIL Image object
img = Image.open(io.BytesIO(img_bytes))
# PIL image object to numpy array
img_arr = np.asarray(img)
print('img shape', img_arr.shape)
# process your img_arr here
# access other keys of json
# print(request.json['other_key'])
result_dict = {'output': 'output_key'}
return result_dict
def run_server_api():
app.run(host='0.0.0.0', port=8080)
if __name__ == "__main__":
run_server_api()
I got to this question after if got this same error message. However in my case we had two URL's with different subdomains (http://example1.xxx.com/someservice and http://example2.yyy.com/someservice) which were directed to the same server. This server was having only one wildcard certificate for the *.xxx.com domain. When using the service via the second domain, the found certicate (*.xxx.com) does not match with the requested domain (*.yyy.com) and the error occurs.
In this case we should not try to fix such an errormessage by lowering SSL security, but should check the server and certificates on it.
What I have done in this situation is that I put in the option elements OnClick event like this:
<option onClick="something();">Option Name</option>
Then just create a script function like this:
function something(){
alert("Hello");
}
UPDATE:
Unfortunately I can't comment so I'm updating here
TrueBlueAussie apparently jsfiddle is having some issues, check here if it works or not: http://js.do/code/klm
pcolor()
with the vmin
, vmax
parameters.It is detailed in this answer: https://stackoverflow.com/a/3376734/21974
For compatibility and ease of use it's often better to use FIND to do this.
You must also consider if you would like to match case sensitively or case insensitively.
The method with 78 points (I believe I was referring to paxdiablo's post) will only match Case Sensitively, so you must put a separate check for every case variation for every possible iteration you may want to match.
( What a pain! At only 3 letters that means 9 different tests in order to accomplish the check! )
In addition, many times it is preferable to match command output, a variable in a loop, or the value of a pointer variable in your batch/CMD which is not as straight forward.
For these reasons this is a preferable alternative methodology:
Use: Find [/I] [/V] "Characters to Match"
[/I] (case Insensitive) [/V] (Must NOT contain the characters)
As Single Line:
ECHO.%Variable% | FIND /I "ABC">Nul && ( Echo.Found "ABC" ) || ( Echo.Did not find "ABC" )
Multi-line:
ECHO.%Variable%| FIND /I "ABC">Nul && (
Echo.Found "ABC"
) || (
Echo.Did not find "ABC"
)
As mentioned this is great for things which are not in variables which allow string substitution as well:
FOR %A IN (
"Some long string with Spaces does not contain the expected string"
oihu AljB
lojkAbCk
Something_Else
"Going to evaluate this entire string for ABC as well!"
) DO (
ECHO.%~A| FIND /I "ABC">Nul && (
Echo.Found "ABC" in "%A"
) || ( Echo.Did not find "ABC" )
)
Output From a command:
NLTest | FIND /I "ABC">Nul && ( Echo.Found "ABC" ) || ( Echo.Did not find "ABC" )
As you can see this is the superior way to handle the check for multiple reasons.
Constant Value Description
----------------------------------------------------------------
vbCr Chr(13) Carriage return
vbCrLf Chr(13) & Chr(10) Carriage return–linefeed combination
vbLf Chr(10) Line feed
vbCr : - return to line beginning
Represents a carriage-return character for print and display functions.
vbCrLf : - similar to pressing Enter
Represents a carriage-return character combined with a linefeed character for print and display
functions.
vbLf : - go to next line
Represents a linefeed character for print and display functions.
Read More from Constants Class
I recommend this article by my colleague Nick Parlante (from back when he was still at Stanford). The count of structurally different binary trees (problem 12) has a simple recursive solution (which in closed form ends up being the Catalan formula which @codeka's answer already mentioned).
I'm not sure how the number of structurally different binary search trees (BSTs for short) would differ from that of "plain" binary trees -- except that, if by "consider tree node values" you mean that each node may be e.g. any number compatible with the BST condition, then the number of different (but not all structurally different!-) BSTs is infinite. I doubt you mean that, so, please clarify what you do mean with an example!
Dictionary<string, Dictionary<string, string>> like = new Dictionary<string, Dictionary<string, string>>();
Dictionary<string, string> first = like.Values.First();
{{ app.user.username|default('') }}
Just present login username for example, filter function default('') should be nice when user is NOT login by just avoid annoying error message.
Actually, ojdbc14.jar doesn't really say anything about the real version of the driver (see JDBC Driver Downloads), except that it predates Oracle 11g. In such situation, you should provide the exact version.
Anyway, I think you'll find some explanation in What is going on with DATE and TIMESTAMP? In short, they changed the behavior in 9.2 drivers and then again in 11.1 drivers.
This might explain the differences you're experiencing (and I suggest using the most recent version i.e. the 11.2 drivers).