The question has been answered. But I wanted to add a concrete example.
class Point{
public:
Point(int theX, int theY) :x(theX), y(theY)
{}
// Print the object
friend ostream& operator <<(ostream& outputStream, const Point& p);
private:
int x;
int y;
};
ostream& operator <<(ostream& outputStream, const Point& p){
int posX = p.x;
int posY = p.y;
outputStream << "x="<<posX<<","<<"y="<<posY;
return outputStream;
}
This example requires understanding operator overload.
If you use macOS High Sierra or upper version you can find the bash script at the location:
sudo /Library/Application\ Support/VirtualBox/LaunchDaemons/VirtualBoxStartup.sh restart
So If you got this kind of error:
/Library/Application Support/VirtualBox/VBoxDrv.kext failed to load - (libkern/kext) system policy prevents loading; check the system/kernel logs for errors or try kextutil(8).
You can solve it via System Preferences > Security & Privacy
section and Allow
the VirtualBox.
In the Unix world, there were a few possible arrangements for the sizes of integers and pointers for 64-bit platforms. The two mostly widely used were ILP64 (actually, only a very few examples of this; Cray was one such) and LP64 (for almost everything else). The acronynms come from 'int, long, pointers are 64-bit' and 'long, pointers are 64-bit'.
Type ILP64 LP64 LLP64
char 8 8 8
short 16 16 16
int 64 32 32
long 64 64 32
long long 64 64 64
pointer 64 64 64
The ILP64 system was abandoned in favour of LP64 (that is, almost all later entrants used LP64, based on the recommendations of the Aspen group; only systems with a long heritage of 64-bit operation use a different scheme). All modern 64-bit Unix systems use LP64. MacOS X and Linux are both modern 64-bit systems.
Microsoft uses a different scheme for transitioning to 64-bit: LLP64 ('long long, pointers are 64-bit'). This has the merit of meaning that 32-bit software can be recompiled without change. It has the demerit of being different from what everyone else does, and also requires code to be revised to exploit 64-bit capacities. There always was revision necessary; it was just a different set of revisions from the ones needed on Unix platforms.
If you design your software around platform-neutral integer type names, probably using the C99 <inttypes.h>
header, which, when the types are available on the platform, provides, in signed (listed) and unsigned (not listed; prefix with 'u'):
int8_t
- 8-bit integersint16_t
- 16-bit integersint32_t
- 32-bit integersint64_t
- 64-bit integersuintptr_t
- unsigned integers big enough to hold pointersintmax_t
- biggest size of integer on the platform (might be larger than int64_t
)You can then code your application using these types where it matters, and being very careful with system types (which might be different). There is an intptr_t
type - a signed integer type for holding pointers; you should plan on not using it, or only using it as the result of a subtraction of two uintptr_t
values (ptrdiff_t
).
But, as the question points out (in disbelief), there are different systems for the sizes of the integer data types on 64-bit machines. Get used to it; the world isn't going to change.
Try
\d \w |\d
or add a positive lookahead if you don't want to include the trailing space in the match
\d \w(?= )|\d
When you have two alternatives where one is an extension of the other, put the longer one first, otherwise it will have no opportunity to be matched.
Short answer:
ALTER SCHEMA new_schema TRANSFER old_schema.table_name
I can confirm that the data in the table remains intact, which is probably quite important :)
Long answer as per MSDN docs,
ALTER SCHEMA schema_name
TRANSFER [ Object | Type | XML Schema Collection ] securable_name [;]
If it's a table (or anything besides a Type or XML Schema collection), you can leave out the word Object since that's the default.
Use the Validator to get the errors for a specific entity
if( $form->isValid() )
{
// ...
}
else
{
// get a ConstraintViolationList
$errors = $this->get('validator')->validate( $user );
$result = '';
// iterate on it
foreach( $errors as $error )
{
// Do stuff with:
// $error->getPropertyPath() : the field that caused the error
// $error->getMessage() : the error message
}
}
API reference:
pg_hba.conf
entry define login methods by IP addresses. You need to show the relevant portion of pg_hba.conf
in order to get proper help.
Change this line:
host all all <my-ip-address>/32 md5
To reflect your local network settings. So, if your IP is 192.168.16.78
(class C) with a mask of 255.255.255.0
, then put this:
host all all 192.168.16.0/24 md5
Make sure your WINDOWS MACHINE is in that network 192.168.16.0
and try again.
You can use Jquery's on method and listen for the scroll
event.
This has been discussed on SO multiple times. Here are a few links to get you started:
SO: Capturing image from webcam in java?
openCVF applet: http://www.colorfulwolf.com/blog/2011/07/05/accessing-the-webcam-from-inside-a-java-applet/
config: http://ganeshtiwaridotcomdotnp.blogspot.in/2011/12/opencv-javacv-eclipse-project.html
Whenever you have seen coding from open source community like Guava and from Google Developer (Android Library) they used this approach
List<String> strings = new ArrayList<String>();
because it's hide the implementation detail from user. You precisely
List<String> strings = new ArrayList<String>();
it's generic approach and this specialized approach
ArrayList<String> strings = new ArrayList<String>();
For Reference: Effective Java 2nd Edition: Item 52: Refer to objects by their interfaces
This will give you true if url does not return 200 OK
function check_404($url) {
$headers=get_headers($url, 1);
if ($headers[0]!='HTTP/1.1 200 OK') return true; else return false;
}
Your question can be conveniently divided into several parts:
Does a VPN hide location? Yes, he is capable of this. This is not about GPS determining your location. If you try to change the region via VPN in an application that requires GPS access, nothing will work. However, sites define your region differently. They get an IP address and see what country or region it belongs to. If you can change your IP address, you can change your region. This is exactly what VPNs can do.
How to hide location on Android? There is nothing difficult in figuring out how to set up a VPN on Android, but a couple of nuances still need to be highlighted. Let's start with the fact that not all Android VPNs are created equal. For example, VeePN outperforms many other services in terms of efficiency in circumventing restrictions. It has 2500+ VPN servers and a powerful IP and DNS leak protection system.
You can easily change the location of your Android device by using a VPN. Follow these steps for any device model (Samsung, Sony, Huawei, etc.):
Download and install a trusted VPN.
Install the VPN on your Android device.
Open the application and connect to a server in a different country.
Your Android location will now be successfully changed!
Is it legal? Yes, changing your location on Android is legal. Likewise, you can change VPN settings in Microsoft Edge on your PC, and all this is within the law. VPN allows you to change your IP address, safeguarding your privacy and protecting your actual location from being exposed. However, VPN laws may vary from country to country. There are restrictions in some regions.
Brief summary: Yes, you can change your region on Android and a VPN is a necessary assistant for this. It's simple, safe and legal. Today, VPN is the best way to change the region and unblock sites with regional restrictions.
You only need this:
JFrame frame = new JFrame();
frame.setExtendedState(JFrame.MAXIMIZED_BOTH);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
When you use the MAXIMIZED_BOTH modifier, it will max all the way across the window (height and width).
There are some that suggested using this:
frame.setUndecorated(true);
I won't recommend it, because your window won't have a header, thus no close/restore/minimize button.
The vshost.exe file is the executable run by Visual Studio (Visual Studio host executable). This is the executable that links to Visual Studio and improves debugging.
When you're distributing your application to others, you do not use the vshost.exe or .pdb (debug database) files.
I think what u r looking for is this
<article *ngFor="let news of (news$ | async)?.articles">
<h4 class="head">{{news.title}}</h4>
<div class="desc"> {{news.description}}</div>
<footer>
{{news.author}}
</footer>
The docs say regarding list-style-position
: outside
CSS1 did not specify the precise location of the marker box and for reasons of compatibility, CSS2 remains equally ambiguous. For more precise control of marker boxes, please use markers.
Further up that page is the stuff about markers.
One example is:
LI:before {
display: marker;
content: "(" counter(counter) ")";
counter-increment: counter;
width: 6em;
text-align: center;
}
lst=[[0]*m for i in range(n)]
initialize all matrix n=rows and m=columns
As of the current JRE implementation, Function.identity()
will always return the same instance while each occurrence of identifier -> identifier
will not only create its own instance but even have a distinct implementation class. For more details, see here.
The reason is that the compiler generates a synthetic method holding the trivial body of that lambda expression (in the case of x->x
, equivalent to return identifier;
) and tell the runtime to create an implementation of the functional interface calling this method. So the runtime sees only different target methods and the current implementation does not analyze the methods to find out whether certain methods are equivalent.
So using Function.identity()
instead of x -> x
might save some memory but that shouldn’t drive your decision if you really think that x -> x
is more readable than Function.identity()
.
You may also consider that when compiling with debug information enabled, the synthetic method will have a line debug attribute pointing to the source code line(s) holding the lambda expression, therefore you have a chance of finding the source of a particular Function
instance while debugging. In contrast, when encountering the instance returned by Function.identity()
during debugging an operation, you won’t know who has called that method and passed the instance to the operation.
Or you can try something like this:
Html.DropDownList("Types", Model.Types, new { @readonly = "true" })
Do whatever you want as long as its minimal, consistent, and doesn't break any rules.
Personally, I find the Boost style easiest; it matches the standard library (giving a uniform look to code) and is simple. I personally tack on m
and p
prefixes to members and parameters, respectively, giving:
#ifndef NAMESPACE_NAMES_THEN_PRIMARY_CLASS_OR_FUNCTION_THEN_HPP
#define NAMESPACE_NAMES_THEN_PRIMARY_CLASS_OR_FUNCTION_THEN_HPP
#include <boost/headers/go/first>
#include <boost/in_alphabetical/order>
#include <then_standard_headers>
#include <in_alphabetical_order>
#include "then/any/detail/headers"
#include "in/alphabetical/order"
#include "then/any/remaining/headers/in"
// (you'll never guess)
#include "alphabetical/order/duh"
#define NAMESPACE_NAMES_THEN_MACRO_NAME(pMacroNames) ARE_ALL_CAPS
namespace lowercase_identifers
{
class separated_by_underscores
{
public:
void because_underscores_are() const
{
volatile int mostLikeSpaces = 0; // but local names are condensed
while (!mostLikeSpaces)
single_statements(); // don't need braces
for (size_t i = 0; i < 100; ++i)
{
but_multiple(i);
statements_do();
}
}
const complex_type& value() const
{
return mValue; // no conflict with value here
}
void value(const complex_type& pValue)
{
mValue = pValue ; // or here
}
protected:
// the more public it is, the more important it is,
// so order: public on top, then protected then private
template <typename Template, typename Parameters>
void are_upper_camel_case()
{
// gman was here
}
private:
complex_type mValue;
};
}
#endif
That. (And like I've said in comments, do not adopt the Google Style Guide for your code, unless it's for something as inconsequential as naming convention.)
Here's the Typescript version of Abubakar Ahmad's answer
function imageTo64(
url: string,
callback: (path64: string | ArrayBuffer) => void
): void {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
xhr.onload = (): void => {
const reader = new FileReader();
reader.readAsDataURL(xhr.response);
reader.onloadend = (): void => callback(reader.result);
}
}
h1 { font-size: 150%; }
h2 { font-size: 120%; }
Tune as needed.
As an alternative to $dollarsign
notation, use a within
block:
breast <- within(breast, {
class <- as.numeric(as.character(class))
})
Note that you want to convert your vector to a character before converting it to a numeric. Simply calling as.numeric(class)
will not the ids corresponding to each factor level (1, 2) rather than the levels themselves.
You can fix the rounding by subtracting 0.5 for toFixed, e.g.
(f - 0.005).toFixed(2)
If you are using a relatively recent version of JSHint, the generally preferred approach is to create a .jshintrc file in the root of your project, and put this config in it:
{
"globals": {
"$": false
}
}
This declares to JSHint that $ is a global variable, and the false indicates that it should not be overridden.
The .jshintrc file was not supported in really old versions of JSHint (such as v0.5.5 like the original question in 2012). If you cannot or do not want to use the .jshintrc file, you can add this at the top of the script file:
/*globals $:false */
There is also a shorthand "jquery" jshint option as seen on the JSHint options page..
Quite simple:
$input = array(
array(
'tag_name' => 'google'
),
array(
'tag_name' => 'technology'
)
);
echo implode(', ', array_map(function ($entry) {
return $entry['tag_name'];
}, $input));
and new in php v5.5.0, array_column
:
echo implode(', ', array_column($input, 'tag_name'));
OpenSuse
"sudo zypper install libxml2-devel"
It will install any other dependencies or required packages/libraries
I'm assuming you figured this out already but:
Technical Reference for Log Files in Configuration Manager
That's a list of client-side logs and what they do. They are located in Windows\CCM\Logs
AppEnforce.log
will show you the actual command-line executed and the resulting exit code for each Deployment Type (only for the new style ConfigMgr Applications)
This is my go-to for troubleshooting apps. Haven't really found any other logs that are exceedingly useful.
I know this is not the case but if you need to keep the original freq column, you can use another tidyverse
approach together with rep
:
library(purrr)
df <- data.frame(var1 = c('a', 'b', 'c'), var2 = c('d', 'e', 'f'), freq = 1:3)
df %>%
map_df(., rep, .$freq)
#> # A tibble: 6 x 3
#> var1 var2 freq
#> <fct> <fct> <int>
#> 1 a d 1
#> 2 b e 2
#> 3 b e 2
#> 4 c f 3
#> 5 c f 3
#> 6 c f 3
Created on 2019-12-21 by the reprex package (v0.3.0)
I would like to give another example in which multiple (3) joins are used.
DataClasses1DataContext ctx = new DataClasses1DataContext();
var Owners = ctx.OwnerMasters;
var Category = ctx.CategoryMasters;
var Status = ctx.StatusMasters;
var Tasks = ctx.TaskMasters;
var xyz = from t in Tasks
join c in Category
on t.TaskCategory equals c.CategoryID
join s in Status
on t.TaskStatus equals s.StatusID
join o in Owners
on t.TaskOwner equals o.OwnerID
select new
{
t.TaskID,
t.TaskShortDescription,
c.CategoryName,
s.StatusName,
o.OwnerName
};
You need a root node
<?xml version="1.0" encoding="ISO-8859-1"?>
<documents>
<document>
<name>Sample Document</name>
<type>document</type>
<url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&titletype=Title&fontsize=9&fontface=Arial&spacing=1.0&text=&wordcount3=0</url>
</document>
<document>
<name>Sample</name>
<type>document</type>
<url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&titletype=Title&fontsize=9&fontface=Arial&spacing=1.0&text=&</url>
</document>
</documents>
If you don't reference the imageBytes to carry bytes in the stream, the method won't return anything. Make sure you reference imageBytes = m.ToArray();
public static byte[] SerializeImage() {
MemoryStream m;
string PicPath = pathToImage";
byte[] imageBytes;
using (Image image = Image.FromFile(PicPath)) {
using ( m = new MemoryStream()) {
image.Save(m, image.RawFormat);
imageBytes = new byte[m.Length];
//Very Important
imageBytes = m.ToArray();
}//end using
}//end using
return imageBytes;
}//SerializeImage
These two terms differentiate between two different ways of walking a tree.
It is probably easiest just to exhibit the difference. Consider the tree:
A
/ \
B C
/ / \
D E F
A depth first traversal would visit the nodes in this order
A, B, D, C, E, F
Notice that you go all the way down one leg before moving on.
A breadth first traversal would visit the node in this order
A, B, C, D, E, F
Here we work all the way across each level before going down.
(Note that there is some ambiguity in the traversal orders, and I've cheated to maintain the "reading" order at each level of the tree. In either case I could get to B before or after C, and likewise I could get to E before or after F. This may or may not matter, depends on you application...)
Both kinds of traversal can be achieved with the pseudocode:
Store the root node in Container
While (there are nodes in Container)
N = Get the "next" node from Container
Store all the children of N in Container
Do some work on N
The difference between the two traversal orders lies in the choice of Container
.
The recursive implementation looks like
ProcessNode(Node)
Work on the payload Node
Foreach child of Node
ProcessNode(child)
/* Alternate time to work on the payload Node (see below) */
The recursion ends when you reach a node that has no children, so it is guaranteed to end for finite, acyclic graphs.
At this point, I've still cheated a little. With a little cleverness you can also work-on the nodes in this order:
D, B, E, F, C, A
which is a variation of depth-first, where I don't do the work at each node until I'm walking back up the tree. I have however visited the higher nodes on the way down to find their children.
This traversal is fairly natural in the recursive implementation (use the "Alternate time" line above instead of the first "Work" line), and not too hard if you use a explicit stack, but I'll leave it as an exercise.
This typically occurs when there is unintended output from the script before you start the session. With your current code, you could try to use output buffering to solve it.
try adding a call to the ob_start();
function at the very top of your script and ob_end_flush();
at the very end of the document.
On a system like OSX you might not have pgrep so you can try this appraoch, when looking for processes by name:
while ps axg | grep process_name$ > /dev/null; do sleep 1; done
The $
symbol at the end of the process name ensures that grep matches only process_name to the end of line in the ps output and not itself.
To increase the height of TextField Widget just make use of the maxLines: properties that comes with the widget. For Example: TextField( maxLines: 5 ) // it will increase the height and width of the Textfield.
According to an article on Medium, this will work:
install --upgrade pandas==1.0.0rc0
mysqli is provided by php-mysql-5.3.3-40.el6_6.x86_64
You may need to try the following
yum install php-mysql-5.3.3-40.el6_6.x86_64
SELECT
t.*,
(SELECT COUNT(*) FROM city AS tt WHERE tt.name=t.name) AS count
FROM `city` AS t
WHERE
(SELECT count(*) FROM city AS tt WHERE tt.name=t.name) > 1 ORDER BY count DESC
For ** Laravel 5 or Laravel 5.1 LTS both **, if you have multiple Controllers in Admin folder, Route::group
will be really helpful for you. For example:
Update: Works with Laravel 5.4
My folder Structure:
Http
----Controllers
----Api
----V1
PostsApiController.php
CommentsApiController.php
PostsController.php
PostAPIController:
<?php namespace App\Http\Controllers\Api\V1;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class PostApiController extends Controller {
...
In My Route.php, I set namespace
group to Api\V1
and overall it looks like:
Route::group(
[
'namespace' => 'Api\V1',
'prefix' => 'v1',
], function(){
Route::get('posts', ['uses'=>'PostsApiController@index']);
Route::get('posts/{id}', ['uses'=>'PostssAPIController@show']);
});
For move details to create sub-folder visit this link.
Repeat is supposed to be a simple loop n times loop... a conditionless version of a loop.
#define repeat(n) for (int i = 0; i < n; i++)
repeat(10) {
//do stuff
}
you can also also add an extra barce to isolate the i variable even more
#define repeat(n) { for (int i = 0; i < n; i++)
#define endrepeat }
repeat(10) {
//do stuff
} endrepeat;
[edit] Someone posted a concern about passing a something other than a value, such as an expression. just change to loop to run backwards, causing the expression to be evaluated only once
#define repeat(n) { for (int i = (n); i > 0; --i)
This doesn't answer your question but, in case you missed it, Chris Pederick's Web Developer is now available for Chrome: https://chrome.google.com/extensions/detail/bfbameneiokkgbdmiekhjnmfkcnldhhm.
A solution that works with inherited classes too:
from itertools import chain
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Mixin(object):
def as_dict(self):
tables = [base.__table__ for base in self.__class__.__bases__ if base not in [Base, Mixin]]
tables.append(self.__table__)
return {c.name: getattr(self, c.name) for c in chain.from_iterable([x.columns for x in tables])}
Add an attribute colspan
(abbriviation for 'column span') in your top cell (<td>
) and set its value to 2.
Your table should resembles the following;
<table>
<tr>
<td colspan = "2">
<!-- Merged Columns -->
</td>
</tr>
<tr>
<td>
<!-- Column 1 -->
</td>
<td>
<!-- Column 2 -->
</td>
</tr>
</table>
See also
W3 official docs on HTML Tables
General ternary syntax:
value_true if <test> else value_false
Another way can be:
[value_false, value_true][<test>]
e.g:
count = [0,N+1][count==N]
This evaluates both branches before choosing one. To only evaluate the chosen branch:
[lambda: value_false, lambda: value_true][<test>]()
e.g.:
count = [lambda:0, lambda:N+1][count==N]()
I like
#if DEBUG
//Code run in debugging mode
#else
//Code run in release mode
#endif
I think not only is the question not clear but most people also are not cognizant of the difference. Examine the following saying,
POSIX thread IDs are not the same as the thread IDs returned by the Linux specific
gettid()
system call. POSIX thread IDs are assigned and maintained by the threading implementation. The thread ID returned bygettid()
is a number (similar to a process ID) that is assigned by the kernel. Although each POSIX thread has a unique kernel thread ID in the Linux NPTL threading implementation, an application generally doesn’t need to know about the kernel IDs (and won’t be portable if it depends on knowing them).Excerpted from: The Linux Programming Interface: A Linux and UNIX System Programming Handbook, Michael Kerrisk
IMHO, there is only one portable way that pass a structure in which define a variable holding numbers in an ascending manner e.g. 1,2,3...
to per thread. By doing this, threads' id can be kept track. Nonetheless, int pthread_equal(tid1, tid2)
function should be used.
if (pthread_equal(tid1, tid2)) printf("Thread 2 is same as thread 1.\n");
else printf("Thread 2 is NOT same as thread 1.\n");
Pattern p = Pattern.compile("tom"); //the regular-expression pattern
Matcher m = p.matcher("(bob)(tom)(harry)"); //The data to find matches with
while (m.find()) {
//do something???
}
Use regex to find a match maybe?
Or create an array
String[] a = new String[]{
"tom",
"bob",
"harry"
};
if(a.contains(stringtomatch)){
//do something
}
Remove the []
from the name ([myApp]) of module
angular.module('myApp', [])
And add ng-app="myApp"
to the html and it should work.
Change Integrated security to false in the connection string.
You can check/verify this by opening up the SQL management studio with the username/password you have and see if you can connect/open the database from there. NOTE! Could be a firewall issue as well.
You might want to have some of columns being normalized and the others be unchanged like some of regression tasks which data labels or categorical columns are unchanged So I suggest you this pythonic way (It's a combination of @shg and @Cina answers ):
features_to_normalize = ['A', 'B', 'C']
# could be ['A','B']
df[features_to_normalize] = df[features_to_normalize].apply(lambda x:(x-x.min()) / (x.max()-x.min()))
Try this.... Replace body with parent selector
$('body').on('click', '#my-button', function () {
console.log("yeahhhh!!! but this doesn't work for me :(");
});
$('#test').click(function() {_x000D_
var startDate = moment("01.01.2019", "DD.MM.YYYY");_x000D_
var endDate = moment("01.02.2019", "DD.MM.YYYY");_x000D_
_x000D_
var result = 'Diff: ' + endDate.diff(startDate, 'days');_x000D_
_x000D_
$('#result').html(result);_x000D_
});
_x000D_
#test {_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: #ffb;_x000D_
padding: 10px;_x000D_
border: 2px solid #999;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>_x000D_
_x000D_
<div id='test'>Click Me!!!</div>_x000D_
<div id='result'></div>
_x000D_
you can use send instead of sendFile so you wont face with error! this works will help you!
fs.readFile('public/index1.html',(err,data)=>{
if(err){
consol.log(err);
}else {
res.setHeader('Content-Type', 'application/pdf');
for telling browser that your response is type of PDF
res.setHeader('Content-Disposition', 'attachment; filename='your_file_name_for_client.pdf');
if you want that file open immediately on the same page after user download it.write 'inline' instead attachment in above code.
res.send(data)
// Work on POSIX and Windows
var fs = require("fs");
var stdinBuffer = fs.readFileSync(0); // STDIN_FILENO = 0
console.log(stdinBuffer.toString());
Use Libre Office API Here is an example
libreoffice --headless --convert-to html docx-file-path --outdir html-dir-path
If the table doesn't exist, you can create one with the same schema like so:
CREATE TABLE table2 LIKE table1;
Then, to copy the data over:
INSERT INTO table2 SELECT * FROM table1
For student level programs, Clang has the benefit that it is, by default, stricter wrt. the C standard. For example, the following K&R version of Hello World is accepted without warning by GCC, but rejected by Clang with some pretty descriptive error messages:
main()
{
puts("Hello, world!");
}
With GCC, you have to give it -Werror
to get it to really make a point about this not being a valid C89 program. Also, you still need to use c99
or gcc -std=c99
to get the C99 language.
I think it was not possible earlier but I recently heard about PyMob, which seems interesting because the apps are written in Python and the final outputs are native source codes in various platforms (Obj-C for iOS, Java for Android etc). This is certainly quite unique. This webpage explains it in more detail.
I haven't given it a shot yet, but will take a look soon.
You don't need the assignment, list.append(x)
will always append x
to a
and therefore there's no need te redefine a
.
a = []
for i in range(5):
a.append(i)
print(a)
is all you need. This works because list
s are mutable.
Also see the docs on data structures.
As mentioned by sombody above, restarting eclipse worked for me for the user defined environment variable.
After I restart eclipse IDE, System.getenv()
is picking up my environment variable.
Efficient way to iterate your ArrayList
followed by this link. This type will improve the performance of looping during iteration
int size = list.size();
for(int j = 0; j < size; j++) {
System.out.println(list.get(i));
}
If your Main
class is in a package called FileManagement
, then try:
java -cp . FileManagement.Main
in the parent folder of the FileManagement
folder.
If your Main
class is not in a package (the default package) then cd to the FileManagement
folder and try:
java -cp . Main
More info about the CLASSPATH and how the JRE find classes:
What exactly do you want to know? ActiveRecord has methods that serialize records into JSON. For instance, open up your rails console and enter ModelName.all.to_json
and you will see JSON output. render :json
essentially calls to_json
and returns the result to the browser with the correct headers. This is useful for AJAX calls in JavaScript where you want to return JavaScript objects to use. Additionally, you can use the callback
option to specify the name of the callback you would like to call via JSONP.
For instance, lets say we have a User
model that looks like this: {name: 'Max', email:' [email protected]'}
We also have a controller that looks like this:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
render json: @user
end
end
Now, if we do an AJAX call using jQuery like this:
$.ajax({
type: "GET",
url: "/users/5",
dataType: "json",
success: function(data){
alert(data.name) // Will alert Max
}
});
As you can see, we managed to get the User with id 5 from our rails app and use it in our JavaScript code because it was returned as a JSON object. The callback option just calls a JavaScript function of the named passed with the JSON object as the first and only argument.
To give an example of the callback
option, take a look at the following:
class UsersController < ApplicationController
def show
@user = User.find(params[:id])
render json: @user, callback: "testFunction"
end
end
Now we can crate a JSONP request as follows:
function testFunction(data) {
alert(data.name); // Will alert Max
};
var script = document.createElement("script");
script.src = "/users/5";
document.getElementsByTagName("head")[0].appendChild(script);
The motivation for using such a callback is typically to circumvent the browser protections that limit cross origin resource sharing (CORS). JSONP isn't used that much anymore, however, because other techniques exist for circumventing CORS that are safer and easier.
(4castle's answer is better than the below if you can assume Java >= 9)
You need to create a matcher and use that to iteratively find matches.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
...
List<String> allMatches = new ArrayList<String>();
Matcher m = Pattern.compile("your regular expression here")
.matcher(yourStringHere);
while (m.find()) {
allMatches.add(m.group());
}
After this, allMatches
contains the matches, and you can use allMatches.toArray(new String[0])
to get an array if you really need one.
You can also use MatchResult
to write helper functions to loop over matches
since Matcher.toMatchResult()
returns a snapshot of the current group state.
For example you can write a lazy iterator to let you do
for (MatchResult match : allMatches(pattern, input)) {
// Use match, and maybe break without doing the work to find all possible matches.
}
by doing something like this:
public static Iterable<MatchResult> allMatches(
final Pattern p, final CharSequence input) {
return new Iterable<MatchResult>() {
public Iterator<MatchResult> iterator() {
return new Iterator<MatchResult>() {
// Use a matcher internally.
final Matcher matcher = p.matcher(input);
// Keep a match around that supports any interleaving of hasNext/next calls.
MatchResult pending;
public boolean hasNext() {
// Lazily fill pending, and avoid calling find() multiple times if the
// clients call hasNext() repeatedly before sampling via next().
if (pending == null && matcher.find()) {
pending = matcher.toMatchResult();
}
return pending != null;
}
public MatchResult next() {
// Fill pending if necessary (as when clients call next() without
// checking hasNext()), throw if not possible.
if (!hasNext()) { throw new NoSuchElementException(); }
// Consume pending so next call to hasNext() does a find().
MatchResult next = pending;
pending = null;
return next;
}
/** Required to satisfy the interface, but unsupported. */
public void remove() { throw new UnsupportedOperationException(); }
};
}
};
}
With this,
for (MatchResult match : allMatches(Pattern.compile("[abc]"), "abracadabra")) {
System.out.println(match.group() + " at " + match.start());
}
yields
a at 0 b at 1 a at 3 c at 4 a at 5 a at 7 b at 8 a at 10
You could do this:
for idx, item in enumerate(list):
if 'foo' in item:
item = replace_all(...)
list[idx] = item
Your linker (ld) obviously doesn't like the order in which make arranges the GCC arguments so you'll have to change your Makefile a bit:
CC=gcc
CFLAGS=-Wall
LDFLAGS=-lm
.PHONY: all
all: client
.PHONY: clean
clean:
$(RM) *~ *.o client
OBJECTS=client.o
client: $(OBJECTS)
$(CC) $(CFLAGS) $(OBJECTS) -o client $(LDFLAGS)
In the line defining the client target change the order of $(LDFLAGS) as needed.
A Scala solution, adapted from Vasya Novikov's answer and specialized for binary trees:
/** An immutable Binary Tree. */
case class BTree[T](value: T, left: Option[BTree[T]], right: Option[BTree[T]]) {
/* Adapted from: http://stackoverflow.com/a/8948691/643684 */
def pretty: String = {
def work(tree: BTree[T], prefix: String, isTail: Boolean): String = {
val (line, bar) = if (isTail) ("+-- ", " ") else ("+-- ", "¦")
val curr = s"${prefix}${line}${tree.value}"
val rights = tree.right match {
case None => s"${prefix}${bar} +-- Ø"
case Some(r) => work(r, s"${prefix}${bar} ", false)
}
val lefts = tree.left match {
case None => s"${prefix}${bar} +-- Ø"
case Some(l) => work(l, s"${prefix}${bar} ", true)
}
s"${curr}\n${rights}\n${lefts}"
}
work(this, "", true)
}
}
'.'.join()
or ".".join()
.. So any string instance has the method join()
You might need a bit more background on what a Materialized View actually is. In Oracle these are an object that consists of a number of elements when you try to build it elsewhere.
An MVIEW is essentially a snapshot of data from another source. Unlike a view the data is not found when you query the view it is stored locally in a form of table. The MVIEW is refreshed using a background procedure that kicks off at regular intervals or when the source data changes. Oracle allows for full or partial refreshes.
In SQL Server, I would use the following to create a basic MVIEW to (complete) refresh regularly.
First, a view. This should be easy for most since views are quite common in any database Next, a table. This should be identical to the view in columns and data. This will store a snapshot of the view data. Then, a procedure that truncates the table, and reloads it based on the current data in the view. Finally, a job that triggers the procedure to start it's work.
Everything else is experimentation.
For Sequelize 4
Query
SELECT * FROM Student WHERE LastName='Doe'
AND (FirstName = "John" or FirstName = "Jane") AND Age BETWEEN 18 AND 24
Syntax with Operators
const Op = require('Sequelize').Op;
var r = await to (Student.findAll(
{
where: {
LastName: "Doe",
FirstName: {
[Op.or]: ["John", "Jane"]
},
Age: {
// [Op.gt]: 18
[Op.between]: [18, 24]
}
}
}
));
Notes
$
(e.g $and
, $or
...){freezeTableName: true}
set in the table model then Sequelize will query against the plural form of its name ( Student -> Students )The below css code always keep the button at the bottom of the page
position:absolute;
bottom:0;
Since you want to do it in relative positioning, you should go for margin-top:100%
position:relative;
margin-top:100%;
EDIT1: JSFiddle1
EDIT2: To place button at center of the screen,
position:relative;
left: 50%;
margin-top:50%;
I have a similar problem and as I'm newbie, here are some facts for somebody to comment:
I'm sending form data to Google sheet this way (scriptURL is https://script.google.com/macros/s/AKfy..., showSuccess() is showing a simple image):
fetch(scriptURL, {method: 'POST', body: new FormData(form)})
.then(response => showSuccess())
.catch(error => alert('Error! ' + error.message))
Executed in Edge my HTML doesn't show error and Network tab reports this 3 requests: Executed in Chrome my HTML (index.htm) shows Failed to fetch error and Network tab reports this 2 requests: The value in the second column is blocked:other and there is also an error in Console tab:
GET https://script.googleusercontent.com/macros/echo?user_content_key=D-ABF... net::ERR_BLOCKED_BY_CLIENT
In order to suspend installed Chrome extensions, I executed my code in an Incognito window and there is no error message and Network tab reports this 2 requests:
My guess is that something (extension?) prevents Chrome to read the request's answer (the GET request is blocked).
This warning shows up when you connect to a MySQL/MariaDB server with invalid or missing credentials (username/password). So this is typically not a code problem, but a server configuration issue.
See the manual page on mysql_connect("localhost", "user", "pw")
for examples.
Check that you actually used a $username
and $password
.
(using password: NO)
.Only the local test server usually allows to connect with username root
, no password, and the test
database name.
You can test if they're really correct using the command line client:
mysql --user="username" --password="password" testdb
Username and password are case-sensitive and whitespace is not ignored. If your password contains meta characters like $
, escape them, or put the password in single quotes.
Most shared hosting providers predeclare mysql accounts in relation to the unix user account (sometimes just prefixes or extra numeric suffixes). See the docs for a pattern or documentation, and CPanel or whatever interface for setting a password.
See the MySQL manual on Adding user accounts using the command line. When connected as admin user you can issue a query like:
CREATE USER 'username'@'localhost' IDENTIFIED BY 'newpassword';
Or use Adminer or WorkBench or any other graphical tool to create, check or correct account details.
If you can't fix your credentials, then asking the internet to "please help" will have no effect. Only you and your hosting provider have permissions and sufficient access to diagnose and fix things.
Verify that you could reach the database server, using the host name given by your provider:
ping dbserver.hoster.example.net
Check this from a SSH console directly on your webserver. Testing from your local development client to your shared hosting server is rarely meaningful.
Often you just want the server name to be "localhost"
, which normally utilizes a local named socket when available. Othertimes you can try "127.0.0.1"
as fallback.
Should your MySQL/MariaDB server listen on a different port, then use "servername:3306"
.
If that fails, then there's a perhaps a firewall issue. (Off-topic, not a programming question. No remote guess-helping possible.)
When using constants like e.g. DB_USER
or DB_PASSWORD
, check that they're actually defined.
If you get a "Warning: Access defined for 'DB_USER'@'host'"
and a "Notice: use of undefined constant 'DB_PASS'"
, then that's your problem.
Verify that your e.g. xy/db-config.php
was actually included and whatelse.
Check for correctly set GRANT
permissions.
It's not sufficient to have a username
+password
pair.
Each MySQL/MariaDB account can have an attached set of permissions.
Those can restrict which databases you are allowed to connect to, from which client/server the connection may originate from, and which queries are permitted.
The "Access denied" warning thus may as well show up for mysql_query
calls, if you don't have permissions to SELECT
from a specific table, or INSERT
/UPDATE
, and more commonly DELETE
anything.
You can adapt account permissions when connected per command line client using the admin account with a query like:
GRANT ALL ON yourdb.* TO 'username'@'localhost';
If the warning shows up first with Warning: mysql_query(): Access denied for user ''@'localhost'
then you may have a php.ini-preconfigured account/password pair.
Check that mysql.default_user=
and mysql.default_password=
have meaningful values.
Oftentimes this is a provider-configuration. So contact their support for mismatches.
Find the documentation of your shared hosting provider:
e.g. HostGator, GoDaddy, 1and1, DigitalOcean, BlueHost, DreamHost, MediaTemple, ixWebhosting, lunarhosting, or just google yours´.
Else consult your webhosting provider through their support channels.
Note that you may also have depleted the available connection pool. You'll get access denied warnings for too many concurrent connections. (You have to investigate the setup. That's an off-topic server configuration issue, not a programming question.)
Your libmysql client version may not be compatible with the database server. Normally MySQL and MariaDB servers can be reached with PHPs compiled in driver. If you have a custom setup, or an outdated PHP version, and a much newer database server, or significantly outdated one - then the version mismatch may prevent connections. (No, you have to investigate yourself. Nobody can guess your setup).
More references:
Btw, you probably don't want to use
mysql_*
functions anymore. Newcomers often migrate to mysqli, which however is just as tedious. Instead read up on PDO and prepared statements.
$db = new PDO("mysql:host=localhost;dbname=testdb", "username", "password");
In current versions of Matplotlib, you can do axis.set_xticklabels(labels, fontsize='small')
.
See this article from JoelOnSoftware for why you don't want to use strcat
.
Look at fread for an alternative. Use it with 1 for the size when you're reading bytes or characters.
When modules are in parallel locations, as in the question:
application/app2/some_folder/some_file.py
application/app2/another_folder/another_file.py
This shorthand makes one module visible to the other:
import sys
sys.path.append('../')
It should also be mentioned that <span>
tags allow inside them -- block-level items negate MD natively inside them unless you configure them not to do so, but in-line styles natively allow MD within them. As such, I often do something akin to...
This is a superfluous paragraph thing.
<span class="class-red">And thus I delve into my topic, Lorem ipsum lollipop bubblegum.</span>
And thus with that I conclude.
I am not 100% sure if this is universal but seems to be the case in all MD editors I've used.
If you only need to look at the cells that are in use you can use:
sub IterateCells()
For Each Cell in ActiveSheet.UsedRange.Cells
'do some stuff
Next
End Sub
that will hit everything in the range from A1 to the last cell with data (the bottom right-most cell)
The best way is using "DEFAULT 0". Other way:
/************ ROLE ************/
drop table if exists `role`;
create table `role` (
`id_role` bigint(20) unsigned not null auto_increment,
`date_created` datetime,
`date_deleted` datetime,
`name` varchar(35) not null,
`description` text,
primary key (`id_role`)
) comment='';
drop trigger if exists `role_date_created`;
create trigger `role_date_created` before insert
on `role`
for each row
set new.`date_created` = now();
If you want to just untrack a file and not delete from local and remote repo then use this command:
git update-index --assume-unchanged file_name_with_path
You can use the VBA string functions (as @onedaywhen points out in the comments, they are not really the VBA functions, but their equivalents from the MS Jet libraries. As far as function signatures go, they are called and work the same, even though the actual presence of MS Access is not required for them to be available.):
SELECT DISTINCT Left(LastName, 1)
FROM Authors;
SELECT DISTINCT Mid(LastName, 1, 1)
FROM Authors;
In batch file:
1 @echo off(solo)=>output nothing
2 echo off(solo)=> the “echo off” shows in the command line
3 echo off(then echo something) =>
4 @echo off(then echo something)=>
See, echo off(solo), means no output in the command line, but itself shows; @echo off(solo), means no output in the command line, neither itself;
I had facing the same issue while writing a simple rest api using node.js eventually found out it was due to wifi blockage and security reason . try once connecting it using your mobile hotspot . if this be the reason it will get resolved immediately.
This would be the "arrow function expression" introduced in ECMAScript 6.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/arrow_functions
For historical purposes (if the wiki page changes later), it is:
An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value. Arrow functions are always anonymous.
I think it will help somebody.
function isValidDate($thedate) {
$data = [
'separators' => array("/", "-", "."),
'date_array' => '',
'day_index' => '',
'year' => '',
'month' => '',
'day' => '',
'status' => false
];
// loop through to break down the date
foreach ($data['separators'] as $separator) {
$data['date_array'] = explode($separator, $thedate);
if (count($data['date_array']) == 3) {
$data['status'] = true;
break;
}
}
// err, if more than 4 character or not int
if ($data['status']) {
foreach ($data['date_array'] as $value) {
if (strlen($value) > 4 || !is_numeric($value)) {
$data['status'] = false;
break;
}
}
}
// get the year
if ($data['status']) {
if (strlen($data['date_array'][0]) == 4) {
$data['year'] = $data['date_array'][0];
$data['day_index'] = 2;
}elseif (strlen($data['date_array'][2]) == 4) {
$data['year'] = $data['date_array'][2];
$data['day_index'] = 0;
}else {
$data['status'] = false;
}
}
// get the month
if ($data['status']) {
if (strlen($data['date_array'][1]) == 2) {
$data['month'] = $data['date_array'][1];
}else {
$data['status'] = false;
}
}
// get the day
if ($data['status']) {
if (strlen($data['date_array'][$data['day_index']]) == 2) {
$data['day'] = $data['date_array'][$data['day_index']];
}else {
$data['status'] = false;
}
}
// finally validate date
if ($data['status']) {
return checkdate($data['month'] , $data['day'], $data['year']);
}
return false;
}
Full process (Unix svn package):
Check files are not in SVN:
> svn st -u folder
? folder
Add all (including ignored files):
> svn add folder
A folder
A folder/file1.txt
A folder/folder2
A folder/folder2/file2.txt
A folder/folderToIgnore
A folder/folderToIgnore/fileToIgnore1.txt
A fileToIgnore2.txt
Remove "Add" Flag to All * Ignore * files:
> cd folder
> svn revert --recursive folderToIgnore
Reverted 'folderToIgnore'
Reverted 'folderToIgnore/fileToIgnore1.txt'
> svn revert fileToIgnore2.txt
Reverted 'fileToIgnore2.txt'
Edit svn ignore on folder
svn propedit svn:ignore .
Add two singles lines with just the following:
folderToIgnore
fileToIgnore2.txt
Check which files will be upload and commit:
> cd ..
> svn st -u
A folder
A folder/file1.txt
A folder/folder2
A folder/folder2/file2.txt
> svn ci -m "Commit message here"
It is worth noting that if you use the setContentOffset
approach, it may cause your table view/collection view to jump a little. I would honestly try to go about this another way. A recommendation is to use the scroll view delegate methods you are given for free.
Redirects the browser to the specified URL.
This method adds a "Location" header to the current response. Note that it does not send out the header until send() is called. In a controller action you may use this method as follows:
return Yii::$app->getResponse()->redirect($url);
In other places, if you want to send out the "Location" header immediately, you should use the following code:
Yii::$app->getResponse()->redirect($url)->send();
return;
It is recommended to check default terminal shell before set JAVA_HOME environment variable, via following commands:
$ echo $SHELL
/bin/bash
If your default terminal is /bin/bash (Bash), then you should use @Adrian Petrescu method.
If your default terminal is /bin/zsh (Z Shell), then you should set these environment variable in ~/.zshenv file with following contents:
export JAVA_HOME="$(/usr/libexec/java_home)"
Similarly, any other terminal type not mentioned above, you should set environment variable in its respective terminal env file.
I've been looking for an easy to use tool for this type of testing for a while now. I just came across this the other day: Network Delay Simulator
If you're running Windows, you should check it out. It was super easy to set up and get going, and seems to work really well. It allows you to define bandwidth, latency, and packet loss in each direction. The other really nice thing is that you can define "Flow Match Conditions" so that it only affects the traffic you want it to. Oh yeah, and it's free.
===
(or !==
)==
in Obj-C (pointer equality).==
(or !=
)isEqual:
in Obj-C behavior.Here I compare three instances (class is a reference type)
class Person {}
let person = Person()
let person2 = person
let person3 = Person()
person === person2 // true
person === person3 // false
First, please do not use extract(), it can be a security problem because it is easy to manipulate POST parameters
In addition, you don't have to use variable variable names (that sounds odd), instead:
foreach($_POST as $key => $value) {
echo "POST parameter '$key' has '$value'";
}
To ensure that you have only parameters beginning with 'item_name' you can check it like so:
$param_name = 'item_name';
if(substr($key, 0, strlen($param_name)) == $param_name) {
// do something
}
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);
}));
According to Microsoft's MSDN, the lock is equivalent to:
object __lockObj = x;
bool __lockWasTaken = false;
try
{
System.Threading.Monitor.Enter(__lockObj, ref __lockWasTaken);
// Your code...
}
finally
{
if (__lockWasTaken) System.Threading.Monitor.Exit(__lockObj);
}
If you need to create locks in runtime, you can use open source DynaLock. You can create new locks in run-time and specify boundaries to the locks with context concept.
DynaLock is open-source and source code is available at GitHub
This will get you the timezone as a PHP variable. I wrote a function using jQuery and PHP. This is tested, and does work!
On the PHP page where you are want to have the timezone as a variable, have this snippet of code somewhere near the top of the page:
<?php
session_start();
$timezone = $_SESSION['time'];
?>
This will read the session variable "time", which we are now about to create.
On the same page, in the <head>
section, first of all you need to include jQuery:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
Also in the <head>
section, paste this jQuery:
<script type="text/javascript">
$(document).ready(function() {
if("<?php echo $timezone; ?>".length==0){
var visitortime = new Date();
var visitortimezone = "GMT " + -visitortime.getTimezoneOffset()/60;
$.ajax({
type: "GET",
url: "http://example.com/timezone.php",
data: 'time='+ visitortimezone,
success: function(){
location.reload();
}
});
}
});
</script>
You may or may not have noticed, but you need to change the url to your actual domain.
One last thing. You are probably wondering what the heck timezone.php is. Well, it is simply this: (create a new file called timezone.php and point to it with the above url)
<?php
session_start();
$_SESSION['time'] = $_GET['time'];
?>
If this works correctly, it will first load the page, execute the JavaScript, and reload the page. You will then be able to read the $timezone variable and use it to your pleasure! It returns the current UTC/GMT time zone offset (GMT -7) or whatever timezone you are in.
You can read more about this on my blog
In your base class Clubs
the following are declared protected
which means these can only be accessed by the class itself or any class which derives from Clubs
.
In your main
code, you try to access these outside of the class itself. eg:
Console.WriteLine("How far to the hole?");
myClub.distance = Console.ReadLine();
You have (somewhat correctly) provided public accessors to these variables. eg:
public string mydistance
{
get
{
return distance;
}
set
{
distance = value;
}
}
which means your main code could be changed to
Console.WriteLine("How far to the hole?");
myClub.mydistance = Console.ReadLine();
Make sure you have enabled the ADB integration.
In Menu: Tools -> Android -> Enable ADB integration (v1.0)
When I had this problem, the issue was I did not have the private key necessary for the developer certificate to be valid.
The solution was:
Have the developer who created the certificate export their private key matching the iOS developer public key. see http://developer.apple.com/ios/manage/certificates/team/howto.action
Open this file (Certificates.p12) on your machine (with KeyChain), and enter the password the other developer used when exporting. It is now imported into your KeyChain.
Now connect iOS device and rebuild targeting the iOS device.
I assume that you want them sorted by something else also, to get a consistent ordering between all items where AVC is the same. For example by name:
var sortedList = list.OrderBy(x => c.AVC).ThenBy(x => x.Name).ToList();
C++ is a programming language and Visual C++ is an IDE for developing with languages such as C and C++.
VC++ contains tools for, amongst others, developing against the .net framework and the Windows API.
The difference between an operating system and a kernel:
The kernel is a part of an operating system. The operating system is the software package that communicates directly to the hardware and our application. The kernel is the lowest level of the operating system. The kernel is the main part of the operating system and is responsible for translating the command into something that can be understood by the computer. The main functions of the kernel are:
This works on the Spring Tool Suite v 3.1.0.RELEASE, but I'm guessing it's also available on Eclipse as well.
After deleting the artifacts by hand (as stated by palacsint above) in the /username/.m2
directory, re-index the files by doing the following:
Go to:
Windows->Preferences->Maven->User Settings
menu.Click the Reindex
button next to the Local Repository
text box. Click "Apply" then "OK" and you're done.
1) git rebase -i HEAD~4
To elaborate: It works on the current branch; the HEAD~4 means squashing the latest four commits; interactive mode (-i)
2) At this point, the editor opened, with the list of commits, to change the second and following commits, replacing pick with squash then save it.
output: Successfully rebased and updated refs/heads/branch-name.
3) git push origin refs/heads/branch-name --force
output:
remote:
remote: To create a merge request for branch-name, visit:
remote: http://xxx/sc/server/merge_requests/new?merge_request%5Bsource_branch%5D=sss
remote:To ip:sc/server.git
+ 84b4b60...5045693 branch-name -> branch-name (forced update)
To test an android apps in a real device with Android Studio, You must keep two things in mind
Now , let me tell you how you can enable USB debugging on your android phone:
Now let me tell you how you can download the driver on your Windows PC:
select your table -> view dependencies -> Objects that depend on
While it's not been too long that I made the switch to Rubymine, I found it challenging ignoring .idea files of Rubymine from been committed to git.
Here's how I fixed it
If you've not done any staging/commit at all, or you just spinned up a new project in Ruby mine, then simply do this
Option 1
Add the line below to the .gitignore file which is usually placed at the root of your repository.
# Ignore .idea files
.idea/
This will ensure that all .idea files are ignored from been tracked by git, although they will still remain in your project folder locally.
Option 2
If you've however done some staging/commit, or you just opened up an existing project in Ruby mine, then simply do this
Run the code in your terminal/command line
git rm -r --cached .idea
This deletes already tracked .idea files in git
Next, include .idea/ to the .gitignore file which is usually placed at the root of your repository.
# Ignore .idea files
.idea/
This will ensure that all .idea files are ignored from been tracked by git, although they will still remain in your project folder locally.
Option 3
If you've however done some staging/commit, or you just opened up an existing project in Ruby mine, and want to totally delete .idea files locally and in git, then simply do this
Run the code in your terminal/command line
git rm -r --cached .idea
This deletes already tracked .idea files in git
Run the code in your terminal/command line
rm -r .idea
This deletes all .idea files including the folder locally
Next, include .idea/ to the .gitignore file which is usually placed at the root of your repository.
# Ignore .idea files
.idea/
This will ensure that all .idea files are ignored from been tracked by git, and also deleted from your project folder locally.
That's all
I hope this helps
$.ajax({
url: "<?php echo site_url('upToWeb/ajax_edit/')?>/" + id,
type: "GET",
dataType: "JSON",
success: function (data) {
if (data.web == 0) {
if (confirm('Data product upToWeb ?')) {
$.ajax({
url: "<?php echo site_url('upToWeb/set_web/')?>/" + data.id_item,
type: "post",
dataType: "json",
data: {web: 1},
success: function (respons) {
location.href = location.pathname;
},
error: function (xhr, ajaxOptions, thrownError) { // Ketika terjadi error
alert(xhr.responseText); // munculkan alert
}
});
}
}
else {
if (confirm('Data product DownFromWeb ?')) {
$.ajax({
url: "<?php echo site_url('upToWeb/set_web/')?>/" + data.id_item,
type: "post",
dataType: "json",
data: {web: 0},
success: function (respons) {
location.href = location.pathname;
},
error: function (xhr, ajaxOptions, thrownError) { // Ketika terjadi error
alert(xhr.responseText); // munculkan alert
}
});
}
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert('Error get data from ajax');
}
});
This is not a code issue. It is your default IE settings
To change the "always open" setting:
EDIT: If you ask me , instead of making any changes in the code i would add the following text "Internet Explorer users: To download file, "Rightclick" the link and hit "Save target as" to download the file."
EDIT 2: THIS solution will work perfectly for you. Its a solution i just copied from the other answer. Im not trying to pass it off as my own
Content-Type: application/octet-stream
Content-Disposition: attachment;filename=\"filename.xxx\"
However you must make sure that you specify the type of file(s) you allow. You have mentioned in your post that you want this for any type of file. This will be an issue.
For ex. If your site has images and if the end user clicks these images then they will be downloaded on his computer instead of opening in a new page. Got the point. So you need to specify the file extensions.
If you are creating a code library, then I would use namespace. However, you can still only have one Color enum inside that namespace. If you need an enum that might use a common name, but might have different constants for different classes, use your approach.
Just for fun, as other answers are much better than this.
#include <boost/hana/functional/partial.hpp>
#include <iostream>
#include <range/v3/range/conversion.hpp>
#include <range/v3/view/filter.hpp>
int main() {
using ranges::to;
using ranges::views::filter;
using boost::hana::partial;
auto const& not_space = partial(std::not_equal_to<>{}, ' ');
auto const& to_string = to<std::string>;
std::string input = "2C F4 32 3C B9 DE";
std::string output = input | filter(not_space) | to_string;
assert(output == "2CF4323CB9DE");
}
It is possible to edit same file in Split mode. It is best explained in following youtube video.
Below code works absolutely fine to me and working. This code will read RSA private and public key though java code. You can refer to http://snipplr.com/view/18368/
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyFactory;
import java.security.NoSuchAlgorithmException;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
public class Demo {
public static final String PRIVATE_KEY="/home/user/private.der";
public static final String PUBLIC_KEY="/home/user/public.der";
public static void main(String[] args) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
//get the private key
File file = new File(PRIVATE_KEY);
FileInputStream fis = new FileInputStream(file);
DataInputStream dis = new DataInputStream(fis);
byte[] keyBytes = new byte[(int) file.length()];
dis.readFully(keyBytes);
dis.close();
PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(keyBytes);
KeyFactory kf = KeyFactory.getInstance("RSA");
RSAPrivateKey privKey = (RSAPrivateKey) kf.generatePrivate(spec);
System.out.println("Exponent :" + privKey.getPrivateExponent());
System.out.println("Modulus" + privKey.getModulus());
//get the public key
File file1 = new File(PUBLIC_KEY);
FileInputStream fis1 = new FileInputStream(file1);
DataInputStream dis1 = new DataInputStream(fis1);
byte[] keyBytes1 = new byte[(int) file1.length()];
dis1.readFully(keyBytes1);
dis1.close();
X509EncodedKeySpec spec1 = new X509EncodedKeySpec(keyBytes1);
KeyFactory kf1 = KeyFactory.getInstance("RSA");
RSAPublicKey pubKey = (RSAPublicKey) kf1.generatePublic(spec1);
System.out.println("Exponent :" + pubKey.getPublicExponent());
System.out.println("Modulus" + pubKey.getModulus());
}
}
Imagine you are developing a web-application and you decide to decouple the functionality from the presentation of the application, because it affords greater freedom.
You create an API and let others implement their own front-ends over it as well. What you just did here is implement an SOA methodology, i.e. using web-services.
Web services make functional building-blocks accessible over standard Internet protocols independent of platforms and programming languages.
So, you design an interchange mechanism between the back-end (web-service) that does the processing and generation of something useful, and the front-end (which consumes the data), which could be anything. (A web, mobile, or desktop application, or another web-service). The only limitation here is that the front-end and back-end must "speak" the same "language".
That's where SOAP and REST come in. They are standard ways you'd pick communicate with the web-service.
SOAP:
SOAP internally uses XML to send data back and forth. SOAP messages have rigid structure and the response XML then needs to be parsed. WSDL is a specification of what requests can be made, with which parameters, and what they will return. It is a complete specification of your API.
REST:
REST is a design concept.
The World Wide Web represents the largest implementation of a system conforming to the REST architectural style.
It isn't as rigid as SOAP. RESTful web-services use standard URIs and methods to make calls to the webservice. When you request a URI, it returns the representation of an object, that you can then perform operations upon (e.g. GET, PUT, POST, DELETE). You are not limited to picking XML to represent data, you could pick anything really (JSON included)
Flickr's REST API goes further and lets you return images as well.
JSON and XML, are functionally equivalent, and common choices. There are also RPC-based frameworks like GRPC based on Protobufs, and Apache Thrift that can be used for communication between the API producers and consumers. The most common format used by web APIs is JSON because of it is easy to use and parse in every language.
There is a Select2 plugin allowing to set a lot of cool stuff along with placeholder. It is a jQuery replacement for select boxes. Here is an official site https://select2.github.io/examples.html
The thing is - if you want to disable fancy search option, please use the following option set.
data-plugin-options='
{
"placeholder": "Select status",
"allowClear": true,
"minimumResultsForSearch": -1
}
Especially I like the allowClear option.
Thank you.
AppDomain.UnhandledException Event
This event provides notification of uncaught exceptions. It allows the application to log information about the exception before the system default handler reports the exception to the user and terminates the application.
public App()
{
AppDomain currentDomain = AppDomain.CurrentDomain;
currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);
}
static void MyHandler(object sender, UnhandledExceptionEventArgs args)
{
Exception e = (Exception) args.ExceptionObject;
Console.WriteLine("MyHandler caught : " + e.Message);
Console.WriteLine("Runtime terminating: {0}", args.IsTerminating);
}
If the UnhandledException event is handled in the default application domain, it is raised there for any unhandled exception in any thread, no matter what application domain the thread started in. If the thread started in an application domain that has an event handler for UnhandledException, the event is raised in that application domain. If that application domain is not the default application domain, and there is also an event handler in the default application domain, the event is raised in both application domains.
For example, suppose a thread starts in application domain "AD1", calls a method in application domain "AD2", and from there calls a method in application domain "AD3", where it throws an exception. The first application domain in which the UnhandledException event can be raised is "AD1". If that application domain is not the default application domain, the event can also be raised in the default application domain.
as explained here
With help from numpy one can calculate for example a linear fitting.
# plot the data itself
pylab.plot(x,y,'o')
# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])
Use this
openssl ciphers -v | awk '{print $2}' | sort | uniq
The simplest is to just give the 'trans' (formerly 'formatter' argument the name of the log function:
m + geom_boxplot() + scale_y_continuous(trans='log10')
EDIT: Or if you don't like that, then either of these appears to give different but useful results:
m <- ggplot(diamonds, aes(y = price, x = color), log="y")
m + geom_boxplot()
m <- ggplot(diamonds, aes(y = price, x = color), log10="y")
m + geom_boxplot()
EDIT2 & 3: Further experiments (after discarding the one that attempted successfully to put "$" signs in front of logged values):
fmtExpLg10 <- function(x) paste(round_any(10^x/1000, 0.01) , "K $", sep="")
ggplot(diamonds, aes(color, log10(price))) +
geom_boxplot() +
scale_y_continuous("Price, log10-scaling", trans = fmtExpLg10)
Note added mid 2017 in comment about package syntax change:
scale_y_continuous(formatter = 'log10') is now scale_y_continuous(trans = 'log10') (ggplot2 v2.2.1)
You may use the ==
operator to compare unicode objects for equality.
>>> s1 = u'Hello'
>>> s2 = unicode("Hello")
>>> type(s1), type(s2)
(<type 'unicode'>, <type 'unicode'>)
>>> s1==s2
True
>>>
>>> s3='Hello'.decode('utf-8')
>>> type(s3)
<type 'unicode'>
>>> s1==s3
True
>>>
But, your error message indicates that you aren't comparing unicode objects. You are probably comparing a unicode
object to a str
object, like so:
>>> u'Hello' == 'Hello'
True
>>> u'Hello' == '\x81\x01'
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False
See how I have attempted to compare a unicode object against a string which does not represent a valid UTF8 encoding.
Your program, I suppose, is comparing unicode objects with str objects, and the contents of a str object is not a valid UTF8 encoding. This seems likely the result of you (the programmer) not knowing which variable holds unicide, which variable holds UTF8 and which variable holds the bytes read in from a file.
I recommend http://nedbatchelder.com/text/unipain.html, especially the advice to create a "Unicode Sandwich."
You can use the visible selector:
For me, I just changed the selinux from enforcing to permissive and then I was able to start nginx without any error.
Simply add fill:"desiredColor" in the svg tag of the image: example:
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="#bbb9c6">
<path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"/><path d="M0 0h24v24H0z" fill="none"/></svg>
You have to loop through each element in the 2d-array, and get the nth column.
function getCol(matrix, col){
var column = [];
for(var i=0; i<matrix.length; i++){
column.push(matrix[i][col]);
}
return column;
}
var array = [new Array(20), new Array(20), new Array(20)]; //..your 3x20 array
getCol(array, 0); //Get first column
If the schema of id is not of type ObjectId you cannot operate with function : findbyId()
As a beginner I would suggest you go through http://www.mkyong.com/android/android-custom-dialog-example/
I'll rundown what it basically does
Dialog
dialog.show()
method..success()
only gets called if your webserver responds with a 200 OK HTTP header - basically when everything is fine.
The callbacks attached to done() will be fired when the deferred is resolved. The callbacks attached to fail() will be fired when the deferred is rejected.
promise.done(doneCallback).fail(failCallback)
.done() has only one callback and it is the success callback
i observe DOM manipulation of angular with JQuery and i did set a finish for my app (some sort of predefined and satisfactory situation that i need for my app-abstract) for example i expect my ng-repeater to produce 7 result and there for i will set an observation function with the help of setInterval for this purpose .
$(document).ready(function(){
var interval = setInterval(function(){
if($("article").size() == 7){
myFunction();
clearInterval(interval);
}
},50);
});
Rails4 has some added datatypes for Postgres.
For example, railscast #400 names two of them:
Rails 4 has support for native datatypes in Postgres and we’ll show two of these here, although a lot more are supported: array and hstore. We can store arrays in a string-type column and specify the type for hstore.
Besides, you can also use cidr, inet and macaddr. For more information:
I was just reading this article, and it says:
Important: the order of the video files is vital; Chrome currently has a bug in which it will not autoplay a .webm video if it comes after anything else.
So it looks like your problem would be solved if you put the .webm first in your list of sources. Hope that helps.
Your approach is OK
Maybe slightly clearer (to me anyway!)
UPDATE
T1
SET
[Description] = t2.[Description]
FROM
Table1 T1
JOIN
[Table2] t2 ON t2.[ID] = t1.DescriptionID
Both this and your query should run the same performance wise because it is the same query, just laid out differently.
You can use as many joins as you want, however, the more you use the more it will impact performance
If you only want to print this div, you must use the instruction:
@media print{
*{display:none;}
#mydiv{display:block;}
}
I managed to get the access my local server by ip using the command shown below:
jupyter notebook --ip xx.xx.xx.xx --port 8888
replace the xx.xx.xx.xx
by your local ip of the jupyter server.
Way more elegant solution than $parent.$index
is using ng-init
:
<ul ng-repeat="section in sections" ng-init="sectionIndex = $index">
<li class="section_title {{section.active}}" >
{{section.name}}
</li>
<ul>
<li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu(sectionIndex)" ng-repeat="tutorial in section.tutorials">
{{tutorial.name}}
</li>
</ul>
</ul>
Useful variation for docker-compose users:
docker-compose ps -q | xargs docker container inspect \
-f '{{ range .Mounts }}{{ .Name }}:{{ .Destination }} {{ end }}'
This will very neatly output parseable volume info. Example from my wordpress docker-compose:
ubuntu@core $ docker-compose ps -q | xargs docker container inspect -f '{{ range .Mounts }}{{ .Name }}:{{ .Destination }} {{ end }}'
core_wpdb:/var/lib/mysql
core_wpcode:/code core_wphtml:/var/www/html
The output contains one line for each container, listing the volumes (and mount points) used. Alter the {{ .Name }}:{{ .Destination }} portion to output the info you would like.
If you just want a simple list of volumes, one per line
$ docker-compose ps -q | xargs docker container inspect \
-f '{{ range .Mounts }}{{ .Name }} {{ end }}' \
| xargs -n 1 echo
core_wpdb
core_wpcode
core_wphtml
Great to generate a list of volumes to backup. I use this technique along with Blacklabelops Volumerize to backup all volumes used by all containers within a docker-compose. The docs for Volumerize don't call it out, but you don't need to use it in a persistent container or to use the built-in facilities for starting and stopping services. I prefer to leave critical operations such as backup and service control to the actual user (outside docker). My backups are triggered by the actual (non-docker) user account, and use docker-compose stop to stop services, backup all volumes in use, and finally docker-compose start to restart.
Redirect the output to DEVNULL:
import os
import subprocess
FNULL = open(os.devnull, 'w')
retcode = subprocess.call(['echo', 'foo'],
stdout=FNULL,
stderr=subprocess.STDOUT)
It is effectively the same as running this shell command:
retcode = os.system("echo 'foo' &> /dev/null")
Update: This answer applies to the original question relating to python 2.7. As of python >= 3.3 an official subprocess.DEVNULL
symbol was added.
retcode = subprocess.call(['echo', 'foo'],
stdout=subprocess.DEVNULL,
stderr=subprocess.STDOUT)
To see all commands that are being executed by the script, add the -x
flag to your shabang line, and execute the command normally:
#! /bin/bash -x
matchdir="/home/joao/robocup/runner_workdir/matches/testmatch/"
teamAComm="`pwd`/a.sh"
teamBComm="`pwd`/b.sh"
include="`pwd`/server_official.conf"
serverbin='/usr/local/bin/rcssserver'
cd $matchdir
$serverbin include="$include" server::team_l_start="${teamAComm}" server::team_r_start="${teamBComm}" CSVSaver::save='true' CSVSaver::filename='out.csv'
Then if you sometimes want to ignore the debug output, redirect stderr
somewhere.
Simply setting the Network Setting to bridged did the trick for me.
Your IP will change when you do this. However, in my case it didn't change immediately. ifconfig
returned the same ip. I rebooted the vm and boom, the ip set itself to one start with 192.* and I was immediately allowed ssh access.
You can simply use this code at the end. (Do not use False)
Application.CutCopyMode = True
If the project is maven placed it in src/main/resources
, in the package phase it will copy it in ../WEB-INF/classes/hibernate.cfg.xml
Use font
property of UILabel
:
label.font = UIFont(name:"HelveticaNeue-Bold", size: 16.0)
or use default system font
to bold text:
label.font = UIFont.boldSystemFont(ofSize: 16.0)
you might use
a.view(1,5)
Out:
1 2 3 4 5
[torch.FloatTensor of size 1x5]
I suggest Pdfkit. (installation guide)
It creates pdf from html files. I chose it to create pdf in 2 steps from my Python Pyramid stack:
pdfkit.from_string(...)
method by passing the rendered html as parameterThis way you get a pdf document with styling and images supported.
You can install it as follows :
using pip
pip install pdfkit
#logo {
width: 400px;
height: 200px;
/*Scale down will take the necessary specified space that is 400px x 200px without stretching the image*/
object-fit:scale-down;
}
If your content is going to wrap and be of unknown height, this is your best bet:
http://cssdeck.com/labs/aplvrmue
.badge {
height: 100px;
width: 100px;
display: table-cell;
text-align: center;
vertical-align: middle;
border-radius: 50%; /* may require vendor prefixes */
background: yellow;
}
.badge {_x000D_
height: 100px;_x000D_
width: 100px;_x000D_
display: table-cell;_x000D_
text-align: center;_x000D_
vertical-align: middle;_x000D_
border-radius: 50%;_x000D_
background: yellow;_x000D_
}
_x000D_
<div class="badge">1</div>
_x000D_
Yours:
<div style="height:42px;width:42px">
<img src="http://someimage.jpg">
Is it okay to use this code?
<div class= "box">
<img src= "http://someimage.jpg" class= "img">
</div>
<style type="text/css">
.box{width: 42; height: 42;}
.img{width: 20; height:20;}
</style>
Just trying, though late. :3 For someone else reading this, letme know if the way i wrote the code were not good. im new in this kind of language. and i still want to learn more.
<div>
with some proportions
div {
position: relative;
width: 100%;
height: 100%;
}
<img>
's with their own proportions
img {
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
width: auto; /* to keep proportions */
height: auto; /* to keep proportions */
max-width: 100%; /* not to stand out from div */
max-height: 100%; /* not to stand out from div */
margin: auto auto 0; /* position to bottom and center */
}
In order to read a file chosen by the user, using a file open dialog, you can use the <input type="file">
tag. You can find information on it from MSDN. When the file is chosen you can use the FileReader API to read the contents.
function onFileLoad(elementId, event) {_x000D_
document.getElementById(elementId).innerText = event.target.result;_x000D_
}_x000D_
_x000D_
function onChooseFile(event, onLoadFileHandler) {_x000D_
if (typeof window.FileReader !== 'function')_x000D_
throw ("The file API isn't supported on this browser.");_x000D_
let input = event.target;_x000D_
if (!input)_x000D_
throw ("The browser does not properly implement the event object");_x000D_
if (!input.files)_x000D_
throw ("This browser does not support the `files` property of the file input.");_x000D_
if (!input.files[0])_x000D_
return undefined;_x000D_
let file = input.files[0];_x000D_
let fr = new FileReader();_x000D_
fr.onload = onLoadFileHandler;_x000D_
fr.readAsText(file);_x000D_
}
_x000D_
<input type='file' onchange='onChooseFile(event, onFileLoad.bind(this, "contents"))' />_x000D_
<p id="contents"></p>
_x000D_
The steps in order to make a full check are:
Prepare the captor :
ArgumentCaptor<SomeArgumentClass> someArgumentCaptor = ArgumentCaptor.forClass(SomeArgumentClass.class);
verify the call to dependent on component (collaborator of subject under test). times(1) is the default value, so ne need to add it.
verify(dependentOnComponent, times(1)).send(someArgumentCaptor.capture());
Get the argument passed to collaborator
SomeArgumentClass someArgument = messageCaptor.getValue();
someArgument can be used for assertions
Windows -> Preferences -> Server -> Runtime Environment -> Delete all Apache servers available. Add the same. Now run your application on server. Its done :)
you can try to reinstall the latest version of xcode / dev. tools for snow leopard - this should fix your errors
An easy route would be to have the gmail account configured/enabled for POP3 access. This would allow you to send out via normal SMTP through the gmail servers.
Then you'd just send through smtp.gmail.com (on port 587)
simply write:-
select convert (date,DATEADD(YEAR,DATEDIFF(YEAR,0,GETDATE()),0))
start date of the year.
select convert (date,DATEADD(YEAR, DATEDIFF(YEAR,0,GETDATE()) + 1, -1))
Rather than using a DisplayFilter you could use a very simple CaptureFilter like
port 53
See the "Capture only DNS (port 53) traffic" example on the CaptureFilters wiki.
After a long time fighting with this problem, I think I have found a better solution.
The combination of two functions makes it possible to escape a string to use as HTML.
One, to escape double quote if you use the string inside a JavaScript function call; and a second one to escape the single quote, avoiding those simple quotes that go around the argument.
Solution:
mysql_real_escape_string(htmlspecialchars($string))
Solve:
echo 'onclick="javascript_function(\'' . mysql_real_escape_string(htmlspecialchars($string))"
to set the height of table, you need to first set css property "display: block" then you can add "width/height" properties. I find this Mozilla Article a very good resource to learn how to style tables : Link
I had a hard time trying to figure this out on Xamarin. From the suggestions above I came up with this solution.
private string getRealPathFromURI(Android.Net.Uri contentUri)
{
string filename = "";
string thepath = "";
Android.Net.Uri filePathUri;
ICursor cursor = this.ContentResolver.Query(contentUri, null, null, null, null);
if (cursor.MoveToFirst())
{
int column_index = cursor.GetColumnIndex(MediaStore.Images.Media.InterfaceConsts.Data);//Instead of "MediaStore.Images.Media.DATA" can be used "_data"
filePathUri = Android.Net.Uri.Parse(cursor.GetString(column_index));
filename = filePathUri.LastPathSegment;
thepath = filePathUri.Path;
}
return thepath;
}
The spec says seconds:
http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-4.2.2
expires_in
OPTIONAL. The lifetime in seconds of the access token. For
example, the value "3600" denotes that the access token will
expire in one hour from the time the response was generated.
I agree with OP that it's careless for Google to not document this.
I thought about this very often during my PhD (in computer science). I came up with multiple solutions, depending on the ability to distinguish socks and thus find correct pairs as fast as possible.
Suppose the cost of looking at socks and memorizing their distinctive patterns is negligible (e). Then the best solution is simply to throw all socks on a table. This involves those steps:
This is indeed the fastest possibility and is executed in n + 1 = O(n) complexity. But it supposes that you perfectly remember all patterns... In practice, this is not the case, and my personal experience is that you sometimes don't find the matching pair at first attempt:
This now depends on our ability to find matching pairs. This is particularly true if you have dark/grey pairs or white sports socks that often have very similar patterns! Let's admit that you have a probability of P of finding the corresponding sock. You'll need, on average, 1/P tries before finding the corresponding sock to form a pair. The overall complexity is 1 + (n/2) * (1 + 1/P) = O(n).
Both are linear in the number of socks and are very similar solutions. Let's slightly modify the problem and admit you have multiple pairs of similar socks in the set, and that it is easy to store multiple pairs of socks in one move (1+e). For K distinct patterns, you may implement:
The overall complexity becomes n+K = O(n). It is still linear, but choosing the correct algorithm may now greatly depend on the values of P and K! But one may object again that you may have difficulties to find (or create) cluster for each sock.
Besides, you may also loose time by looking on websites what is the best algorithm and proposing your own solution :)
Use bellow command from CLI interface
[root@localhost~]# mysqladmin variables -p<password> | grep datadir
I faced this exact same issue with Laravel 8.x on Ubuntu 20.
I run: sudo apt install php7.4-xml
and composer update
within the project directory. This fixed the issue.
You can, but you should not https://web.archive.org/web/20151009224806/http://docs.mongodb.org/manual/tutorial/create-an-auto-incrementing-field/
Each object in mongo already has an id, and they are sortable in insertion order. What is wrong with getting collection of user objects, iterating over it and use this as incremented ID? Er go for kind of map-reduce job entirely
Let's use input abc
as an example.
Start off with just the last element (c
) in a set (["c"]
), then add the second last element (b
) to its front, end and every possible positions in the middle, making it ["bc", "cb"]
and then in the same manner it will add the next element from the back (a
) to each string in the set making it:
"a" + "bc" = ["abc", "bac", "bca"] and "a" + "cb" = ["acb" ,"cab", "cba"]
Thus entire permutation:
["abc", "bac", "bca","acb" ,"cab", "cba"]
Code:
public class Test
{
static Set<String> permutations;
static Set<String> result = new HashSet<String>();
public static Set<String> permutation(String string) {
permutations = new HashSet<String>();
int n = string.length();
for (int i = n - 1; i >= 0; i--)
{
shuffle(string.charAt(i));
}
return permutations;
}
private static void shuffle(char c) {
if (permutations.size() == 0) {
permutations.add(String.valueOf(c));
} else {
Iterator<String> it = permutations.iterator();
for (int i = 0; i < permutations.size(); i++) {
String temp1;
for (; it.hasNext();) {
temp1 = it.next();
for (int k = 0; k < temp1.length() + 1; k += 1) {
StringBuilder sb = new StringBuilder(temp1);
sb.insert(k, c);
result.add(sb.toString());
}
}
}
permutations = result;
//'result' has to be refreshed so that in next run it doesn't contain stale values.
result = new HashSet<String>();
}
}
public static void main(String[] args) {
Set<String> result = permutation("abc");
System.out.println("\nThere are total of " + result.size() + " permutations:");
Iterator<String> it = result.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
JavascriptExecutor js = ((JavascriptExecutor) driver);
Scroll down:
js.executeScript("window.scrollTo(0, document.body.scrollHeight);");
Scroll up:
js.executeScript("window.scrollTo(0, -document.body.scrollHeight);");
You can also simply set the Source attribute rather than using the child elements. To do this your class needs to return the image as a Bitmap Image. Here is an example of one way I've done it
<Image Width="90" Height="90"
Source="{Binding Path=ImageSource}"
Margin="0,0,0,5" />
And the class property is simply this
public object ImageSource {
get {
BitmapImage image = new BitmapImage();
try {
image.BeginInit();
image.CacheOption = BitmapCacheOption.OnLoad;
image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
image.UriSource = new Uri( FullPath, UriKind.Absolute );
image.EndInit();
}
catch{
return DependencyProperty.UnsetValue;
}
return image;
}
}
I suppose it may be a little more work than the value converter, but it is another option.
I had an issue with the parseActivityForResult arguments. I got this to work:
package JMA.BarCodeScanner;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class JMABarcodeScannerActivity extends Activity {
Button captureButton;
TextView tvContents;
TextView tvFormat;
Activity activity;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
activity = this;
captureButton = (Button)findViewById(R.id.capture);
captureButton.setOnClickListener(listener);
tvContents = (TextView)findViewById(R.id.tvContents);
tvFormat = (TextView)findViewById(R.id.tvFormat);
}
public void onActivityResult(int requestCode, int resultCode, Intent intent)
{
switch (requestCode)
{
case IntentIntegrator.REQUEST_CODE:
if (resultCode == Activity.RESULT_OK)
{
IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (intentResult != null)
{
String contents = intentResult.getContents();
String format = intentResult.getFormatName();
tvContents.setText(contents.toString());
tvFormat.setText(format.toString());
//this.elemQuery.setText(contents);
//this.resume = false;
Log.d("SEARCH_EAN", "OK, EAN: " + contents + ", FORMAT: " + format);
} else {
Log.e("SEARCH_EAN", "IntentResult je NULL!");
}
}
else if (resultCode == Activity.RESULT_CANCELED) {
Log.e("SEARCH_EAN", "CANCEL");
}
}
}
private View.OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.initiateScan();
}
};
}
Latyout for Activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:id="@+id/capture"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Take a Picture"/>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tvContents"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tvFormat"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
and
is the same as &&
but with lower precedence. They both use short-circuit evaluation.
WARNING: and
even has lower precedence than =
so you'll usually want to avoid and
. An example when and
should be used can be found in the Rails Guide under "Avoiding Double Render Errors".
Use the css "rotate()" method:
div {
width: 100px;
height: 100px;
background-color: yellow;
border: 1px solid black;
}
div#rotate{
transform: rotate(90deg);
}
_x000D_
<div>
normal div
</div>
<br>
<div id="rotate">
This div is rotated 90 degrees
</div>
_x000D_
The target container should have the white-space:pre
style.
Try it below.
<script>_x000D_
function copycontent(){_x000D_
var content = document.getElementById('ta').value;_x000D_
document.getElementById('target').innerText = content;_x000D_
}_x000D_
</script>_x000D_
<textarea id='ta' rows='3'>_x000D_
line 1_x000D_
line 2_x000D_
line 3_x000D_
</textarea>_x000D_
<button id='btn' onclick='copycontent();'>_x000D_
Copy_x000D_
</button>_x000D_
<p id='target' style='white-space:pre'>_x000D_
_x000D_
</p>
_x000D_
using ssh from java should not be as hard as jsch makes it. you might be better off with sshj.
This work for me
rm .git/logs/refs/remotes/origin/master
Linting is the process of running a program that will analyse code for potential errors.
See lint on wikipedia:
lint was the name originally given to a particular program that flagged some suspicious and non-portable constructs (likely to be bugs) in C language source code. The term is now applied generically to tools that flag suspicious usage in software written in any computer language.
Try using the not()
method instead of the :not()
selector.
$(".content a").click(function() {
$(".content a").not(this).hide("slow");
});
The datasource is by default .\SQLEXPRESS (its the instance where databases are placed by default) or if u changed the name of the instance during installation of sql server so i advise you to do this :
connectionString="Data Source=.\\yourInstance(defaulT Data source is SQLEXPRESS);
Initial Catalog=databaseName;
User ID=theuser if u use it;
Password=thepassword if u use it;
integrated security=true(if u don t use user and pass; else change it false)"
Without to knowing your instance, I could help with this one. Hope it helped
You can try:
WebElement getmenu= driver.findElement(By.xpath("//*[@id='ui-id-2']/span[2]")); //xpath the parent
Actions act = new Actions(driver);
act.moveToElement(getmenu).perform();
Thread.sleep(3000);
WebElement clickElement= driver.findElement(By.linkText("Sofa L"));//xpath the child
act.moveToElement(clickElement).click().perform();
If you had case the web have many category, use the first method. For menu you wanted, you just need the second method.
What happens with bittorrent and a DHT is that at the beginning bittorrent uses information embedded in the torrent file to go to either a tracker or one of a set of nodes from the DHT. Then once it finds one node, it can continue to find others and persist using the DHT without needing a centralized tracker to maintain it.
The original information bootstraps the later use of the DHT.
simply add to your data structure ( mItems ) , and then notify your adapter about dataset change
private void addItem(String item) {
mItems.add(item);
mAdapter.notifyDataSetChanged();
}
addItem("New Item");
A slightly modified version of @sidanmor 's code. The main point is, not every webpage is purely ASCII, user should be able to handle the decoding manually (even encode into base64)
function httpGet(url) {
return new Promise((resolve, reject) => {
const http = require('http'),
https = require('https');
let client = http;
if (url.toString().indexOf("https") === 0) {
client = https;
}
client.get(url, (resp) => {
let chunks = [];
// A chunk of data has been recieved.
resp.on('data', (chunk) => {
chunks.push(chunk);
});
// The whole response has been received. Print out the result.
resp.on('end', () => {
resolve(Buffer.concat(chunks));
});
}).on("error", (err) => {
reject(err);
});
});
}
(async(url) => {
var buf = await httpGet(url);
console.log(buf.toString('utf-8'));
})('https://httpbin.org/headers');
I think that what you want to do is turn the JSON string back into an object when it arrives back in your XMLHttpRequest - correct?
If so, you need to eval the string to turn it into a JavaScript object - note that this can be unsafe as you're trusting that the JSON string isn't malicious and therefore executing it. Preferably you could use jQuery's parseJSON
Try using %0A
in the URL, just like you've used %20
instead of the space character.
itertools.groupby
is a tool for grouping items.
From the docs, we glean further what it might do:
# [k for k, g in groupby('AAAABBBCCDAABBB')] --> A B C D A B
# [list(g) for k, g in groupby('AAAABBBCCD')] --> AAAA BBB CC D
groupby
objects yield key-group pairs where the group is a generator.
Features
Comparisons
# Define a printer for comparing outputs
>>> def print_groupby(iterable, keyfunc=None):
... for k, g in it.groupby(iterable, keyfunc):
... print("key: '{}'--> group: {}".format(k, list(g)))
# Feature A: group consecutive occurrences
>>> print_groupby("BCAACACAADBBB")
key: 'B'--> group: ['B']
key: 'C'--> group: ['C']
key: 'A'--> group: ['A', 'A']
key: 'C'--> group: ['C']
key: 'A'--> group: ['A']
key: 'C'--> group: ['C']
key: 'A'--> group: ['A', 'A']
key: 'D'--> group: ['D']
key: 'B'--> group: ['B', 'B', 'B']
# Feature B: group all occurrences
>>> print_groupby(sorted("BCAACACAADBBB"))
key: 'A'--> group: ['A', 'A', 'A', 'A', 'A']
key: 'B'--> group: ['B', 'B', 'B', 'B']
key: 'C'--> group: ['C', 'C', 'C']
key: 'D'--> group: ['D']
# Feature C: group by a key function
>>> # islower = lambda s: s.islower() # equivalent
>>> def islower(s):
... """Return True if a string is lowercase, else False."""
... return s.islower()
>>> print_groupby(sorted("bCAaCacAADBbB"), keyfunc=islower)
key: 'False'--> group: ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'D']
key: 'True'--> group: ['a', 'a', 'b', 'b', 'c']
Uses
Note: Several of the latter examples derive from Víctor Terrón's PyCon (talk) (Spanish), "Kung Fu at Dawn with Itertools". See also the groupby
source code written in C.
* A function where all items are passed through and compared, influencing the result. Other objects with key functions include sorted()
, max()
and min()
.
Response
# OP: Yes, you can use `groupby`, e.g.
[do_something(list(g)) for _, g in groupby(lxml_elements, criteria_func)]
In java, DateFormatter by default uses DST,To avoid day Light saving (DST) you need to manually do a trick,
first you have to get the DST offset i.e. for how many millisecond DST applied, for ex somewhere DST is also for 45 minutes and for some places it is for 30 min
but in most cases DST is of 1 hour
you have to use Timezone object and check with the date whether it is falling under DST or not and then you have to manually add offset of DST into it. for eg:
TimeZone tz = TimeZone.getTimeZone("EST");
boolean isDST = tz.inDaylightTime(yourDateObj);
if(isDST){
int sec= tz.getDSTSavings()/1000;// for no. of seconds
Calendar cal= Calendar.getInstance();
cal.setTime(yourDateObj);
cal.add(Calendar.Seconds,sec);
System.out.println(cal.getTime());// your Date with DST neglected
}
If you want to keep your controller code clean, you can subclass UITextView like below, and change the class name in the Interface Builder.
RoundTextView.h
#import <UIKit/UIKit.h>
@interface RoundTextView : UITextView
@end
RoundTextView.m
#import "RoundTextView.h"
#import <QuartzCore/QuartzCore.h>
@implementation RoundTextView
-(id) initWithCoder:(NSCoder *)aDecoder {
if (self = [super initWithCoder:aDecoder]) {
[self.layer setBorderColor:[[[UIColor grayColor] colorWithAlphaComponent:0.333] CGColor]];
[self.layer setBorderWidth:1.0];
self.layer.cornerRadius = 5;
self.clipsToBounds = YES;
}
return self;
}
@end
You have to override your ;
delimiter with something like $$
to avoid this kind of error.
After your function definition, you can set the delimiter back to ;
.
This should work:
DELIMITER $$
CREATE FUNCTION F_Dist3D (x1 decimal, y1 decimal)
RETURNS decimal
DETERMINISTIC
BEGIN
DECLARE dist decimal;
SET dist = SQRT(x1 - y1);
RETURN dist;
END$$
DELIMITER ;
The method tf.shape is a TensorFlow static method. However, there is also the method get_shape for the Tensor class. See
https://www.tensorflow.org/api_docs/python/tf/Tensor#get_shape
you shouldn't include c-files in other c-files. Instead create a header file where the function is declared that you want to call. Like so: file ClasseAusiliaria.h:
int addizione(int a, int b); // this tells the compiler that there is a function defined and the linker will sort the right adress to call out.
In your Main.c file you can then include the newly created header file:
#include <stdlib.h>
#include <stdio.h>
#include <ClasseAusiliaria.h>
int main(void)
{
int risultato;
risultato = addizione(5,6);
printf("%d\n",risultato);
}
static object Lock = new object();
lock (Lock)
{
// do stuff
}
@ECHO OFF
SET THEDIR=path-to-folder
Echo Deleting all files from %THEDIR%
DEL "%THEDIR%\*" /F /Q /A
Echo Deleting all folders from %THEDIR%
FOR /F "eol=| delims=" %%I in ('dir "%THEDIR%\*" /AD /B 2^>nul') do rd /Q /S "%THEDIR%\%%I"
@ECHO Folder deleted.
EXIT
...deletes all files and folders underneath the given directory, but not the directory itself.
You need to set property for the control:
listView1.View = View.Details;
Using regular expressions and Linq:
List<string> groups = (from Match m in Regex.Matches(str, @"\d{4}")
select m.Value).ToList();
I find this to be more readable, but it's just a personal opinion. It can also be a one-liner : ).
If text-decoration: none
or border: 0
doesn't work, try applying inline style in your html.
The MitM Me addon will do this - but I think self-signed certificates is probably a better solution.
There's also [the bad idea of] using several (20+) horizontal or vertical 1px divs to construct a circle. This jQuery plugin uses this method to construct different shapes.
(Assuming you are looking at the reports in the Crystal Report Designer...)
Your menu options might be a little different depending on the version of Crystal Reports you're using, but you can either:
For some reason Andrew method of creating the checkbox by hand didn't work for me using Mvc 5. Instead I used this
@Html.CheckBox("checkResp")
to create a checkbox that would play nice with the controller.