If you're not in an ipython notebook (like the OP), you can also just declare the size when you declare the figure:
width = 12
height = 12
plt.figure(figsize=(width, height))
If you are looking to count the number of NAs in the entire dataframe you could also use
sum(is.na(df))
Simply $("#3").remove();
would be enough. But 3
isn't a good id (I think it's even illegal, as it starts with a digit).
You need to search the World from the top right search bar and delete the expired certificate. Make sure you selected Login and All items.
x = cumsum(c(0, runif(100, -1, +1)))
y = cumsum(c(0, runif(100, -1, +1)))
fit = lm(y ~ x)
> names(summary(fit))
[1] "call" "terms"
[3] "residuals" "coefficients"
[5] "aliased" "sigma"
[7] "df" "r.squared"
[9] "adj.r.squared" "fstatistic"
[11] "cov.unscaled"
summary(fit)$r.squared
As per comments, First you need to install an instance of SQL Server if you don't already have one - https://msdn.microsoft.com/en-us/library/ms143219.aspx
Once this is installed you must connect to this instance (server) and then you can create a database here - https://msdn.microsoft.com/en-US/library/ms186312.aspx
Try
String[] splited = str.split("\\s");
http://download.oracle.com/javase/tutorial/essential/regex/pre_char_classes.html
Some "front ends", with the "Use Booleans" option enabled, will treat all TINYINT(1) columns as Boolean, and vice versa.
This allows you to, in the application, use TRUE and FALSE rather than 1 and 0.
This doesn't affect the database at all, since it's implemented in the application.
There is not really a BOOLEAN
type in MySQL. BOOLEAN is just a synonym for TINYINT(1), and TRUE and FALSE are synonyms for 1 and 0.
If the conversion is done in the compiler, there will be no difference in performance in the application. Otherwise, the difference still won't be noticeable.
You should use whichever method allows you to code more efficiently, though not using the feature may reduce dependency on that particular "front end" vendor.
Under "Settings -> Editor -> General -> Auto Import"
there are several options regarding automatic imports. Only unambiguous imports may be added automatically; this is one of the options.
You need to create a service to be able to share data between controllers.
app.factory('myService', function() {
var savedData = {}
function set(data) {
savedData = data;
}
function get() {
return savedData;
}
return {
set: set,
get: get
}
});
In your controller A:
myService.set(yourSharedData);
In your controller B:
$scope.desiredLocation = myService.get();
Remember to inject myService in the controllers by passing it as a parameter.
If you have multiple source files, you probably actually want to use link-time-optimization to output one bitcode file for the entire program. The other answers given will cause you to end up with a bitcode file for every source file.
Instead, you want to compile with link-time-optimization
clang -flto -c program1.c -o program1.o
clang -flto -c program2.c -o program2.o
and for the final linking step, add the argument -Wl,-plugin-opt=also-emit-llvm
clang -flto -Wl,-plugin-opt=also-emit-llvm program1.o program2.o -o program
This gives you both a compiled program and the bitcode corresponding to it (program.bc). You can then modify program.bc in any way you like, and recompile the modified program at any time by doing
clang program.bc -o program
although be aware that you need to include any necessary linker flags (for external libraries, etc) at this step again.
Note that you need to be using the gold linker for this to work. If you want to force clang to use a specific linker, create a symlink to that linker named "ld" in a special directory called "fakebin" somewhere on your computer, and add the option
-B/home/jeremy/fakebin
to any linking steps above.
The problem is that img tag is inline element and you can't restrict width of inline element.
So to restrict img tag width first you need to convert it into a inline-block element
img.Image{
display: inline-block;
}
Not with primitive arrays. You'll need to use a List or some other data structure:
List<Integer> items = Collections.unmodifiableList(Arrays.asList(0,1,2,3));
Almost all of the python files should live in their respective folders (C:\Python26
and C:\Python27
). Some installers (ActiveState) will also associate .py*
files and add the python path to %PATH%
with an install if you tick the "use this as the default installation" box.
Addition to the accepted answer:
if you are going to use
@Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 },null)
this will create actionlink where you can't create new custom attribute or style for the link.
However, the 4th parameter in ActionLink extension will solve that problem. Use the 4th parameter for customization in your way.
@Html.ActionLink("LinkName", "ActionName", "ControllerName", new { @id = idValue, @secondParam= = 2 }, new { @class = "btn btn-info", @target = "_blank" })
Using -f
and -d
switches on /bin/test
:
F_NAME="${1}"
if test -f "${F_NAME}"
then
echo "${F_NAME} is a file"
elif test -d "${F_NAME}"
then
echo "${F_NAME} is a directory"
else
echo "${F_NAME} is not valid"
fi
There are literal arrowheads in the Spacing Modifier Letters block:
U+02C2 ? ˂ Modifier Letter Left Arrowhead
U+02C3 ? ˃ Modifier Letter Right Arrowhead
U+02C4 ^ ˄ Modifier Letter Up Arrowhead
U+02C5 ? ˅ Modifier Letter Down Arrowhead
Uri.parse(STRING);
See doc:
String: an RFC 2396-compliant, encoded URI
Url must be canonicalized before using, like this:
Uri.parse(Uri.decode(STRING));
DickFeynman's answer is a workable solution for any circumstance in which JQuery is not a good fit, or isn't otherwise necessary. As ComFreek notes, this requires setting the CORS headers on the server-side. If it's your service, and you have a handle on the bigger question of security, then that's entirely feasible.
Here's a listing of a Flask service, setting the CORS headers, grabbing data from a database, responding with JSON, and working happily with DickFeynman's approach on the client-side:
#!/usr/bin/env python
from __future__ import unicode_literals
from flask import Flask, Response, jsonify, redirect, request, url_for
from your_model import *
import os
try:
import simplejson as json;
except ImportError:
import json
try:
from flask.ext.cors import *
except:
from flask_cors import *
app = Flask(__name__)
@app.before_request
def before_request():
try:
# Provided by an object in your_model
app.session = SessionManager.connect()
except:
print "Database connection failed."
@app.teardown_request
def shutdown_session(exception=None):
app.session.close()
# A route with a CORS header, to enable your javascript client to access
# JSON created from a database query.
@app.route('/whatever-data/', methods=['GET', 'OPTIONS'])
@cross_origin(headers=['Content-Type'])
def json_data():
whatever_list = []
results_json = None
try:
# Use SQL Alchemy to select all Whatevers, WHERE size > 0.
whatevers = app.session.query(Whatever).filter(Whatever.size > 0).all()
if whatevers and len(whatevers) > 0:
for whatever in whatevers:
# Each whatever is able to return a serialized version of itself.
# Refer to your_model.
whatever_list.append(whatever.serialize())
# Convert a list to JSON.
results_json = json.dumps(whatever_list)
except SQLAlchemyError as e:
print 'Error {0}'.format(e)
exit(0)
if len(whatevers) < 1 or not results_json:
exit(0)
else:
# Because we used json.dumps(), rather than jsonify(),
# we need to create a Flask Response object, here.
return Response(response=str(results_json), mimetype='application/json')
if __name__ == '__main__':
#@NOTE Not suitable for production. As configured,
# your Flask service is in debug mode and publicly accessible.
app.run(debug=True, host='0.0.0.0', port=5001) # http://localhost:5001/
your_model contains the serialization method for your whatever, as well as the database connection manager (which could stand a little refactoring, but suffices to centralize the creation of database sessions, in bigger systems or Model/View/Control architectures). This happens to use postgreSQL, but could just as easily use any server side data store:
#!/usr/bin/env python
# Filename: your_model.py
import time
import psycopg2
import psycopg2.pool
import psycopg2.extras
from psycopg2.extensions import adapt, register_adapter, AsIs
from sqlalchemy import update
from sqlalchemy.orm import *
from sqlalchemy.exc import *
from sqlalchemy.dialects import postgresql
from sqlalchemy import Table, Column, Integer, ForeignKey
from sqlalchemy.ext.declarative import declarative_base
class SessionManager(object):
@staticmethod
def connect():
engine = create_engine('postgresql://id:passwd@localhost/mydatabase',
echo = True)
Session = sessionmaker(bind = engine,
autoflush = True,
expire_on_commit = False,
autocommit = False)
session = Session()
return session
@staticmethod
def declareBase():
engine = create_engine('postgresql://id:passwd@localhost/mydatabase', echo=True)
whatever_metadata = MetaData(engine, schema ='public')
Base = declarative_base(metadata=whatever_metadata)
return Base
Base = SessionManager.declareBase()
class Whatever(Base):
"""Create, supply information about, and manage the state of one or more whatever.
"""
__tablename__ = 'whatever'
id = Column(Integer, primary_key=True)
whatever_digest = Column(VARCHAR, unique=True)
best_name = Column(VARCHAR, nullable = True)
whatever_timestamp = Column(BigInteger, default = time.time())
whatever_raw = Column(Numeric(precision = 1000, scale = 0), default = 0.0)
whatever_label = Column(postgresql.VARCHAR, nullable = True)
size = Column(BigInteger, default = 0)
def __init__(self,
whatever_digest = '',
best_name = '',
whatever_timestamp = 0,
whatever_raw = 0,
whatever_label = '',
size = 0):
self.whatever_digest = whatever_digest
self.best_name = best_name
self.whatever_timestamp = whatever_timestamp
self.whatever_raw = whatever_raw
self.whatever_label = whatever_label
# Serialize one way or another, just handle appropriately in the client.
def serialize(self):
return {
'best_name' :self.best_name,
'whatever_label':self.whatever_label,
'size' :self.size,
}
In retrospect, I might have serialized the whatever objects as lists, rather than a Python dict, which might have simplified their processing in the Flask service, and I might have separated concerns better in the Flask implementation (The database call probably shouldn't be built-in the the route handler), but you can improve on this, once you have a working solution in your own development environment.
Also, I'm not suggesting people avoid JQuery. But, if JQuery's not in the picture, for one reason or another, this approach seems like a reasonable alternative.
It works, in any case.
Here's my implementation of DickFeynman's approach, in the the client:
<script type="text/javascript">
var addr = "dev.yourserver.yourorg.tld"
var port = "5001"
function Get(whateverUrl){
var Httpreq = new XMLHttpRequest(); // a new request
Httpreq.open("GET",whateverUrl,false);
Httpreq.send(null);
return Httpreq.responseText;
}
var whatever_list_obj = JSON.parse(Get("http://" + addr + ":" + port + "/whatever-data/"));
whatever_qty = whatever_list_obj.length;
for (var i = 0; i < whatever_qty; i++) {
console.log(whatever_list_obj[i].best_name);
}
</script>
I'm not going to list my console output, but I'm looking at a long list of whatever.best_name strings.
More to the point: The whatever_list_obj is available for use in my javascript namespace, for whatever I care to do with it, ...which might include generating graphics with D3.js, mapping with OpenLayers or CesiumJS, or calculating some intermediate values which have no particular need to live in my DOM.
Using List.tabulate
, like this,
List.tabulate(3)( x => 2*x )
res: List(0, 2, 4)
List.tabulate(3)( _ => Math.random )
res: List(0.935455779102479, 0.6004888906328091, 0.3425278797788426)
List.tabulate(3)( _ => (Math.random*10).toInt )
res: List(8, 0, 7)
$x
is always a scalar. The hint is the sigil $
: any variable (or dereferencing of some other type) starting with $
is a scalar. (See perldoc perldata for more about data types.)
A reference is just a particular type of scalar.
The built-in function ref
will tell you what kind of reference it is. On the other hand, if you have a blessed reference, ref
will only tell you the package name the reference was blessed into, not the actual core type of the data (blessed references can be hashrefs, arrayrefs or other things). You can use Scalar::Util 's reftype
will tell you what type of reference it is:
use Scalar::Util qw(reftype);
my $x = bless {}, 'My::Foo';
my $y = { };
print "type of x: " . ref($x) . "\n";
print "type of y: " . ref($y) . "\n";
print "base type of x: " . reftype($x) . "\n";
print "base type of y: " . reftype($y) . "\n";
...produces the output:
type of x: My::Foo
type of y: HASH
base type of x: HASH
base type of y: HASH
For more information about the other types of references (e.g. coderef, arrayref etc), see this question: How can I get Perl's ref() function to return REF, IO, and LVALUE? and perldoc perlref.
Note: You should not use ref
to implement code branches with a blessed object (e.g. $ref($a) eq "My::Foo" ? say "is a Foo object" : say "foo not defined";
) -- if you need to make any decisions based on the type of a variable, use isa
(i.e if ($a->isa("My::Foo") { ...
or if ($a->can("foo") { ...
). Also see polymorphism.
In my opinion, extension methods are the most comfortable way to solve this.
I took Steve in CO's excellent answer and put it into an extension class as follows, together with a second method I added to support the other direction (string -> secure string) as well, so you can create a secure string and convert it into a normal string afterwards:
public static class Extensions
{
// convert a secure string into a normal plain text string
public static String ToPlainString(this System.Security.SecureString secureStr)
{
String plainStr=new System.Net.NetworkCredential(string.Empty, secureStr).Password;
return plainStr;
}
// convert a plain text string into a secure string
public static System.Security.SecureString ToSecureString(this String plainStr)
{
var secStr = new System.Security.SecureString(); secStr.Clear();
foreach (char c in plainStr.ToCharArray())
{
secStr.AppendChar(c);
}
return secStr;
}
}
With this, you can now simply convert your strings back and forth like so:
// create a secure string
System.Security.SecureString securePassword = "MyCleverPwd123".ToSecureString();
// convert it back to plain text
String plainPassword = securePassword.ToPlainString(); // convert back to normal string
But keep in mind the decoding method should only be used for testing.
Very very easy: [1,2,3]
A list is like a column.
1
2
3
If you want a list like a row, double corchete:
[[1, 2, 3]] ---> 1, 2, 3
and
[[1, 2, 3], [4, 5, 6]] ---> 1, 2, 3
4, 5, 6
Finally:
np.savetxt("file", [['r1c1', 'r1c2'], ['r2c1', 'r2c2']], delimiter=';', fmt='%s')
Note, the comma between square brackets, inner list are elements of the outer list
Just to add another solution to the list, what I've found is that Visual Studio (2012 in my case) occasionally locks files under different processes.
So, on a crash, devenv.exe might still be running and holding onto the file(s). Alternatively (as I just discovered), vstestrunner or vstestdiscovery might be holding onto the file as well.
Kill all those processes and it might fix up the issue.
Make sure the WOExerciseListViewController is a Target Member; that worked for me!
int myArray[10] = { 5, 5, 5, 5, 5, 5, 5, 5, 5, 5 }; // All elements of myArray are 5
int myArray[10] = { 0 }; // Will initialize all elements to 0
int myArray[10] = { 5 }; // Will initialize myArray[0] to 5 and other elements to 0
static int myArray[10]; // Will initialize all elements to 0
/************************************************************************************/
int myArray[10];// This will declare and define (allocate memory) but won’t initialize
int i; // Loop variable
for (i = 0; i < 10; ++i) // Using for loop we are initializing
{
myArray[i] = 5;
}
/************************************************************************************/
int myArray[10] = {[0 ... 9] = 5}; // This works only in GCC
For people who are still getting error despite of passing absolute path, should check that if file has a valid name. For me I was trying to create a file with '/' in the file name. As soon as I removed '/', I was able to create the file.
You should only ever access one view's contents from another if you're creating more complex controls/modules/components. Otherwise, you should do this through the standard Model-View-Controller architecture: You should connect the enabled state of the controls you care about to some model-level predicate that supplies the right information.
For example, if I wanted to enable a Save button only when all required information was entered, I'd have a predicate method that tells when the model objects representing that form are in a state that can be saved. Then in the context where I'm choosing whether to enable the button, I'd just use the result of that method.
This results in a much cleaner separation of business logic from presentation logic, allowing both of them to evolve more independently — letting you create one front-end with multiple back-ends, or multiple front-ends with a single back-end with ease.
It will also be much, much easier to write unit and acceptance tests for, because you can follow a "Trust But Verify" pattern in doing so:
You can write one set of tests that set up your model objects in various ways and check that the "is savable" predicate returns an appropriate result.
You can write a separate set of that check whether your Save button is connected in an appropriate fashion to the "is savable" predicate (whatever that is for your framework, in Cocoa on Mac OS X this would often be through a binding).
As long as both sets of tests are passing, you can be confident that your user interface will work the way you want it to.
To trigger an enter keypress, I had to modify @ebynum response, specifically, using the keyCode property.
e = $.Event('keyup');
e.keyCode= 13; // enter
$('input').trigger(e);
Another addition: be careful when replacing multiples and converting the type of the column back from object to float. If you want to be certain that your None
's won't flip back to np.NaN
's apply @andy-hayden's suggestion with using pd.where
.
Illustration of how replace can still go 'wrong':
In [1]: import pandas as pd
In [2]: import numpy as np
In [3]: df = pd.DataFrame({"a": [1, np.NAN, np.inf]})
In [4]: df
Out[4]:
a
0 1.0
1 NaN
2 inf
In [5]: df.replace({np.NAN: None})
Out[5]:
a
0 1
1 None
2 inf
In [6]: df.replace({np.NAN: None, np.inf: None})
Out[6]:
a
0 1.0
1 NaN
2 NaN
In [7]: df.where((pd.notnull(df)), None).replace({np.inf: None})
Out[7]:
a
0 1.0
1 NaN
2 NaN
Had the same problem and this solved it for me (Powershell as admin):
Set-ItemProperty -Path HKLM:\Software\Policies\Microsoft\Windows\PowerShell -Name ExecutionPolicy -Value ByPass
Assuming you have access to it via outlets or programmatic code, you can remove it by referencing your view foo
and the removeFromSuperview
method
foo.removeFromSuperview()
Solution #1: Your statement
.Range(Cells(RangeStartRow, RangeStartColumn), Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues
does not refer to a proper Range
to act upon. Instead,
.Range(.Cells(RangeStartRow, RangeStartColumn), .Cells(RangeEndRow, RangeEndColumn)).PasteSpecial xlValues
does (and similarly in some other cases).
Solution #2:
Activate Worksheets("Cable Cards")
prior to using its cells.
Explanation:
Cells(RangeStartRow, RangeStartColumn)
(e.g.) gives you a Range
, that would be ok, and that is why you often see Cells
used in this way. But since it is not applied to a specific object, it applies to the ActiveSheet
. Thus, your code attempts using .Range(rng1, rng2)
, where .Range
is a method of one Worksheet
object and rng1
and rng2
are in a different Worksheet
.
There are two checks that you can do to make this quite evident:
Activate your Worksheets("Cable Cards")
prior to executing your Sub
and it will start working (now you have well-formed references to Range
s). For the code you posted, adding .Activate
right after With...
would indeed be a solution, although you might have a similar problem somewhere else in your code when referring to a Range
in another Worksheet
.
With a sheet other than Worksheets("Cable Cards")
active, set a breakpoint at the line throwing the error, start your Sub
, and when execution breaks, write at the immediate window
Debug.Print Cells(RangeStartRow, RangeStartColumn).Address(external:=True)
Debug.Print .Cells(RangeStartRow, RangeStartColumn).Address(external:=True)
and see the different outcomes.
Conclusion:
Using Cells
or Range
without a specified object (e.g., Worksheet
, or Range
) might be dangerous, especially when working with more than one Sheet
, unless one is quite sure about what Sheet
is active.
Boolean
wraps the boolean primitive type. In JDK 5 and upwards, Oracle (or Sun before Oracle bought them) introduced autoboxing/unboxing, which essentially allows you to do this
boolean result = Boolean.TRUE;
or
Boolean result = true;
Which essentially the compiler does,
Boolean result = Boolean.valueOf(true);
So, for your answer, it's YES.
Don't try commiting / adding files. Just run the following 2 commands (:
git remote add origin http://xyzremotedir/xyzgitproject.git git push origin master
I'm going to make a couple of assumptions in my answer. I'm assuming your data starts in A1 and there are no empty cells in the first column of each row that has data.
This code will:
This is not a fast method but will iterate through each one individually as you suggested is your intention.
Sub iterateThroughAll()
ScreenUpdating = False
Dim wks As Worksheet
Set wks = ActiveSheet
Dim rowRange As Range
Dim colRange As Range
Dim LastCol As Long
Dim LastRow As Long
LastRow = wks.Cells(wks.Rows.Count, "A").End(xlUp).Row
Set rowRange = wks.Range("A1:A" & LastRow)
'Loop through each row
For Each rrow In rowRange
'Find Last column in current row
LastCol = wks.Cells(rrow, wks.Columns.Count).End(xlToLeft).Column
Set colRange = wks.Range(wks.Cells(rrow, 1), wks.Cells(rrow, LastCol))
'Loop through all cells in row up to last col
For Each cell In colRange
'Do something to each cell
Debug.Print (cell.Value)
Next cell
Next rrow
ScreenUpdating = True
End Sub
Using the regex provided by @JustinLevene did not have the proper escape sequences on the back-slashes. Updated to now be correct, and added in condition to match the FTP protocol as well: Will match to all urls with or without protocols, and with out without "www."
Code: ^((http|ftp|https):\/\/)?([\w_-]+(?:(?:\.[\w_-]+)+))([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?
Example: https://regex101.com/r/uQ9aL4/65
To do this, I had to come up with an intermediate data structure:
class KeyDataPoint {
String key;
DateTime timestamp;
Number data;
// obvious constructor and getters
}
With this in place, the approach is to "flatten" each MultiDataPoint into a list of (timestamp, key, data) triples and stream together all such triples from the list of MultiDataPoint.
Then, we apply a groupingBy
operation on the string key in order to gather the data for each key together. Note that a simple groupingBy
would result in a map from each string key to a list of the corresponding KeyDataPoint triples. We don't want the triples; we want DataPoint instances, which are (timestamp, data) pairs. To do this we apply a "downstream" collector of the groupingBy
which is a mapping
operation that constructs a new DataPoint by getting the right values from the KeyDataPoint triple. The downstream collector of the mapping
operation is simply toList
which collects the DataPoint objects of the same group into a list.
Now we have a Map<String, List<DataPoint>>
and we want to convert it to a collection of DataSet objects. We simply stream out the map entries and construct DataSet objects, collect them into a list, and return it.
The code ends up looking like this:
Collection<DataSet> convertMultiDataPointToDataSet(List<MultiDataPoint> multiDataPoints) {
return multiDataPoints.stream()
.flatMap(mdp -> mdp.getData().entrySet().stream()
.map(e -> new KeyDataPoint(e.getKey(), mdp.getTimestamp(), e.getValue())))
.collect(groupingBy(KeyDataPoint::getKey,
mapping(kdp -> new DataPoint(kdp.getTimestamp(), kdp.getData()), toList())))
.entrySet().stream()
.map(e -> new DataSet(e.getKey(), e.getValue()))
.collect(toList());
}
I took some liberties with constructors and getters, but I think they should be obvious.
- name: set pkg copy dir name
set_fact:
PKG_DIR: >-
{% if ansible_os_family == "RedHat" %}centos/*.rpm
{%- elif ansible_distribution == "Ubuntu" %}ubuntu/*.deb
{%- elif ansible_distribution == "Kylin Linux Advanced Server" %}kylin/*.deb
{%- else %}{%- endif %}
In python, everything is an object, also "simple" variables types (int, float, etc..).
When you changes a variable value, you actually changes it's pointer, and if you compares between two variables it's compares their pointers. (To be clear, pointer is the address in physical computer memory where a variable is stored).
As a result, when you changes an inner variable value, you changes it's value in the memory and it's affects all the variables that point to this address.
For your example, when you do:
a = b = 5
This means that a and b points to the same address in memory that contains the value 5, but when you do:
a = 6
It's not affect b because a is now points to another memory location that contains 6 and b still points to the memory address that contains 5.
But, when you do:
a = b = [1,2,3]
a and b, again, points to the same location but the difference is that if you change the one of the list values:
a[0] = 2
It's changes the value of the memory that a is points on, but a is still points to the same address as b, and as a result, b changes as well.
how about using limit 0,1
for mysql optimisation
and about your code:
$DBH = new PDO( "connection string goes here" );
$STH - $DBH -> prepare( "select figure from table1" );
$STH -> execute();
$result = $STH ->fetch(PDO::FETCH_ASSOC)
echo $result["figure"];
$DBH = null;
The method I prefer assigns an array of data to the combobox. Click on the body of your userform and change the "Click" event to "Initialize". Now the combobox will fill upon the initializing of the userform. I hope this helps.
Sub UserForm_Initialize()
ComboBox1.List = Array("1001", "1002", "1003", "1004", "1005", "1006", "1007", "1008", "1009", "1010")
End Sub
This is called string interpolation; it doesn't exist as such in Java.
One approach is to use String.format:
String string = String.format("A string %s", aVariable);
Another approach is to use a templating library such as Velocity or FreeMarker.
(Similar to Doin idea) To show what is being matched, I use this code
$keys = array_keys($_GET);
foreach($keys as $i=>$key){
echo "$i => $key <br>";
}
Save it to r.php on the server root and then do some tests in .htaccess
For example, i want to match urls that do not start with a language prefix
RewriteRule ^(?!(en|de)/)(.*)$ /r.php?$1&$2 [L] #$1&$2&...
RewriteRule ^(.*)$ /r.php?nomatch [L] #report nomatch and exit
The solution is very simple and worked for me.
Try this :
git pull --rebase <url>
then
git push -u origin master
Option 1: Likely fastest (but not supported by some browsers if used on Document or SVGElement) :
var elements = document.getElementById('parentContainer').children;
Option 2: Likely slowest :
var elements = document.getElementById('parentContainer').getElementsByTagName('*');
Option 3: Requires change to code (wrap a form instead of a div around it) :
// Since what you're doing looks like it should be in a form...
var elements = document.forms['parentContainer'].elements;
var matches = [];
for (var i = 0; i < elements.length; i++)
if (elements[i].value.indexOf('q17_') == 0)
matches.push(elements[i]);
You can simply use DataFrame.fillna
to fill the nan
's directly:
In [27]: df
Out[27]:
A B C
0 -0.166919 0.979728 -0.632955
1 -0.297953 -0.912674 -1.365463
2 -0.120211 -0.540679 -0.680481
3 NaN -2.027325 1.533582
4 NaN NaN 0.461821
5 -0.788073 NaN NaN
6 -0.916080 -0.612343 NaN
7 -0.887858 1.033826 NaN
8 1.948430 1.025011 -2.982224
9 0.019698 -0.795876 -0.046431
In [28]: df.mean()
Out[28]:
A -0.151121
B -0.231291
C -0.530307
dtype: float64
In [29]: df.fillna(df.mean())
Out[29]:
A B C
0 -0.166919 0.979728 -0.632955
1 -0.297953 -0.912674 -1.365463
2 -0.120211 -0.540679 -0.680481
3 -0.151121 -2.027325 1.533582
4 -0.151121 -0.231291 0.461821
5 -0.788073 -0.231291 -0.530307
6 -0.916080 -0.612343 -0.530307
7 -0.887858 1.033826 -0.530307
8 1.948430 1.025011 -2.982224
9 0.019698 -0.795876 -0.046431
The docstring of fillna
says that value
should be a scalar or a dict, however, it seems to work with a Series
as well. If you want to pass a dict, you could use df.mean().to_dict()
.
Works in 2020
$response = Http::withHeaders([
'Content-Type' => 'application/json',
'Authorization'=> 'key='. $token,
])->post($url, [
'notification' => [
'body' => $request->summary,
'title' => $request->title,
'image' => 'http://'.request()->getHttpHost().$path,
],
'priority'=> 'high',
'data' => [
'click_action'=> 'FLUTTER_NOTIFICATION_CLICK',
'status'=> 'done',
],
'to' => '/topics/all'
]);
When connecting to SQL Server with Windows Authentication (as opposed to a local SQL Server account), attempting to use a linked server may result in the error message:
Cannot create an instance of OLE DB provider "(OLEDB provider name)"...
The most direct answer to this problem is provided by Microsoft KB 2647989, because "Security settings for the MSDAINITIALIZE DCOM class are incorrect."
The solution is to fix the security settings for MSDAINITIALIZE. In Windows Vista and later, the class is owned by TrustedInstaller, so the ownership of MSDAINITIALIZE must be changed before the security can be adjusted. The KB above has detailed instructions for doing so.
This MSDN blog post describes the reason:
MSDAINITIALIZE is a COM class that is provided by OLE DB. This class can parse OLE DB connection strings and load/initialize the provider based on property values in the connection string. MSDAINITILIAZE is initiated by users connected to SQL Server. If Windows Authentication is used to connect to SQL Server, then the provider is initialized under the logged in user account. If the logged in user is a SQL login, then provider is initialized under SQL Server service account. Based on the type of login used, permissions on MSDAINITIALIZE have to be provided accordingly.
The issue dates back at least to SQL Server 2000; KB 280106 from Microsoft describes the error (see "Message 3") and has the suggested fix of setting the In Process flag for the OLEDB provider.
While setting In Process can solve the immediate problem, it may not be what you want. According to Microsoft,
Instantiating the provider outside the SQL Server process protects the SQL Server process from errors in the provider. When the provider is instantiated outside the SQL Server process, updates or inserts referencing long columns (text, ntext, or image) are not allowed. -- Linked Server Properties doc for SQL Server 2008 R2.
The better answer is to go with the Microsoft guidance and adjust the MSDAINITIALIZE security.
If you want to parse the format yourself you could do it easily with a regex such as
private static Pattern pattern = Pattern.compile("(\\d{2}):(\\d{2}):(\\d{2}).(\\d{3})");
public static long dateParseRegExp(String period) {
Matcher matcher = pattern.matcher(period);
if (matcher.matches()) {
return Long.parseLong(matcher.group(1)) * 3600000L
+ Long.parseLong(matcher.group(2)) * 60000
+ Long.parseLong(matcher.group(3)) * 1000
+ Long.parseLong(matcher.group(4));
} else {
throw new IllegalArgumentException("Invalid format " + period);
}
}
However, this parsing is quite lenient and would accept 99:99:99.999 and just let the values overflow. This could be a drawback or a feature.
For MS SQL you can do this.
select CAST(DATEPART(MONTH, DateTyme) as VARCHAR) +'/'+
CAST(DATEPART(YEAR, DateTyme) as VARCHAR) as 'Date' from #temp
group by Name, CAST(DATEPART(MONTH, DateTyme) as VARCHAR) +'/'+
CAST(DATEPART(YEAR, DateTyme) as VARCHAR)
If you use Spring Boot, you can also enable a “debug” mode by starting your application with a --debug flag.
java -jar myapp.jar --debug
You can also specify debug=true in your application.properties.
When the debug mode is enabled, a selection of core loggers (embedded container, Hibernate, and Spring Boot) are configured to output more information. Enabling the debug mode does not configure your application to log all messages with DEBUG level.
Alternatively, you can enable a “trace” mode by starting your application with a --trace flag (or trace=true in your application.properties). Doing so enables trace logging for a selection of core loggers (embedded container, Hibernate schema generation, and the whole Spring portfolio).
https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-logging.html
The snippet you're showing doesn't seem to be directly responsible for the error.
This is how you can CAUSE the error:
namespace MyNameSpace
{
int i; <-- THIS NEEDS TO BE INSIDE THE CLASS
class MyClass
{
...
}
}
If you don't immediately see what is "outside" the class, this may be due to misplaced or extra closing bracket(s) }
.
-[NSString initWithData:encoding]
will return nil
if the specified encoding doesn't match the data's encoding.
Make sure your data is encoded in UTF-8 (or change NSUTF8StringEncoding to whatever encoding that's appropriate for the data).
The Content
table likely to have multiple duplicate Application
values that can't be mapped to Libraries
. Is it possible to drop the Application
column from the Libraries
Primary Key Index and add it as a Unique Key Index instead?
For windows: Go to your "system properties" please.then follow as bellow.
Advanced system settings(from left sidebar)->Environment variables(very last option)->path(from lower box/system variables called as I know)->edit
then concatenate the "php" location you have in your pc (usually it is where your xampp is installed say c:/xampp/php)
N.B : Please never forget to set semicolon (;) between your recent concatenated path and the existed path in your "Path"
Something like C:\Program Files\Git\usr\bin;C:\xampp\php
Hope this will help.Happy coding. :) :)
You are trying to instantiate an interface, you need to give the concrete class that you want to use i.e. Queue<Edge> theQueue = new LinkedBlockingQueue<Edge>();
.
If you just want a C-style string representing the same content:
char const* ca = str.c_str();
If you want a C-style string with new contents, one way (given that you don't know the string size at compile-time) is dynamic allocation:
char* ca = new char[str.size()+1];
std::copy(str.begin(), str.end(), ca);
ca[str.size()] = '\0';
Don't forget to delete[]
it later.
If you want a statically-allocated, limited-length array instead:
size_t const MAX = 80; // maximum number of chars
char ca[MAX] = {};
std::copy(str.begin(), (str.size() >= MAX ? str.begin() + MAX : str.end()), ca);
std::string
doesn't implicitly convert to these types for the simple reason that needing to do this is usually a design smell. Make sure that you really need it.
If you definitely need a char*
, the best way is probably:
vector<char> v(str.begin(), str.end());
char* ca = &v[0]; // pointer to start of vector
You can access keys in the App.Config using:
ConfigurationSettings.AppSettings["KeyName"]
Take alook at this Thread
In my opinion, all the answers you got up to now are valid, but in my experience, I would express it in a few words:
Use enums if you want the compiler to check the validity of the value of an identifier.
Otherwise, you can use strings as you always did (probably you defined some "conventions" for your application) and you will be very flexible... but you will not get 100% security against typos on your strings and you will realize them only in runtime.
If you want to create a cmd shortcut (for example on your desktop) add /k parameter (/k means keep, /c will close window):
cmd /k echo hello && cd c:\ && cd Windows
Have you tried the __name__
attribute of the class? ie type(x).__name__
will give you the name of the class, which I think is what you want.
>>> import itertools
>>> x = itertools.count(0)
>>> type(x).__name__
'count'
If you're still using Python 2, note that the above method works with new-style classes only (in Python 3+ all classes are "new-style" classes). Your code might use some old-style classes. The following works for both:
x.__class__.__name__
You can keep primitive type by setting default value, in the your case just add "required = false" property:
@RequestParam(value = "i", required = false, defaultValue = "10") int i
P.S. This page from Spring documentation might be useful: Annotation Type RequestParam
The reason IMHO is because they are/were too lazy to implement/correct that mistake. Suggesting that C/C++ programmers does not understand unsigned, structure, union, bit flag... Is just preposterous.
Ether you were talking with a basic/bash/java programmer on the verge of beginning programming a la C, without any real knowledge this language or you are just talking out of your own mind. ;)
when you deal every day on format either from file or hardware you begin to question, what in the hell they were thinking.
A good example here would be trying to use an unsigned byte as a self rotating loop. For those of you who do not understand the last sentence, how on earth you call yourself a programmer.
DC
I'm having this problem every once in a while, It is happening due to computer or VM operation problems during a git operation.
The best solution for me is to remove the git objects and all related ref git files:
sudo rm -r .git/objects/* .git/refs/heads/* .git/refs/remotes/* .git/refs/stash .git/refs/tags/*
and then pull the repo:
git pull
That solves everything for me in the easiest way without risking my source code or cloning the repo again.
Try the net use command
Integer Array doesn't contain size() or length() method. Try the below code, it'll work. ArrayList contains size() method. String contains length(). Since you have used int array[], so it will be array.length
public class Example {
int array[] = {1, 99, 10000, 84849, 111, 212, 314, 21, 442, 455, 244, 554, 22, 22, 211};
public void Printrange() {
for (int i = 0; i < array.length; i++) {
if (array[i] > 100 && array[i] < 500) {
System.out.println("numbers with in range" + i);
}
}
}
}
Here what i did, it works fine.
docker ps -a
docker rm name_of_the_docker_container
This isn't a great answer, but if you know the target workstation has Powershell you can do something like this (assuming BAT / CMD script):
CALL:ECHORED "Print me in red!"
:ECHORED
%Windir%\System32\WindowsPowerShell\v1.0\Powershell.exe write-host -foregroundcolor Red %1
goto:eof
It's an old answer but I figured I'd clarify & simplify a bit
PowerShell is now included in all versions of Windows since 7. Therefore the syntax for this answer can be shortened to a simpler form:
-fore
instead of -foregroundcolor
-back
instead of -backgroundcolor
echo
powershell write-host -fore Cyan This is Cyan text
powershell write-host -back Red This is Red background
The complete list of colors and more information is available in the
- PowerShell Documentation for Write-Host
what might get you where you want in plain SQL92:
select * from tbl where lower(answer) = upper(answer)
or, if you also want to be robust for leading/trailing spaces:
select * from tbl where lower(answer) = trim(upper(answer))
You may need to write code that handles a range with multiple areas, which this does:
Public Function GetAddressWithSheetname(Range As Range, Optional blnBuildAddressForNamedRangeValue As Boolean = False) As String
Const Seperator As String = ","
Dim WorksheetName As String
Dim TheAddress As String
Dim Areas As Areas
Dim Area As Range
WorksheetName = "'" & Range.Worksheet.Name & "'"
For Each Area In Range.Areas
' ='Sheet 1'!$H$8:$H$15,'Sheet 1'!$C$12:$J$12
TheAddress = TheAddress & WorksheetName & "!" & Area.Address(External:=False) & Seperator
Next Area
GetAddressWithSheetname = Left(TheAddress, Len(TheAddress) - Len(Seperator))
If blnBuildAddressForNamedRangeValue Then
GetAddressWithSheetname = "=" & GetAddressWithSheetname
End If
End Function
You can use:
case text1: case text4:
do stuff;
break;
static
means that the method is associated with the class, not a specific instance (object) of that class. This means that you can call a static method without creating an object of the class.
Because of use of a static
keyword main()
is your first method to be invoked..
static
doesn't need to any object to instance...
so,main( )
is called by the Java interpreter before any objects are made.
Install the Package Manager as directed on https://packagecontrol.io/installation
Open the Package Manager using Ctrl+Shift+P
Type Package Control to show related commands (Install Package, Remove Package etc.) with packages
Enjoy it!
Fetch API, need to deal with two promises to get the response data in JSON Object property. While axios result into JSON object.
Also error handling is different in fetch, as it does not handle server side error in the catch block, the Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing. While in axios you can catch all error in catch block.
I will say better to use axios, straightforward to handle interceptors, headers config, set cookies and error handling.
Installing a newer release of IDEA Community (2018.3 instead of 2017.x) was solved my issue with same error but java version:11. Reimport hadn't worked for me. But it worth a try.
Here is a solution similar to jayson.centeno's and other answers, but using the built-in extension from System.Net.Http.Formatting
.
public static void Register(HttpConfiguration config)
{
// add support for the 'format' query param
// cref: http://blogs.msdn.com/b/hongyes/archive/2012/09/02/support-format-in-asp-net-web-api.aspx
config.Formatters.JsonFormatter.AddQueryStringMapping("$format", "json", "application/json");
config.Formatters.XmlFormatter.AddQueryStringMapping("$format", "xml", "application/xml");
// ... additional configuration
}
The solution was primarily geared toward supporting $format for OData in the early releases of WebApi, but it also applies to the non-OData implementation, and returns the
Content-Type: application/json; charset=utf-8
header in the response.
It allows you to tack &$format=json
or &$format=xml
to the end of your uri when testing with a browser. It does not interfere with other expected behavior when using a non-browser client where you can set your own headers.
Trying to compress a PDF I made with 400ppi tiffs, mostly 8-bit, a few 24-bit, with PackBits compression, using tiff2pdf
compressed with Zip/Deflate. One problem I had with every one of these methods: none of the above methods preserved the bookmarks TOC that I painstakingly manually created in Acrobat Pro X. Not even the recommended ebook
setting for gs
. Sure, I could just open a copy of the original with the TOC intact and do a Replace pages
but unfortunately, none of these methods did a satisfactory job to begin with. Either they reduced the size so much that the quality was unacceptably pixellated, or they didn't reduce the size at all and in one case actually increased it despite quality loss.
pdftk compress
:
no change in size
bookmarks TOC are gone
gs screen
:
takes a ridiculously long time and 100% CPU
errors:
sfopen: gs_parse_file_name failed. ?
| ./base/gsicc_manage.c:1651: gsicc_set_device_profile(): cannot find device profile
74.8MB-->10.2MB hideously pixellated
bookmarks TOC are gone
gs printer
:
takes a ridiculously long time and 100% CPU
no errors
74.8MB-->66.1MB
light blue background on pages 1-4
bookmarks TOC are gone
gs ebook
:
errors:
sfopen: gs_parse_file_name failed.
./base/gsicc_manage.c:1050: gsicc_open_search(): Could not find default_rgb.ic
| ./base/gsicc_manage.c:1651: gsicc_set_device_profile(): cannot find device profile
74.8MB-->32.2MB
badly pixellated
bookmarks TOC are gone
qpdf --linearize
:
very fast, a few seconds
no size change
bookmarks TOC are gone
pdf2ps
:
took very long time
output_pdf2ps.ps 74.8MB-->331.6MB
ps2pdf
:
pretty fast
74.8MB-->79MB
very slightly degraded with sl. bluish background
bookmarks TOC are gone
private String encodeFileToBase64Binary(File file){
String encodedfile = null;
try {
FileInputStream fileInputStreamReader = new FileInputStream(file);
byte[] bytes = new byte[(int)file.length()];
fileInputStreamReader.read(bytes);
encodedfile = Base64.encodeBase64(bytes).toString();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return encodedfile;
}
If the stashed files need to merge with the current version so use the previous ways using diff. Otherwise you might use git pop
for unstashing them, git add fileWantToKeep
for staging your file, and do a git stash save --keep-index
, for stashing everything except what is on stage.
Remember that the difference of this way with the previous ones is that it "pops" the file from stash. The previous answers keep it git checkout stash@{0} -- <filename>
so it goes according to your needs.
I agree with others – it is asking for name clashes, ambiguities and then the fact is it is less explicit. While I can see the use of using
, my personal preference is to limit it. I would also strongly consider what some others pointed out:
If you want to find a function name that might be a fairly common name, but you only want to find it in the std
namespace (or the reverse – you want to change all calls that are not in namespace std
, namespace X
, ...), then how do you propose to do this?
You could write a program to do it, but wouldn't it be better to spend time working on your project itself rather than writing a program to maintain your project?
Personally, I actually don't mind the std::
prefix. I like the look more than not having it. I don't know if that is because it is explicit and says to me "this isn't my code... I am using the standard library" or if it is something else, but I think it looks nicer. This might be odd given that I only recently got into C++ (used and still do C and other languages for much longer and C is my favourite language of all time, right above assembly).
There is one other thing although it is somewhat related to the above and what others point out. While this might be bad practise, I sometimes reserve std::name
for the standard library version and name for program-specific implementation. Yes, indeed this could bite you and bite you hard, but it all comes down to that I started this project from scratch, and I'm the only programmer for it. Example: I overload std::string
and call it string
. I have helpful additions. I did it in part because of my C and Unix (+ Linux) tendency towards lower-case names.
Besides that, you can have namespace aliases. Here is an example of where it is useful that might not have been referred to. I use the C++11 standard and specifically with libstdc++. Well, it doesn't have complete std::regex
support. Sure, it compiles, but it throws an exception along the lines of it being an error on the programmer's end. But it is lack of implementation.
So here's how I solved it. Install Boost's regex, and link it in. Then, I do the following so that when libstdc++ has it implemented entirely, I need only remove this block and the code remains the same:
namespace std
{
using boost::regex;
using boost::regex_error;
using boost::regex_replace;
using boost::regex_search;
using boost::regex_match;
using boost::smatch;
namespace regex_constants = boost::regex_constants;
}
I won't argue on whether that is a bad idea or not. I will however argue that it keeps it clean for my project and at the same time makes it specific: True, I have to use Boost, but I'm using it like the libstdc++ will eventually have it. Yes, starting your own project and starting with a standard (...) at the very beginning goes a very long way with helping maintenance, development and everything involved with the project!
Just to clarify something: I don't actually think it is a good idea to use a name of a class/whatever in the STL deliberately and more specifically in place of. The string is the exception (ignore the first, above, or second here, pun if you must) for me as I didn't like the idea of 'String'.
As it is, I am still very biased towards C and biased against C++. Sparing details, much of what I work on fits C more (but it was a good exercise and a good way to make myself a. learn another language and b. try not be less biased against object/classes/etc which is maybe better stated as less closed-minded, less arrogant, and more accepting.). But what is useful is what some already suggested: I do indeed use list (it is fairly generic, is it not ?), and sort (same thing) to name two that would cause a name clash if I were to do using namespace std;
, and so to that end I prefer being specific, in control and knowing that if I intend it to be the standard use then I will have to specify it. Put simply: no assuming allowed.
And as for making Boost's regex part of std
. I do that for future integration and – again, I admit fully this is bias - I don't think it is as ugly as boost::regex:: ...
. Indeed, that is another thing for me. There are many things in C++ that I still have yet to come to fully accept in looks and methods (another example: variadic templates versus var arguments [though I admit variadic templates are very very useful!]). Even those that I do accept it was difficult, and I still have issues with them.
Well this should change your format to text.
Worksheets("Sheetname").Activate
Worksheets("SheetName").Columns(1).Select 'or Worksheets("SheetName").Range("A:A").Select
Selection.NumberFormat = "@"
Create a button with an id share and add the following code snippet.
share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
String shareBody = "Your body here";
String shareSub = "Your subject here";
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, shareSub);
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
startActivity(Intent.createChooser(sharingIntent, "Share using"));
}
});
The above code snippet will open the share chooser on share button click action. However, note...The share code snippet might not output very good results using emulator. For actual results, run the code snippet on android device to get the real results.
I had same issue, none of the solutions worked for me.
Open Settings Menu -> Developer Options -> USB Debugging should be on
Works for me
UIView *customColorView = [[UIView alloc] init];
customColorView.backgroundColor = [UIColor colorWithRed:180/255.0
green:138/255.0
blue:171/255.0
alpha:0.5];
cell.selectedBackgroundView = customColorView;
First:
I think you can do it 2 ways
http://our.api.com/Product/<id>
: if you just want one record
http://our.api.com/Product
: if you want all records
http://our.api.com/Product/<id1>,<id2>
:as James suggested can be an option since what comes after the Product tag is a parameter
Or the one I like most is:
You can use the the Hypermedia as the engine of application state (HATEOAS) property of a RestFul WS and do a call http://our.api.com/Product
that should return the equivalent urls of http://our.api.com/Product/<id>
and call them after this.
Second
When you have to do queries on the url calls. I would suggest using HATEOAS again.
1) Do a get call to http://our.api.com/term/pumas/productType/clothing/color/black
2) Do a get call to http://our.api.com/term/pumas/productType/clothing,bags/color/black,red
3) (Using HATEOAS) Do a get call to `http://our.api.com/term/pumas/productType/ -> receive the urls all clothing possible urls -> call the ones you want (clothing and bags) -> receive the possible color urls -> call the ones you want
For me the error was:
Error: unexpected input in "?"
and the fix was opening the script in a hex editor and removing the first 3 characters from the file. The file was starting with an UTF-8 BOM and it seems that Rscript can't read that.
EDIT: OP requested an example. Here it goes.
? ~ cat a.R
cat('hello world\n')
? ~ xxd a.R
00000000: efbb bf63 6174 2827 6865 6c6c 6f20 776f ...cat('hello wo
00000010: 726c 645c 6e27 290a rld\n').
? ~ R -f a.R
R version 3.4.4 (2018-03-15) -- "Someone to Lean On"
Copyright (C) 2018 The R Foundation for Statistical Computing
Platform: x86_64-pc-linux-gnu (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
Natural language support but running in an English locale
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
> cat('hello world\n')
Error: unexpected input in "?"
Execution halted
Just update your eclipse.ini file (you can find it in the root-directory of eclipse) by this:
-vm
path/javaw.exe
for example:
-vm
C:/Program Files/Java/jdk1.7.0_09/jre/bin/javaw.exe
Use the DotNetZip library at http://www.codeplex.com/DotNetZip
class library and toolset for manipulating zip files. Use VB, C# or any .NET language to easily create, extract, or update zip files...
DotNetZip works on PCs with the full .NET Framework, and also runs on mobile devices that use the .NET Compact Framework. Create and read zip files in VB, C#, or any .NET language, or any scripting environment...
If all you want is a better DeflateStream or GZipStream class to replace the one that is built-into the .NET BCL, DotNetZip has that, too. DotNetZip's DeflateStream and GZipStream are available in a standalone assembly, based on a .NET port of Zlib. These streams support compression levels and deliver much better performance than the built-in classes. There is also a ZlibStream to complete the set (RFC 1950, 1951, 1952)...
You could do Char(13)
and Char(10)
. Cr and Lf.
Char()
works in SQL Server, I don't know about other databases.
Add
tools:ignore="ContentDescription"
to your image. Make sure you have xmlns:tools="http://schemas.android.com/tools"
.
in your root layout.
This work fine for me in prod environment
<base href="/" id="baseHref">
<script>
(function() {
document.getElementById('baseHref').href = '/' + window.location.pathname.split('/')[1] + "/";
})();
</script>
If the HTML is not XML you can't do it with etree. But even then, you don't have to use an external library for parsing a HTML table. In python 3 you can reach your goal with HTMLParser
from html.parser
. I've the code of the simple derived HTMLParser class here in a github repo.
You can use that class (here named HTMLTableParser
) the following way:
import urllib.request
from html_table_parser import HTMLTableParser
target = 'http://www.twitter.com'
# get website content
req = urllib.request.Request(url=target)
f = urllib.request.urlopen(req)
xhtml = f.read().decode('utf-8')
# instantiate the parser and feed it
p = HTMLTableParser()
p.feed(xhtml)
print(p.tables)
The output of this is a list of 2D-lists representing tables. It looks maybe like this:
[[[' ', ' Anmelden ']],
[['Land', 'Code', 'Für Kunden von'],
['Vereinigte Staaten', '40404', '(beliebig)'],
['Kanada', '21212', '(beliebig)'],
...
['3424486444', 'Vodafone'],
[' Zeige SMS-Kurzwahlen für andere Länder ']]]
Building on the Python 2 solution from @GarethLatty, the following is a way to get a single line equivalent without intermediate variables in Python 2.
t=iter([1, 1, 2, 3, 5, 8, 13, 21, 34, 55]);h,t = [(h,list(t)) for h in t][0]
If you need it to be exception-proof (i.e. supporting empty list), then add:
t=iter([]);h,t = ([(h,list(t)) for h in t]+[(None,[])])[0]
If you want to do it without the semicolon, use:
h,t = ([(h,list(t)) for t in [iter([1,2,3,4])] for h in t]+[(None,[])])[0]
If you need to rotate and fix the image orientation below extension would be useful.
extension UIImage {
public func imageRotatedByDegrees(degrees: CGFloat) -> UIImage {
//Calculate the size of the rotated view's containing box for our drawing space
let rotatedViewBox: UIView = UIView(frame: CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height))
let t: CGAffineTransform = CGAffineTransform(rotationAngle: degrees * CGFloat.pi / 180)
rotatedViewBox.transform = t
let rotatedSize: CGSize = rotatedViewBox.frame.size
//Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize)
let bitmap: CGContext = UIGraphicsGetCurrentContext()!
//Move the origin to the middle of the image so we will rotate and scale around the center.
bitmap.translateBy(x: rotatedSize.width / 2, y: rotatedSize.height / 2)
//Rotate the image context
bitmap.rotate(by: (degrees * CGFloat.pi / 180))
//Now, draw the rotated/scaled image into the context
bitmap.scaleBy(x: 1.0, y: -1.0)
bitmap.draw(self.cgImage!, in: CGRect(x: -self.size.width / 2, y: -self.size.height / 2, width: self.size.width, height: self.size.height))
let newImage: UIImage = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return newImage
}
public func fixedOrientation() -> UIImage {
if imageOrientation == UIImageOrientation.up {
return self
}
var transform: CGAffineTransform = CGAffineTransform.identity
switch imageOrientation {
case UIImageOrientation.down, UIImageOrientation.downMirrored:
transform = transform.translatedBy(x: size.width, y: size.height)
transform = transform.rotated(by: CGFloat.pi)
break
case UIImageOrientation.left, UIImageOrientation.leftMirrored:
transform = transform.translatedBy(x: size.width, y: 0)
transform = transform.rotated(by: CGFloat.pi/2)
break
case UIImageOrientation.right, UIImageOrientation.rightMirrored:
transform = transform.translatedBy(x: 0, y: size.height)
transform = transform.rotated(by: -CGFloat.pi/2)
break
case UIImageOrientation.up, UIImageOrientation.upMirrored:
break
}
switch imageOrientation {
case UIImageOrientation.upMirrored, UIImageOrientation.downMirrored:
transform.translatedBy(x: size.width, y: 0)
transform.scaledBy(x: -1, y: 1)
break
case UIImageOrientation.leftMirrored, UIImageOrientation.rightMirrored:
transform.translatedBy(x: size.height, y: 0)
transform.scaledBy(x: -1, y: 1)
case UIImageOrientation.up, UIImageOrientation.down, UIImageOrientation.left, UIImageOrientation.right:
break
}
let ctx: CGContext = CGContext(data: nil,
width: Int(size.width),
height: Int(size.height),
bitsPerComponent: self.cgImage!.bitsPerComponent,
bytesPerRow: 0,
space: self.cgImage!.colorSpace!,
bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)!
ctx.concatenate(transform)
switch imageOrientation {
case UIImageOrientation.left, UIImageOrientation.leftMirrored, UIImageOrientation.right, UIImageOrientation.rightMirrored:
ctx.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: size.height, height: size.width))
default:
ctx.draw(self.cgImage!, in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
break
}
let cgImage: CGImage = ctx.makeImage()!
return UIImage(cgImage: cgImage)
}
}
Add this into your httpd.conf file
Timeout 2400
ProxyTimeout 2400
ProxyBadHeader Ignore
Right Click on Project >> Properties >> Select Web Tab >> Under server Select "Use Visual development server" so indirectly it will uncheck "Local IIS Server"
Hope so it may resolve this issue.
try this
@Html.DropDownListFor(model => model.UserName, new List<SelectListItem>
{ new SelectListItem{Text="Active", Value="True",Selected =true },
new SelectListItem{Text="Deactive", Value="False"}})
A mutable object has to have at least a method able to mutate the object. For example, the list
object has the append
method, which will actually mutate the object:
>>> a = [1,2,3]
>>> a.append('hello') # `a` has mutated but is still the same object
>>> a
[1, 2, 3, 'hello']
but the class float
has no method to mutate a float object. You can do:
>>> b = 5.0
>>> b = b + 0.1
>>> b
5.1
but the =
operand is not a method. It just make a bind between the variable and whatever is to the right of it, nothing else. It never changes or creates objects. It is a declaration of what the variable will point to, since now on.
When you do b = b + 0.1
the =
operand binds the variable to a new float, wich is created with te result of 5 + 0.1
.
When you assign a variable to an existent object, mutable or not, the =
operand binds the variable to that object. And nothing more happens
In either case, the =
just make the bind. It doesn't change or create objects.
When you do a = 1.0
, the =
operand is not wich create the float, but the 1.0
part of the line. Actually when you write 1.0
it is a shorthand for float(1.0)
a constructor call returning a float object. (That is the reason why if you type 1.0
and press enter you get the "echo" 1.0
printed below; that is the return value of the constructor function you called)
Now, if b
is a float and you assign a = b
, both variables are pointing to the same object, but actually the variables can't comunicate betweem themselves, because the object is inmutable, and if you do b += 1
, now b
point to a new object, and a
is still pointing to the oldone and cannot know what b
is pointing to.
but if c
is, let's say, a list
, and you assign a = c
, now a
and c
can "comunicate", because list
is mutable, and if you do c.append('msg')
, then just checking a
you get the message.
(By the way, every object has an unique id number asociated to, wich you can get with id(x)
. So you can check if an object is the same or not checking if its unique id has changed.)
<ul style="color: red;">
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
EDIT (2019-02-03)
Note that the following answer only works on older versions of Python. More recently, OrderedDict
has been rewritten in C. In addition this does touch double-underscore attributes which is frowned upon.
I just wrote a subclass of OrderedDict
in a project of mine for a similar purpose. Here's the gist.
Insertion operations are also constant time O(1)
(they don't require you to rebuild the data structure), unlike most of these solutions.
>>> d1 = ListDict([('a', '1'), ('b', '2')])
>>> d1.insert_before('a', ('c', 3))
>>> d1
ListDict([('c', 3), ('a', '1'), ('b', '2')])
You can use localStorage and its "storage" eventListener to transfer sessionStorage data from one tab to another.
This code would need to exist on ALL tabs. It should execute before your other scripts.
// transfers sessionStorage from one tab to another
var sessionStorage_transfer = function(event) {
if(!event) { event = window.event; } // ie suq
if(!event.newValue) return; // do nothing if no value to work with
if (event.key == 'getSessionStorage') {
// another tab asked for the sessionStorage -> send it
localStorage.setItem('sessionStorage', JSON.stringify(sessionStorage));
// the other tab should now have it, so we're done with it.
localStorage.removeItem('sessionStorage'); // <- could do short timeout as well.
} else if (event.key == 'sessionStorage' && !sessionStorage.length) {
// another tab sent data <- get it
var data = JSON.parse(event.newValue);
for (var key in data) {
sessionStorage.setItem(key, data[key]);
}
}
};
// listen for changes to localStorage
if(window.addEventListener) {
window.addEventListener("storage", sessionStorage_transfer, false);
} else {
window.attachEvent("onstorage", sessionStorage_transfer);
};
// Ask other tabs for session storage (this is ONLY to trigger event)
if (!sessionStorage.length) {
localStorage.setItem('getSessionStorage', 'foobar');
localStorage.removeItem('getSessionStorage', 'foobar');
};
I tested this in chrome, ff, safari, ie 11, ie 10, ie9
This method "should work in IE8" but i could not test it as my IE was crashing every time i opened a tab.... any tab... on any website. (good ol IE) PS: you'll obviously need to include a JSON shim if you want IE8 support as well. :)
Credit goes to this full article: http://blog.guya.net/2015/06/12/sharing-sessionstorage-between-tabs-for-secure-multi-tab-authentication/
You can use this simple 'inline' method to construct a string_list_type parameter (works in SQL Server 2014):
declare @p1 dbo.string_list_type
insert into @p1 values(N'myFirstString')
insert into @p1 values(N'mySecondString')
Example use when executing a stored proc:
exec MyStoredProc @MyParam=@p1
For general case of syntax you can look at annex A of the ANSI C standard.
In the Backus-Naur form from there, you can see that typedef
has the type storage-class-specifier
.
In the type declaration-specifiers
you can see that you can mix many specifier types, the order of which does not matter.
For example, it is correct to say,
long typedef long a;
to define the type a
as an alias for long long
. So , to understand the typedef on the exhaustive use you need to consult some backus-naur form that defines the syntax (there are many correct grammars for ANSI C, not only that of ISO).
When you use typedef to define an alias for a function type you need to put the alias in the same place where you put the identifier of the function. In your case you define the type FunctionFunc
as an alias for a pointer to function whose type checking is disabled at call and returning nothing.
You are using Ajax incorrectly. The idea is not to have it return anything, but instead hand off the data to something called a callback function, which handles the data.
That is:
function handleData( responseData ) {
// Do what you want with the data
console.log(responseData);
}
$.ajax({
url: "hi.php",
...
success: function ( data, status, XHR ) {
handleData(data);
}
});
Returning anything in the submit handler will not do anything. You must instead either hand off the data, or do what you want with it directly inside the success function.
You must make sure that the input string has enough space to hold all the padding characters. Try this:
char hello[11] = "Hello";
StringPadRight(hello, 10, "0");
Note that I allocated 11 bytes for the hello
string to account for the null terminator at the end.
Its hard to detach your production dB or other running dB's and deal with that downtime, so I almost always use a Backup / restore method.
If you also want to make sure to keep your login's in sync check out the MS KB article on using the stored proc sp_help_revlogin to do this.
After adding dependencies open "Gradle" ('View'->Tool Windows->Gradle) tab and hit "refresh"
example of adding (compile 'io.reactivex:rxjava:1.1.0'):
If Idea still can not resolve dependency, hence it is possibly the dependency is not in mavenCentral() repository and you need add repository where this dependency located into repositories{}
round(..)
function returning a floatThat float (double-precision in Python) is always a perfect representation of an integer, as long as it's in the range [-253..253]. (Pedants pay attention: it's not two's complement in doubles, so the range is symmetric about zero.)
See the discussion here for details.
input file element:
<input type="file" id="fileinput" />
get file :
var myFile = $('#fileinput').prop('files');
CSS
select.inpSelect {
//Remove original arrows
-webkit-appearance: none;
//Use png at assets/selectArrow.png for the arrow on the right
//Set the background color to a BadAss Green color
background: url(assets/selectArrow.png) no-repeat right #BADA55;
}
To my opinion the best option to route to css & js use the following code:
<link rel="stylesheet" type="text/css" href="{{ URL::to('route/to/css') }}">
So if you have css file called main.css inside of css folder in public folder it should be the following:
<link rel="stylesheet" type="text/css" href="{{ URL::to('css/main.css') }}">
1) What is an API?
API is a contract. A promise to perform described services when asked in specific ways.
2) How is it used?
According to the rules specified in the contract. The whole point of an API is to define how it's used.
3) When and where is it used?
It's used when 2 or more separate systems need to work together to achieve something they can't do alone.
The limit of requests in .Net can be configured from two properties together:
Web.Config/system.web/httpRuntime/maxRequestLength
Web.Config/system.webServer/security/requestFiltering/requestLimits/maxAllowedContentLength
(in bytes)References:
Example:
<location path="upl">
<system.web>
<!--The default size is 4096 kilobytes (4 MB). MaxValue is 2147483647 KB (2 TB)-->
<!-- 100 MB in kilobytes -->
<httpRuntime maxRequestLength="102400" />
</system.web>
<system.webServer>
<security>
<requestFiltering>
<!--The default size is 30000000 bytes (28.6 MB). MaxValue is 4294967295 bytes (4 GB)-->
<!-- 100 MB in bytes -->
<requestLimits maxAllowedContentLength="104857600" />
</requestFiltering>
</security>
</system.webServer>
</location>
I understand the current answer but needed a more clear example. Here is an example of what I used with an Adapter
(RecyclerView.Adapter) and an Activity
.
This will implement the interface
that we have in our Adapter
. In this example, it will be called when the user clicks on an item in the RecyclerView
.
public class MyActivity extends Activity implements AdapterCallback {
private MyAdapter myAdapter;
@Override
public void onMethodCallback() {
// do something
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
myAdapter = new MyAdapter(this);
}
}
In the Activity
, we initiated our Adapter
and passed this as an argument to the constructer. This will initiate our interface
for our callback method. You can see that we use our callback method for user clicks.
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private AdapterCallback adapterCallback;
public MyAdapter(Context context) {
try {
adapterCallback = ((AdapterCallback) context);
} catch (ClassCastException e) {
throw new ClassCastException("Activity must implement AdapterCallback.", e);
}
}
@Override
public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int position) {
// simple example, call interface here
// not complete
viewHolder.itemView.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
try {
adapterCallback.onMethodCallback();
} catch (ClassCastException e) {
// do something
}
}
});
}
public static interface AdapterCallback {
void onMethodCallback();
}
}
When you "call" a function you are basically just telling the program to execute that function. So if you had a function that added two numbers such as:
def add(a,b):
return a + b
you would call the function like this:
add(3,5)
which would return 8. You can put any two numbers in the parentheses in this case. You can also call a function like this:
answer = add(4,7)
Which would set the variable answer equal to 11 in this case.
bool isNegative(int n) {
int i;
for (i = 0; i <= Int32.MaxValue; i++) {
if (n == i)
return false;
}
return true;
}
Do a reset of the configuration and set the root level to OFF
LogManager.getLogManager().reset();
Logger globalLogger = Logger.getLogger(java.util.logging.Logger.GLOBAL_LOGGER_NAME);
globalLogger.setLevel(java.util.logging.Level.OFF);
this is one simple approach using spring boot
TestClass.java
@Configuration
@Profile("one")
@PropertySource("file:/{selected location}/app.properties")
public class TestClass {
@Autowired
Environment env;
@Bean
public boolean test() {
System.out.println(env.getProperty("test.one"));
return true;
}
}
the app.properties context, in your selected location
test.one = 1234
your spring boot application
@SpringBootApplication
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(testApplication.class, args);
}
}
and the predefined application.properties context
spring.profiles.active = one
you can write as many configuration class as you like and enable/disable them just by setting spring.profiles.active = the profile name/names {separated by commas}
as you can see spring boot is great it just needs sometime to get familiar with, it's worth mentioning that you may use @Value on your fields as well
@Value("${test.one}")
String str;
From ggplot 2.2.0
labels can easily be stacked by using position = position_stack(vjust = 0.5)
in geom_text
.
ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
geom_bar(stat = "identity") +
geom_text(size = 3, position = position_stack(vjust = 0.5))
Also note that "position_stack()
and position_fill()
now stack values in the reverse order of the grouping, which makes the default stack order match the legend."
Answer valid for older versions of ggplot
:
Here is one approach, which calculates the midpoints of the bars.
library(ggplot2)
library(plyr)
# calculate midpoints of bars (simplified using comment by @DWin)
Data <- ddply(Data, .(Year),
transform, pos = cumsum(Frequency) - (0.5 * Frequency)
)
# library(dplyr) ## If using dplyr...
# Data <- group_by(Data,Year) %>%
# mutate(pos = cumsum(Frequency) - (0.5 * Frequency))
# plot bars and add text
p <- ggplot(Data, aes(x = Year, y = Frequency)) +
geom_bar(aes(fill = Category), stat="identity") +
geom_text(aes(label = Frequency, y = pos), size = 3)
Make sure that you do not have any null or NaN values in the list you want to sort. If there are NaN values, then your sort will be off, impacting the sorting of the non-null values.
Check out Python: sort function breaks in the presence of nan
Start thinking in terms of a: blast from the past
Once upon a time, long long ago, there lived in the land of computing interpreters and compilers. All kinds of fuss ensued over the merits of one over the other. The general opinion at that time was something along the lines of:
A one or two order of magnitude difference in the runtime performance existed between an interpreted program and a compiled program. Other distinguishing points, run-time mutability of the code for example, were also of some interest but the major distinction revolved around the run-time performance issues.
Today the landscape has evolved to such an extent that the compiled/interpreted distinction is pretty much irrelevant. Many compiled languages call upon run-time services that are not completely machine code based. Also, most interpreted languages are "compiled" into byte-code before execution. Byte-code interpreters can be very efficient and rival some compiler generated code from an execution speed point of view.
The classic difference is that compilers generated native machine code, interpreters read source code and generated machine code on the fly using some sort of run-time system. Today there are very few classic interpreters left - almost all of them compile into byte-code (or some other semi-compiled state) which then runs on a virtual "machine".
Important note: You should only apply plugin at bottom of build.gradle (App level)
apply plugin: 'com.google.gms.google-services'
I mistakenly apply this plugin at top of the build.gradle. So I get error.
One more tips : You no need to remove even you use the 3.1.0 or above. Because google not officially announced
classpath 'com.google.gms:google-services:3.1.0'
The file is created wherever the root of the python interpreter was started.
Eg, you start python in /home/user/program
, then the file "test.py" would be located at /home/user/program/test.py
Something like this may be:
String str = "abcdefghijklmnopqrtuvwxyz";
if (str.length() > 8)
str = str.substring(0, 8) + "...";
You should probably use SQL_Latin1_General_Cp1_CI_AS_KI_WI
as your collation. The one you specify in your question is explictly case sensitive.
You can see a list of collations here.
This is not a security measure for weak code to be left unattended. Always get a permanent solution to weak code and secure your websites properly before implementing this strategy
The best tool by far according to my knowledge would be to add multiple javascript files that simply changes the integrity of the page back to normal by refreshing or replacing content. Disabling this developer tool would not be the greatest idea since bypassing is always in question since the code is part of the browser and not a server rendering, thus it could be cracked.
Should you have js file one
checking for <element>
changes on important elements and js file two
and js file three
checking that this file exists per period you will have full integrity restore on the page within the period.
Lets take an example of the 4 files and show you what I mean.
index.html
<!DOCTYPE html>
<html>
<head id="mainhead">
<script src="ks.js" id="ksjs"></script>
<script src="mainfile.js" id="mainjs"></script>
<link rel="stylesheet" href="style.css" id="style">
<meta id="meta1" name="description" content="Proper mitigation against script kiddies via Javascript" >
</head>
<body>
<h1 id="heading" name="dontdel" value="2">Delete this from console and it will refresh. If you change the name attribute in this it will also refresh. This is mitigating an attack on attribute change via console to exploit vulnerabilities. You can even try and change the value attribute from 2 to anything you like. If This script says it is 2 it should be 2 or it will refresh. </h1>
<h3>Deleting this wont refresh the page due to it having no integrity check on it</h3>
<p>You can also add this type of error checking on meta tags and add one script out of the head tag to check for changes in the head tag. You can add many js files to ensure an attacker cannot delete all in the second it takes to refresh. Be creative and make this your own as your website needs it.
</p>
<p>This is not the end of it since we can still enter any tag to load anything from everywhere (Dependent on headers etc) but we want to prevent the important ones like an override in meta tags that load headers. The console is designed to edit html but that could add potential html that is dangerous. You should not be able to enter any meta tags into this document unless it is as specified by the ks.js file as permissable. <br>This is not only possible with meta tags but you can do this for important tags like input and script. This is not a replacement for headers!!! Add your headers aswell and protect them with this method.</p>
</body>
<script src="ps.js" id="psjs"></script>
</html>
mainfile.js
setInterval(function() {
// check for existence of other scripts. This part will go in all other files to check for this file aswell.
var ksExists = document.getElementById("ksjs");
if(ksExists) {
}else{ location.reload();};
var psExists = document.getElementById("psjs");
if(psExists) {
}else{ location.reload();};
var styleExists = document.getElementById("style");
if(styleExists) {
}else{ location.reload();};
}, 1 * 1000); // 1 * 1000 milsec
ps.js
/*This script checks if mainjs exists as an element. If main js is not existent as an id in the html file reload!You can add this to all js files to ensure that your page integrity is perfect every second. If the page integrity is bad it reloads the page automatically and the process is restarted. This will blind an attacker as he has one second to disable every javascript file in your system which is impossible.
*/
setInterval(function() {
// check for existence of other scripts. This part will go in all other files to check for this file aswell.
var mainExists = document.getElementById("mainjs");
if(mainExists) {
}else{ location.reload();};
//check that heading with id exists and name tag is dontdel.
var headingExists = document.getElementById("heading");
if(headingExists) {
}else{ location.reload();};
var integrityHeading = headingExists.getAttribute('name');
if(integrityHeading == 'dontdel') {
}else{ location.reload();};
var integrity2Heading = headingExists.getAttribute('value');
if(integrity2Heading == '2') {
}else{ location.reload();};
//check that all meta tags stay there
var meta1Exists = document.getElementById("meta1");
if(meta1Exists) {
}else{ location.reload();};
var headExists = document.getElementById("mainhead");
if(headExists) {
}else{ location.reload();};
}, 1 * 1000); // 1 * 1000 milsec
ks.js
/*This script checks if mainjs exists as an element. If main js is not existent as an id in the html file reload! You can add this to all js files to ensure that your page integrity is perfect every second. If the page integrity is bad it reloads the page automatically and the process is restarted. This will blind an attacker as he has one second to disable every javascript file in your system which is impossible.
*/
setInterval(function() {
// check for existence of other scripts. This part will go in all other files to check for this file aswell.
var mainExists = document.getElementById("mainjs");
if(mainExists) {
}else{ location.reload();};
//Check meta tag 1 for content changes. meta1 will always be 0. This you do for each meta on the page to ensure content credibility. No one will change a meta and get away with it. Addition of a meta in spot 10, say a meta after the id="meta10" should also be covered as below.
var x = document.getElementsByTagName("meta")[0];
var p = x.getAttribute("name");
var s = x.getAttribute("content");
if (p != 'description') {
location.reload();
}
if ( s != 'Proper mitigation against script kiddies via Javascript') {
location.reload();
}
// This will prevent a meta tag after this meta tag @ id="meta1". This prevents new meta tags from being added to your pages. This can be used for scripts or any tag you feel is needed to do integrity check on like inputs and scripts. (Yet again. It is not a replacement for headers to be added. Add your headers aswell!)
var lastMeta = document.getElementsByTagName("meta")[1];
if (lastMeta) {
location.reload();
}
}, 1 * 1000); // 1 * 1000 milsec
style.css
Now this is just to show it works on all files and tags aswell
#heading {
background-color:red;
}
If you put all these files together and build the example you will see the function of this measure. This will prevent some unforseen injections should you implement it correctly on all important elements in your index file especially when working with PHP.
Why I chose reload instead of change back to normal value per attribute is the fact that some attackers could have another part of the website already configured and ready and it lessens code amount. The reload will remove all the attacker's hard work and he will probably go play somewhere easier.
Another note: This could become a lot of code so keep it clean and make sure to add definitions to where they belong to make edits easy in future. Also set the seconds to your preferred amount as 1 second intervals on large pages could have drastic effects on older computers your visitors might be using
Here's something useful...
First of all we'll click on the link , run some code, and than we'll perform default action. This will be possible using event.currentTarget Take a look. Here we'll gonna try to access Google on a new tab, but before we need to run some code.
<a href="https://www.google.com.br" target="_blank" id="link">Google</a>
<script type="text/javascript">
$(document).ready(function() {
$("#link").click(function(e) {
// Prevent default action
e.preventDefault();
// Here you'll put your code, what you want to execute before default action
alert(123);
// Prevent infinite loop
$(this).unbind('click');
// Execute default action
e.currentTarget.click();
});
});
</script>
Another easy way:
//In your ListViewActivity:
public void refreshListView() {
listAdapter = new ListAdapter(this);
setListAdapter(listAdapter);
}
redirect with query string
$('#results').on('click', '.item', function () {
var NestId = $(this).data('id');
// var url = '@Url.Action("Details", "Artists",new { NestId = '+NestId+' })';
var url = '@ Url.Content("~/Artists/Details?NestId =' + NestId + '")'
window.location.href = url;
})
Since the true Binding URL for the web service is located in the file, you could do these simple steps from your local machine:
1) Save the file to your local computer for example:
C:\Documents and Settings\[user]\Desktop\Webservice1.asmx
2) In Visual Studio Right Click on your project > Choose Add Web Reference, A dialog will open.
3) In the URL Box Copy the local file location above C:\Documents and Settings[user]\Desktop\Webservice1.asmx, Click Next
4) Now you will see the functions appear, choose your name for the reference, Click add reference
5) You are done! you can start using it as a namespace in your application don't worry that you used a local file, because anyway the true URL for the service is located in the file at the Binding section
Encapsulation is wrapping up of data and methods in a single unit and making the data accessible only through methods(getter/setter) to ensure safety of data.
Abstraction is hiding internal implementation details of how work is done.
Take and example of following stack class:
Class Stack
{
private top;
void push();
int pop();
}
Now encapsulation helps to safeguard internal data as top cannot be accessed directly outside.
And abstraction helps to do push or pop on stack without worrying about what are steps to push or pop
Use dynamic_cast
for converting pointers/references within an inheritance hierarchy.
Use static_cast
for ordinary type conversions.
Use reinterpret_cast
for low-level reinterpreting of bit patterns. Use with extreme caution.
Use const_cast
for casting away const/volatile
. Avoid this unless you are stuck using a const-incorrect API.
canvas.toDataURL()
will provide you a data url which can be used as source:
var image = new Image();
image.id = "pic";
image.src = canvas.toDataURL();
document.getElementById('image_for_crop').appendChild(image);
Here's a complete example with some random lines. The black-bordered image is generated on a <canvas>
, whereas the blue-bordered image is a copy in a <img>
, filled with the <canvas>
's data url.
// This is just image generation, skip to DATAURL: below
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d");
// Just some example drawings
var gradient = ctx.createLinearGradient(0, 0, 200, 100);
gradient.addColorStop("0", "#ff0000");
gradient.addColorStop("0.5" ,"#00a0ff");
gradient.addColorStop("1.0", "#f0bf00");
ctx.beginPath();
ctx.moveTo(0, 0);
for (let i = 0; i < 30; ++i) {
ctx.lineTo(Math.random() * 200, Math.random() * 100);
}
ctx.strokeStyle = gradient;
ctx.stroke();
// DATAURL: Actual image generation via data url
var target = new Image();
target.src = canvas.toDataURL();
document.getElementById('result').appendChild(target);
_x000D_
canvas { border: 1px solid black; }
img { border: 1px solid blue; }
body { display: flex; }
div + div {margin-left: 1ex; }
_x000D_
<div>
<p>Original:</p>
<canvas id="canvas" width=200 height=100></canvas>
</div>
<div id="result">
<p>Result via <img>:</p>
</div>
_x000D_
See also:
Array.from(myMap.keys())
does not work in google application scripts.
Trying to use it results in the error TypeError: Cannot find function from in object function Array() { [native code for Array.Array, arity=1] }
.
To get a list of keys in GAS do this:
var keysList = Object.keys(myMap);
Yesterday's date can be calculated as,
var prev_date = new Date();
prev_date.setDate(prev_date.getDate() - 1);
DIV
s do not have a value
property.
Technically, according to the DTDs, they shouldn't have a value
attribute either, but generally you'll want to use .getAttribute()
in this case:
function overlay()
{
var cookieValue = document.getElementById('demo').getAttribute('value');
alert(cookieValue);
}
I wondered the same myself. I found that under File(menu) there is an item "Project Settings". It opens a dialog box with 3 choices: "Default Location", "Project-relative Location", and "Custom location" "Project-relative" puts the build products in the project folder, like before. This is not in the Preferences menu and must be set every time a project is created. Hope this helps.
The Problem is Windows and Microsoft applications put byte order marks at the beginning of all your files so other applications often break or don't read these UTF-8 encoding marks. I perfect example of this problem was triggering quirsksmode in old IE web browsers when encoding in UTF-8 as browsers often display web pages based on what encoding falls at the start of the page. It makes a mess when other applications view those UTF-8 Visual Studio pages.
I usually do not recommend Visual Studio Extensions, but I do this one to fix that issue:
Fix File Encoding: https://vlasovstudio.com/fix-file-encoding/
The FixFileEncoding above install REMOVES the byte order mark and forces VS to save ALL FILES without signature in UTF-8. After installing go to Tools > Option then choose "FixFileEncoding". It should allow you to set all saves as UTF-8 . Add "cshtml to the list of files to always save in UTF-8 without the byte order mark as so: ".(htm|html|cshtml)$)".
Now open one of your files in Visual Studio. To verify its saving as UTF-8 go to File > Save As, then under the Save button choose "Save With Encoding". It should choose "UNICODE (Save without Signature)" by default from the list of encodings. Now when you save that page it should always save as UTF-8 without byte order mark at the beginning of the file when saving in Visual Studio.
Like this:
{% if age > 18 %}
{% with patient as p %}
<my html here>
{% endwith %}
{% else %}
{% with patient.parent as p %}
<my html here>
{% endwith %}
{% endif %}
If the html is too big and you don't want to repeat it, then the logic would better be placed in the view. You set this variable and pass it to the template's context:
p = (age > 18 && patient) or patient.parent
and then just use {{ p }} in the template.
public Date addMonths(String dateAsString, int nbMonths) throws ParseException {
String format = "MM/dd/yyyy" ;
SimpleDateFormat sdf = new SimpleDateFormat(format) ;
Date dateAsObj = sdf.parse(dateAsString) ;
Calendar cal = Calendar.getInstance();
cal.setTime(dateAsObj);
cal.add(Calendar.MONTH, nbMonths);
Date dateAsObjAfterAMonth = cal.getTime() ;
System.out.println(sdf.format(dateAsObjAfterAMonth));
return dateAsObjAfterAMonth ;
}`
Since C# 7.0 supports using static
directive and Local functions you don't need preprocessor macros for most cases.
Place the following line at the end
export LD_LIBRARY_PATH=<your path>
Save and Exit.
Execute this command
sudo ldconfig
Try this jobber
String stringy =null;
byte[] buffer = new byte[100000];
for (int i = 0; i < buffer.length; i++) {
buffer[i] =0;
}
stringy =StringUtils.toAsciiString(buffer);
def awgn(sinal):
regsnr=54
sigpower=sum([math.pow(abs(sinal[i]),2) for i in range(len(sinal))])
sigpower=sigpower/len(sinal)
noisepower=sigpower/(math.pow(10,regsnr/10))
noise=math.sqrt(noisepower)*(np.random.uniform(-1,1,size=len(sinal)))
return noise
Here is the snippet you can use to programmatically get user.config file location:
public static string GetDefaultExeConfigPath(ConfigurationUserLevel userLevel)
{
try
{
var UserConfig = ConfigurationManager.OpenExeConfiguration(userLevel);
return UserConfig.FilePath;
}
catch (ConfigurationException e)
{
return e.Filename;
}
}
ApplicationSettings (i.e. settings.settings) use PerUserRoamingAndLocal for user settings by default (as I remembered).
Update: Strange but there are too many incorrect answers here. If you are looking for you user scoped settings file (user.config) it will be located in the following folder (for Windows XP):
C:\Documents and Settings\(username)\Local Settings\Application Data\(company-name-if-exists)\(app-name).exe_(Url|StrongName)_(hash)\(app-version)\
Url or StrongName depends on have you application assembly strong name or not.
BinaryFormatter
may produce invalid output in some specific cases. For example it will omit unpaired surrogate characters. It may also have problems with values of interface types. Read this documentation page including community content.
If you find your error to be persistent you may want to consider using XML serializer like DataContractSerializer
or XmlSerializer
.
Once you've dropped all the tables (and the indexes will disappear when the table goes) then there's nothing left in a SQLite database as far as I know, although the file doesn't seem to shrink (from a quick test I just did).
So deleting the file would seem to be fastest - it should just be recreated when your app tries to access the db file.
It depends on what you are after in the Dictionary
Models.TestModels obj = new Models.TestModels();
foreach (var keyValuPair in obj.sp)
{
// KeyValuePair<int, dynamic>
}
foreach (var key in obj.sp.Keys)
{
// Int
}
foreach (var value in obj.sp.Values)
{
// dynamic
}
I used these options to convert to the H.264/AAC .mp4 format for HTML5 playback (I think it may help other guys with this problem in some way):
ffmpeg -i input.flv -vcodec mpeg4 -acodec aac output.mp4
UPDATE
As @LordNeckbeard mentioned, the previous line will produce MPEG-4 Part 2
(back in 2012 that worked somehow, I don't remember/understand why). Use the libx264
encoder to produce the proper video with H.264/AAC. To test the output file you can just drag it to a browser window and it should playback just fine.
ffmpeg -i input.flv -vcodec libx264 -acodec aac output.mp4
If you know the highest index (such as stored in a variable "i") then you can do
myArray[i + 1] = someValue;
However if you don't know then you can either use
myArray.push(someValue);
as other answers suggested, or you can use
myArray[myArray.length] = someValue;
Note that the array is zero based so .length return the highest index plus one.
Also note that you don't have to add in order and you can actually skip values, as in
myArray[myArray.length + 1000] = someValue;
In which case the values in between will have a value of undefined.
It is therefore a good practice when looping through a JavaScript to verify that a value actually exists at that point.
This can be done by something like the following:
if(myArray[i] === "undefined"){ continue; }
if you are certain that you don't have any zeros in the array then you can just do:
if(!myArray[i]){ continue; }
Of course make sure in this case that you don't use as the condition myArray[i] (as some people over the internet suggest based on the end that as soon as i is greater then the highest index it will return undefined which evaluates to false)
addEventListener
is the proper DOM method to use for attaching event handlers.
Internet Explorer (up to version 8) used an alternate attachEvent
method.
Internet Explorer 9 supports the proper addEventListener
method.
The following should be an attempt to write a cross-browser addEvent
function.
function addEvent(evnt, elem, func) {
if (elem.addEventListener) // W3C DOM
elem.addEventListener(evnt,func,false);
else if (elem.attachEvent) { // IE DOM
elem.attachEvent("on"+evnt, func);
}
else { // No much to do
elem["on"+evnt] = func;
}
}
Perhaps you want Hash#merge ?
1.9.3p194 :015 > h={}
=> {}
1.9.3p194 :016 > h.merge(:key => 'bar')
=> {:key=>"bar"}
1.9.3p194 :017 >
If you want to change the array in place use merge!
1.9.3p194 :016 > h.merge!(:key => 'bar')
=> {:key=>"bar"}
The substitute of fcntl
on windows are win32api
calls. The usage is completely different. It is not some switch you can just flip.
In other words, porting a fcntl
-heavy-user module to windows is not trivial. It requires you to analyze what exactly each fcntl
call does and then find the equivalent win32api
code, if any.
There's also the possibility that some code using fcntl
has no windows equivalent, which would require you to change the module api and maybe the structure/paradigm of the program using the module you're porting.
If you provide more details about the fcntl
calls people can find windows equivalents.
While I agree with CMS about doing this in an unobtrusive manner (via a lib like jquery or dojo), here's what also work:
<script type="text/javascript">
function parse(a, b, c) {
alert(c);
}
</script>
<a href="#x" onclick="parse('#', false, 'xyc"foo');return false;">Test</a>
The reason it barfs is not because of JavaScript, it's because of the HTML parser. It has no concept of escaped quotes to it trundles along looking for the end quote and finds it and returns that as the onclick function. This is invalid javascript though so you don't find about the error until JavaScript tries to execute the function..
A clean way to download a file is:
import urllib
testfile = urllib.URLopener()
testfile.retrieve("http://randomsite.com/file.gz", "file.gz")
This downloads a file from a website and names it file.gz
. This is one of my favorite solutions, from Downloading a picture via urllib and python.
This example uses the urllib
library, and it will directly retrieve the file form a source.
You can do the following:
echo '<div class="my_class">';
echo ($cart->count_product > 0) ? $cart->count_product : '';
echo '</div>';
If you want to have it inside your statement, do this:
if($cart->count_product > 0)
{
echo '<div class="my_class">'.$cart->count_product.'</div>';
}
You don't need the else
statement, since you're only going to output the above when it's truthy anyway.
One thing you can do is, you might have subfolders for each projects. So, install mongoose in that subfolders and require() mongoose from own folders in each sub applications. Not from the project root or from global. So one sub project, one mongoose installation and one mongoose instance.
-app_root/
--foo_app/
---db_access.js
---foo_db_connect.js
---node_modules/
----mongoose/
--bar_app/
---db_access.js
---bar_db_connect.js
---node_modules/
----mongoose/
In foo_db_connect.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/foo_db');
module.exports = exports = mongoose;
In bar_db_connect.js
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/bar_db');
module.exports = exports = mongoose;
In db_access.js files
var mongoose = require("./foo_db_connect.js"); // bar_db_connect.js for bar app
Now, you can access multiple databases with mongoose.
Just had a very similar problem and solved it by adding
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
Apparently the site I'm fetching redirects to another location and php-curl doesn't follow redirects by default.
I think the answer is here (possibly duplicate):
How to test if a file is a directory in a batch script?
IF EXIST %VAR%\NUL ECHO It's a directory
Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.
As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)
if exist "c:\folder\" echo folder exists
should be enough for modern windows.
Often you will want to specify a manifest, like so:
jar -cvfm myJar.jar myManifest.txt myApp.class
Which reads: "create verbose jarFilename manifestFilename", followed by the files you want to include. Verbose means print messages about what it's doing.
Note that the name of the manifest file you supply can be anything, as jar
will automatically rename it and put it into the right directory within the jar file.
If you want to keep reference:
Array.prototype.push.apply(destinationArray, sourceArray);
Here is the below code, it will return the Enum name from Enum value.
public enum Test {
PLUS("Plus One"), MINUS("MinusTwo"), TIMES("MultiplyByFour"), DIVIDE(
"DivideByZero");
private String operationName;
private Test(final String operationName) {
setOperationName(operationName);
}
public String getOperationName() {
return operationName;
}
public void setOperationName(final String operationName) {
this.operationName = operationName;
}
public static Test getOperationName(final String operationName) {
for (Test oprname : Test.values()) {
if (operationName.equals(oprname.toString())) {
return oprname;
}
}
return null;
}
@Override
public String toString() {
return operationName;
}
}
public class Main {
public static void main(String[] args) {
Test test = Test.getOperationName("Plus One");
switch (test) {
case PLUS:
System.out.println("Plus.....");
break;
case MINUS:
System.out.println("Minus.....");
break;
default:
System.out.println("Nothing..");
break;
}
}
}
Just in case this answer helps someone: as found here, you might save yourself a lot of trouble running Sysinternals Autoruns as administrator. Just go to the "Services" tab and delete your service.
It did the trick for me on a machine where I didn't have any permission to edit the registry.
E.g. by naming the fields like
<input type="text" name="item[0][name]" />
<input type="text" name="item[0][email]" />
<input type="text" name="item[1][name]" />
<input type="text" name="item[1][email]" />
<input type="text" name="item[2][name]" />
<input type="text" name="item[2][email]" />
(which is also possible when adding elements via javascript)
The corresponding php script might look like
function show_Names($e)
{
return "The name is $e[name] and email is $e[email], thank you";
}
$c = array_map("show_Names", $_POST['item']);
print_r($c);
If you installed MySQL Server and you still get
mysql -u root -p command not found
You're most likely experiencing this because you have an older mac version.
Try this:
in the home directory in terminal open -t .bash_profile
paste export PATH=${PATH}:/usr/local/mysql/bin/
inside and save it
instead of writing mysql -u root -p
paste the following in your terminal:
/usr/local/mysql/bin/mysql -u root -p
Enter your password. Now you're in.
double doubleVal = 1.745;
double doubleVal1 = 0.745;
System.out.println(new BigDecimal(doubleVal));
System.out.println(new BigDecimal(doubleVal1));
outputs:
1.74500000000000010658141036401502788066864013671875
0.74499999999999999555910790149937383830547332763671875
Which shows the real value of the two doubles and explains the result you get. As pointed out by others, don't use the double constructor (apart from the specific case where you want to see the actual value of a double).
More about double precision:
The accepted answer by Josh David Miller works great if you are trying to dynamically add a directive that uses an inline template
. However if your directive takes advantage of templateUrl
his answer will not work. Here is what worked for me:
.directive('helperModal', [, "$compile", "$timeout", function ($compile, $timeout) {
return {
restrict: 'E',
replace: true,
scope: {},
templateUrl: "app/views/modal.html",
link: function (scope, element, attrs) {
scope.modalTitle = attrs.modaltitle;
scope.modalContentDirective = attrs.modalcontentdirective;
},
controller: function ($scope, $element, $attrs) {
if ($attrs.modalcontentdirective != undefined && $attrs.modalcontentdirective != '') {
var el = $compile($attrs.modalcontentdirective)($scope);
$timeout(function () {
$scope.$digest();
$element.find('.modal-body').append(el);
}, 0);
}
}
}
}]);
setInterval(function() {
updatechat();
}, 2000);
function updatechat() {
alert('hello world');
}
It sounds like you have a connection leak in your application because it fails to close pooled connections. You aren't having issues just with <idle> in transaction
sessions, but with too many connections overall.
Killing connections is not the right answer for that, but it's an OK-ish temporary workaround.
Rather than re-starting PostgreSQL to boot all other connections off a PostgreSQL database, see: How do I detach all other users from a postgres database? and How to drop a PostgreSQL database if there are active connections to it? . The latter shows a better query.
For setting timeouts, as @Doon suggested see How to close idle connections in PostgreSQL automatically?, which advises you to use PgBouncer to proxy for PostgreSQL and manage idle connections. This is a very good idea if you have a buggy application that leaks connections anyway; I very strongly recommend configuring PgBouncer.
A TCP keepalive won't do the job here, because the app is still connected and alive, it just shouldn't be.
In PostgreSQL 9.2 and above, you can use the new state_change
timestamp column and the state
field of pg_stat_activity
to implement an idle connection reaper. Have a cron job run something like this:
SELECT pg_terminate_backend(pid)
FROM pg_stat_activity
WHERE datname = 'regress'
AND pid <> pg_backend_pid()
AND state = 'idle'
AND state_change < current_timestamp - INTERVAL '5' MINUTE;
In older versions you need to implement complicated schemes that keep track of when the connection went idle. Do not bother; just use pgbouncer.
You can simply use:
mvn --settings YourOwnSettings.xml clean install
or
mvn -s YourOwnSettings.xml clean install
in /etc/my.cnf
:
[mysqld]
...
performance_schema = 0
table_cache = 0
table_definition_cache = 0
max-connect-errors = 10000
query_cache_size = 0
query_cache_limit = 0
...
Good work on server with 256MB Memory.
For those looking for a dplyr/tidyverse version. Building on Gavin Simpson solution:
# Create DF
set.seed(123)
x <- rnorm(100)
DF <- data.frame(x = x,
y = 4 + (1.5*x) + rnorm(100, sd = 2),
b = gl(5, 20))
# Change reference level
DF = DF %>% mutate(b = relevel(b, 3))
m2 <- lm(y ~ x + b, data = DF)
summary(m2)
Pre-crement means increment on the same line. Post-increment means increment after the line executes.
int j=0;
System.out.println(j); //0
System.out.println(j++); //0. post-increment. It means after this line executes j increments.
int k=0;
System.out.println(k); //0
System.out.println(++k); //1. pre increment. It means it increments first and then the line executes
When it comes with OR, AND operators, it becomes more interesting.
int m=0;
if((m == 0 || m++ == 0) && (m++ == 1)) { //false
/* in OR condition if first line is already true then compiler doesn't check the rest. It is technique of compiler optimization */
System.out.println("post-increment "+m);
}
int n=0;
if((n == 0 || n++ == 0) && (++n == 1)) { //true
System.out.println("pre-increment "+n); //1
}
In Array
System.out.println("In Array");
int[] a = { 55, 11, 15, 20, 25 } ;
int ii, jj, kk = 1, mm;
ii = ++a[1]; // ii = 12. a[1] = a[1] + 1
System.out.println(a[1]); //12
jj = a[1]++; //12
System.out.println(a[1]); //a[1] = 13
mm = a[1];//13
System.out.printf ( "\n%d %d %d\n", ii, jj, mm ) ; //12, 12, 13
for (int val: a) {
System.out.print(" " +val); //55, 13, 15, 20, 25
}
In C++ post/pre-increment of pointer variable
#include <iostream>
using namespace std;
int main() {
int x=10;
int* p = &x;
std::cout<<"address = "<<p<<"\n"; //prints address of x
std::cout<<"address = "<<p<<"\n"; //prints (address of x) + sizeof(int)
std::cout<<"address = "<<&x<<"\n"; //prints address of x
std::cout<<"address = "<<++&x<<"\n"; //error. reference can't re-assign because it is fixed (immutable)
}
When you use df.apply()
, each row of your DataFrame will be passed to your lambda function as a pandas Series. The frame's columns will then be the index of the series and you can access values using series[label]
.
So this should work:
df['D'] = (df.apply(lambda x: myfunc(x[colNames[0]], x[colNames[1]]), axis=1))
There is no .net native method for shutting off the computer. You need to P/Invoke the ExitWindows or ExitWindowsEx API call.
Here you can check for couple of things.
DateTime.TryParseExact
. Check the complete list of formats, available here. CultureInfo.InvariantCulture
which is more likely add problem. So instead of passing a NULL
value or setting it to CultureInfo provider = new CultureInfo("en-US")
, you may write it like.
.
if (!DateTime.TryParseExact(txtStartDate.Text, formats,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out startDate))
{
//your condition fail code goes here
return false;
}
else
{
//success code
}
On UNIX / Linux / Mac OS X you can copy and override files, can't you? So how about this solution:
cp /dev/null /var/mail/root
I used the same method mentioned by @S-T after the pip uninstall command. And even after that the I got the message that Django was already installed. So i deleted the 'Django-1.7.6.egg-info' folder from '/usr/lib/python2.7/dist-packages' and then it worked for me.
Use CardView for Round Rectangle. CardView give more functionality like cardCornerRadius, cardBackgroundColor, cardElevation & many more. CardView make UI more suitable then Custom Round Rectangle drawable.
I stumbled upon this problem during attempt to dockerise Avahi which needs to be aware of its public IP to function properly. Assigning static IP to the container is tricky due to lack of support for static IP assignment in Docker.
This article describes technique how to assign static IP to the container on Debian:
Docker service should be started with DOCKER_OPTS="--bridge=br0 --ip-masq=false --iptables=false"
. I assume that br0
bridge is already configured.
Container should be started with --cap-add=NET_ADMIN --net=bridge
Inside container pre-up ip addr flush dev eth0
in /etc/network/interfaces
can be used to dismiss IP address assigned by Docker as in following example:
auto lo
iface lo inet loopback
auto eth0
iface eth0 inet static
pre-up ip addr flush dev eth0
address 192.168.0.249
netmask 255.255.255.0
gateway 192.168.0.1
/etc/init.d/networking start
. Also entry script needs to edit or populate /etc/hosts
file in order to remove references to Docker-assigned IP.Format formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String s = formatter.format(date);
The command has to be entered in the directory of the repository. The error is complaining that your current directory isn't a git repo
ls
show the right files?git init
? (git-init documentation)Either of those would cause your error.
There are 2 .net framework version are given under the features in add role/ features in server 2012
a. 3.5
b. 4.5
Depending up on used framework you can enable HTTP-Activation under WCF services. :)
Try to Install the android tracker plugin. you will find it on the studio.
Restart the studio
It is ||
, for example:
select 'Mr ' || ename from emp;
The only "interesting" feature I can think of is that 'x' || null
returns 'x'
, not null
as you might perhaps expect.
the correct syntax is -
with t1
as
(select * from tab1
where conditions...
),
t2
as
(select * from tab2
where conditions...
(you can access columns of t1 here as well)
)
select * from t1, t2
where t1.col1=t2.col2;
Sadly, many JSON C++ libraries have APIs that are non trivial to use, while JSON was intended to be easy to use.
So I tried jsoncpp from the gSOAP tools on the JSON doc shown in one of the answers above and this is the code generated with jsoncpp to construct a JSON object in C++ which is then written in JSON format to std::cout:
value x(ctx);
x["appDesc"]["description"] = "SomeDescription";
x["appDesc"]["message"] = "SomeMessage";
x["appName"]["description"] = "Home";
x["appName"]["message"] = "Welcome";
x["appName"]["imp"][0] = "awesome";
x["appName"]["imp"][1] = "best";
x["appName"]["imp"][2] = "good";
std::cout << x << std::endl;
and this is the code generated by jsoncpp to parse JSON from std::cin and extract its values (replace USE_VAL
as needed):
value x(ctx);
std::cin >> x;
if (x.soap->error)
exit(EXIT_FAILURE); // error parsing JSON
#define USE_VAL(path, val) std::cout << path << " = " << val << std::endl
if (x.has("appDesc"))
{
if (x["appDesc"].has("description"))
USE_VAL("$.appDesc.description", x["appDesc"]["description"]);
if (x["appDesc"].has("message"))
USE_VAL("$.appDesc.message", x["appDesc"]["message"]);
}
if (x.has("appName"))
{
if (x["appName"].has("description"))
USE_VAL("$.appName.description", x["appName"]["description"]);
if (x["appName"].has("message"))
USE_VAL("$.appName.message", x["appName"]["message"]);
if (x["appName"].has("imp"))
{
for (int i2 = 0; i2 < x["appName"]["imp"].size(); i2++)
USE_VAL("$.appName.imp[]", x["appName"]["imp"][i2]);
}
}
This code uses the JSON C++ API of gSOAP 2.8.28. I don't expect people to change libraries, but I think this comparison helps to put JSON C++ libraries in perspective.
This is my solution
var error=0;
var test = [" ", " "];
if(test[0].match(/^\s*$/g)) {
$("#output").html("MATCH!");
error+=1;
} else {
$("#output").html("no_match");
}
For SQL Server 2017 it is : C:\Windows\SysWOW64\SQLServerManager14.msc
For SQL Server 2016 it is : C:\Windows\SysWOW64\SQLServerManager13.msc
For SQL Server 2016 it is :C:\Windows\SysWOW64\SQLServerManager12.msc
and to add it back to the start menu, copy it from the original location provided above and paste it to
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Microsoft SQL Server 2017\Configuration Tools\
This would put back the configuration manager under start menu.
Source: How to open sql server configuration manager in windows 10?
Instead of using sed
to filter out the certificate, you can also pipe the openssl s_client
output through openssl x509 -out certfile.txt
, for example:
echo "" | openssl s_client -connect my.server.com:443 -showcerts 2>/dev/null | openssl x509 -out certfile.txt
This is what worked for me.
1.clear db.
heroku pg:reset --app YOUR_APP
After running that you will have to type in your app name again to confirm.
2.migrate db to recreate.
heroku run rake db:migrate --app YOUR_APP
3.add seed data to db.
heroku run rake db:seed --app YOUR_APP
For me none of the packages mentioned above did help.
I finally managed to install lxml
after running:
sudo apt-get install python3.5-dev
You are simply reducing the values from a number. So substracting 6 from 3 (date) will return -3 only.
You need to individually add/remove unit of time in date object
var date = new Date();
date.setDate( date.getDate() - 6 );
date.setFullYear( date.getFullYear() - 1 );
$("#searchDateFrom").val((date.getMonth() ) + '/' + (date.getDate()) + '/' + (date.getFullYear()));
Here's an implementation for ColdFusion (requires CF10 because of the merge argument to ArrayAppend() ):
public array function permutateArray(arr){
if (not isArray(arguments.arr) ) {
return ['The ARR argument passed to the permutateArray function is not of type array.'];
}
var len = arrayLen(arguments.arr);
var perms = [];
var rest = [];
var restPerms = [];
var rpLen = 0;
var next = [];
//for one or less item there is only one permutation
if (len <= 1) {
return arguments.arr;
}
for (var i=1; i <= len; i++) {
// copy the original array so as not to change it and then remove the picked (current) element
rest = arraySlice(arguments.arr, 1);
arrayDeleteAt(rest, i);
// recursively get the permutation of the rest of the elements
restPerms = permutateArray(rest);
rpLen = arrayLen(restPerms);
// Now concat each permutation to the current (picked) array, and append the concatenated array to the end result
for (var j=1; j <= rpLen; j++) {
// for each array returned, we need to make a fresh copy of the picked(current) element array so as to not change the original array
next = arraySlice(arguments.arr, i, 1);
arrayAppend(next, restPerms[j], true);
arrayAppend(perms, next);
}
}
return perms;
}
Based on KhanSharp's js solution above.
Update to Android Studio 3.0.1 which treats these as warnings. Android 3.0 was treating such warnings as errors and hence causing the gradle sync operation to fail.
You can set environment variables in the notebook using os.environ
. Do the following before initializing TensorFlow to limit TensorFlow to first GPU.
import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID" # see issue #152
os.environ["CUDA_VISIBLE_DEVICES"]="0"
You can double check that you have the correct devices visible to TF
from tensorflow.python.client import device_lib
print device_lib.list_local_devices()
I tend to use it from utility module like notebook_util
import notebook_util
notebook_util.pick_gpu_lowest_memory()
import tensorflow as tf
WHERE username LIKE '%[_]d'; -- @Lasse solution
WHERE username LIKE '%$_d' ESCAPE '$';
WHERE username LIKE '%^_d' ESCAPE '^';
I was facing the same problem under Windows7. The error message looks like that:
Fatal Python error: Py_Initialize: unable to load the file system codec ModuleNotFoundError: No module named 'encodings' Current thread 0x000011f4 (most recent call first):
I have installed python 2.7(uninstalled now), and I checked "Add Python to environment variables in Advanced Options" while installing python 3.6. It comes out that the Environment Variable "PYTHONHOME" and "PYTHONPATH" is still python2.7.
Finally I solved it by modify "PYTHONHOME" to python3.6 install path and remove variable "PYTHONPATH".