One of the cases is the post-install process fails. Right after node-sass is installed, the post-install script will be executed. It requires Python and a C++ builder for that process. The log 'gyp: No Xcode or CLT version detected!' maybe because it couldn't find any C++ builder. So try installing Python and any C++ builder then put their directories in environment variables so that npm can find them. (I come from Windows)
so this happened to me on windows recently. I fix it by following the following steps using a PowerShell with admin privileges:
node_modules
foldernpm install --global windows-build-tools
npm install
Step 1: $ npm cache clean --force
Step 2: Delete node_modules by $ rm -rf node_modules
folder or delete it manually by going into the directory and right-click > delete / move to trash. If are not updating your packages you can delete the package-lock.json
file too.
Step 3: npm install
To start again,
$ npm start
This worked for me. Hopes it works for you too.
PS: Still if it is there, kindly check the error it is displaying in red and act accordingly. This error is specific to node.js environment. Happy Coding!!
For the Collatz problem, you can get a significant boost in performance by caching the "tails". This is a time/memory trade-off. See: memoization (https://en.wikipedia.org/wiki/Memoization). You could also look into dynamic programming solutions for other time/memory trade-offs.
Example python implementation:
import sys
inner_loop = 0
def collatz_sequence(N, cache):
global inner_loop
l = [ ]
stop = False
n = N
tails = [ ]
while not stop:
inner_loop += 1
tmp = n
l.append(n)
if n <= 1:
stop = True
elif n in cache:
stop = True
elif n % 2:
n = 3*n + 1
else:
n = n // 2
tails.append((tmp, len(l)))
for key, offset in tails:
if not key in cache:
cache[key] = l[offset:]
return l
def gen_sequence(l, cache):
for elem in l:
yield elem
if elem in cache:
yield from gen_sequence(cache[elem], cache)
raise StopIteration
if __name__ == "__main__":
le_cache = {}
for n in range(1, 4711, 5):
l = collatz_sequence(n, le_cache)
print("{}: {}".format(n, len(list(gen_sequence(l, le_cache)))))
print("inner_loop = {}".format(inner_loop))
tsc
requires a config file or .ts(x) files to compile.
To solve both of your issues, create a file called tsconfig.json
with the following contents:
{
"compilerOptions": {
"outFile": "../../built/local/tsc.js"
},
"exclude": [
"node_modules"
]
}
Also, modify your npm run with this
tsc --config /path/to/a/tsconfig.json
https://github.com/nodejs/node-gyp#on-windows
try
npm config set python D:\Library\Python\Python27\python.exe
This seems issue with my node upgrade. How ever I solved it with the following approach.
First uninstall the cli, clear cashe, and reinstall with these commands
npm uninstall -g @angular/cli
npm cache clean
npm install -g @angular/cli
Then install node-pre-gyp
npm install -g node-pre-gyp
Restart your terminal and see if the issue is solved.
Install the latest version of mongodb.
Make sure your package.json is using the latest version of mongodb, then remove node_modules/mongodb and do npm install again. If you didn't use mongodb as a direct dependency, try to find which package is using mongdb. I used:
find . -type f -name package.json | xargs grep mongodb
...
./sails-mongo/package.json: "mongodb": "1.4.26",
...
So I updated ./sails-mongo/package.json to:
"mongodb": "2.1.7",
Then remove node_modules/mongodb and do npm install again. Seems fine now.
I don't like the current suggested way of using
require('../browser_build/bson')
Since looking at ../browser_build/bson.js, a 4k+ lines file, which seem also a "non-native" implementation. So although it won't spit out any complains, it is still "using pure JS version", which means slower performance.
Looking at https://github.com/mongodb/js-bson/issues/145 and https://github.com/mongodb/js-bson/issues/165, it seems like the issue was caused by:
antoniofruci commented on Sep 15, 2015
I just found out that c++ code has been moved out 6 months ago and it is now an optional dependency: bson-ext. Indeed, if you install latest version no error occurs.
So I tried to remove the whole node_modules and still got the same error. And looking at package.json of node_modules/mongodb, its version is still 1.4.26, not latest 2.1.7.
Apparently my mongodb comes as a dependency of another package I installed: sails-mongo. Modifying the package.json of sails-mongo and redoing npm install finally solve the issue.
I just solved this issue. The problem was in version conflict. Nodejs 10 installed with npm. So before installing nodejs - remove old npm. Or remove new node -> remove npm -> install node again.
This is the only way which helped me.
I managed to get it working by following Option 2 on the Windows installation instructions on the following page: https://github.com/nodejs/node-gyp.
I had to close the current command line interface and reopen it after doing the installation on another one logged in as Administrator.
for me the solution was:
rm -rf ~/.node_gyp and
sudo npm install -g [email protected]
cd /usr/local/lib sudo ln -s ../../lib/libSystem.B.dylib libgcc_s.10.5.dylib
brew install gcc
npm install
If you have a package-lock.json
file, you may have to delete that file then run npm i
. That worked for me
For Windows users something like this should work:
PS C:\angular> npm install --python=C:\Python27\python.exe
I have experienced the same problem when trying to publish my nodejs app in a private server running CentOs using root user. The same error is fired by "postinstall": "./node_modules/bower/bin/bower install" in my package.json file so the only solution that was working for me is to use both options to avoid the error:
1: use --allow-root option for bower install command
"postinstall": "./node_modules/bower/bin/bower --allow-root install"
2: use --unsafe-perm option for npm install command
npm install --unsafe-perm
None of the above worked for me. I originally installed Command Line Tools separately, and then all of Xcode. What worked for me was to uninstall Command Line Tools as shown here. Then, when trying to run xcode-select
again, I was asked to reinstall them.
*By the way, the very reason why I found this thread was because I had installed some libraries (particularly gcc
) with macports
, presumably using the old Command Line Tools, and then I installed the full Xcode midway into development. So anyways, for my case, I had to reinstall macports
after removing the stand-alone Command Line Tools, reinstalling them, reinstalling gcc
, and then my compilation worked.
IMPORTANT! The solution below is now regarded as unstable, and you should use Node Version Management instead: Node Version Manager on Github. David Walsh also has a good introduction to NVM. NVM works beautifully and I've been using it to manage legacy WordPress projects for a few years.
Please don't use this - use NVM
I just had this exactly issue when trying to install the Sage theme for WordPress. When I ran npm install
on the theme directory, it failed.
Looking in the dependencies in package.json
, I could see that the engine I was running for Node was out of date. Running node -v
on the command line showed that I was on v0.10.9, and the latest version of Sage requires >= 0.12.0
So here's the fix for that. These steps are from David Walsh's blog
sudo npm cache clean -f
sudo npm install -g n
sudo n stable
You should then get a progress display, after which you will be up to date.
When I ran npm install
after doing this, everything worked fine, and I was able to run gulp
to build the initial dist
directory.
The right way is 1) Download and Install python 2.7.14 from here. 2) Set environment variable for python from here.
done!
note: Please set environment variable accordingly. I answered here for windows.
Try that - will set it globally:
npm config set msvs_version 2012 --global
You may use java.util.Date
class and then use SimpleDateFormat
to format the Date
.
Date date=new Date(millis);
We can use java.time package (tutorial) - DateTime APIs introduced in the Java SE 8.
var instance = java.time.Instant.ofEpochMilli(millis);
var localDateTime = java.time.LocalDateTime
.ofInstant(instance, java.time.ZoneId.of("Asia/Kolkata"));
var zonedDateTime = java.time.ZonedDateTime
.ofInstant(instance,java.time.ZoneId.of("Asia/Kolkata"));
// Format the date
var formatter = java.time.format.DateTimeFormatter.ofPattern("u-M-d hh:mm:ss a O");
var string = zonedDateTime.format(formatter);
You can also name columns directly in the cbind
call, e.g.
cbind(date=c(0,1), high=c(2,3))
Output:
date high
[1,] 0 2
[2,] 1 3
@(ViewContext.RouteData.Values["parameterName"])
worked with ROUTE PARAM.
Request.Params["paramName"]
did not work with ROUTE PARAM.
I am achieving it something like this.
>>> import requests
>>> url = "http://news.bbc.co.uk/2/hi/health/2284783.stm"
>>> res = requests.get(url)
>>> text = res.text
Faced same issue on Ubuntu 16LTS when tensor flow was installed over existing python installation.
Workaround: 1.)Uninstall tensorflow from pip and pip3
sudo pip uninstall tensorflow
sudo pip3 uninstall tensorflow
2.)Uninstall python & python3
sudo apt-get remove python-dev python3-dev python-pip python3-pip
3.)Install only a single version of python(I used python 3)
sudo apt-get install python3-dev python3-pip
4.)Install tensorflow to python3
sudo pip3 install --upgrade pip
for non GPU tensorflow, run this command
sudo pip3 install --upgrade tensorflow
for GPU tensorflow, run below command
sudo pip3 install --upgrade tensorflow-gpu
Suggest not to install GPU and vanilla version of tensorflow
Yes we do it all the time. You return a static instance rather than a new Object
static Direction getOppositeDirection(Direction d){
Direction result = null;
if (d != null){
int newCode = -d.getCode();
for (Direction direction : Direction.values()){
if (d.getCode() == newCode){
result = direction;
}
}
}
return result;
}
You can link directly with Media Fragments URI, just change the filename to file.webm#t=50
This is pretty cool, you can do all sorts of things. But I don't know the current state of browser support.
Apache HttpComponents also have an async http client now too:
/**
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.0-beta4</version>
</dependency>
**/
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.concurrent.Future;
import org.apache.http.HttpResponse;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.client.methods.AsyncCharConsumer;
import org.apache.http.nio.client.methods.HttpAsyncMethods;
import org.apache.http.protocol.HttpContext;
public class HttpTest {
public static void main(final String[] args) throws Exception {
final CloseableHttpAsyncClient httpclient = HttpAsyncClients
.createDefault();
httpclient.start();
try {
final Future<Boolean> future = httpclient.execute(
HttpAsyncMethods.createGet("http://www.google.com/"),
new MyResponseConsumer(), null);
final Boolean result = future.get();
if (result != null && result.booleanValue()) {
System.out.println("Request successfully executed");
} else {
System.out.println("Request failed");
}
System.out.println("Shutting down");
} finally {
httpclient.close();
}
System.out.println("Done");
}
static class MyResponseConsumer extends AsyncCharConsumer<Boolean> {
@Override
protected void onResponseReceived(final HttpResponse response) {
}
@Override
protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl)
throws IOException {
while (buf.hasRemaining()) {
System.out.print(buf.get());
}
}
@Override
protected void releaseResources() {
}
@Override
protected Boolean buildResult(final HttpContext context) {
return Boolean.TRUE;
}
}
}
According to documentation you're correct (http://php.net/manual/en/pdo.connections.php):
The connection remains active for the lifetime of that PDO object. To close the connection, you need to destroy the object by ensuring that all remaining references to it are deleted--you do this by assigning NULL to the variable that holds the object. If you don't do this explicitly, PHP will automatically close the connection when your script ends.
Note that if you initialise the PDO object as a persistent connection it will not automatically close the connection.
In jQuery it would be as simple as $('#yourDivID').empty()
See the documentation.
Unload event is not working fine on IE 9. I tried it with load event (onload()), it is working fine on IE 9 and FF5.
Example:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
jQuery(window).bind("load", function() {
$("[name=customerName]").val('');
});
</script>
</head>
<body>
<h1>body.jsp</h1>
<form action="success.jsp">
<div id="myDiv">
Your Full Name: <input name="yourName" id="fullName"
value="Your Full Name" /><br> <br> <input type="submit"><br>
</div>
</form>
</body>
</html>
Swift 4
enum ImageFormat {
case png
case jpeg(CGFloat)
}
extension UIImage {
func base64(format: ImageFormat) -> String? {
var imageData: Data?
switch format {
case .png: imageData = UIImagePNGRepresentation(self)
case .jpeg(let compression): imageData = UIImageJPEGRepresentation(self, compression)
}
return imageData?.base64EncodedString()
}
}
extension String {
func imageFromBase64() -> UIImage? {
guard let data = Data(base64Encoded: self) else { return nil }
return UIImage(data: data)
}
}
For me, no combination of window.requestAnimationFrame
or setTimeout
produced consistent results. Sometimes it worked, but not always—or sometimes it would be too late.
I fixed it by looping window.requestAnimationFrame
as many times as necessary.
(Typically 0 or 2-3 times)
The key is diff > 0
: here we can ensure exactly when the page updates.
// Ensure new image was loaded before scrolling
if (oldH > 0 && images.length > prevState.images.length) {
(function scroll() {
const newH = ref.scrollHeight;
const diff = newH - oldH;
if (diff > 0) {
const newPos = top + diff;
window.scrollTo(0, newPos);
} else {
window.requestAnimationFrame(scroll);
}
}());
}
To add to tacaswell's answer, the colorbar()
function has an optional cax
input you can use to pass an axis on which the colorbar should be drawn. If you are using that input, you can directly set a label using that axis.
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
fig, ax = plt.subplots()
heatmap = ax.imshow(data)
divider = make_axes_locatable(ax)
cax = divider.append_axes('bottom', size='10%', pad=0.6)
cb = fig.colorbar(heatmap, cax=cax, orientation='horizontal')
cax.set_xlabel('data label') # cax == cb.ax
No, you don't have to include all of POI's dependencies. Maven's transitive dependency mechanism will take care of that. As noted you just have to express a dependency on the appropriate POI artifact. For example:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.8-beta4</version>
</dependency>
Edit(UPDATE): I don't know about previous versions but to resolve imports to XSSFWorkbook and other classes in org.apache.poi package you need to add dependency for poi-ooxml too. The dependencies will be:
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
In Kotlin,
You have to override getHeaders() method like :
val volleyEnrollRequest = object : JsonObjectRequest(GET_POST_PARAM, TARGET_URL, PAYLOAD_BODY_IF_YOU_WISH,
Response.Listener {
// Success Part
},
Response.ErrorListener {
// Failure Part
}
) {
// Providing Request Headers
override fun getHeaders(): Map<String, String> {
// Create HashMap of your Headers as the example provided below
val headers = HashMap<String, String>()
headers["Content-Type"] = "application/json"
headers["app_id"] = APP_ID
headers["app_key"] = API_KEY
return headers
}
}
Apparently --max-depth
option is not in Mac OS X's version of the du
command. You can use the following instead.
du -h -d 1 | sort -n
I faced this problem (404) too and the root cause was my file was named INDEX.md
. I was developing on Windows and my local Jekyll site worked (since Windows treats file names case insensitive by default). When pushed to Github, it didn't work. Once I renamed the INDEX.md
to index.md
, things worked well.
If you do not want to include that your code script (as advised by others above), then simply you may do the following after generating the figure window:
Go to "Edit" in the figure window
Go to "Figure Properties"
At the bottom, you can type the name you want in "Figure Name" field. You can uncheck "Show Figure Number".
That's all.
Good luck.
(A "bit" late, but this hasn't been mentioned at all)
You didn't specify your DBMS.
In standard SQL (and most modern DBMS like Oracle, PostgreSQL, DB2, Firebird, Apache Derby, HSQLDB and H2) you can specify NULLS LAST
or NULLS FIRST
:
Use NULLS LAST
to sort them to the end:
select *
from some_table
order by some_column DESC NULLS LAST
You could also use wp_list_categories();
wp_list_categories( array('taxonomy' => 'product_cat', 'title_li' => '') );
Using Java 7:
Paths.get(string).toUri().toURL();
However, you probably want to get a URI
. Eg, a URI
begins with file:///
but a URL with file:/
(at least, that's what toString
produces).
Open "SQL Shell (psql)" from your Applications (Mac).
Click enter for the default settings. Enter the password when prompted.
*) Type \?
for help
*) Type \conninfo
to see which user you are connected as.
*) Type \l
to see the list of Databases.
*) Connect to a database by \c <Name of DB>
, for example \c GeneDB1
You should see the key prompt change to the new DB, like so:
*) Now that you're in a given DB, you want to know the Schemas for that DB. The best command to do this is \dn
.
Other commands that also work (but not as good) are select schema_name from information_schema.schemata;
and select nspname from pg_catalog.pg_namespace;
:
-) Now that you have the Schemas, you want to know the tables in those Schemas. For that, you can use the dt
command. For example \dt "GeneSchema1".*
*) Now you can do your queries. For example:
*) Here is what the above DB, Schema, and Tables look like in pgAdmin:
A switch
statement can only be used for integral values, not for values of user-defined type. And even if it could, your input operation doesn't work, either.
You might want this:
#include <string>
#include <iostream>
std::string input;
if (!std::getline(std::cin, input)) { /* error, abort! */ }
if (input == "Option 1")
{
// ...
}
else if (input == "Option 2")
{
// ...
}
// etc.
You can also just download and run ez_setup.py, though the SetupTools documentation no longer suggests this. Worked fine for me as recently as 2 weeks ago.
This is null-safe
Number tmp = getValueByReflection(inv.var1(), classUnderTest, runtimeInstance);
Long value1 = tmp == null ? null : tmp.longValue();
Actually, if you try to use function "children" it will not be succesfull because it's possible to the table has a first child like 'th'. So you have to use function 'find' instead.
Wrong way:
var $row = $(this).closest('table').children('tr:first');
Correct way:
var $row = $(this).closest('table').find('tr:first');
it might be too late but there is neat solution based on Task.WaitAny (c# 5 +) :
public static bool ConnectWithTimeout(this Socket socket, string host, int port, int timeout)
{
bool connected = false;
Task result = socket.ConnectAsync(host, port);
int index = Task.WaitAny(new[] { result }, timeout);
connected = socket.Connected;
if (!connected) {
socket.Close();
}
return connected;
}
echo "<p><a href=\"javascript:history.go(-1)\" title=\"Return to previous page\">«Go back</a></p>";
Will go back one page.
echo "<p><a href=\"javascript:history.go(-2)\" title=\"Return to previous page\">«Go back</a></p>";
Will go back two pages.
If I invoke clone() method on array of Objects of type A, how will it clone its elements?
The elements of the array will not be cloned.
Will the copy be referencing to the same objects?
Yes.
Or will it call (element of type A).clone() for each of them?
No, it will not call clone()
on any of the elements.
Another way round to check a package (including Apache) installed version on Debian-based system, we can use:
apt-cache policy <package_name>
e.g. for Apache
apt-cache policy apache2
which will show something like (look at the Installed
line):
$ apt-cache policy apache2
apache2:
Installed: (none)
Candidate: 2.2.22-1ubuntu1.9
Version table:
2.2.22-1ubuntu1.9 0
500 http://hk.archive.ubuntu.com/ubuntu/ precise-updates/main amd64 Packages
500 http://security.ubuntu.com/ubuntu/ precise-security/main amd64 Packages
2.2.22-1ubuntu1 0
500 http://hk.archive.ubuntu.com/ubuntu/ precise/main amd64 Packages
Here how to install pip the easy way.
C:\Python27
.C:\Python27\Scripts
path to your environment variable. Because it includes the pip.exe
file.cmd
and type as pip install package_name
You should not care in most programming languages, unless you need to write very specific mathematical functions, or code optimized for one specific architecture... Just make sure the size of the type is enough for you (use something bigger than an Int if you know you'll need more than 32-bits for example)
You do it exactly as you showed with this line:
get.setHeader("Content-Type", "application/x-zip");
So your header is fine and the problem is some other input to the web service. You'll want to debug that on the server side.
explode
does the job:
$parts = explode('.', $string);
You can also directly fetch parts of the result into variables:
list($part1, $part2) = explode('.', $string);
[txt_field setValue:ColorFromHEX(@"#525252") forKeyPath:@"_placeholderLabel.textColor"];
There is no need to use :checkbox
, also replace #activelist
with #inactivelist
:
$('#inactivelist').change(function () {
alert('changed');
});
With the release of the latest Android Support Library (rev 22.2.0) we've got a Design Support Library and as part of this a new view called NavigationView. So instead of doing everything on our own with the ScrimInsetsFrameLayout
and all the other stuff we simply use this view and everything is done for us.
Add the Design Support Library
to your build.gradle
file
dependencies {
// Other dependencies like appcompat
compile 'com.android.support:design:22.2.0'
}
Add the NavigationView
to your DrawerLayout
:
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"> <!-- this is important -->
<!-- Your contents -->
<android.support.design.widget.NavigationView
android:id="@+id/navigation"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="start"
app:menu="@menu/navigation_items" /> <!-- The items to display -->
</android.support.v4.widget.DrawerLayout>
Create a new menu-resource in /res/menu
and add the items and icons you wanna display:
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<group android:checkableBehavior="single">
<item
android:id="@+id/nav_home"
android:icon="@drawable/ic_action_home"
android:title="Home" />
<item
android:id="@+id/nav_example_item_1"
android:icon="@drawable/ic_action_dashboard"
android:title="Example Item #1" />
</group>
<item android:title="Sub items">
<menu>
<item
android:id="@+id/nav_example_sub_item_1"
android:title="Example Sub Item #1" />
</menu>
</item>
</menu>
Init the NavigationView and handle click events:
public class MainActivity extends AppCompatActivity {
NavigationView mNavigationView;
DrawerLayout mDrawerLayout;
// Other stuff
private void init() {
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mNavigationView = (NavigationView) findViewById(R.id.navigation_view);
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
@Override
public boolean onNavigationItemSelected(MenuItem menuItem) {
mDrawerLayout.closeDrawers();
menuItem.setChecked(true);
switch (menuItem.getItemId()) {
case R.id.nav_home:
// TODO - Do something
break;
// TODO - Handle other items
}
return true;
}
});
}
}
Be sure to set android:windowDrawsSystemBarBackgrounds
and android:statusBarColor
in values-v21
otherwise your Drawer won`t be displayed "under" the StatusBar
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Other attributes like colorPrimary, colorAccent etc. -->
<item name="android:windowDrawsSystemBarBackgrounds">true</item>
<item name="android:statusBarColor">@android:color/transparent</item>
</style>
Add a Header to the NavigationView. For this simply create a new layout and add app:headerLayout="@layout/my_header_layout"
to the NavigationView.
colorPrimary
attributetextColorPrimary
attributetextColorSecondary
attributeYou can also check the example app by Chris Banes which highlights the NavigationView along with the other new views that are part of the Design Support Library (like the FloatingActionButton, TextInputLayout, Snackbar, TabLayout etc.)
PHP has JSON_PRETTY_PRINT option since 5.4.0 (release date 01-Mar-2012).
This should do the job:
$json = json_decode($string);
echo json_encode($json, JSON_PRETTY_PRINT);
See http://www.php.net/manual/en/function.json-encode.php
Note: Don't forget to echo "<pre>" before and "</pre>" after, if you're printing it in HTML to preserve formatting ;)
There is no single MVC pattern you could obey to. MVC just states more or less that you should not mingle data and view, so that e.g. views are responsible for holding data or classes which are processing data are directly affecting the view.
But nevertheless, the way Android deals with classes and resources, you're sometimes even forced to follow the MVC pattern. More complicated in my opinion are the activities which are responsible sometimes for the view, but nevertheless act as an controller in the same time.
If you define your views and layouts in the XML files, load your resources from the res folder, and if you avoid more or less to mingle these things in your code, then you're anyway following an MVC pattern.
You can unpack the values to access the elements:
s = set([1, 2, 3])
v1, v2, v3 = s
print(v1,v2,v3)
#1 2 3
You can also join if the number of columns are not same in both tables and can map static value to table column
from t1 in Table1
join t2 in Table2
on new {X = t1.Column1, Y = 0 } on new {X = t2.Column1, Y = t2.Column2 }
select new {t1, t2}
If you look at the function (by typing it's name at the console) you will see that it is just a simple functionalized version of the [<-
function which is described at ?"["
. [
is a rather basic function to R so you would be well-advised to look at that page for further details. Especially important is learning that the index argument (the second argument in replace
can be logical, numeric or character classed values. Recycling will occur when there are differing lengths of the second and third arguments:
You should "read" the function call as" "within the first argument, use the second argument as an index for placing the values of the third argument into the first":
> replace( 1:20, 10:15, 1:2)
[1] 1 2 3 4 5 6 7 8 9 1 2 1 2 1 2 16 17 18 19 20
Character indexing for a named vector:
> replace(c(a=1, b=2, c=3, d=4), "b", 10)
a b c d
1 10 3 4
Logical indexing:
> replace(x <- c(a=1, b=2, c=3, d=4), x>2, 10)
a b c d
1 2 10 10
The backgroundTint
attribute will help you to add a tint(shade) to the background. You can provide a color value for the same in the form of - "#rgb", "#argb", "#rrggbb", or "#aarrggbb".
The backgroundTintMode
on the other hand will help you to apply the background tint. It must have constant values like src_over, src_in, src_atop,
etc.
Refer this to get a clear idea of the the constant values that can be used. Search for the backgroundTint
attribute and the description along with various attributes will be available.
All modules in Python have to have a certain directory structure. You can find details here.
Create an empty file called __init__.py
under the model
directory, such that your directory structure would look something like that:
.
+-- project
+-- src
+-- hello-world.py
+-- model
+-- __init__.py
+-- order.py
Also in your hello-world.py
file change the import statement to the following:
from model.order import SellOrder
That should fix it
P.S.: If you are placing your model
directory in some other location (not in the same directory branch), you will have to modify the python path using sys.path
.
You should add a shebang if the script is intended to be executable. You should also install the script with an installing software that modifies the shebang to something correct so it will work on the target platform. Examples of this is distutils and Distribute.
When calling just git tag <TAGNAME>
without any additional parameters, Git will create a new tag from your current HEAD (i.e. the HEAD of your current branch). When adding additional commits into this branch, the branch HEAD will keep up with those new commits, while the tag always refers to the same commit.
When calling git tag <TAGNAME> <COMMIT>
you can even specify which commit to use for creating the tag.
Regardless, a tag is still simply a "pointer" to a certain commit (not a branch).
Not to belabor the point, but if you are working in a Dockerfile
, you would solve this particular issue with Composer by installing the unzip
utility. Below is an example using the official PHP image to install unzip
and the zip
PHP extension for good measure.
FROM php:7.4-apache
# Install Composer
COPY --from=composer /usr/bin/composer /usr/bin/composer
# Install unzip utility and libs needed by zip PHP extension
RUN apt-get update && apt-get install -y \
zlib1g-dev \
libzip-dev \
unzip
RUN docker-php-ext-install zip
This is a helpful GitHub issue where the above is lovingly lifted from.
As for someone don't like gray background like academic editor, try this:
p <- p + theme_bw()
p
From RFC 6750, Section 1.2:
Bearer Token
A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).
The Bearer Token or Refresh token is created for you by the Authentication server. When a user authenticates your application (client) the authentication server then goes and generates for your a Bearer Token (refresh token) which you can then use to get an access token.
The Bearer Token is normally some kind of cryptic value created by the authentication server, it isn't random it is created based upon the user giving you access and the client your application getting access.
See also: Mozilla MDN Header Information.
You can make a vertical rule like this: <hr style="width: 1px; height: 20px; display: inline-block;">
It's possible to remove the workspace in Eclipse without much complications. The options are available under Preferences->General->Startup and Shutdown->Workspaces.
Note that this does not actually delete the files from the system, it simply removes it from the list of suggested workspaces. It changes the org.eclipse.ui.ide.prefs
file in Jon's answer from within Eclipse.
Arrays' constructors are different. Here are some ways to make an empty string array:
var arr = new string[0];
var arr = new string[]{};
var arr = Enumerable.Empty<string>().ToArray()
(sorry, on mobile)
There are two semantically correct solutions to this question:
I've tried a couple of plugins doing this and my favourite is jekyll-figure
.
jekyll-figure
One way to install jekyll-figure
is to add gem "jekyll-figure"
to your Gemfile in your plugins group.
Then run bundle install
from your terminal window.
jekyll-figure
Simply wrap your markdown in {% figure %}
and {% endfigure %}
tags.
You caption goes in the opening {% figure %}
tag, and you can even style it with markdown!
Example:
{% figure caption:"Le logo de **Jekyll** et son clin d'oeil à Robert Louis Stevenson" %}
![Le logo de Jekyll](/assets/images/2018-08-07-jekyll-logo.png)
{% endfigure %}
Now that your images and captions are semantically correct, you can apply CSS as you wish to:
figure
(for both image and caption)figure img
(for image only)figcaption
(for caption only)You'll need to create an image.html
file in your _includes
folder, and include it using Liquid in Markdown.
Create the image.html
document in your _includes folder :
<!-- _includes/image.html -->
<figure>
{% if include.url %}
<a href="{{ include.url }}">
{% endif %}
<img
{% if include.srcabs %}
src="{{ include.srcabs }}"
{% else %}
src="{{ site.baseurl }}/assets/images/{{ include.src }}"
{% endif %}
alt="{{ include.alt }}">
{% if include.url %}
</a>
{% endif %}
{% if include.caption %}
<figcaption>{{ include.caption }}</figcaption>
{% endif %}
</figure>
An image in /assets/images
with a caption:
This is [Jekyll](https://jekyllrb.com)'s logo :
{% include image.html
src="jekyll-logo.png" <!-- image filename (placed in /assets/images) -->
alt="Jekyll's logo" <!-- alt text -->
caption="This is Jekyll's logo, featuring Dr. Jekyll's serum!" <!-- Caption -->
%}
An (external) image using an absolute URL: (change src=""
to srcabs=""
)
This is [Jekyll](https://jekyllrb.com)'s logo :
{% include image.html
srcabs="https://jekyllrb.com/img/logo-2x.png" <!-- absolute URL to image file -->
alt="Jekyll's logo" <!-- alt text -->
caption="This is Jekyll's logo, featuring Dr. Jekyll's serum!" <!-- Caption -->
%}
A clickable image: (add url=""
argument)
This is [Jekyll](https://jekyllrb.com)'s logo :
{% include image.html
src="https://jekyllrb.com/img/logo-2x.png" <!-- absolute URL to image file -->
url="https://jekyllrb.com" <!-- destination url -->
alt="Jekyll's logo" <!-- alt text -->
caption="This is Jekyll's logo, featuring Dr. Jekyll's serum!" <!-- Caption -->
%}
An image without a caption:
This is [Jekyll](https://jekyllrb.com)'s logo :
{% include image.html
src="https://jekyllrb.com/img/logo-2x.png" <!-- absolute URL to image file -->
alt="Jekyll's logo" <!-- alt text -->
%}
Now that your images and captions are semantically correct, you can apply CSS as you wish to:
figure
(for both image and caption)figure img
(for image only)figcaption
(for caption only)In addition to the nested scrolling NestedScrollView
added one major functionality, which could even make it interesting outside of nested contexts: It has build in support for OnScrollChangeListener
. Adding a OnScrollChangeListener
to the original ScrollView
below API 23 required subclassing ScrollView
or messing around with the ViewTreeObserver
of the ScrollView
which often means even more work than subclassing. With NestedScrollView
it can be done using the build-in setter.
quit()
: Quits this driver, closing every associated window that was open.
close()
: Close the current window, quitting the browser if it's the last window currently open.
I'm not so comfortable with regular expressions, and my example results from a datetimepicker field formatted m/d/Y h:mA. In this legal example, you have to arrive before the actual deposition hearing. I use replace function to clean up the dates so that I can process them as Date objects and compare them.
function compareDateTimes() {
//date format ex "04/20/2017 01:30PM"
//the problem is that this format results in Invalid Date
//var d0 = new Date("04/20/2017 01:30PM"); => Invalid Date
var start_date = $(".letter #depo_arrival_time").val();
var end_date = $(".letter #depo_dateandtime").val();
if (start_date=="" || end_date=="") {
return;
}
//break it up for processing
var d1 = stringToDate(start_date);
var d2 = stringToDate(end_date);
var diff = d2.getTime() - d1.getTime();
if (diff < 0) {
end_date = moment(d2).format("MM/DD/YYYY hh:mA");
$(".letter #depo_arrival_time").val(end_date);
}
}
function stringToDate(the_date) {
var arrDate = the_date.split(" ");
var the_date = arrDate[0];
var the_time = arrDate[1];
var arrTime = the_time.split(":");
var blnPM = (arrTime[1].indexOf("PM") > -1);
//first fix the hour
if (blnPM) {
if (arrTime[0].indexOf("0")==0) {
var clean_hour = arrTime[0].substr(1,1);
arrTime[0] = Number(clean_hour) + 12;
}
arrTime[1] = arrTime[1].replace("PM", ":00");
} else {
arrTime[1] = arrTime[1].replace("AM", ":00");
}
var date_object = new Date(the_date);
//now replace the time
date_object = String(date_object).replace("00:00:00", arrTime.join(":"));
date_object = new Date(date_object);
return date_object;
}
If your object looks like this:
obj = {
"_id":"5078c3a803ff4197dc81fbfb",
"email":"[email protected]",
"image":"some_image_url",
"name":"Name 1"
}
Probably the simplest method in JavaScript is:
obj.id = obj._id
del object['_id']
As a result, you will get:
obj = {
"id":"5078c3a803ff4197dc81fbfb",
"email":"[email protected]",
"image":"some_image_url",
"name":"Name 1"
}
You can use dependency:analyze -DignoreNonCompile
This will print a list of used undeclared and unused declared dependencies (while ignoring runtime
/provided
/test
/system
scopes for unused dependency analysis.)
runtime
are considered as unused **The problem is almost certainly that you're not using the MPI compiler wrappers. Whenever you're compiling an MPI program, you should use the MPI wrappers:
mpicc
mpiCC
, mpicxx
, mpic++
mpifort
, mpif77
, mpif90
These wrappers do all of the dirty work for you of making sure that all of the appropriate compiler flags, libraries, include directories, library directories, etc. are included when you compile your program.
you could also specify multiple style values like this
$('#navigation ul li').css({'display': 'inline-block','background-color': '#ff0000', 'color': '#ffffff'});
Didn't find any answer using closest()
and I think it's the most simple answer when you don't know how many levels up the required element is, so posting an answer:
You can use the closest()
function combined with selectors to get the first element that matches when traversing upwards from the element:
('#element').closest('div') // returns the innermost 'div' in its parents
('#element').closest('.container') // returns innermost element with 'container' class among parents
('#element').closest('#foo') // returns the closest parent with id 'foo'
First of all, there's no such thing as a JSON object. What you've got in your question is a JavaScript object literal (see here for a great discussion on the difference). Here's how you would go about serializing what you've got to JSON though:
I would use an anonymous type filled with your results
type:
string json = JsonConvert.SerializeObject(new
{
results = new List<Result>()
{
new Result { id = 1, value = "ABC", info = "ABC" },
new Result { id = 2, value = "JKL", info = "JKL" }
}
});
Also, note that the generated JSON has result items with id
s of type Number
instead of strings. I doubt this will be a problem, but it would be easy enough to change the type of id
to string
in the C#.
I'd also tweak your results
type and get rid of the backing fields:
public class Result
{
public int id { get ;set; }
public string value { get; set; }
public string info { get; set; }
}
Furthermore, classes conventionally are PascalCased
and not camelCased
.
Here's the generated JSON from the code above:
{
"results": [
{
"id": 1,
"value": "ABC",
"info": "ABC"
},
{
"id": 2,
"value": "JKL",
"info": "JKL"
}
]
}
Aus_lacy's post gave me the idea of trying related methods, of which join does work:
In [196]:
hl.name = 'hl'
Out[196]:
'hl'
In [199]:
df.join(hl).head(4)
Out[199]:
high low loc_h loc_l hl
2014-01-01 17:00:00 1.376235 1.375945 1.376235 1.375945 1.376090
2014-01-01 17:01:00 1.376005 1.375775 NaN NaN NaN
2014-01-01 17:02:00 1.375795 1.375445 NaN 1.375445 1.375445
2014-01-01 17:03:00 1.375625 1.375515 NaN NaN NaN
Some insight into why concat works on the example but not this data would be nice though!
When you set a string variable, it doesn't save quotes of it, they are a part of its definition. so you don't need to use :1
I've been working on this problem of ditching those irritable Google error pages today. It is possible with the Android example code seen above and in plenty of other forums (ask how I know):
wv.setWebViewClient(new WebViewClient() {
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
if (view.canGoBack()) {
view.goBack();
}
Toast.makeText(getBaseContext(), description, Toast.LENGTH_LONG).show();
}
}
});
IF you put it in shouldOverrideUrlLoading() as one more webclient. At least, this is working for me on my 2.3.6 device. We'll see where else it works later. That would only depress me now, I'm sure. The goBack bit is mine. You may not want it.
function select_option(index)
{
var optwewant;
for (opts in $('#span_id').children('select'))
{
if (opts.value() = index)
{
optwewant = opts;
break;
}
}
alert (optwewant);
}
Assign the second variable for the $.each function()
as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).
$.each(json, function(arrayID,group) {
console.log('<a href="'+group.GROUP_ID+'">');
$.each(group.EVENTS, function(eventID,eventData) {
console.log('<p>'+eventData.SHORT_DESC+'</p>');
});
});
Should print out everything you were trying in your question.
http://jsfiddle.net/niklasvh/hZsQS/
edit renamed the variables to make it bit easier to understand what is what.
This is how simply I sort from previous examples:
if my array is items
:
0: {id: 14, auctionID: 76, userID: 1, amount: 39}
1: {id: 1086, auctionID: 76, userID: 1, amount: 55}
2: {id: 1087, auctionID: 76, userID: 1, amount: 55}
I thought simply calling items.sort()
would sort it it, but there was two problems:
1. Was sorting them strings
2. Was sorting them first key
This is how I modified the sort function:
for(amount in items){
if(item.hasOwnProperty(amount)){
i.sort((a, b) => a.amount - b.amount);
}
}
It is possible to get both the primary and secondary axes on one side of the chart by designating the secondary axis for one of the series.
To get the primary axis on the right side with the secondary axis, you need to set to "High" the Axis Labels option in the Format Axis dialog box for the primary axis.
To get the secondary axis on the left side with the primary axis, you need to set to "Low" the Axis Labels option in the Format Axis dialog box for the secondary axis.
I know of no way to get a third set of axis labels on a single chart. You could fake in axis labels & ticks with text boxes and lines, but it would be hard to get everything aligned correctly.
The more feasible route is that suggested by zx8754: Create a second chart, turning off titles, left axes, etc. and lay it over the first chart. See my very crude mockup which hasn't been fine-tuned yet.
I think you need to define an object and then push in array
var obj = {};
obj[name] = val;
ary.push(obj);
You can just do:
git rev-parse HEAD
To explain a bit further: git rev-parse
is git's basic command for interpreting any of the exotic ways that you can specify the name of a commit and HEAD
is a reference to your current commit or branch. (In a git bisect
session, it points directly to a commit ("detached HEAD") rather than a branch.)
Alternatively (and easier to remember) would be to just do:
git show
... which defaults to showing the commit that HEAD
points to. For a more concise version, you can do:
$ git show --oneline -s
c0235b7 Autorotate uploaded images based on EXIF orientation
To get dpi:
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
// will either be DENSITY_LOW, DENSITY_MEDIUM or DENSITY_HIGH
int dpiClassification = dm.densityDpi;
// these will return the actual dpi horizontally and vertically
float xDpi = dm.xdpi;
float yDpi = dm.ydpi;
I think Nosql is "more suitable" in these scenarios at least (more supplementary is welcome)
Easy to scale horizontally by just adding more nodes.
Query on large data set
Imagine tons of tweets posted on twitter every day. In RDMS, there could be tables with millions (or billions?) of rows, and you don't want to do query on those tables directly, not even mentioning, most of time, table joins are also needed for complex queries.
Disk I/O bottleneck
If a website needs to send results to different users based on users' real-time info, we are probably talking about tens or hundreds of thousands of SQL read/write requests per second. Then disk i/o will be a serious bottleneck.
Update Nevermind, this doesn't work in IE or it's new brother, FF. Works on every other type of element as expected, but doesn't work on file inputs. A much better way to do this is to just create a file input and a label that links to it. Make the file input display none and boom, it works in IE9+ seamlessly.
By using pseudo elements positioned/sized against their container, we can get by with only one input file (no additional markup needed), and style as per usual.
<input type="file" class="foo">
.foo {
display: block;
position: relative;
width: 300px;
margin: auto;
cursor: pointer;
border: 0;
height: 60px;
border-radius: 5px;
outline: 0;
}
.foo:hover:after {
background: #5978f8;
}
.foo:after {
transition: 200ms all ease;
border-bottom: 3px solid rgba(0,0,0,.2);
background: #3c5ff4;
text-shadow: 0 2px 0 rgba(0,0,0,.2);
color: #fff;
font-size: 20px;
text-align: center;
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: block;
content: 'Upload Something';
line-height: 60px;
border-radius: 5px;
}
Enjoy guys!
Old Update
Turned this into a Stylus mixin. Should be easy enough for one of you cool SCSS cats to convert it.
file-button(button_width = 150px)
display block
position relative
margin auto
cursor pointer
border 0
height 0
width 0
outline none
&:after
position absolute
top 0
text-align center
display block
width button_width
left -(button_width / 2)
Usage:
<input type="file">
input[type="file"]
file-button(200px)
Your memcpy
code is correct.
My guess is you are lacking an include of string.h. So the compiler assumes a wrong prototype of memcpy
and thus the warning.
Anyway, you should just assign the structs for the sake of simplicity (as Joachim Pileborg pointed out).
I've just spent quite some time troubleshooting this very problem. None of the proposed solutions worked. Turned out that our sysadmin by mistake assigned the same static IP to two unrelated servers belonging to different groups, but sitting on the same network. The end results were intermittently dropped vnc connections, browser that had to be refreshed several times to fetch the web page, and other strange things.
Using JSONSerialization
always felt unSwifty and unwieldy, but it is even more so with the arrival of Codable
in Swift 4. If you wield a [String:Any]
in front of a simple struct
it will ... hurt. Check out this in a Playground:
import Cocoa
let data = "[{\"form_id\":3465,\"canonical_name\":\"df_SAWERQ\",\"form_name\":\"Activity 4 with Images\",\"form_desc\":null}]".data(using: .utf8)!
struct Form: Codable {
let id: Int
let name: String
let description: String?
private enum CodingKeys: String, CodingKey {
case id = "form_id"
case name = "form_name"
case description = "form_desc"
}
}
do {
let f = try JSONDecoder().decode([Form].self, from: data)
print(f)
print(f[0])
} catch {
print(error)
}
With minimal effort handling this will feel a whole lot more comfortable. And you are given a lot more information if your JSON does not parse properly.
psoul's excellent post answers to your question so I won't replicate his good work, but I feel it'd help to explain why this is at once a perfectly valid but also terribly silly question. After all, this is a place to learn, right?
Modern computer programs are produced through a series of conversions, starting with the input of a human-readable body of text instructions (called "source code") and ending with a computer-readable body of instructions (called alternatively "binary" or "machine code").
The way that a computer runs a set of machine code instructions is ultimately very simple. Each action a processor can take (e.g., read from memory, add two values) is represented by a numeric code. If I told you that the number 1 meant scream and the number 2 meant giggle, and then held up cards with either 1 or 2 on them expecting you to scream or giggle accordingly, I would be using what is essentially the same system a computer uses to operate.
A binary file is just a set of those codes (usually call "op codes") and the information ("arguments") that the op codes act on.
Now, assembly language is a computer language where each command word in the language represents exactly one op-code on the processor. There is a direct 1:1 translation between an assembly language command and a processor op-code. This is why coding assembly for an x386 processor is different than coding assembly for an ARM processor.
Disassembly is simply this: a program reads through the binary (the machine code), replacing the op-codes with their equivalent assembly language commands, and outputs the result as a text file. It's important to understand this; if your computer can read the binary, then you can read the binary too, either manually with an op-code table in your hand (ick) or through a disassembler.
Disassemblers have some new tricks and all, but it's important to understand that a disassembler is ultimately a search and replace mechanism. Which is why any EULA which forbids it is ultimately blowing hot air. You can't at once permit the computer reading the program data and also forbid the computer reading the program data.
(Don't get me wrong, there have been attempts to do so. They work as well as DRM on song files.)
However, there are caveats to the disassembly approach. Variable names are non-existent; such a thing doesn't exist to your CPU. Library calls are confusing as hell and often require disassembling further binaries. And assembly is hard as hell to read in the best of conditions.
Most professional programmers can't sit and read assembly language without getting a headache. For an amateur it's just not going to happen.
Anyway, this is a somewhat glossed-over explanation, but I hope it helps. Everyone can feel free to correct any misstatements on my part; it's been a while. ;)
Use a regex like ^\d
I achieve this by writing below a few lines of code
extension UIImage {
public func correctlyOrientedImage() -> UIImage {
guard imageOrientation != .up else { return self }
UIGraphicsBeginImageContextWithOptions(size, false, scale)
draw(in: CGRect(origin: .zero, size: size))
let normalizedImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return normalizedImage
}
}
The present solution produces the same flow as your OP. It does not use Labels, but this was not a requirement of the OP. You only asked for "a simple conditional loop that will go to the next iteration if a condition is true", and since this is cleaner to read, it is likely a better option than that using a Label.
What you want inside your for
loop follows the pattern
If (your condition) Then
'Do something
End If
In this case, your condition is Not(Return = 0 And Level = 0)
, so you would use
For i = 2 To 24
Level = Cells(i, 4)
Return = Cells(i, 5)
If (Not(Return = 0 And Level = 0)) Then
'Do something
End If
Next i
PS: the condition is equivalent to (Return <> 0 Or Level <> 0)
NSDate *todaysDate = [NSDate new];
NSDateFormatter *formatter = [NSDateFormatter new];
[formatter setDateFormat:@"MM-dd-yyyy HH:mm:ss"];
NSString *strDateTime = [formatter stringFromDate:todaysDate];
NSString *strFileName = [NSString stringWithFormat:@"/Users/Shared/Recording_%@.mov",strDateTime];
NSLog(@"filename:%@",strFileName);
Log will be : filename:/Users/Shared/Recording_06-28-2016 12:53:26.mov
1. Add all set element in list -> al.addAll(s);
2. Sort all the elements in list using -> Collections.sort(al);
public class SortSetProblem {
public static void main(String[] args) {
ArrayList<String> al = new ArrayList();
Set<String> s = new HashSet<>();
s.add("ved");
s.add("prakash");
s.add("sharma");
s.add("apple");
s.add("ved");
s.add("banana");
System.out.println("Before Sorting");
for (String s1 : s) {
System.out.print(" " + s1);
}
System.out.println("After Sorting");
al.addAll(s);
Collections.sort(al);
for (String set : al) {
System.out.print(" " + set);
}
}
}
input - ved prakash sharma apple ved banana
Output - apple banana prakash sharma ved
You can use the NotMapped
attribute data annotation to instruct Code-First to exclude a particular property
public class Customer
{
public int CustomerID { set; get; }
public string FirstName { set; get; }
public string LastName{ set; get; }
[NotMapped]
public int Age { set; get; }
}
[NotMapped]
attribute is included in the System.ComponentModel.DataAnnotations
namespace.
You can alternatively do this with Fluent API
overriding OnModelCreating
function in your DBContext
class:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().Ignore(t => t.LastName);
base.OnModelCreating(modelBuilder);
}
http://msdn.microsoft.com/en-us/library/hh295847(v=vs.103).aspx
The version I checked is EF 4.3
, which is the latest stable version available when you use NuGet.
Edit : SEP 2017
Data annotation
If you are using asp.net core (2.0 at the time of this writing), The [NotMapped]
attribute can be used on the property level.
public class Customer
{
public int Id { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
[NotMapped]
public int FullName { set; get; }
}
Fluent API
public class SchoolContext : DbContext
{
public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().Ignore(t => t.FullName);
base.OnModelCreating(modelBuilder);
}
public DbSet<Customer> Customers { get; set; }
}
In addition to gmaggio's answer if you need to dynamically REPLACE
and UPDATE
according to another column you can do for example:
UPDATE your_table t1
INNER JOIN other_table t2
ON t1.field_id = t2.field_id
SET t1.your_field = IF(LOCATE('articles/updates/', t1.your_field) > 0,
REPLACE(t1.your_field, 'articles/updates/', t2.new_folder), t1.your_field)
WHERE...
In my example the string articles/news/
is stored in other_table t2
and there is no need to use LIKE
in the WHERE
clause.
Change the function that you get one single Result=[array, listp, freep]. So there is only one result to be displayed
We have had the same issue in eclipse or intellij. After trying many alternative solutions, I found simple solution - add this config to your application.properties:
spring.main.web-application-type=none
The R file can't be generated if your layout contains errors. If your res
folder is empty, then it's safe to assume that there's no res/layout
folder with any layouts in it, but your activity is probably calling setContentView
and not finding anything -- that qualifies as a problem with your layout.
You try to access private member of one class from another. The fact that bar-class is declared within foo-class means that bar in visible only inside foo class, but that is still other class.
And what is p->param?
Actually, it isn't clear what do you want to do
Below is the example to remove the element from the list.
List<int> items = new List<int>() { 2, 2, 3, 4, 2, 7, 3,3,3};
var result = items.Remove(2);//Remove the first ocurence of matched elements and returns boolean value
var result1 = items.RemoveAll(lst => lst == 3);// Remove all the matched elements and returns count of removed element
items.RemoveAt(3);//Removes the elements at the specified index
if you have existing project and you would like to add remote repository url then you need to do following command
git init
if you would like to add readme.md file then you can create it and add it using below command.
git add README.md
make your first commit using below command
git commit -m "first commit"
Now you completed all local repository process, now how you add remote repository url ? check below command this is for ssh url, you can change it for https.
git remote add origin [email protected]:user-name/repository-name.git
How you push your first commit see below command :
git push -u origin master
If you don't mind something related to Bootstrap, an excellent (unofficial) Bootstrap Switch is available.
It uses radio types or checkboxes as switches. A type
attribute has been added since V.1.8.
Source code is available on Github.
I would not recommend to use those kind of old Switch buttons now, as they always seemed to suffer of usability issues as pointed by many people.
Please consider having a look at modern Switches like those.
This is how it would be done in a loop in C++(11):
for (const auto& attack : m_attack)
{
if (attack->m_num == input)
{
attack->makeDamage();
}
}
There is no for each
in C++. Another option is to use std::for_each with a suitable functor (this could be anything that can be called with an Attack*
as argument).
For now, this is the best way.
this.setState(previousState => ({
myArray: [...previousState.myArray, 'new value']
}));
The accepted solution only works on arrays, but not objects or associative arrays. Unfortunately, since Angular depends on the JavaScript implementation of array enumeration, the order of object properties cannot be consistently controlled. Some browsers may iterate through object properties lexicographically, but this cannot be guaranteed.
e.g. Given the following assignment:
$scope.cards = {
"card2": {
values: {
opt1: 9,
opt2: 12
}
},
"card1": {
values: {
opt1: 9,
opt2: 11
}
}
};
and the directive <ul ng-repeat="(key, card) in cards | orderBy:myValueFunction">
, ng-repeat may iterate over "card1" prior to "card2", regardless of sort order.
To workaround this, we can create a custom filter to convert the object to an array, and then apply a custom sort function before returning the collection.
myApp.filter('orderByValue', function () {
// custom value function for sorting
function myValueFunction(card) {
return card.values.opt1 + card.values.opt2;
}
return function (obj) {
var array = [];
Object.keys(obj).forEach(function (key) {
// inject key into each object so we can refer to it from the template
obj[key].name = key;
array.push(obj[key]);
});
// apply a custom sorting function
array.sort(function (a, b) {
return myValueFunction(b) - myValueFunction(a);
});
return array;
};
});
We cannot iterate over (key, value) pairings in conjunction with custom filters (since the keys for arrays are numerical indexes), so the template should be updated to reference the injected key names.
<ul ng-repeat="card in cards | orderByValue">
<li>{{card.name}} {{value(card)}}</li>
</ul>
Here is a working fiddle utilizing a custom filter on an associative array: http://jsfiddle.net/av1mLpqx/1/
Reference: https://github.com/angular/angular.js/issues/1286#issuecomment-22193332
I've seen some people promote 'package by feature' over 'package by layer' but I've used quite a few approaches over many years and found 'package by layer' much better than 'package by feature'.
Further to that I have found that a hybrid: 'package by module, layer then feature' strategy works extremely well in practice as it has many advantages of 'package by feature':
I explain in depth here: Java Package Name Structure and Organization but my standard package structure is:
revdomain.moduleType.moduleName.layer.[layerImpl].feature.subfeatureN.subfeatureN+1...
Where:
revdomain Reverse domain e.g. com.mycompany
moduleType [app*|framework|util]
moduleName e.g. myAppName if module type is an app or 'finance' if its an accounting framework
layer [model|ui|persistence|security etc.,]
layerImpl eg., wicket, jsp, jpa, jdo, hibernate (Note: not used if layer is model)
feature eg., finance
subfeatureN eg., accounting
subfeatureN+1 eg., depreciation
*Sometimes 'app' left out if moduleType is an application but putting it in there makes the package structure consistent across all module types.
I have solved my problem by running my Nginx as the user I'm currently logged in with, mulagala.
By default the user as nginx is defined at the very top section of the nginx.conf
file as seen below;
user nginx; # Default Nginx user
Change nginx to the name of your current user - here, mulagala.
user mulagala; # Custom Nginx user (as username of the current logged in user)
However, this may not address the actual problem and may actually have casual side effect(s).
For an effective solution, please refer to Joseph Barbere's solution.
I hit this in MVC 5 and Visual Studio Express 2013. I had two properties with an IndexAttribute
like below. Commenting out one of them and recompiling resulted in scaffolding the MVC 5 controller with views, using Entity Framework succeeding. Mysteriously, when I uncommented the attribute, recompiled, and tried again, the scaffolder ran just fine.
Perhaps the underlying entity data model or "something" was cached/corrupted, and removing and re-adding the IndexAttribute
simply triggered a rebuild of that "something".
[Index(IsUnique = true)]
public string Thing1 { get; set; }
[Index(IsUnique = true)]
public string Thing2 { get; set; }
Check out from dateutil.relativedelta import *
for adding a specific amount of time to a date, you can continue to use timedelta
for the simple stuff i.e.
use_date = use_date + datetime.timedelta(minutes=+10)
use_date = use_date + datetime.timedelta(hours=+1)
use_date = use_date + datetime.timedelta(days=+1)
use_date = use_date + datetime.timedelta(weeks=+1)
or you can start using relativedelta
use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(years=+1)
for the last day of next month:
use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)
Right now this will provide 29/02/2016
for the penultimate day of next month:
use_date = use_date+relativedelta(months=+1)
use_date = use_date+relativedelta(day=31)
use_date = use_date+relativedelta(days=-1)
last Friday of the next month:
use_date = use_date+relativedelta(months=+1, day=31, weekday=FR(-1))
2nd Tuesday of next month:
new_date = use_date+relativedelta(months=+1, day=1, weekday=TU(2))
As @mrroot5 points out dateutil's rrule
functions can be applied, giving you an extra bang for your buck, if you require date occurences.
for example:
Calculating the last day of the month for 9 months from the last day of last month.
Then, calculate the 2nd Tuesday for each of those months.
from dateutil.relativedelta import *
from dateutil.rrule import *
from datetime import datetime
use_date = datetime(2020,11,21)
#Calculate the last day of last month
use_date = use_date+relativedelta(months=-1)
use_date = use_date+relativedelta(day=31)
#Generate a list of the last day for 9 months from the calculated date
x = list(rrule(freq=MONTHLY, count=9, dtstart=use_date, bymonthday=(-1,)))
print("Last day")
for ld in x:
print(ld)
#Generate a list of the 2nd Tuesday in each of the next 9 months from the calculated date
print("\n2nd Tuesday")
x = list(rrule(freq=MONTHLY, count=9, dtstart=use_date, byweekday=TU(2)))
for tuesday in x:
print(tuesday)
Last day
2020-10-31 00:00:00
2020-11-30 00:00:00
2020-12-31 00:00:00
2021-01-31 00:00:00
2021-02-28 00:00:00
2021-03-31 00:00:00
2021-04-30 00:00:00
2021-05-31 00:00:00
2021-06-30 00:00:00
2nd Tuesday
2020-11-10 00:00:00
2020-12-08 00:00:00
2021-01-12 00:00:00
2021-02-09 00:00:00
2021-03-09 00:00:00
2021-04-13 00:00:00
2021-05-11 00:00:00
2021-06-08 00:00:00
2021-07-13 00:00:00
This is by no means an exhaustive list of what is available. Documentation is available here: https://dateutil.readthedocs.org/en/latest/
To check for the NULL data for column1 and consider your datatype of it is String, you could use below command :
select * from tbl_name where column1 is null or column1 <> '';
I don't know the performance of RegEx, but here is another alternative for RegEx leverages native HashSet and works in O( max(str.length, delimeter.length) ) complexity instead:
var multiSplit = function(str,delimiter){
if (!(delimiter instanceof Array))
return str.split(delimiter);
if (!delimiter || delimiter.length == 0)
return [str];
var hashSet = new Set(delimiter);
if (hashSet.has(""))
return str.split("");
var lastIndex = 0;
var result = [];
for(var i = 0;i<str.length;i++){
if (hashSet.has(str[i])){
result.push(str.substring(lastIndex,i));
lastIndex = i+1;
}
}
result.push(str.substring(lastIndex));
return result;
}
multiSplit('1,2,3.4.5.6 7 8 9',[',','.',' ']);
// Output: ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
multiSplit('1,2,3.4.5.6 7 8 9',' ');
// Output: ["1,2,3.4.5.6", "7", "8", "9"]
You can use reflection.
Type typeOfMyObject = myObject.GetType();
PropertyInfo[] properties =typeOfMyObject.GetProperties();
In the new ES2015 standard for JavaScript (formerly called ES6), objects can be created with computed keys: Object Initializer spec.
The syntax is:
var obj = {
[myKey]: value,
}
If applied to the OP's scenario, it would turn into:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
return {
[this.attr('name')]: this.attr('value'),
};
})
callback(null, inputs);
}
Note: A transpiler is still required for browser compatiblity.
Using Babel or Google's traceur, it is possible to use this syntax today.
In earlier JavaScript specifications (ES5 and below), the key in an object literal is always interpreted literally, as a string.
To use a "dynamic" key, you have to use bracket notation:
var obj = {};
obj[myKey] = value;
In your case:
stuff = function (thing, callback) {
var inputs = $('div.quantity > input').map(function(){
var key = this.attr('name')
, value = this.attr('value')
, ret = {};
ret[key] = value;
return ret;
})
callback(null, inputs);
}
composer dump-autoload
PATH vendor/composer/autoload_classmap.php
php artisan dump-autoload
No matter what $action is, it will always either not be "add" OR not be "delete", which is why the if condition always passes. What you want is to use && instead of ||:
(!isset($action)) || ($action !="add" && $action !="delete"))
Reinstall everything??? no way! just add the path to SDK tools and platform tools in your classpath from Environment Variables.
Then restart Eclipse.
other way go to Devices -> Reset adb
, or simply open the task manager and kill the adb.exe
process.
Flatlist's extraData wasn't working for me and I happened to be using a prop from redux. This sounded similar to issues from the comments in ED209's answer. I ended up manually calling setState when I receive the prop.
componentWillReceiveProps(nextProps: StateProps) {
if (this.props.yourProp != null && nextProps.yourProp) {
this.setState({ yourState: processProp(nextProps.yourProp) });
}
}
<FlatList
data={this.state.yourState}
extraData={this.state.yourState}
/>
For those of you using > React 17 use getDerivedStateFromProps
Ran into the same problem in Spark 2.0.2. Resolved it by feeding it the jars. Here's what I ran:
$ spark-shell --jars aws-java-sdk-1.7.4.jar,hadoop-aws-2.7.3.jar,jackson-annotations-2.7.0.jar,jackson-core-2.7.0.jar,jackson-databind-2.7.0.jar,joda-time-2.9.6.jar
scala> val hadoopConf = sc.hadoopConfiguration
scala> hadoopConf.set("fs.s3.impl","org.apache.hadoop.fs.s3native.NativeS3FileSystem")
scala> hadoopConf.set("fs.s3.awsAccessKeyId",awsAccessKeyId)
scala> hadoopConf.set("fs.s3.awsSecretAccessKey", awsSecretAccessKey)
scala> val sqlContext = new org.apache.spark.sql.SQLContext(sc)
scala> sqlContext.read.parquet("s3://your-s3-bucket/")
obviously, you need to have the jars in the path where you're running spark-shell from
The best way I have found is to use jQuery JSON
$ declare -a arr
$ arr=("a")
$ arr=("${arr[@]}" "new")
$ echo ${arr[@]}
a new
$ arr=("${arr[@]}" "newest")
$ echo ${arr[@]}
a new newest
make sure that the imported R is not from another module. I had moved a class from a module to the main project, and the R was the one from the module.
An output reg foo
is just shorthand for output foo_wire; reg foo; assign foo_wire = foo
. It's handy when you plan to register that output anyway. I don't think input reg
is meaningful for module
(perhaps task
). input wire
and output wire
are the same as input
and output
: it's just more explicit.
The default timeout is 900 second. You can specify different timeout.
-T seconds
--timeout=seconds
The default is to retry 20 times. You can specify different tries.
-t number
--tries=number
link: wget man document
E.X You can use Singleton for global information that needs to be injected.
In my case, I was keeping the Logged user detail(username, permissions etc.) in Global Static Class. And when I tried to implement the Unit Test, there was no way I could inject dependency into Controller classes. Thus I have changed my Static Class to Singleton pattern.
public class SysManager
{
private static readonly SysManager_instance = new SysManager();
static SysManager() {}
private SysManager(){}
public static SysManager Instance
{
get {return _instance;}
}
}
http://csharpindepth.com/Articles/General/Singleton.aspx#cctor
For DataTables >=1.10, use:
$('table').dataTable({searching: false, paging: false, info: false});
For DataTables <1.10, use:
$('table').dataTable({bFilter: false, bInfo: false});
or using pure CSS:
.dataTables_filter, .dataTables_info { display: none; }
I used to declare the configuration in application.properties
like this (you can use you own property file)
server.host = localhost
server.port = 8081
and in application you can get it easily by @Value("${server.host}")
and @Value("${server.port}")
as field level annotation.
or if in your case it is dynamic than you can get from system properties
Here is the example
@Value("#{systemproperties['server.host']}")
@Value("#{systemproperties['server.port']}")
For a better understanding of this annotation , see this example Multiple uses of @Value annotation
Try svn revert filename
for every file you don't need and haven't yet committed. Or alternatively do svn revert -R folder
for the problematic folder and then re-do the operation with correct ignoring configuration.
you can undo any scheduling operations:
$ svn add mistake.txt whoops
A mistake.txt
A whoops
A whoops/oopsie.c
$ svn revert mistake.txt whoops
Reverted mistake.txt
Reverted whoops
There is a really cool solution from Danny Markov for that. It uses navigator.getUserMedia method and should work in modern browsers. I have tested it successfully with Firefox and Chrome. IE didn't work:
Here is a demo:
https://tutorialzine.github.io/pwa-photobooth/
Link to Danny Markovs description page:
http://tutorialzine.com/2016/09/everything-you-should-know-about-progressive-web-apps/
Link to GitHub:
@media print{_x000D_
body{_x000D_
visibility: hidden; /* no print*/_x000D_
}_x000D_
.print{_x000D_
_x000D_
visibility:visible; /*print*/_x000D_
}_x000D_
}
_x000D_
<body>_x000D_
<div class="noprint"> <!---no print--->_x000D_
<div class="noprint"> <!---no print--->_x000D_
<div class="print"> <!---print--->_x000D_
<div class="print"> <!---print--->_x000D_
_x000D_
_x000D_
</body>
_x000D_
You always don't need a cursor for this. You can do it with a while loop. You should avoid cursors whenever possible. While loop is faster than cursors.
I created a jQuery version of PhpMyCoder's answer:
$('form').submit(function( e ) {
if(!($('#file')[0].files[0].size < 10485760 && get_extension($('#file').val()) == 'jpg')) { // 10 MB (this size is in bytes)
//Prevent default and display error
alert("File is wrong type or over 10Mb in size!");
e.preventDefault();
}
});
function get_extension(filename) {
return filename.split('.').pop().toLowerCase();
}
How about playing with these two properties?
disableClose: boolean - Whether the user can use escape or clicking on the backdrop to close the modal.
hasBackdrop: boolean - Whether the dialog has a backdrop.
Java String
s are immutable.
In your first example, you are changing the reference to the String
, thus assigning it the value of two other Strings
combined: str + " Morning"
.
On the contrary, a StringBuilder
or StringBuffer
can be modified through its methods.
You can add a form onsubmit handler, something like:
<form onsubmit="return validate();">
</form>
<script>function validate() {
// check if input is bigger than 3
var value = document.getElementById('titleeee').value;
if (value.length < 3) {
return false; // keep form from submitting
}
// else form is good let it submit, of course you will
// probably want to alert the user WHAT went wrong.
return true;
}</script>
Respectfully to all those saying you can't insert a parameter in the middle of an alias I just tested it and found that it did work.
alias mycommand = "python3 "$1" script.py --folderoutput RESULTS/"
when I then ran mycommand foobar it worked exactly as if I had typed the command out longhand.
List is Doubly Linked List so it is easy to insert and delete an element. We have to just change the few pointers, whereas in vector if we want to insert an element in the middle then each element after it has to shift by one index. Also if the size of the vector is full then it has to first increase its size. So it is an expensive operation. So wherever insertion and deletion operations are required to be performed more often in such a case list should be used.
I'm assuming that the buttons are supposed to be next to each other on the same line, they should not each be centered using the 'auto' margin, but placed inside a div with a defined width that has a margin '0 auto':
CSS:
#centerbuttons{
width:250px;
margin:0 auto;
}
HTML (after removing the margin properties from your buttons' CSS):
<div id="centerbuttons">
<input value="Search" title="Search" type="submit">
<input value="I'm Feeling Lucky" title="I'm Feeling Lucky" name="lucky" type="submit">
</div>
I got this error when my .env
file was not set up properly. Make sure you have a .env
file with valid database login credentials.
Had the same issue and got curious about the performance of each solution.
Here's is the %timeit
:
import numpy as np
lst = [['a','b','c'], [1,2,3], ['x','y','z']]
The first numpy-way, transforming the array:
%timeit list(np.array(lst).T[0])
4.9 µs ± 163 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Fully native using list comprehension (as explained by @alecxe):
%timeit [item[0] for item in lst]
379 ns ± 23.1 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Another native way using zip
(as explained by @dawg):
%timeit list(zip(*lst))[0]
585 ns ± 7.26 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
Second numpy-way. Also explained by @dawg:
%timeit list(np.array(lst)[:,0])
4.95 µs ± 179 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
Surprisingly (well, at least for me) the native way using list comprehension is the fastest and about 10x faster than the numpy-way. Running the two numpy-ways without the final list
saves about one µs which is still in the 10x difference.
Note that, when I surrounded each code snippet with a call to len
, to ensure that Generators run till the end, the timing stayed the same.
The issue is two-fold:
As a prerequisite (as of August, 2016), you need to link an AdSense account and then turn on monetization in your YouTube channel. It's a painful change that broke a lot of live streams.
You will need to use the following URL format for the embed:
<iframe width="560" height="315" src="https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID&autoplay=1" frameborder="0" allowfullscreen></iframe>
The &autoplay=1
is not necessary, but I like to include it. Change CHANNEL
to your channel's ID. One thing to note is that WordPress may reformat the URL once you commit your change. Therefore, you'll need a plugin that allows you to use raw code and not have it override. Using a custom PHP code plugin can help and you would just echo the code like so:
<?php echo '<iframe width="560" height="315" src="https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID&autoplay=1" frameborder="0" allowfullscreen></iframe>'; ?>
Let me know if that worked for you!
To perform an HTTP PUT:
URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestMethod("PUT");
OutputStreamWriter out = new OutputStreamWriter(
httpCon.getOutputStream());
out.write("Resource content");
out.close();
httpCon.getInputStream();
To perform an HTTP DELETE:
URL url = new URL("http://www.example.com/resource");
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
httpCon.setDoOutput(true);
httpCon.setRequestProperty(
"Content-Type", "application/x-www-form-urlencoded" );
httpCon.setRequestMethod("DELETE");
httpCon.connect();
The FULLY WORKING SOLUTION for both Android
or React-native
users facing this issue just add this
android:usesCleartextTraffic="true"
in AndroidManifest.xml file like this:
android:usesCleartextTraffic="true"
tools:ignore="GoogleAppIndexingWarning">
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
in between <application>
.. </application>
tag like this:
<application
android:name=".MainApplication"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:allowBackup="false"
android:theme="@style/AppTheme"
android:usesCleartextTraffic="true"
tools:ignore="GoogleAppIndexingWarning">
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
<activity
android:name=".MainActivity"
android:label="@string/app_name"/>
</application>
A static method, field, property, or event is callable on a class even when no instance of the class has been created. If any instances of the class are created, they cannot be used to access the static member. Only one copy of static fields and events exists, and static methods and properties can only access static fields and static events. Static members are often used to represent data or calculations that do not change in response to object state; for instance, a math library might contain static methods for calculating sine and cosine. Static class members are declared using the static keyword before the return type of the membe
To clarify the terminology right: arrays are fixed length structures (and the length of an existing cannot be altered) the expression add at the end is meaningless (by itself).
What you can do is create a new array one element larger and fill in the new element in the last slot:
public static int[] append(int[] array, int value) {
int[] result = Arrays.copyOf(array, array.length + 1);
result[result.length - 1] = value;
return result;
}
This quickly gets inefficient, as each time append is called a new array is created and the old array contents is copied over.
One way to drastically reduce the overhead is to create a larger array and keep track of up to which index it is actually filled. Adding an element becomes as simple a filling the next index and incrementing the index. If the array fills up completely, a new array is created with more free space.
And guess what ArrayList does: exactly that. So when a dynamically sized array is needed, ArrayList is a good choice. Don't reinvent the wheel.
EDIT:
Updating the answer with latest information
The maximum size allowed for a notification payload depends on which provider API you employ.
When using the legacy binary interface, maximum payload size is 2KB (2048 bytes).
When using the HTTP/2 provider API, maximum payload size is 4KB (4096 bytes). For Voice over Internet Protocol (VoIP) notifications, the maximum size is 5KB (5120 bytes)
OLD ANSWER: According to the apple doc the payload for iOS 8 is 2 kilobytes (2048 bytes) and 256 bytes for iOS 7 and prior. (removed the link as it was an old doc and it's broken now)
So if you just send text you have 2028 (iOS 8+) or 236 (iOS 7-) characters available.
The Notification Payload
Each remote notification includes a payload. The payload contains information about how the system should alert the user as well as any custom data you provide. In iOS 8 and later, the maximum size allowed for a notification payload is 2 kilobytes; Apple Push Notification service refuses any notification that exceeds this limit. (Prior to iOS 8 and in OS X, the maximum payload size is 256 bytes.)
But I've tested and you can send 2 kilobytes to iOS 7 devices too, even in production configurations
Returning a list of absolute filepaths, does not recurse into subdirectories
L = [os.path.join(os.getcwd(),f) for f in os.listdir('.') if os.path.isfile(os.path.join(os.getcwd(),f))]
public static Action<Func<TabPage, bool>> GetTabHider(this TabControl container) {
if (container == null) throw new ArgumentNullException("container");
var orderedCache = new List<TabPage>();
var orderedEnumerator = container.TabPages.GetEnumerator();
while (orderedEnumerator.MoveNext()) {
var current = orderedEnumerator.Current as TabPage;
if (current != null) {
orderedCache.Add(current);
}
}
return (Func<TabPage, bool> where) => {
if (where == null) throw new ArgumentNullException("where");
container.TabPages.Clear();
foreach (TabPage page in orderedCache) {
if (where(page)) {
container.TabPages.Add(page);
}
}
};
}
Used like this:
var showOnly = this.TabContainer1.GetTabHider();
showOnly((tab) => tab.Text != "tabPage1");
Original ordering is retained by retaining a reference to the anonymous function instance.
You could add the user to the Database Level Role db_datareader.
Members of the db_datareader fixed database role can run a SELECT statement against any table or view in the database.
See Books Online for reference:
http://msdn.microsoft.com/en-us/library/ms189121%28SQL.90%29.aspx
You can add a database user to a database role using the following query:
EXEC sp_addrolemember N'db_datareader', N'userName'
Another interesting project is texlive.js.
It allows you to compile (La)TeX to PDF in the browser.
In order to be able to justify the text, you need to know the width of the image. You can just use the normal width of the image, or use a different width, but IE 6 might get cranky at you and not scale.
Here's what you need:
<style type="text/css">
#container { width: 100px; //whatever width you want }
#image {width: 100%; //fill up whole div }
#text { text-align: justify; }
</style>
<div id="container">
<img src="" id="image" />
<p id="text">oooh look! text!</p>
</div>
Use autocmd CursorMoved * exe printf('match IncSearch /\V\<%s\>/', escape(expand('<cword>'), '/\'))
Make sure you have IncSearch
set to something. e.g call s:Attr('IncSearch', 'reverse')
. Alternatively you can use another highlight group in its place.
This will highlight all occurrences of words under your cursor without a delay. I find that a delay slows me down when I'm wizzing through code. The highlight color will match the color of the word, so it stays consistent with your scheme.
In case anyone else finds this thread with my problem -- I was using an "integer" column type in MySQL. The row I was attempting to insert had a primary key with a value larger than allowed by integer. Switching to "bigint" fixed the problem.
There is a command-line tool called XSD2DB, that generates database from xsd-files, available at sourceforge.
Since none of the answers mentioned the upcoming Ranges library, which is available in the standard library since C++20, and currently separately available on GitHub as range-v3
, I would like to add a way to perform this conversion using it.
To modify the string in-place:
str |= action::transform([](unsigned char c){ return std::tolower(c); });
To generate a new string:
auto new_string = original_string
| view::transform([](unsigned char c){ return std::tolower(c); });
(Don't forget to #include <cctype>
and the required Ranges headers.)
Note: the use of unsigned char
as the argument to the lambda is inspired by cppreference, which states:
Like all other functions from
<cctype>
, the behavior ofstd::tolower
is undefined if the argument's value is neither representable asunsigned char
nor equal toEOF
. To use these functions safely with plainchar
s (orsigned char
s), the argument should first be converted tounsigned char
:char my_tolower(char ch) { return static_cast<char>(std::tolower(static_cast<unsigned char>(ch))); }
Similarly, they should not be directly used with standard algorithms when the iterator's value type is
char
orsigned char
. Instead, convert the value tounsigned char
first:std::string str_tolower(std::string s) { std::transform(s.begin(), s.end(), s.begin(), // static_cast<int(*)(int)>(std::tolower) // wrong // [](int c){ return std::tolower(c); } // wrong // [](char c){ return std::tolower(c); } // wrong [](unsigned char c){ return std::tolower(c); } // correct ); return s; }
You need to add in the seconds, too:
unsigned long time_in_micros = 1000000 * tv.tv_sec + tv.tv_usec;
Note that this will only last for about 232/106 =~ 4295 seconds, or roughly 71 minutes though (on a typical 32-bit system).
in Bootstrap Table 4.x
If you are creating the table in the init parameters instead of using HTML.
You can specify the width parameters in the columns attribute:
$("table").bootstrapTable({
columns: [
{ field: "title", title: "title", width: "100px" }
]
});
I thought Activity was deprecated
No.
So for API Level 22 (with a minimum support for API Level 15 or 16), what exactly should I use both to host the components, and for the components themselves? Are there uses for all of these, or should I be using one or two almost exclusively?
Activity
is the baseline. Every activity inherits from Activity
, directly or indirectly.
FragmentActivity
is for use with the backport of fragments found in the support-v4
and support-v13
libraries. The native implementation of fragments was added in API Level 11, which is lower than your proposed minSdkVersion
values. The only reason why you would need to consider FragmentActivity
specifically is if you want to use nested fragments (a fragment holding another fragment), as that was not supported in native fragments until API Level 17.
AppCompatActivity
is from the appcompat-v7
library. Principally, this offers a backport of the action bar. Since the native action bar was added in API Level 11, you do not need AppCompatActivity
for that. However, current versions of appcompat-v7
also add a limited backport of the Material Design aesthetic, in terms of the action bar and various widgets. There are pros and cons of using appcompat-v7
, well beyond the scope of this specific Stack Overflow answer.
ActionBarActivity
is the old name of the base activity from appcompat-v7
. For various reasons, they wanted to change the name. Unless some third-party library you are using insists upon an ActionBarActivity
, you should prefer AppCompatActivity
over ActionBarActivity
.
So, given your minSdkVersion
in the 15-16 range:
If you want the backported Material Design look, use AppCompatActivity
If not, but you want nested fragments, use FragmentActivity
If not, use Activity
Just adding from comment as note: AppCompatActivity
extends FragmentActivity
, so anyone who needs to use features of FragmentActivity
can use AppCompatActivity
.
Generate the private key and server certificate with specific expiry date or with infinite(XXX) expiry time and self sign it.
$ openssl req -x509 -sha256 -newkey rsa:2048 -keyout key.pem -out cert.pem -days XXX
$ Enter a private key passphrase...`
Then it will work!
Just add in the '0' in your select.
INSERT INTO table_name (a,b,c,d)
SELECT
other_table.a AS a,
other_table.b AS b,
other_table.c AS c,
'0' AS d
FROM other_table
ActiveSupport::OrderedHash is another option if you don't want to use ruby 1.9.2 or roll your own workarounds.
I had the same problem.
My height changed to its original height while my slide was animating to the left, ( in a responsive website )
so I fixed it with CSS only :
.carousel .item.left img{
width: 100% !important;
}
You could try something like this:
echo 'maps.google.com' | rev | cut -d'.' -f 1 | rev
Explanation
rev
reverses "maps.google.com" to be moc.elgoog.spam
cut
uses dot (ie '.') as the delimiter, and chooses the first field, which is moc
com
/*
If your delimiters are slash-based, escape it:
\/*
*
means "0 or more of the previous repeatable pattern", which can be a single character, a character class or a group.
I think we should sent in this format
var array = [1, 2, 3, 4, 5];
$.post('/controller/MyAction', $.param({ data: array }, true), function(data) {});
Its already mentioned in Pass array to mvc Action via AJAX
It worked for me
AS per point 1, your PEAR path is c:\xampplite\php\pear\
However, your path is pointing to \xampplite\php\pear\PEAR
Putting the two one above the other you can clearly see one is too long:
c:\xampplite\php\pear\
\xampplite\php\pear\PEAR
Your include path is set to go one PEAR too deep into the pear tree. The PEAR subfolder of the pear folder includes the PEAR component. You need to adjust your include path up one level.
(you don't need the c: by the way, your path is fine as is, just too deep)
You can just do that too, it seems to work well too.
sc create "Servicename" binPath= "Path\To\your\App.exe" DisplayName= "My Custom Service"
You can open the registry and add a string named Description in your service's registry key to add a little more descriptive information about it. It will be shown in services.msc.
I think init_js should use declare instead of local!
function scan3() {
declare -n outvar=$1 # -n makes it a nameref.
local nl=$'\x0a'
outvar="output${nl}${nl}" # two total. quotes preserve newlines
}
@media (max-width: 767px) {
img {
display: table;
margin: 0 auto;
}
}
The solution found here helped us to update master to a previous commit that had already been pushed:
git checkout master
git reset --hard e3f1e37
git push --force origin e3f1e37:master
The key difference from the accepted answer is the commit hash "e3f1e37:" before master in the push command.
Found a solution:
mysql> UPDATE table SET last_update=now(), last_monitor=last_update WHERE id=1;
I found this in MySQL Docs and after a few tests it works:
the following statement sets col2 to the current (updated) col1 value, not the original col1 value. The result is that col1 and col2 have the same value. This behavior differs from standard SQL.
UPDATE t1 SET col1 = col1 + 1, col2 = col1;
Your expression is never going to evaluate.
You are comparing a
with a property of a
.
a
is of type Answer. a.Correct
, I'm guessing is a boolean.
Long form:-
Answer = answer.SingleOrDefault(a => a.Correct == true);
Short form:-
Answer = answer.SingleOrDefault(a => a.Correct);
TL:DR; return promises from you actions only when necessary, but DRY chaining the same actions.
For a long time I also though that returning actions contradicts the Vuex cycle of uni-directional data flow.
But, there are EDGE CASES where returning a promise from your actions might be "necessary".
Imagine a situation where an action can be triggered from 2 different components, and each handles the failure case differently. In that case, one would need to pass the caller component as a parameter to set different flags in the store.
Dumb example
Page where the user can edit the username in navbar and in /profile page (which contains the navbar). Both trigger an action "change username", which is asynchronous. If the promise fails, the page should only display an error in the component the user was trying to change the username from.
Of course it is a dumb example, but I don't see a way to solve this issue without duplicating code and making the same call in 2 different actions.
$(document).ready(function() {
$('#btnSun').click(function(){
myFunction();
});
$.fn.myFunction = function() {
alert('hi');
};
});
Put ' ; ' after function definition...
To add on to this:
If you're using CMAKE to generate a Visual Studio solution, and you want Visual Studio to output compiled files into /bin, Peter's answer needs to be modified a bit:
# set output directories for all builds (Debug, Release, etc.)
foreach( OUTPUTCONFIG ${CMAKE_CONFIGURATION_TYPES} )
string( TOUPPER ${OUTPUTCONFIG} OUTPUTCONFIG )
set( CMAKE_ARCHIVE_OUTPUT_DIRECTORY_${OUTPUTCONFIG} ${CMAKE_SOURCE_DIR}/lib )
set( CMAKE_LIBRARY_OUTPUT_DIRECTORY_${OUTPUTCONFIG} ${CMAKE_SOURCE_DIR}/lib )
set( CMAKE_RUNTIME_OUTPUT_DIRECTORY_${OUTPUTCONFIG} ${CMAKE_SOURCE_DIR}/bin )
endforeach( OUTPUTCONFIG CMAKE_CONFIGURATION_TYPES )
Because a dictionary is a single value. You need to use keyword expansion if you want to pass it as a group of keyword arguments.
IRIs do not replace URIs, because only URIs (effectively, ASCII) are permissible in some contexts -- including HTTP.
Instead, you specify an IRI and it gets transformed into a URI when going out on the wire.
Use jQuery to get the width of the window.
if ($(window).width() < 960) {
alert('Less than 960');
}
else {
alert('More than 960');
}
If you are using a custom TableViewCell, you can also override awakeFromNib
:
override func awakeFromNib() {
super.awakeFromNib()
// Set background color
let view = UIView()
view.backgroundColor = UIColor.redColor()
selectedBackgroundView = view
}
Alternatively you can use npm which automatically looks into the .bin folder. Then you can use tsc
DOS Batch files. Not sure if this qualifies as programming language at all.
It's not that you can't solve your problems, but if you are used to bash
...
Just my two cents.
This is not a real answer, we have duplicate class
...but it works :)
class A {
//do some things
}
class B {
//do some things
}
class copy_B is copy all class B
class copy_B extends A {
//do some things (copy class B)
}
class A_B extends copy_B{}
now
class C_A extends A{}
class C_B extends B{}
class C_A_b extends A_B{} //extends A & B
<table>
<tr><td><img ...><td><img ...>
<tr><td>caption1<td>caption2
</table>
Style as desired.
Following script shows the result for get last 5 characters and last 1 character in a string using JavaScript:
var testword='ctl03_Tabs1';
var last5=testword.substr(-5); //Get 5 characters
var last1=testword.substr(-1); //Get 1 character
Output :
Tabs1 // Got 5 characters
1 // Got 1 character
Naming convention for collection
In order to name a collection few precautions to be taken :
Things to keep in mind while creating a database name are :
For more information. Please check the below link : http://www.tutorial-points.com/2016/03/schema-design-and-naming-conventions-in.html
Do you have to use an OrderedDict or do you specifically want a map-like type that's ordered in some way with fast positional indexing? If the latter, then consider one of Python's many sorted dict types (which orders key-value pairs based on key sort order). Some implementations also support fast indexing. For example, the sortedcontainers project has a SortedDict type for just this purpose.
>>> from sortedcontainers import SortedDict
>>> sd = SortedDict()
>>> sd['foo'] = 'python'
>>> sd['bar'] = 'spam'
>>> print sd.iloc[0] # Note that 'bar' comes before 'foo' in sort order.
'bar'
>>> # If you want the value, then simple do a key lookup:
>>> print sd[sd.iloc[1]]
'python'
add label
to subview
of custom view
, no need of self.view.addSubview(view)
, because viewForHeaderInSection
return the UIView
view.addSubview(label)
Default-Values are only considered for parameters NOT given to the function.
So given a function
procedure foo( bar1 IN number DEFAULT 3,
bar2 IN number DEFAULT 5,
bar3 IN number DEFAULT 8 );
if you call this procedure with no arguments then it will behave as if called with
foo( bar1 => 3,
bar2 => 5,
bar3 => 8 );
but 'NULL' is still a parameter.
foo( 4,
bar3 => NULL );
This will then act like
foo( bar1 => 4,
bar2 => 5,
bar3 => Null );
( oracle allows you to either give the parameter in order they are specified in the procedure, specified by name, or first in order and then by name )
one way to treat NULL the same as a default value would be to default the value to NULL
procedure foo( bar1 IN number DEFAULT NULL,
bar2 IN number DEFAULT NULL,
bar3 IN number DEFAULT NULL );
and using a variable with the desired value then
procedure foo( bar1 IN number DEFAULT NULL,
bar2 IN number DEFAULT NULL,
bar3 IN number DEFAULT NULL )
AS
v_bar1 number := NVL( bar1, 3);
v_bar2 number := NVL( bar2, 5);
v_bar3 number := NVL( bar3, 8);
I have solved this problem by importing the following dependency. you must manually import httpclient
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
<exclusions>
<exclusion>
<groupId>commons-logging</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
</dependency>
If you want to convert to the new ES6 Map do this:
var kvArray = [['key1', 'value1'], ['key2', 'value2']];
var myMap = new Map(kvArray);
Why should you use this type of Map? Well that is up to you. Take a look at this.
Try BeanComparator from Apache Commons.
import org.apache.commons.beanutils.BeanComparator;
BeanComparator fieldComparator = new BeanComparator("fruitName");
Collections.sort(fruits, fieldComparator);
you can resolve by installing the UNMET dependencies globally.
example : npm install -g @angular/[email protected]
install each one by one. its worked for me.
Can't you just use count?
words = 'the quick brown fox jumps over the lazy gray dog'
words.count('z')
#output: 1
please modify your router.module.ts as:
const routes: Routes = [
{
path: '',
redirectTo: 'one',
pathMatch: 'full'
},
{
path: 'two',
component: ClassTwo, children: [
{
path: 'three',
component: ClassThree,
outlet: 'nameThree',
},
{
path: 'four',
component: ClassFour,
outlet: 'nameFour'
},
{
path: '',
redirectTo: 'two',
pathMatch: 'full'
}
]
},];
and in your component1.html
<h3>In One</h3>
<nav>
<a routerLink="/two" class="dash-item">...Go to Two...</a>
<a routerLink="/two/three" class="dash-item">... Go to THREE...</a>
<a routerLink="/two/four" class="dash-item">...Go to FOUR...</a>
</nav>
<router-outlet></router-outlet> // Successfully loaded component2.html
<router-outlet name="nameThree" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
<router-outlet name="nameFour" ></router-outlet> // Error: Cannot match any routes. URL Segment: 'three'
One more .... Hex Color Picker... it add's hex tab to your interface builder's color panel ... so now you can use hex color directly from Interface Builder..
You can use .filter()
with boolean operators ie &&:
var find = my_array.filter(function(result) {
return result.param1 === "srting1" && result.param2 === 'string2';
});
return find[0];
// Swift 2
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
let orientation: UIInterfaceOrientationMask =
[UIInterfaceOrientationMask.Portrait, UIInterfaceOrientationMask.PortraitUpsideDown]
return orientation
}
You can create a 'comment' table, with an id as primary key, then you add a text field to capture the text inserted by the user and you need another field to link the comment table to the article table (foreign key). Plus you need a field to store the user that has entered a comment, this field can be the user's email. Then you capture via GET or POST the user's email and comment and you insert everything in the DB:
"INSERT INTO comment (comment, email, approved) VALUES ('$comment', '$email', '$approved')"
This is a first hint. Of course adding a comment feature it takes a little bit. Then you should think about a form to let the admin to approve the comments and how to publish the comments in the end of articles.
The easiest way to check your workstation is to download the VMware Processor Check for 64-Bit Compatibility tool from the VMware website.
You can't run a 64-bit VM session on a 32-bit processor. However, you can run a 64-bit VM session if you have a 64-bit processor but have installed a 32-bit host OS and your processor supports the right extensions. The tool linked above will tell you if yours does.
I faced similar and tried some of the techniques mentioned here. To overcome,
I performed a cleanup of duplicate entries in c:\users\<user name>\.npmrc
Hope it helps someone. Thanks,
Javascript which runs on the client machine can't access the local disk file system due to security restrictions.
If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.
Note that the result of dereferencing an std::map::iterator is an std::pair. The values of first
and second
are not functions, they are variables.
Change:
iter->first()
to
iter->first
Ditto with iter->second
.
=IF(ISNUMBER(SEARCH(LEFT(H2,3),I2)),"YES","NO")))
The standard way to add Multiple functions
<button (click)="removeAt(element.bookId); openDeleteDialog()"> Click Here</button>
or
<button (click)="removeAt(element.bookId)" (click)="openDeleteDialog()"> Click Here</button>