Depending on what you are using this for, you may need to specify the data type (see 'dtype').
For example, to create a 2D array of 8-bit values (suitable for use as a monochrome image):
myarray = numpy.empty(shape=(H,W),dtype='u1')
For an RGB image, include the number of color channels in the shape: shape=(H,W,3)
You may also want to consider zero-initializing with numpy.zeros
instead of using numpy.empty
. See the note here.
Hey I had the same problem. I tried to convert '2017-02-20 12:15:32' varchar to a date with TO_DATE('2017-02-20 12:15:32','YYYY-MM-DD HH24:MI:SS')
and all I received was 2017-02-20 the time disappeared
My solution was to use TO_TIMESTAMP('2017-02-20 12:15:32','YYYY-MM-DD HH24:MI:SS')
now the time doesn't disappear.
I think init_js should use declare instead of local!
function scan3() {
declare -n outvar=$1 # -n makes it a nameref.
local nl=$'\x0a'
outvar="output${nl}${nl}" # two total. quotes preserve newlines
}
I made this function, it seems to work fine:
#include <math.h>
void GetFloattoInt (double fnum, long precision, long *pe, long *pd)
{
long pe_sign;
long intpart;
float decpart;
if(fnum>=0)
{
pe_sign=1;
}
else
{
pe_sign=-1;
}
intpart=(long)fnum;
decpart=fnum-intpart;
*pe=intpart;
*pd=(((long)(decpart*pe_sign*pow(10,precision)))%(long)pow(10,precision));
}
The answer of @PeterOlson may be worked back in the day but it looks like
Object.create
is changed. I would go for the copy-constructor way like @user166390 said in the comments.
The reason I necromanced this post is because I needed such implementation.
Nowadays we can use Object.assign
(credits to @SayanPal solution) & ES6 syntax:
class Person {
constructor(obj) {
obj && Object.assign(this, obj);
}
getFullName() {
return `${this.lastName} ${this.firstName}`;
}
}
Usage:
const newPerson = new Person(person1)
newPerson.getFullName() // -> Freeman Gordon
ES5 answer below
function Person(obj) {
for(var prop in obj){
// for safety you can use the hasOwnProperty function
this[prop] = obj[prop];
}
}
Usage:
var newPerson = new Person(person1);
console.log(newPerson.getFullName()); // -> Freeman Gordon
Using a shorter version, 1.5 liner:
function Person(){
if(arguments[0]) for(var prop in arguments[0]) this[prop] = arguments[0][prop];
}
This should get you started:
set datafile separator ","
plot 'infile' using 0:1
public static void ArrangeGrid(DataGridView Grid)
{
int twidth=0;
if (Grid.Rows.Count > 0)
{
twidth = (Grid.Width * Grid.Columns.Count) / 100;
for (int i = 0; i < Grid.Columns.Count; i++)
{
Grid.Columns[i].Width = twidth;
}
}
}
Have a try on the listings
package. Here is an example of what I used some time ago to have a coloured Java listing:
\usepackage{listings}
[...]
\lstset{language=Java,captionpos=b,tabsize=3,frame=lines,keywordstyle=\color{blue},commentstyle=\color{darkgreen},stringstyle=\color{red},numbers=left,numberstyle=\tiny,numbersep=5pt,breaklines=true,showstringspaces=false,basicstyle=\footnotesize,emph={label}}
[...]
\begin{lstlisting}
public void here() {
goes().the().code()
}
[...]
\end{lstlisting}
You may want to customize that. There are several references of the listings package. Just google them.
Why not just use the option Find and Replace. (every code editor has it)?
For example Visual Studio Code (under Edit option):
You just type in old name and new name and replace everyhting in the project with one click.
NOTE: This renames only file content, NOT file and folder names. Do not forget renaming folders, eg. templates/my_app_name/
rename it to templates/my_app_new_name/
page 1 : Detail page 2 : <% String id = request.getParameter("userid");%> // now you can using id for sql query of hsql detail product
first use this:
LayoutInflater inflater = (LayoutInflater) Read_file.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Read file is current activity in which you want your context.
View layout = inflater.inflate(R.layout.your_layout_name,(ViewGroup)findViewById(R.id.layout_name_id));
then you can use this to find any element in layout.
ImageView myImage = (ImageView) layout.findViewById(R.id.my_image);
I believe there is a better solution than rewrite the RegistrationsController. I did exactly the same thing (I just have Organization instead of Company).
If you set properly your nested form, at model and view level, everything works like a charm.
My User model:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable, :confirmable, :lockable and :timeoutable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :owned_organizations, :class_name => 'Organization', :foreign_key => :owner_id
has_many :organization_memberships
has_many :organizations, :through => :organization_memberships
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :name, :username, :owned_organizations_attributes
accepts_nested_attributes_for :owned_organizations
...
end
My Organization Model:
class Organization < ActiveRecord::Base
belongs_to :owner, :class_name => 'User'
has_many :organization_memberships
has_many :users, :through => :organization_memberships
has_many :contracts
attr_accessor :plan_name
after_create :set_owner_membership, :set_contract
...
end
My view : 'devise/registrations/new.html.erb'
<h2>Sign up</h2>
<% resource.owned_organizations.build if resource.owned_organizations.empty? %>
<%= form_for(resource, :as => resource_name, :url => registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<p><%= f.label :name %><br />
<%= f.text_field :name %></p>
<p><%= f.label :email %><br />
<%= f.text_field :email %></p>
<p><%= f.label :username %><br />
<%= f.text_field :username %></p>
<p><%= f.label :password %><br />
<%= f.password_field :password %></p>
<p><%= f.label :password_confirmation %><br />
<%= f.password_field :password_confirmation %></p>
<%= f.fields_for :owned_organizations do |organization_form| %>
<p><%= organization_form.label :name %><br />
<%= organization_form.text_field :name %></p>
<p><%= organization_form.label :subdomain %><br />
<%= organization_form.text_field :subdomain %></p>
<%= organization_form.hidden_field :plan_name, :value => params[:plan] %>
<% end %>
<p><%= f.submit "Sign up" %></p>
<% end %>
<%= render :partial => "devise/shared/links" %>
For another one-liner solution:
def count_letters(word): return len(filter(lambda x: x not in " ", word))
This works by using the filter function, which lets you pick the elements of a list that return true when passed to a boolean-valued function that you pass as the first argument. I'm using a lambda function to make a quick, throwaway function for that purpose.
>>> count_letters("This is a test")
11
You could easily extend this to exclude any selection of characters you like:
def count_letters(word, exclude): return len(filter(lambda x: x not in exclude, word))
>>> count_letters ("This is a test", "aeiou ")
7
Edit: However, you wanted to get your own code to work, so here are some thoughts. The first problem is that you weren't setting a list for the Counter object to count. However, since you're looking for the total number of letters, you need to join the words back together again rather than counting each word individually. Looping to add up the number of each letter isn't really necessary because you can pull out the list of values and use "sum" to add them.
Here's a version that's as close to your code as I could make it, without the loop:
from collections import Counter
import string
def count_letters(word):
wordsList = string.split(word)
count = Counter("".join(wordsList))
return sum(dict(count).values())
word = "The grey old fox is an idiot"
print count_letters(word)
Edit: In response to a comment asking why not to use a for loop, it's because it's not necessary, and in many cases using the many implicit ways to perform repetitive tasks in Python can be faster, simpler to read, and more memory-efficient.
For example, I could have written
joined_words = []
for curr_word in wordsList:
joined_words.extend(curr_word)
count = Counter(joined_words)
but in doing this I wind up allocating an extra array and executing a loop through the Python interpreter that my solution:
count = Counter("".join(wordsList))
would execute in a chunk of optimized, compiled C code. My solution isn't the only way to simplify that loop, but it's one way.
__future__
is a pseudo-module which programmers can use to enable new language features which are not compatible with the current interpreter. For example, the expression 11/4
currently evaluates to 2
. If the module in which it is executed had enabled true division by executing:
from __future__ import division
the expression 11/4
would evaluate to 2.75
. By importing the __future__
module and evaluating its variables, you can see when a new feature was first added to the language and when it will become the default:
>>> import __future__
>>> __future__.division
_Feature((2, 2, 0, 'alpha', 2), (3, 0, 0, 'alpha', 0), 8192)
Just as an FYI....
select * from sys.types where system_type_id = 231
gives you two rows.
(i'm not sure what this means yet but i'm 100% sure it's messing up my code right now)
edit: i guess what it means is that you should join by the user_type_id in this situation (my situation) or possibly both the user_type_id and the system_type_id
name system_type_id user_type_id schema_id principal_id max_length precision scale collation_name is_nullable is_user_defined is_assembly_type default_object_id rule_object_id
nvarchar 231 231 4 NULL 8000 0 0 SQL_Latin1_General_CP1_CI_AS 1 0 0 0 0
sysname 231 256 4 NULL 256 0 0 SQL_Latin1_General_CP1_CI_AS 0 0 0 0 0
create procedure dbo.yyy_test (
@col_one nvarchar(max),
@col_two nvarchar(max) = 'default',
@col_three nvarchar(1),
@col_four nvarchar(1) = 'default',
@col_five nvarchar(128),
@col_six nvarchar(128) = 'default',
@col_seven sysname
)
as begin
select 1
end
This query:
select parm.name AS Parameter,
parm.max_length,
parm.parameter_id
from sys.procedures sp
join sys.parameters parm ON sp.object_id = parm.object_id
where sp.name = 'yyy_test'
order by parm.parameter_id
Yields:
parameter max_length parameter_id
@col_one -1 1
@col_two -1 2
@col_three 2 3
@col_four 2 4
@col_five 256 5
@col_six 256 6
@col_seven 256 7
And This:
select parm.name as parameter,
parm.max_length,
parm.parameter_id,
typ.name as data_type,
typ.system_type_id,
typ.user_type_id,
typ.collation_name,
typ.is_nullable
from sys.procedures sp
join sys.parameters parm ON sp.object_id = parm.object_id
join sys.types typ ON parm.system_type_id = typ.system_type_id
where sp.name = 'yyy_test'
order by parm.parameter_id
Gives You This:
parameter max_length parameter_id data_type system_type_id user_type_id collation_name is_nullable
@col_one -1 1 nvarchar 231 231 SQL_Latin1_General_CP1_CI_AS 1
@col_one -1 1 sysname 231 256 SQL_Latin1_General_CP1_CI_AS 0
@col_two -1 2 nvarchar 231 231 SQL_Latin1_General_CP1_CI_AS 1
@col_two -1 2 sysname 231 256 SQL_Latin1_General_CP1_CI_AS 0
@col_three 2 3 nvarchar 231 231 SQL_Latin1_General_CP1_CI_AS 1
@col_three 2 3 sysname 231 256 SQL_Latin1_General_CP1_CI_AS 0
@col_four 2 4 nvarchar 231 231 SQL_Latin1_General_CP1_CI_AS 1
@col_four 2 4 sysname 231 256 SQL_Latin1_General_CP1_CI_AS 0
@col_five 256 5 nvarchar 231 231 SQL_Latin1_General_CP1_CI_AS 1
@col_five 256 5 sysname 231 256 SQL_Latin1_General_CP1_CI_AS 0
@col_six 256 6 nvarchar 231 231 SQL_Latin1_General_CP1_CI_AS 1
@col_six 256 6 sysname 231 256 SQL_Latin1_General_CP1_CI_AS 0
@col_seven 256 7 nvarchar 231 231 SQL_Latin1_General_CP1_CI_AS 1
@col_seven 256 7 sysname 231 256 SQL_Latin1_General_CP1_CI_AS 0
Don't know the reason behind this error but I found out this somewhere and it solved my problem.
change your
return @str1+'present in the string' ;
to
set @r = @str1+'present in the string'
Use CollectionUtils.isEmpty(Collection coll)
Null-safe check if the specified collection is empty. Null returns true.
Parameters: coll - the collection to check, may be null
Returns: true if empty or null
when you write formcontrolname Angular 2 do not accept. You have to write formControlName . it is about uppercase second words.
<input type="number" [(ngModel)]="myObject.name" formcontrolname="nameFormControl"/>
if the error still conitnue try to set form control for all of object(myObject) field.
between start <form> </form>
for example: <form [formGroup]="myForm" (ngSubmit)="submitForm(myForm.value)"> set form control for all input field </form>.
1)Yes it is, when there is style then it is styling your code(css).2) is belong to html it is like a container that keep your css.
I used this code to show the dialog at the bottom of the screen:
Dialog dlg = <code to create custom dialog>;
Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();
wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);
This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about
private void showPictureialog() {
final Dialog dialog = new Dialog(this,
android.R.style.Theme_Translucent_NoTitleBar);
// Setting dialogview
Window window = dialog.getWindow();
window.setGravity(Gravity.CENTER);
window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
dialog.setTitle(null);
dialog.setContentView(R.layout.selectpic_dialog);
dialog.setCancelable(true);
dialog.show();
}
you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment
public static void main(String args[])
{
Scanner s = new Scanner(System.in);
System.out.println("Press enter to continue.....");
s.nextLine();
}
This nextline
is a pretty good option as it will help us run next line whenever the enter key is pressed.
Ok,
I managed to solve this tricky issue. The thing was like I was using FrameLayout
. Don't know why but it came to my mind that may be the icon would be getting hidden behind some other view.
I tried putting the icon at the end of my layout and now I am able to see the Toast
as well as the Log
.
Thank you everybody for taking time to solve the issue.. Was surely tricky..
This seems like readings is sometimes an empty string and obviously an error crops up. You can add an extra check to your while loop before the int(readings) command like:
while readings != 0 | readings != '':
global count
readings = int(readings)
With a solution open, go to the Debug - Exceptions (Ctrl+D,E) menu option. From there you can choose to break on Thrown or User-unhandled exceptions.
EDIT: My instance is set up with the C# "profile" perhaps it isn't there for other profiles?
If you are using AndroidX, use below code to check Location Service is enabled or not:
fun isNetworkServiceEnabled(context: Context) = LocationManagerCompat.isLocationEnabled(context.getSystemService(LocationManager::class.java))
angular.module('app').directive('conversation', function() {
return {
restrict: 'E',
link: function ($scope, $elm, $attr) {
$scope.$watch("some_prop", function (newValue, oldValue) {
var typeId = $attr.type-id;
// Your logic.
});
}
};
}
You only need to do one thing. Run session_object.clear()
and then save the new object. This will clear the session (as aptly named) and remove the offending duplicate object from your session.
dplyr
solution using mutate_all
and pipessay you have the following:
> dft
Source: local data frame [11 x 5]
Bureau.Name Account.Code X2014 X2015 X2016
1 Senate 110 158,000 211,000 186,000
2 Senate 115 0 0 0
3 Senate 123 15,000 71,000 21,000
4 Senate 126 6,000 14,000 8,000
5 Senate 127 110,000 234,000 134,000
6 Senate 128 120,000 159,000 134,000
7 Senate 129 0 0 0
8 Senate 130 368,000 465,000 441,000
9 Senate 132 0 0 0
10 Senate 140 0 0 0
11 Senate 140 0 0 0
and want to remove commas from the year variables X2014-X2016, and convert them to numeric. also, let's say X2014-X2016 are read in as factors (default)
dft %>%
mutate_all(funs(as.character(.)), X2014:X2016) %>%
mutate_all(funs(gsub(",", "", .)), X2014:X2016) %>%
mutate_all(funs(as.numeric(.)), X2014:X2016)
mutate_all
applies the function(s) inside funs
to the specified columns
I did it sequentially, one function at a time (if you use multiple
functions inside funs
then you create additional, unnecessary columns)
https://github.com/stephenlb/geo-ip will generate a list of Valid IP Public Addresses including Localities.
'1.0.0.0/8'
to '191.0.0.0/8'
are the valid public IP Address range exclusive of the reserved Private IP Addresses as follows:
import iptools
## Private IP Addresses
private_ips = iptools.IpRangeList(
'0.0.0.0/8', '10.0.0.0/8', '100.64.0.0/10', '127.0.0.0/8',
'169.254.0.0/16', '172.16.0.0/12', '192.0.0.0/24', '192.0.2.0/24',
'192.88.99.0/24', '192.168.0.0/16', '198.18.0.0/15', '198.51.100.0/24',
'203.0.113.0/24', '224.0.0.0/4', '240.0.0.0/4', '255.255.255.255/32'
)
Generates a JSON dump of IP Addresses and associated Geo information.
Note that the valid public IP Address range is
from '1.0.0.0/8'
to '191.0.0.0/8'
excluding the reserved
Private IP Address ranges shown lower down in this readme.
docker build -t geo-ip .
docker run -e IPRANGE='54.0.0.0/30' geo-ip ## a few IPs
docker run -e IPRANGE='54.0.0.0/26' geo-ip ## a few more IPs
docker run -e IPRANGE='54.0.0.0/16' geo-ip ## a lot more IPs
docker run -e IPRANGE='0.0.0.0/0' geo-ip ## ALL IPs ( slooooowwwwww )
docker run -e IPRANGE='0.0.0.0/0' geo-ip > geo-ip.json ## ALL IPs saved to JSON File
docker run geo-ip
A little faster option for scanning all valid public addresses:
for i in $(seq 1 191); do \
docker run -e IPRANGE="$i.0.0.0/8" geo-ip; \
sleep 1; \
done
This prints less than 4,228,250,625 JSON lines to STDOUT. Here is an example of one of the lines:
{"city": "Palo Alto", "ip": "0.0.0.0", "longitude": -122.1274,
"continent": "North America", "continent_code": "NA",
"state": "California", "country": "United States", "latitude": 37.418,
"iso_code": "US", "state_code": "CA", "aso": "PubNub",
"asn": "11404", "zip_code": "94107"}
The dockerfile in the repo above will exclude non-usable IP addresses following the guide from the wikipedia article: https://en.wikipedia.org/wiki/Reserved_IP_addresses
The dockerfile imports a free public Database provided by https://www.maxmind.com/en/home
It doesn't work in IE5, but that's not a big issue.
However, cacheing headers are unreliable in meta elements; for one, any web proxies between the site and the user will completely ignore them. You should always use a real HTTP header for headers such as Cache-Control and Pragma.
If you are manually assembling the XML string use var.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss.fffffffZ"));
That will output the official XML Date Time format. But you don't have to worry about format if you use the built-in serialization methods.
If you have a nested dictionary, and you want this to work even for empty sub-elements, you can use a recursive variant of BrenBarn's suggestion:
def scrub_dict(d):
if type(d) is dict:
return dict((k, scrub_dict(v)) for k, v in d.iteritems() if v and scrub_dict(v))
else:
return d
If you are OK with using the numpy package, then you can do something like the following:
import numpy as np
lines = np.genfromtxt("coors.csv", delimiter=",", dtype=None)
my_dict = dict()
for i in range(len(lines)):
my_dict[lines[i][0]] = lines[i][1]
Follow these steps:
1. Generate an APNs Auth Key
Open the APNs Auth Key page in your Developer Center and click the + button to create a new APNs Auth Key.
In the next page, select Apple Push Notification Authentication Key (Sandbox & Production) and click Continue at the bottom of the page.
Apple will then generate a .p8
key file containing your APNs Auth Key.
Download the .p8
key file to your computer and save it for later. Also, be sure to write down the Key ID somewhere, as you'll need it later when connecting to APNs.
2. Send Push Notifications
Ref: APNS (Configure push notifications)
Important: Save a back up of your key in a secure place. It will not be presented again and cannot be retrieved later.
My own experience with this problem is as follows. Most Spring-related web pages and books seem to suggest that the most appropriate syntax is the following.
<mvc:resources mapping="/resources/**" location="/resources/" />
The above syntax suggests that you can place your static resources (CSS, JavaScript, images) in a folder named "resources" in the root of your application, i.e. /webapp/resources/.
However, in my experience (I am using Eclipse and the Tomcat plugin), the only approach that works is if you place your resources folder inside WEB_INF (or META-INF). So, the syntax I recommend is the following.
<mvc:resources mapping="/resources/**" location="/WEB-INF/resources/" />
In your JSP (or similar) , reference the resource as follows.
<script type="text/javascript"
src="resources/my-javascript.js">
</script>
Needless to mention, the entire question only arose because I wanted my Spring dispatcher servlet (front controller) to intercept everything, everything dynamic, that is. So I have the following in my web.xml.
<servlet>
<servlet-name>front-controller</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
<!-- spring automatically discovers /WEB-INF/<servlet-name>-servlet.xml -->
</servlet>
<servlet-mapping>
<servlet-name>front-controller</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
Finally, since I'm using current best practices, I have the following in my front controller servlet xml (see above).
<mvc:annotation-driven/>
And I have the following in my actual controller implementation, to ensure that I have a default method to handle all incoming requests.
@RequestMapping("/")
I hope this helps.
here is the automatic spin and rotating zoom effect using css3
#obj1{
float:right;
width: 96px;
height: 100px;
-webkit-animation: mymove 20s infinite; /* Chrome, Safari, Opera */
animation: mymove 20s infinite;
animation-delay:2s;
background-image:url("obj1.png");
transform: scale(1.5);
-moz-transform: scale(1.5);
-webkit-transform: scale(1.5);
-o-transform: scale(1.5);
-ms-transform: scale(1.5); /* IE 9 */
margin-bottom: 70px;
}
#obj2{
float:right;
width: 96px;
height: 100px;
-webkit-animation: mymove 20s infinite; /* Chrome, Safari, Opera */
animation: mymove 20s infinite;
animation-delay:2s;
background-image:url("obj2.png");
transform: scale(1.5);
-moz-transform: scale(1.5);
-webkit-transform: scale(1.5);
-o-transform: scale(1.5);
-ms-transform: scale(1.5); /* IE 9 */
margin-bottom: 70px;
}
#obj6{
float:right;
width: 96px;
height: 100px;
-webkit-animation: mymove 20s infinite; /* Chrome, Safari, Opera */
animation: mymove 20s infinite;
animation-delay:2s;
background-image:url("obj6.png");
transform: scale(1.5);
-moz-transform: scale(1.5);
-webkit-transform: scale(1.5);
-o-transform: scale(1.5);
-ms-transform: scale(1.5); /* IE 9 */
margin-bottom: 70px;
}
/* Standard syntax */
@keyframes mymove {
50% {transform: rotate(30deg);
}
<div style="width:100px; float:right; ">
<div id="obj2"></div><br /><br /><br />
<div id="obj6"></div><br /><br /><br />
<div id="obj1"></div><br /><br /><br />
</div>
Here is the demo
context.getPackageManager().getInstalledApplications(PackageManager.GET_META_DATA);
Should return the list of all the installed apps but in android 11 it'll only return the list of system apps. To get the list of all the applications(system+user) we need to provide an additional permission to the application i.e
<uses-permission android:name"android.permission.QUERY_ALL_PACKAGES">
I believe you can pass in event
into the function inline which will be the event
object for the raised event in W3C compliant browsers (i.e. older versions of IE will still require detection inside of your event handler function to look at window.event
).
function sayHi(e) {_x000D_
e.preventDefault();_x000D_
alert("hi");_x000D_
}
_x000D_
<a href="http://google.co.uk" onclick="sayHi(event);">Click to say Hi</a>
_x000D_
event
passed into the onclick
handler to something else like e
, click run, then notice that the redirection does take place after the alert (the result pane goes white, demonstrating a redirect).To support older version Space can be replaced with View as below. Add this view between after left most component and before right most component. This view with weight=1 will stretch and fill the space
<View
android:layout_width="0dp"
android:layout_height="20dp"
android:layout_weight="1" />
Complete sample code is given here. It has has 4 components. Two arrows will be on the right and left side. The Text and Spinner will be in the middle.
<ImageButton
android:id="@+id/btnGenesis"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|center_vertical"
android:layout_marginBottom="2dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="2dp"
android:background="@null"
android:gravity="left"
android:src="@drawable/prev" />
<View
android:layout_width="0dp"
android:layout_height="20dp"
android:layout_weight="1" />
<TextView
android:id="@+id/lblVerseHeading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center"
android:textSize="25sp" />
<Spinner
android:id="@+id/spinnerVerses"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:gravity="center"
android:textSize="25sp" />
<View
android:layout_width="0dp"
android:layout_height="20dp"
android:layout_weight="1" />
<ImageButton
android:id="@+id/btnExodus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center|center_vertical"
android:layout_marginBottom="2dp"
android:layout_marginLeft="0dp"
android:layout_marginTop="2dp"
android:background="@null"
android:gravity="right"
android:src="@drawable/next" />
</LinearLayout>
As has already been mentioned, if you control the server side then it should be possible to send the initial request headers back to the client in the initial response.
In Express, for example, the following works:
app.get('/somepage', (req, res) => {
res.render('somepage.hbs', {headers: req.headers});
})
The headers are then available within the template, so could be hidden visually but included in the markup and read by clientside javascript.
You can create simple float-based forms without having to lose your liquid layout. For example:
<style type="text/css">
.row { clear: left; padding: 6px; }
.row label { float: left; width: 10em; }
.row .field { display: block; margin-left: 10em; }
.row .field input, .row .field select {
width: 100%;
box-sizing: border-box;
-moz-box-sizing: border-box; -webkit-box-sizing: border-box; -khtml-box-sizing: border-box;
}
</style>
<div class="row">
<label for="f-firstname">First name</label>
<span class="field"><input name="firstname" id="f-firstname" value="Bob" /></span>
</div>
<div class="row">
<label for="f-state">State</label>
<span class="field"><select name="state" id="f-state">
<option value="NY">NY</option>
</select></span>
</div>
This does tend to break down, though, when you have complex form layouts where there's a grid of multiple fixed and flexible width columns. At that point you have to decide whether to stick with divs and abandon liquid layout in favour of just dropping everything into fixed pixel positions, or let tables do it.
For me personally, liquid layout is a more important usability feature than the exact elements used to lay out the form, so I usually go for tables.
It means that the access takes constant time i.e. does not depend on the size of the dataset. O(n) means that the access will depend on the size of the dataset linearly.
The O is also known as big-O.
Try jamspell - it works pretty well for automatic spelling correction:
import jamspell
corrector = jamspell.TSpellCorrector()
corrector.LoadLangModel('en.bin')
corrector.FixFragment('Some sentnec with error')
# u'Some sentence with error'
corrector.GetCandidates(['Some', 'sentnec', 'with', 'error'], 1)
# ('sentence', 'senate', 'scented', 'sentinel')
EDIT (26/08/2017): The solution below works well with Angular2 and 4. I've updated it to contain a template variable and click handler and tested it with Angular 4.3.
For Angular4, ngComponentOutlet as described in Ophir's answer is a much better solution. But right now it does not support inputs & outputs yet. If [this PR](https://github.com/angular/angular/pull/15362] is accepted, it would be possible through the component instance returned by the create event.
ng-dynamic-component may be the best and simplest solution altogether, but I haven't tested that yet.
@Long Field's answer is spot on! Here's another (synchronous) example:
import {Compiler, Component, NgModule, OnInit, ViewChild,
ViewContainerRef} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
@Component({
selector: 'my-app',
template: `<h1>Dynamic template:</h1>
<div #container></div>`
})
export class App implements OnInit {
@ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
constructor(private compiler: Compiler) {}
ngOnInit() {
this.addComponent(
`<h4 (click)="increaseCounter()">
Click to increase: {{counter}}
`enter code here` </h4>`,
{
counter: 1,
increaseCounter: function () {
this.counter++;
}
}
);
}
private addComponent(template: string, properties?: any = {}) {
@Component({template})
class TemplateComponent {}
@NgModule({declarations: [TemplateComponent]})
class TemplateModule {}
const mod = this.compiler.compileModuleAndAllComponentsSync(TemplateModule);
const factory = mod.componentFactories.find((comp) =>
comp.componentType === TemplateComponent
);
const component = this.container.createComponent(factory);
Object.assign(component.instance, properties);
// If properties are changed at a later stage, the change detection
// may need to be triggered manually:
// component.changeDetectorRef.detectChanges();
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App ],
bootstrap: [ App ]
})
export class AppModule {}
Live at http://plnkr.co/edit/fdP9Oc.
Yes you can and actually, you should use StyleSheet.create
to create your styles.
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View
} from 'react-native';
class Header extends Component {
constructor(props){
super(props);
}
render() {
const { title, style } = this.props;
const { header, text } = defaultStyle;
const combineStyles = StyleSheet.flatten([header, style]);
return (
<View style={ combineStyles }>
<Text style={ text }>
{ title }
</Text>
</View>
);
}
}
const defaultStyle = StyleSheet.create({
header: {
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#fff',
height: 60,
paddingTop: 15,
shadowColor: '#000',
shadowOffset: { width: 0, height: 3 },
shadowOpacity: 0.4,
elevation: 2,
position: 'relative'
},
text: {
color: '#0d4220',
fontSize: 16
}
});
export default Header;
And then:
<Header title="HOME" style={ {backgroundColor: '#10f1f0'} } />
This should also work (even in SQL-Server 2005):
SELECT *
FROM dbo.MyTable
WHERE Created >= DATEADD(hh,23,DATEADD(day, DATEDIFF(day, 0, Created - 1), 0))
AND Created < DATEADD(hh,7,DATEADD(day, DATEDIFF(day, 0, Created), 0))
You can use Powermock for mocking the call. Like:
PowerMockito.mockStatic(System.class);
PowerMockito.when(System.getenv("MyEnvVariable")).thenReturn("DesiredValue");
You can also mock all the calls with:
PowerMockito.mockStatic(System.class);
PowerMockito.when(System.getenv(Mockito.anyString())).thenReturn(envVariable);
In addition to Idriss answer:
In CSS we write code as depicted bellow, in full length.
body{
width: 800px;
color: #ffffff;
}
body content{
width:750px;
background:#ffffff;
}
In SCSS we can shorten this code using a @mixin
so we don’t have to write color
and width
properties again and again. We can define this through a function, similarly to PHP or other languages.
$color: #ffffff;
$width: 800px;
@mixin body{
width: $width;
color: $color;
content{
width: $width;
background:$color;
}
}
In SASS however, the whole structure is visually quicker and cleaner than SCSS.
It seems that it doesn't support inline CSS currently.
$color: #ffffff
$width: 800px
$stack: Helvetica, sans-serif
body
width: $width
color: $color
font: 100% $stack
content
width: $width
background:$color
From the Apache Maven site
<project>
...
<repositories>
<repository>
<id>my-internal-site</id>
<url>http://myserver/repo</url>
</repository>
</repositories>
...
</project>
"The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml." - Apache Maven site - settings reference
<servers>
<server>
<id>server001</id>
<username>my_login</username>
<password>my_password</password>
<privateKey>${user.home}/.ssh/id_dsa</privateKey>
<passphrase>some_passphrase</passphrase>
<filePermissions>664</filePermissions>
<directoryPermissions>775</directoryPermissions>
<configuration></configuration>
</server>
</servers>
You should use the new HttpClient
. You can find more information here.
http
.get<any>('url', {observe: 'response'})
.subscribe(resp => {
console.log(resp.headers.get('X-Token'));
});
print datetime.utcnow().strftime('%Y%m%d%H%M%S%f')
http://docs.python.org/library/datetime.html#strftime-strptime-behavior
Test results for the 4 implementations
Having to do a lot of formatting for huge data, needed the best performance, so here are the (surprising) results:
for (int i = 0; i < 1000000; i++) { FUNCTION_CALL }
Durations:
formatTimeUnit: 2216 millis
public static String apacheFormat(long millis) throws ParseException {
return DurationFormatUtils.formatDuration(millis, "HH:mm:ss");
}
public static String formatTimeUnit(long millis) throws ParseException {
String formatted = String.format(
"%02d:%02d:%02d",
TimeUnit.MILLISECONDS.toHours(millis),
TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis)),
TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis)));
return formatted;
}
public static String formatDuration(final long millis) {
long seconds = (millis / 1000) % 60;
long minutes = (millis / (1000 * 60)) % 60;
long hours = millis / (1000 * 60 * 60);
StringBuilder b = new StringBuilder();
b.append(hours == 0 ? "00" : hours < 10 ? String.valueOf("0" + hours) :
String.valueOf(hours));
b.append(":");
b.append(minutes == 0 ? "00" : minutes < 10 ? String.valueOf("0" + minutes) :
String.valueOf(minutes));
b.append(":");
b.append(seconds == 0 ? "00" : seconds < 10 ? String.valueOf("0" + seconds) :
String.valueOf(seconds));
return b.toString();
}
public static String combinationFormatter(final long millis) {
long seconds = TimeUnit.MILLISECONDS.toSeconds(millis)
- TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(millis));
long minutes = TimeUnit.MILLISECONDS.toMinutes(millis)
- TimeUnit.HOURS.toMinutes(TimeUnit.MILLISECONDS.toHours(millis));
long hours = TimeUnit.MILLISECONDS.toHours(millis);
StringBuilder b = new StringBuilder();
b.append(hours == 0 ? "00" : hours < 10 ? String.valueOf("0" + hours) :
String.valueOf(hours));
b.append(":");
b.append(minutes == 0 ? "00" : minutes < 10 ? String.valueOf("0" + minutes) :
String.valueOf(minutes));
b.append(":");
b.append(seconds == 0 ? "00" : seconds < 10 ? String.valueOf("0" + seconds) :
String.valueOf(seconds));
return b.toString();
}
The Error is here
lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1
wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this
lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1
Similarly
wsPOR.Range("A2:G" & lastrow).Select
should be
wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select
I was searching for a way to bind to multiple key events - specifically, Shift+Enter - but couldn't find any good resources online. But after logging the keydown binding
<textarea (keydown)=onKeydownEvent($event)></textarea>
I discovered that the keyboard event provided all of the information I needed to detect Shift+Enter. Turns out that $event
returns a fairly detailed KeyboardEvent.
onKeydownEvent(event: KeyboardEvent): void {
if (event.keyCode === 13 && event.shiftKey) {
// On 'Shift+Enter' do this...
}
}
There also flags for the CtrlKey, AltKey, and MetaKey (i.e. Command key on Mac).
No need for the KeyEventsPlugin, JQuery, or a pure JS binding.
It may be possible that there is no other application running. It is possible that the socket wasn't cleanly shutdown from a previous session in which case you may have to wait for a while before the TIME_WAIT expires on that socket. Unfortunately, you won't be able to use the port till that socket expires. If you can start your server after waiting for a while (a few minutes) then the problem is not due to some other application running on port 8080.
I just got this error and it turns out my AD administrator deleted the service account used by EVERY SQL Server instance in the entire company. Thank goodness AD has its own recycle bin.
See if you can run the Active Directory Users and Computers utility (%SystemRoot%\system32\dsa.msc), and check to make sure the account you are relying on still exists.
You can always read the image file as grayscale right from the beginning using imread
from OpenCV:
img = cv2.imread('messi5.jpg', 0)
Furthermore, in case you want to read the image as RGB, do some processing and then convert to Gray Scale you could use cvtcolor
from OpenCV:
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
You can take update / pull on git branch you can use below command
git pull origin <branch-name>
The above command will take an update/pull from giving branch name
If you want to take pull from another branch, you need to go to that branch.
git checkout master
Than
git pull origin development
Hope that will work for you
.toLowerCase function only exists on strings. You can call toString() on anything in javascript to get a string representation. Putting this all together:
var ans = 334;
var temp = ans.toString().toLowerCase();
alert(temp);
The reason why the Set interface doesn't have a get index-type call or even something even more basic, such as first() or last(), is because it is an ambiguous operation, and therefore a potentially dangerous operation. If a method returns a Set, and you call, say first() method on it, what is the expected result, given that the a generic Set makes no guarantees on the ordering? The resultant object could very well vary between each call of the method, or it might not and lull you into a false sense of security, until the library you're using changes changes the implementation underneath and now you find that all your code breaks for no particular reason.
The suggestions about workarounds listed here are good. If you need indexed access, use a list. Be careful with using iterators or toArray with a generic Set, because a) there is no guarantee on the ordering and b) there is no guarantee that the ordering will not change with subsequent invocations or with different underlying implementations. If you need something in between, a SortedSet or a LinkedHashSet is what you want.
// I do wish the Set interface had a get-random-element though.
section {
position: relative;
width: 50%;
border: 1px solid;
}
h1 {
display: inline;
}
div {
position: relative;
float:right;
top: 0;
right: 0;
}
I can't believe javascript isn't more consistent with parsing dates. And I hear the default when there is no timezone is gonna change from UTC to local -- hope the web is prepared ;)
I prefer to let Javascript do the heavy lifting when it comes to parsing dates. However it would be nice to handle the local timezone issue fairly transparently. With both of these things in mind, here is a function to do it with the current status quo -- and when Javascript changes it will still work but then can be removed (with a little time for people to catch up with older browsers/nodejs of course).
function strToDate(dateStr)
{
var dateTry = new Date(dateStr);
if (!dateTry.getTime())
{
throw new Exception("Bad Date! dateStr: " + dateStr);
}
var tz = dateStr.trim().match(/(Z)|([+-](\d{2})\:?(\d{2}))$/);
if (!tz)
{
var newTzOffset = dateTry.getTimezoneOffset() / 60;
var newSignStr = (newTzOffset >= 0) ? '-' : '+';
var newTz = newSignStr + ('0' + Math.abs(newTzOffset)).slice(-2) + ':00';
dateStr = dateStr.trim() + newTz;
dateTry = new Date(dateStr);
if (!dateTry.getTime())
{
throw new Exception("Bad Date! dateStr: " + dateStr);
}
}
return dateTry;
}
We need a date object regardless; so createone. If there is a timezone, we are done. Otherwise, create a local timezone string using the +hh:mm format (more accepted than +hhmm).
Tables work differently; sometimes counter-intuitively.
The solution is to use width
on the table cells instead of max-width
.
Although it may sound like in that case the cells won't shrink below the given width, they will actually.
with no restrictions on c, if you give the table a width of 70px, the widths of a, b and c will come out as 16, 42 and 12 pixels, respectively.
With a table width of 400 pixels, they behave like you say you expect in your grid above.
Only when you try to give the table too small a size (smaller than a.min+b.min+the content of C) will it fail: then the table itself will be wider than specified.
I made a snippet based on your fiddle, in which I removed all the borders and paddings and border-spacing, so you can measure the widths more accurately.
table {_x000D_
width: 70px;_x000D_
}_x000D_
_x000D_
table, tbody, tr, td {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
border: 0;_x000D_
border-spacing: 0;_x000D_
}_x000D_
_x000D_
.a, .c {_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
.b {_x000D_
background-color: #F77;_x000D_
}_x000D_
_x000D_
.a {_x000D_
min-width: 10px;_x000D_
width: 20px;_x000D_
max-width: 20px;_x000D_
}_x000D_
_x000D_
.b {_x000D_
min-width: 40px;_x000D_
width: 45px;_x000D_
max-width: 45px;_x000D_
}_x000D_
_x000D_
.c {}
_x000D_
<table>_x000D_
<tr>_x000D_
<td class="a">A</td>_x000D_
<td class="b">B</td>_x000D_
<td class="c">C</td>_x000D_
</tr>_x000D_
</table>
_x000D_
Mainly two reasons:
One
Like others have said, You might get keys which aren't in your array or that are inherited from the prototype. So if, let's say, a library adds a property to the Array or Object prototypes:
Array.prototype.someProperty = true
You'll get it as part of every array:
for(var item in [1,2,3]){
console.log(item) // will log 1,2,3 but also "someProperty"
}
you could solve this with the hasOwnProperty method:
var ary = [1,2,3];
for(var item in ary){
if(ary.hasOwnProperty(item)){
console.log(item) // will log only 1,2,3
}
}
but this is true for iterating over any object with a for-in loop.
Two
Usually the order of the items in an array is important, but the for-in loop won't necessarily iterate in the right order, that's because it treats the array as an object, which is the way it is implemented in JS, and not as an array. This seems like a small thing, but it can really screw up applications and is hard to debug.
You could do something using the grep command:
find . | grep -v '(dll|exe)$'
The -v
flag on grep
specifically means "find things that don't match this expression."
Create a breakpoint as you normally would, right click the red dot and select "condition".
You may want to comment out the DL is deprecated, please use Fiddle
warning at
C:\Ruby200\lib\ruby\2.0.0\dl.rb
since it’s annoying and you are not the irb/pry or some other gems code owner
you need to use YYYY-MM-DD format to insert date in mysql
I believe this is the simplest way of putting all what it is on the screen into a file. It is a native PS CmdLet so you don't have to change anything in yout script
Start-Transcript -Path Computer.log
Write-Host "everything will end up in Computer.log"
Stop-Transcript
You do see for loops alot of the time, but they are usually not needed. Here is an example of how one might perform a for loop without resorting to the shell
LIST_OF_THINGS_TO_DO = do_this do_that
$(LIST_OF_THINGS_TO_DO):
run $@ > [email protected]
SUBDIRS = snafu fubar
$(SUBDIRS):
cd $@ && $(MAKE)
With array_intersect_key
and array_flip
:
var_dump(array_intersect_key($my_array, array_flip($allowed)));
array(1) {
["foo"]=>
int(1)
}
List of entire available timezones.
$time_zones = array (
0 => 'Africa/Abidjan',
1 => 'Africa/Accra',
2 => 'Africa/Addis_Ababa',
3 => 'Africa/Algiers',
4 => 'Africa/Asmara',
5 => 'Africa/Asmera',
6 => 'Africa/Bamako',
7 => 'Africa/Bangui',
8 => 'Africa/Banjul',
9 => 'Africa/Bissau',
10 => 'Africa/Blantyre',
11 => 'Africa/Brazzaville',
12 => 'Africa/Bujumbura',
13 => 'Africa/Cairo',
14 => 'Africa/Casablanca',
15 => 'Africa/Ceuta',
16 => 'Africa/Conakry',
17 => 'Africa/Dakar',
18 => 'Africa/Dar_es_Salaam',
19 => 'Africa/Djibouti',
20 => 'Africa/Douala',
21 => 'Africa/El_Aaiun',
22 => 'Africa/Freetown',
23 => 'Africa/Gaborone',
24 => 'Africa/Harare',
25 => 'Africa/Johannesburg',
26 => 'Africa/Juba',
27 => 'Africa/Kampala',
28 => 'Africa/Khartoum',
29 => 'Africa/Kigali',
30 => 'Africa/Kinshasa',
31 => 'Africa/Lagos',
32 => 'Africa/Libreville',
33 => 'Africa/Lome',
34 => 'Africa/Luanda',
35 => 'Africa/Lubumbashi',
36 => 'Africa/Lusaka',
37 => 'Africa/Malabo',
38 => 'Africa/Maputo',
39 => 'Africa/Maseru',
40 => 'Africa/Mbabane',
41 => 'Africa/Mogadishu',
42 => 'Africa/Monrovia',
43 => 'Africa/Nairobi',
44 => 'Africa/Ndjamena',
45 => 'Africa/Niamey',
46 => 'Africa/Nouakchott',
47 => 'Africa/Ouagadougou',
48 => 'Africa/Porto-Novo',
49 => 'Africa/Sao_Tome',
50 => 'Africa/Timbuktu',
51 => 'Africa/Tripoli',
52 => 'Africa/Tunis',
53 => 'Africa/Windhoek',
54 => 'America/Adak',
55 => 'America/Anchorage',
56 => 'America/Anguilla',
57 => 'America/Antigua',
58 => 'America/Araguaina',
59 => 'America/Argentina/Buenos_Aires',
60 => 'America/Argentina/Catamarca',
61 => 'America/Argentina/ComodRivadavia',
62 => 'America/Argentina/Cordoba',
63 => 'America/Argentina/Jujuy',
64 => 'America/Argentina/La_Rioja',
65 => 'America/Argentina/Mendoza',
66 => 'America/Argentina/Rio_Gallegos',
67 => 'America/Argentina/Salta',
68 => 'America/Argentina/San_Juan',
69 => 'America/Argentina/San_Luis',
70 => 'America/Argentina/Tucuman',
71 => 'America/Argentina/Ushuaia',
72 => 'America/Aruba',
73 => 'America/Asuncion',
74 => 'America/Atikokan',
75 => 'America/Atka',
76 => 'America/Bahia',
77 => 'America/Bahia_Banderas',
78 => 'America/Barbados',
79 => 'America/Belem',
80 => 'America/Belize',
81 => 'America/Blanc-Sablon',
82 => 'America/Boa_Vista',
83 => 'America/Bogota',
84 => 'America/Boise',
85 => 'America/Buenos_Aires',
86 => 'America/Cambridge_Bay',
87 => 'America/Campo_Grande',
88 => 'America/Cancun',
89 => 'America/Caracas',
90 => 'America/Catamarca',
91 => 'America/Cayenne',
92 => 'America/Cayman',
93 => 'America/Chicago',
94 => 'America/Chihuahua',
95 => 'America/Coral_Harbour',
96 => 'America/Cordoba',
97 => 'America/Costa_Rica',
98 => 'America/Creston',
99 => 'America/Cuiaba',
100 => 'America/Curacao',
101 => 'America/Danmarkshavn',
102 => 'America/Dawson',
103 => 'America/Dawson_Creek',
104 => 'America/Denver',
105 => 'America/Detroit',
106 => 'America/Dominica',
107 => 'America/Edmonton',
108 => 'America/Eirunepe',
109 => 'America/El_Salvador',
110 => 'America/Ensenada',
111 => 'America/Fort_Nelson',
112 => 'America/Fort_Wayne',
113 => 'America/Fortaleza',
114 => 'America/Glace_Bay',
115 => 'America/Godthab',
116 => 'America/Goose_Bay',
117 => 'America/Grand_Turk',
118 => 'America/Grenada',
119 => 'America/Guadeloupe',
120 => 'America/Guatemala',
121 => 'America/Guayaquil',
122 => 'America/Guyana',
123 => 'America/Halifax',
124 => 'America/Havana',
125 => 'America/Hermosillo',
126 => 'America/Indiana/Indianapolis',
127 => 'America/Indiana/Knox',
128 => 'America/Indiana/Marengo',
129 => 'America/Indiana/Petersburg',
130 => 'America/Indiana/Tell_City',
131 => 'America/Indiana/Vevay',
132 => 'America/Indiana/Vincennes',
133 => 'America/Indiana/Winamac',
134 => 'America/Indianapolis',
135 => 'America/Inuvik',
136 => 'America/Iqaluit',
137 => 'America/Jamaica',
138 => 'America/Jujuy',
139 => 'America/Juneau',
140 => 'America/Kentucky/Louisville',
141 => 'America/Kentucky/Monticello',
142 => 'America/Knox_IN',
143 => 'America/Kralendijk',
144 => 'America/La_Paz',
145 => 'America/Lima',
146 => 'America/Los_Angeles',
147 => 'America/Louisville',
148 => 'America/Lower_Princes',
149 => 'America/Maceio',
150 => 'America/Managua',
151 => 'America/Manaus',
152 => 'America/Marigot',
153 => 'America/Martinique',
154 => 'America/Matamoros',
155 => 'America/Mazatlan',
156 => 'America/Mendoza',
157 => 'America/Menominee',
158 => 'America/Merida',
159 => 'America/Metlakatla',
160 => 'America/Mexico_City',
161 => 'America/Miquelon',
162 => 'America/Moncton',
163 => 'America/Monterrey',
164 => 'America/Montevideo',
165 => 'America/Montreal',
166 => 'America/Montserrat',
167 => 'America/Nassau',
168 => 'America/New_York',
169 => 'America/Nipigon',
170 => 'America/Nome',
171 => 'America/Noronha',
172 => 'America/North_Dakota/Beulah',
173 => 'America/North_Dakota/Center',
174 => 'America/North_Dakota/New_Salem',
175 => 'America/Ojinaga',
176 => 'America/Panama',
177 => 'America/Pangnirtung',
178 => 'America/Paramaribo',
179 => 'America/Phoenix',
180 => 'America/Port-au-Prince',
181 => 'America/Port_of_Spain',
182 => 'America/Porto_Acre',
183 => 'America/Porto_Velho',
184 => 'America/Puerto_Rico',
185 => 'America/Rainy_River',
186 => 'America/Rankin_Inlet',
187 => 'America/Recife',
188 => 'America/Regina',
189 => 'America/Resolute',
190 => 'America/Rio_Branco',
191 => 'America/Rosario',
192 => 'America/Santa_Isabel',
193 => 'America/Santarem',
194 => 'America/Santiago',
195 => 'America/Santo_Domingo',
196 => 'America/Sao_Paulo',
197 => 'America/Scoresbysund',
198 => 'America/Shiprock',
199 => 'America/Sitka',
200 => 'America/St_Barthelemy',
201 => 'America/St_Johns',
202 => 'America/St_Kitts',
203 => 'America/St_Lucia',
204 => 'America/St_Thomas',
205 => 'America/St_Vincent',
206 => 'America/Swift_Current',
207 => 'America/Tegucigalpa',
208 => 'America/Thule',
209 => 'America/Thunder_Bay',
210 => 'America/Tijuana',
211 => 'America/Toronto',
212 => 'America/Tortola',
213 => 'America/Vancouver',
214 => 'America/Virgin',
215 => 'America/Whitehorse',
216 => 'America/Winnipeg',
217 => 'America/Yakutat',
218 => 'America/Yellowknife',
219 => 'Antarctica/Casey',
220 => 'Antarctica/Davis',
221 => 'Antarctica/DumontDUrville',
222 => 'Antarctica/Macquarie',
223 => 'Antarctica/Mawson',
224 => 'Antarctica/McMurdo',
225 => 'Antarctica/Palmer',
226 => 'Antarctica/Rothera',
227 => 'Antarctica/South_Pole',
228 => 'Antarctica/Syowa',
229 => 'Antarctica/Troll',
230 => 'Antarctica/Vostok',
231 => 'Arctic/Longyearbyen',
232 => 'Asia/Aden',
233 => 'Asia/Almaty',
234 => 'Asia/Amman',
235 => 'Asia/Anadyr',
236 => 'Asia/Aqtau',
237 => 'Asia/Aqtobe',
238 => 'Asia/Ashgabat',
239 => 'Asia/Ashkhabad',
240 => 'Asia/Baghdad',
241 => 'Asia/Bahrain',
242 => 'Asia/Baku',
243 => 'Asia/Bangkok',
244 => 'Asia/Beirut',
245 => 'Asia/Bishkek',
246 => 'Asia/Brunei',
247 => 'Asia/Calcutta',
248 => 'Asia/Chita',
249 => 'Asia/Choibalsan',
250 => 'Asia/Chongqing',
251 => 'Asia/Chungking',
252 => 'Asia/Colombo',
253 => 'Asia/Dacca',
254 => 'Asia/Damascus',
255 => 'Asia/Dhaka',
256 => 'Asia/Dili',
257 => 'Asia/Dubai',
258 => 'Asia/Dushanbe',
259 => 'Asia/Gaza',
260 => 'Asia/Harbin',
261 => 'Asia/Hebron',
262 => 'Asia/Ho_Chi_Minh',
263 => 'Asia/Hong_Kong',
264 => 'Asia/Hovd',
265 => 'Asia/Irkutsk',
266 => 'Asia/Istanbul',
267 => 'Asia/Jakarta',
268 => 'Asia/Jayapura',
269 => 'Asia/Jerusalem',
270 => 'Asia/Kabul',
271 => 'Asia/Kamchatka',
272 => 'Asia/Karachi',
273 => 'Asia/Kashgar',
274 => 'Asia/Kathmandu',
275 => 'Asia/Katmandu',
276 => 'Asia/Khandyga',
277 => 'Asia/Kolkata',
278 => 'Asia/Krasnoyarsk',
279 => 'Asia/Kuala_Lumpur',
280 => 'Asia/Kuching',
281 => 'Asia/Kuwait',
282 => 'Asia/Macao',
283 => 'Asia/Macau',
284 => 'Asia/Magadan',
285 => 'Asia/Makassar',
286 => 'Asia/Manila',
287 => 'Asia/Muscat',
288 => 'Asia/Nicosia',
289 => 'Asia/Novokuznetsk',
290 => 'Asia/Novosibirsk',
291 => 'Asia/Omsk',
292 => 'Asia/Oral',
293 => 'Asia/Phnom_Penh',
294 => 'Asia/Pontianak',
295 => 'Asia/Pyongyang',
296 => 'Asia/Qatar',
297 => 'Asia/Qyzylorda',
298 => 'Asia/Rangoon',
299 => 'Asia/Riyadh',
300 => 'Asia/Saigon',
301 => 'Asia/Sakhalin',
302 => 'Asia/Samarkand',
303 => 'Asia/Seoul',
304 => 'Asia/Shanghai',
305 => 'Asia/Singapore',
306 => 'Asia/Srednekolymsk',
307 => 'Asia/Taipei',
308 => 'Asia/Tashkent',
309 => 'Asia/Tbilisi',
310 => 'Asia/Tehran',
311 => 'Asia/Tel_Aviv',
312 => 'Asia/Thimbu',
313 => 'Asia/Thimphu',
314 => 'Asia/Tokyo',
315 => 'Asia/Ujung_Pandang',
316 => 'Asia/Ulaanbaatar',
317 => 'Asia/Ulan_Bator',
318 => 'Asia/Urumqi',
319 => 'Asia/Ust-Nera',
320 => 'Asia/Vientiane',
321 => 'Asia/Vladivostok',
322 => 'Asia/Yakutsk',
323 => 'Asia/Yekaterinburg',
324 => 'Asia/Yerevan',
325 => 'Atlantic/Azores',
326 => 'Atlantic/Bermuda',
327 => 'Atlantic/Canary',
328 => 'Atlantic/Cape_Verde',
329 => 'Atlantic/Faeroe',
330 => 'Atlantic/Faroe',
331 => 'Atlantic/Jan_Mayen',
332 => 'Atlantic/Madeira',
333 => 'Atlantic/Reykjavik',
334 => 'Atlantic/South_Georgia',
335 => 'Atlantic/St_Helena',
336 => 'Atlantic/Stanley',
337 => 'Australia/ACT',
338 => 'Australia/Adelaide',
339 => 'Australia/Brisbane',
340 => 'Australia/Broken_Hill',
341 => 'Australia/Canberra',
342 => 'Australia/Currie',
343 => 'Australia/Darwin',
344 => 'Australia/Eucla',
345 => 'Australia/Hobart',
346 => 'Australia/LHI',
347 => 'Australia/Lindeman',
348 => 'Australia/Lord_Howe',
349 => 'Australia/Melbourne',
350 => 'Australia/North',
351 => 'Australia/NSW',
352 => 'Australia/Perth',
353 => 'Australia/Queensland',
354 => 'Australia/South',
355 => 'Australia/Sydney',
356 => 'Australia/Tasmania',
357 => 'Australia/Victoria',
358 => 'Australia/West',
359 => 'Australia/Yancowinna',
360 => 'Europe/Amsterdam',
361 => 'Europe/Andorra',
362 => 'Europe/Athens',
363 => 'Europe/Belfast',
364 => 'Europe/Belgrade',
365 => 'Europe/Berlin',
366 => 'Europe/Bratislava',
367 => 'Europe/Brussels',
368 => 'Europe/Bucharest',
369 => 'Europe/Budapest',
370 => 'Europe/Busingen',
371 => 'Europe/Chisinau',
372 => 'Europe/Copenhagen',
373 => 'Europe/Dublin',
374 => 'Europe/Gibraltar',
375 => 'Europe/Guernsey',
376 => 'Europe/Helsinki',
377 => 'Europe/Isle_of_Man',
378 => 'Europe/Istanbul',
379 => 'Europe/Jersey',
380 => 'Europe/Kaliningrad',
381 => 'Europe/Kiev',
382 => 'Europe/Lisbon',
383 => 'Europe/Ljubljana',
384 => 'Europe/London',
385 => 'Europe/Luxembourg',
386 => 'Europe/Madrid',
387 => 'Europe/Malta',
388 => 'Europe/Mariehamn',
389 => 'Europe/Minsk',
390 => 'Europe/Monaco',
391 => 'Europe/Moscow',
392 => 'Europe/Nicosia',
393 => 'Europe/Oslo',
394 => 'Europe/Paris',
395 => 'Europe/Podgorica',
396 => 'Europe/Prague',
397 => 'Europe/Riga',
398 => 'Europe/Rome',
399 => 'Europe/Samara',
400 => 'Europe/San_Marino',
401 => 'Europe/Sarajevo',
402 => 'Europe/Simferopol',
403 => 'Europe/Skopje',
404 => 'Europe/Sofia',
405 => 'Europe/Stockholm',
406 => 'Europe/Tallinn',
407 => 'Europe/Tirane',
408 => 'Europe/Tiraspol',
409 => 'Europe/Uzhgorod',
410 => 'Europe/Vaduz',
411 => 'Europe/Vatican',
412 => 'Europe/Vienna',
413 => 'Europe/Vilnius',
414 => 'Europe/Volgograd',
415 => 'Europe/Warsaw',
416 => 'Europe/Zagreb',
417 => 'Europe/Zaporozhye',
418 => 'Europe/Zurich',
419 => 'Indian/Antananarivo',
420 => 'Indian/Chagos',
421 => 'Indian/Christmas',
422 => 'Indian/Cocos',
423 => 'Indian/Comoro',
424 => 'Indian/Kerguelen',
425 => 'Indian/Mahe',
426 => 'Indian/Maldives',
427 => 'Indian/Mauritius',
428 => 'Indian/Mayotte',
429 => 'Indian/Reunion',
430 => 'Pacific/Apia',
431 => 'Pacific/Auckland',
432 => 'Pacific/Bougainville',
433 => 'Pacific/Chatham',
434 => 'Pacific/Chuuk',
435 => 'Pacific/Easter',
436 => 'Pacific/Efate',
437 => 'Pacific/Enderbury',
438 => 'Pacific/Fakaofo',
439 => 'Pacific/Fiji',
440 => 'Pacific/Funafuti',
441 => 'Pacific/Galapagos',
442 => 'Pacific/Gambier',
443 => 'Pacific/Guadalcanal',
444 => 'Pacific/Guam',
445 => 'Pacific/Honolulu',
446 => 'Pacific/Johnston',
447 => 'Pacific/Kiritimati',
448 => 'Pacific/Kosrae',
449 => 'Pacific/Kwajalein',
450 => 'Pacific/Majuro',
451 => 'Pacific/Marquesas',
452 => 'Pacific/Midway',
453 => 'Pacific/Nauru',
454 => 'Pacific/Niue',
455 => 'Pacific/Norfolk',
456 => 'Pacific/Noumea',
457 => 'Pacific/Pago_Pago',
458 => 'Pacific/Palau',
459 => 'Pacific/Pitcairn',
460 => 'Pacific/Pohnpei',
461 => 'Pacific/Ponape',
462 => 'Pacific/Port_Moresby',
463 => 'Pacific/Rarotonga',
464 => 'Pacific/Saipan',
465 => 'Pacific/Samoa',
466 => 'Pacific/Tahiti',
467 => 'Pacific/Tarawa',
468 => 'Pacific/Tongatapu',
469 => 'Pacific/Truk',
470 => 'Pacific/Wake',
471 => 'Pacific/Wallis',
472 => 'Pacific/Yap',
473 => 'Brazil/Acre',
474 => 'Brazil/DeNoronha',
475 => 'Brazil/East',
476 => 'Brazil/West',
477 => 'Canada/Atlantic',
478 => 'Canada/Central',
479 => 'Canada/East-Saskatchewan',
480 => 'Canada/Eastern',
481 => 'Canada/Mountain',
482 => 'Canada/Newfoundland',
483 => 'Canada/Pacific',
484 => 'Canada/Saskatchewan',
485 => 'Canada/Yukon',
486 => 'CET',
487 => 'Chile/Continental',
488 => 'Chile/EasterIsland',
489 => 'CST6CDT',
490 => 'Cuba',
491 => 'EET',
492 => 'Egypt',
493 => 'Eire',
494 => 'EST',
495 => 'EST5EDT',
496 => 'Etc/GMT',
497 => 'Etc/GMT+0',
498 => 'Etc/GMT+1',
499 => 'Etc/GMT+10',
500 => 'Etc/GMT+11',
501 => 'Etc/GMT+12',
502 => 'Etc/GMT+2',
503 => 'Etc/GMT+3',
504 => 'Etc/GMT+4',
505 => 'Etc/GMT+5',
506 => 'Etc/GMT+6',
507 => 'Etc/GMT+7',
508 => 'Etc/GMT+8',
509 => 'Etc/GMT+9',
510 => 'Etc/GMT-0',
511 => 'Etc/GMT-1',
512 => 'Etc/GMT-10',
513 => 'Etc/GMT-11',
514 => 'Etc/GMT-12',
515 => 'Etc/GMT-13',
516 => 'Etc/GMT-14',
517 => 'Etc/GMT-2',
518 => 'Etc/GMT-3',
519 => 'Etc/GMT-4',
520 => 'Etc/GMT-5',
521 => 'Etc/GMT-6',
522 => 'Etc/GMT-7',
523 => 'Etc/GMT-8',
524 => 'Etc/GMT-9',
525 => 'Etc/GMT0',
526 => 'Etc/Greenwich',
527 => 'Etc/UCT',
528 => 'Etc/Universal',
529 => 'Etc/UTC',
530 => 'Etc/Zulu',
531 => 'Factory',
532 => 'GB',
533 => 'GB-Eire',
534 => 'GMT',
535 => 'GMT+0',
536 => 'GMT-0',
537 => 'GMT0',
538 => 'Greenwich',
539 => 'Hongkong',
540 => 'HST',
541 => 'Iceland',
542 => 'Iran',
543 => 'Israel',
544 => 'Jamaica',
545 => 'Japan',
546 => 'Kwajalein',
547 => 'Libya',
548 => 'MET',
549 => 'Mexico/BajaNorte',
550 => 'Mexico/BajaSur',
551 => 'Mexico/General',
552 => 'MST',
553 => 'MST7MDT',
554 => 'Navajo',
555 => 'NZ',
556 => 'NZ-CHAT',
557 => 'Poland',
558 => 'Portugal',
559 => 'PRC',
560 => 'PST8PDT',
561 => 'ROC',
562 => 'ROK',
563 => 'Singapore',
564 => 'Turkey',
565 => 'UCT',
566 => 'Universal',
567 => 'US/Alaska',
568 => 'US/Aleutian',
569 => 'US/Arizona',
570 => 'US/Central',
571 => 'US/East-Indiana',
572 => 'US/Eastern',
573 => 'US/Hawaii',
574 => 'US/Indiana-Starke',
575 => 'US/Michigan',
576 => 'US/Mountain',
577 => 'US/Pacific',
578 => 'US/Pacific-New',
579 => 'US/Samoa',
580 => 'UTC',
581 => 'W-SU',
582 => 'WET',
583 => 'Zulu',
)
Floating will result in wrapping if space is not available.
You can use display:inline
and white-space:nowrap
to achieve this. Fiddle
<div id="container" style="white-space:nowrap">
<div id="image" style="display:inline;">
<img src="tree.png"/>
</div>
<div id="texts" style="display:inline; white-space:nowrap;">
A very long text(about 300 words)
</div>
</div>?
It seems that Go have special form of switch dedicate to this (it is called type switch):
func (e *Easy)SetOption(option Option, param interface{}) {
switch v := param.(type) {
default:
fmt.Printf("unexpected type %T", v)
case uint64:
e.code = Code(C.curl_wrapper_easy_setopt_long(e.curl, C.CURLoption(option), C.long(v)))
case string:
e.code = Code(C.curl_wrapper_easy_setopt_str(e.curl, C.CURLoption(option), C.CString(v)))
}
}
Assuming input of
{Anything}id={ID}{space}{Anything}
{Anything}id={ID}{space}{Anything}
--
#! /bin/sh
while read s; do
rhs=${s##*id=}
id=${rhs%% *}
echo $id # Do what you will with $id here
done <so.txt
Or if it's always the 7th field
#! /bin/sh
while read f1 f2 f3 f4 f5 f6 f7 rest
do
echo ${f7##id=}
done <so.txt
See Also
To add to existing answer - related name is a must in case there 2 FKs in the model that point to the same table. For example in case of Bill of material
@with_author
class BOM(models.Model):
name = models.CharField(max_length=200,null=True, blank=True)
description = models.TextField(null=True, blank=True)
tomaterial = models.ForeignKey(Material, related_name = 'tomaterial')
frommaterial = models.ForeignKey(Material, related_name = 'frommaterial')
creation_time = models.DateTimeField(auto_now_add=True, blank=True)
quantity = models.DecimalField(max_digits=19, decimal_places=10)
So when you will have to access this data you only can use related name
bom = material.tomaterial.all().order_by('-creation_time')
It is not working otherwise (at least I was not able to skip the usage of related name in case of 2 FK's to the same table.)
You can use a span tag inside the label
<div class="form-group">
<label for="rg-from">
<span>Ab:</span>
<input type="text" id="rg-from" name="rg-from" value="" class="form-control">
</label>
</div>
A solution, can be:
with open("file", "r") as fd:
lines = fd.read().splitlines()
You get the list of lines without "\r\n" or "\n".
Or, use the classic way:
with open("file", "r") as fd:
for line in fd:
line = line.strip()
You read the file, line by line and drop the spaces and newlines.
If you only want to drop the newlines:
with open("file", "r") as fd:
for line in fd:
line = line.replace("\r", "").replace("\n", "")
Et voilà.
Note: The behavior of Python 3 is a little different. To mimic this behavior, use io.open
.
See the documentation of io.open.
So, you can use:
with io.open("file", "r", newline=None) as fd:
for line in fd:
line = line.replace("\n", "")
When the newline parameter is None
: lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n'.
newline controls how universal newlines works (it only applies to text mode). It can be None, '', '\n', '\r', and '\r\n'. It works as follows:
On input, if newline is None, universal newlines mode is enabled. Lines in the input can end in '\n', '\r', or '\r\n', and these are translated into '\n' before being returned to the caller. If it is '', universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.
Try this code:
view.layer.borderColor = [UIColor redColor].CGColor;
view.layer.borderWidth= 2.0;
[view setClipsToBounds:YES];
Control Panel >> Windows Firewall >> Turn windows firewall on or off >> Turn off.
Advanced settings >> Domain profile >> Windows firewall properties >> Firewall status >> Off.
I believe this is a more easy approach:
public class HibernateProxyTypeAdapter implements JsonSerializer<HibernateProxy>{
public JsonElement serialize(HibernateProxy object_,
Type type_,
JsonSerializationContext context_) {
return new GsonBuilder().create().toJsonTree(initializeAndUnproxy(object_)).getAsJsonObject();
// that will convert enum object to its ordinal value and convert it to json element
}
public static <T> T initializeAndUnproxy(T entity) {
if (entity == null) {
throw new
NullPointerException("Entity passed for initialization is null");
}
Hibernate.initialize(entity);
if (entity instanceof HibernateProxy) {
entity = (T) ((HibernateProxy) entity).getHibernateLazyInitializer()
.getImplementation();
}
return entity;
}
}
And then you will be able to call it like this:
Gson gson = new GsonBuilder()
.registerTypeHierarchyAdapter(HibernateProxy.class, new HibernateProxyTypeAdapter())
.create();
This way all the hibernate objects will be converted automatically.
If you're using a graphical tool. It shows you the schema right next to the table name. In case of DB Browser For Sqlite, click to open the database(top right corner), navigate and open your database, you'll see the information populated in the table as below.
right click on the record/table_name, click on copy create statement and there you have it.
Hope it helped some beginner who failed to work with the commandline.
I had the same problem on Win 7. The solution was to remove following files:
As for .hg/store/lock - there was no such file.
For these who don't get proper results other than mentioned languages, if you're using C# to print a text into console(terminal) window you should replace "\033" with "\x1b". In Visual Basic it would be Chrw(27).
You could use coalesce:
insert into destination select coalesce(field1,'somedata'),... from source;
I found a tool in Github that could possibly be a solution to this question. https://incarnate.github.io/curl-to-php/ I hope that will be useful
"How do I do that? I explored PHPMyAdmin, and I can't find a "change engine" functionality."
In direct response to this part of your question, you can issue an ALTER TABLE tbl engine=InnoDB;
and it'll recreate the table in the proper engine.
That is for people who prefer to have the constant on the left side. In most cases having the constant on the left side will prevent NullPointerException to be thrown (or having another nullcheck). For example the String method equals does also a null check. Having the constant on the left, will keep you from writing the additional check. Which, in another way is also performed later. Having the null value on the left is just being consistent.
like:
String b = null;
"constant".equals(b); // result to false
b.equals("constant"); // NullPointerException
b != null && b.equals("constant"); // result to false
If this was MySQL syntax, the type would have been missing, as some other responses point out. Correct MySQL syntax would have been:
ALTER TABLE Merchant_Pending_Functions MODIFY NumberOfLocations INT NULL
Posting here for clarity to MySQL users.
Note the standard sed
syntax (as in POSIX, so supported by all conforming sed
implementations around (GNU, OS/X, BSD, Solaris...)):
sed '/CLIENTSCRIPT=/a\
CLIENTSCRIPT2="hello"' file
Or on one line:
sed -e '/CLIENTSCRIPT=/a\' -e 'CLIENTSCRIPT2="hello"' file
(-e
xpressions (and the contents of -f
iles) are joined with newlines to make up the sed script sed
interprets).
The -i
option for in-place editing is also a GNU extension, some other implementations (like FreeBSD's) support -i ''
for that.
Alternatively, for portability, you can use perl
instead:
perl -pi -e '$_ .= qq(CLIENTSCRIPT2="hello"\n) if /CLIENTSCRIPT=/' file
Or you could use ed
or ex
:
printf '%s\n' /CLIENTSCRIPT=/a 'CLIENTSCRIPT2="hello"' . w q | ex -s file
sudo apt-get install python-mysqldb
works perfectly in ubuntu
pip install mysql-python
raises an Environment Error
As others have said, only firefox supports this. Here is a work around that does the same thing, and even works with dashed outlines.
.has-outline {_x000D_
display: inline-block;_x000D_
background: #51ab9f;_x000D_
border-radius: 10px;_x000D_
padding: 5px;_x000D_
position: relative;_x000D_
}_x000D_
.has-outline:after {_x000D_
border-radius: 10px;_x000D_
padding: 5px;_x000D_
border: 2px dashed #9dd5cf;_x000D_
position: absolute;_x000D_
content: '';_x000D_
top: -2px;_x000D_
left: -2px;_x000D_
bottom: -2px;_x000D_
right: -2px;_x000D_
}
_x000D_
<div class="has-outline">_x000D_
I can haz outline_x000D_
</div>
_x000D_
In v2.0 of the Graph API, calling /me/friends
returns the person's friends who also use the app.
In addition, in v2.0, you must request the user_friends
permission from each user. user_friends
is no longer included by default in every login. Each user must grant the user_friends
permission in order to appear in the response to /me/friends
. See the Facebook upgrade guide for more detailed information, or review the summary below.
The /me/friendlists
endpoint and user_friendlists
permission are not what you're after. This endpoint does not return the users friends - its lets you access the lists a person has made to organize their friends. It does not return the friends in each of these lists. This API and permission is useful to allow you to render a custom privacy selector when giving people the opportunity to publish back to Facebook.
If you want to access a list of non-app-using friends, there are two options:
If you want to let your people tag their friends in stories that they publish to Facebook using your App, you can use the /me/taggable_friends
API. Use of this endpoint requires review by Facebook and should only be used for the case where you're rendering a list of friends in order to let the user tag them in a post.
If your App is a Game AND your Game supports Facebook Canvas, you can use the /me/invitable_friends
endpoint in order to render a custom invite dialog, then pass the tokens returned by this API to the standard Requests Dialog.
In other cases, apps are no longer able to retrieve the full list of a user's friends (only those friends who have specifically authorized your app using the user_friends
permission).
For apps wanting allow people to invite friends to use an app, you can still use the Send Dialog on Web or the new Message Dialog on iOS and Android.
but still useful - and works with IE11 ! here is another short way to get the common browsers returned for css class:
function get_browser()
{
$browser = '';
$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
if (preg_match('~(?:msie ?|trident.+?; ?rv: ?)(\d+)~', $ua, $matches)) $browser = 'ie ie'.$matches[1];
elseif (preg_match('~(safari|chrome|firefox)~', $ua, $matches)) $browser = $matches[1];
return $browser;
}
So this function returns: 'safari' or 'firefox' or 'chrome', or 'ie ie8', 'ie ie9', 'ie ie10', 'ie ie11'.
hope it helps
By definining the following alias (in ~/.gitconfig) you can easily temporarily disable the fileMode per git command:
[alias]
nfm = "!f(){ git -c core.fileMode=false $@; };f"
When this alias is prefixed to the git command, the file mode changes won't show up with commands that would otherwise show them. For example:
git nfm status
I had the same issue:
The System.Web.Optimization version I was using was outdated for MVC4 RC.
I updated my packages using the package manager in VS 2010.
In this MSDN blog, Mr. Andy talks about how to update your MVC 4 Beta project to MVC 4 RC. Updating my packages got the Scripts (particularly the web optimization one) to resolve for me:
To install the latest System.Web.Optimization package, use Package Manager Console (Tools -> Library Package Manager -> Package Manager Console) and run the below command:
Install-Package -IncludePrerelease Microsoft.AspNet.Web.Optimization
Use the System.Web.Optimization file included in the package in your references.
To update other packages: Tools menu -> Library Package Manager -> Manage NuGet Packages for Solution.
By using the divmod()
function, which does only a single division to produce both the quotient and the remainder, you can have the result very quickly with only two mathematical operations:
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
And then use string formatting to convert the result into your desired output:
print('{:d}:{:02d}:{:02d}'.format(h, m, s)) # Python 3
print(f'{h:d}:{m:02d}:{s:02d}') # Python 3.6+
We can simply pass the output of python inbuilt print function to a file after opening the file with the append option by using just two lines of code:
with open('filename.txt', 'a') as file:
print('\nThis printed data will store in a file', file=file)
Hope this may resolve the issue...
Note: this code works with python3 however, python2 is not being supported currently.
This should work fine
$arr = array( 1 => "A", 10 => "B", 5 => "C" );
max(array_keys($arr));
Custom function to convert stdClass to an array:
function objectToArray($d) {
if (is_object($d)) {
// Gets the properties of the given object
// with get_object_vars function
$d = get_object_vars($d);
}
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return array_map(__FUNCTION__, $d);
} else {
// Return array
return $d;
}
}
Another custom function to convert Array to stdClass:
function arrayToObject($d) {
if (is_array($d)) {
/*
* Return array converted to object
* Using __FUNCTION__ (Magic constant)
* for recursive call
*/
return (object) array_map(__FUNCTION__, $d);
} else {
// Return object
return $d;
}
}
Usage Example:
// Create new stdClass Object
$init = new stdClass;
// Add some test data
$init->foo = "Test data";
$init->bar = new stdClass;
$init->bar->baaz = "Testing";
$init->bar->fooz = new stdClass;
$init->bar->fooz->baz = "Testing again";
$init->foox = "Just test";
// Convert array to object and then object back to array
$array = objectToArray($init);
$object = arrayToObject($array);
// Print objects and array
print_r($init);
echo "\n";
print_r($array);
echo "\n";
print_r($object);
Yes, You can add
# -*- coding: utf-8 -*-
in your source code's first line.
You can read more details here https://www.python.org/dev/peps/pep-0263/
You can use String =~ Regex
. It returns position of full regex match in string.
irb> ("abc" =~ %r"abc") == 0
=> true
irb> ("aabc" =~ %r"abc") == 0
=> false
I'd like to add to my preposter. I suggest a slightly different approach that will allow you to simply assign a new value to your object without using a method. It must be noted though that this is not supported by especially older browsers and IE9 still requires use of a different interface.
Most notably is that my approach does not make use of events.
My proposal makes use of the relatively young feature of getters and setters, particularly setters only. Generally speaking, mutators allow us to "customize" the behavior of how certain properties are assigned a value and retrieved.
One implementation I'll be using here is the Object.defineProperty method. It works in FireFox, GoogleChrome and - I think - IE9. Haven't tested other browsers, but since this is theory only...
Anyways, it accepts three parameters. The first parameter being the object that you wish to define a new property for, the second a string resembling the the name of the new property and the last a "descriptor object" providing information on the behavior of the new property.
Two particularly interesting descriptors are get
and set
. An example would look something like the following. Note that using these two prohibits the use of the other 4 descriptors.
function MyCtor( bindTo ) {
// I'll omit parameter validation here.
Object.defineProperty(this, 'value', {
enumerable: true,
get : function ( ) {
return bindTo.value;
},
set : function ( val ) {
bindTo.value = val;
}
});
}
Now making use of this becomes slightly different:
var obj = new MyCtor(document.getElementById('foo')),
i = 0;
setInterval(function() {
obj.value += ++i;
}, 3000);
I want to emphasize that this only works for modern browsers.
Working fiddle: http://jsfiddle.net/Derija93/RkTMD/1/
So I just solved my own "SMTP connection failure" error and I wanted to post the solution just in case it helps anyone else.
I used the EXACT code given in the PHPMailer example gmail.phps file. It worked simply while I was using MAMP and then I got the SMTP connection error once I moved it on to my personal server.
All of the Stack Overflow answers I read, and all of the troubleshooting documentation from PHPMailer said that it wasn't an issue with PHPMailer. That it was a settings issue on the server side. I tried different ports (587, 465, 25), I tried 'SSL' and 'TLS' encryption. I checked that openssl was enabled in my php.ini file. I checked that there wasn't a firewall issue. Everything checked out, and still nothing.
The solution was that I had to remove this line:
$mail->isSMTP();
Now it all works. I don't know why, but it works. The rest of my code is copied and pasted from the PHPMailer example file.
This code on top should work:
error_reporting(E_ALL);
However, try to edit the code on the phone in the file:
error_reporting =on
You are correct here:
Integer i = 0;
i = i + 1; // <- I think that this is somehow creating a new object!
First: Integer is immutable.
Second: the Integer class is not overriding the +
operator, there is autounboxing and autoboxing involved at that line (In older versions of Java you would get an error on the above line).
When you write i + 1
the compiler first converts the Integer to an (primitive) int
for performing the addition: autounboxing. Next, doing i = <some int>
the compiler converts from int
to an (new) Integer: autoboxing.
So +
is actually being applied to primitive int
s.
Use this code "./" as root on the server as it works for me
<a href="./fruits/index.html">Back to Fruits List</a>
but when you are on a local machine use the following code "../" as the root relative path
<a href="../fruits/index.html">Back to Fruits List</a>
If it is two IEnumerable lists you can't use AddRange
, but you can use Concat
.
IEnumerable<int> first = new List<int>{1,1,2,3,5};
IEnumerable<int> second = new List<int>{8,13,21,34,55};
var allItems = first.Concat(second);
// 1,1,2,3,5,8,13,21,34,55
Add Content-Type
: application/json
and Accept
: application/json
For completeness, the boost way would be to use boost::format
cout << boost::format("%s %s > %s") % a % b % c;
Take your pick. The boost solution has the advantage of type safety with the sprintf
format (for those who find the <<
syntax a bit clunky).
I think you want to specify
-H "Content-Type:text/xml"
with a colon, not an equals.
If you want to search a file for a substring and add a new text to the next line, one of the elegant ways to do it is the following:
import fileinput
for line in fileinput.FileInput(file_path,inplace=1):
if "TEXT_TO_SEARCH" in line:
line=line.replace(line,line+"NEW_TEXT")
print line,
A const
to a pointer indicates a "read-only" memory location. Whereas the ones without const
are a read-write memory areas. So, you "cannot" convert a const
(read-only location) to a normal(read-write) location.
The alternate is to copy the data to a different read-write location and pass this pointer to the required function. You may use strdup()
to perform this action.
To open in a new tab use:
target = "_blank"
To open in the same tab use:
target = "_self"
the problem is blade, try this
<i class="fa" v-bind:class="['{{content['cravings']}}' ? 'fa-checkbox-marked' : 'fa-checkbox-blank-outline']"></i>
Triggering a click via JavaScript will not open a hyperlink. This is a security measure built into the browser.
See this question for some workarounds, though.
 
is the numeric reference for the entity reference
— they are the exact same thing. It's likely your editor is simply inserting the numberic reference instead of the named one.
See the Wikipedia page for the non-breaking space.
sudo make uninstall
did the trick for me using the Ruby 2.4 tar from the official downloads page.
To improve upon @arnorhs answer I've added in the ability to have a more precise result so if you wanted years, months, days & hours for instance since the user joined.
I've added a new parameter to allow you to specify the number of points of precision you wish to have returned.
function get_friendly_time_ago($distant_timestamp, $max_units = 3) {
$i = 0;
$time = time() - $distant_timestamp; // to get the time since that moment
$tokens = [
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
];
$responses = [];
while ($i < $max_units && $time > 0) {
foreach ($tokens as $unit => $text) {
if ($time < $unit) {
continue;
}
$i++;
$numberOfUnits = floor($time / $unit);
$responses[] = $numberOfUnits . ' ' . $text . (($numberOfUnits > 1) ? 's' : '');
$time -= ($unit * $numberOfUnits);
break;
}
}
if (!empty($responses)) {
return implode(', ', $responses) . ' ago';
}
return 'Just now';
}
One significant difference is that you can include a function in your SQL queries, but stored procedures can only be invoked with the CALL
statement:
UDF Example:
CREATE FUNCTION hello (s CHAR(20))
RETURNS CHAR(50) DETERMINISTIC
RETURN CONCAT('Hello, ',s,'!');
Query OK, 0 rows affected (0.00 sec)
CREATE TABLE names (id int, name varchar(20));
INSERT INTO names VALUES (1, 'Bob');
INSERT INTO names VALUES (2, 'John');
INSERT INTO names VALUES (3, 'Paul');
SELECT hello(name) FROM names;
+--------------+
| hello(name) |
+--------------+
| Hello, Bob! |
| Hello, John! |
| Hello, Paul! |
+--------------+
3 rows in set (0.00 sec)
Sproc Example:
delimiter //
CREATE PROCEDURE simpleproc (IN s CHAR(100))
BEGIN
SELECT CONCAT('Hello, ', s, '!');
END//
Query OK, 0 rows affected (0.00 sec)
delimiter ;
CALL simpleproc('World');
+---------------------------+
| CONCAT('Hello, ', s, '!') |
+---------------------------+
| Hello, World! |
+---------------------------+
1 row in set (0.00 sec)
Put a \
at the end of your line or enclose the statement in parens ( .. )
. From IBM:
b = ((i1 < 20) and
(i2 < 30) and
(i3 < 40))
or
b = (i1 < 20) and \
(i2 < 30) and \
(i3 < 40)
ES6 version:
var dataArray = Object.keys(dataObject).map(val => dataObject[val]);
Since AIX doesn't have a "column" command, I created the simplistic script below. It would be even shorter without the doc & input edits... :)
#!/usr/bin/perl
# column.pl: convert STDIN to multiple columns on STDOUT
# Usage: column.pl column-width number-of-columns file...
#
$width = shift;
($width ne '') or die "must give column-width and number-of-columns\n";
$columns = shift;
($columns ne '') or die "must give number-of-columns\n";
($x = $width) =~ s/[^0-9]//g;
($x eq $width) or die "invalid column-width: $width\n";
($x = $columns) =~ s/[^0-9]//g;
($x eq $columns) or die "invalid number-of-columns: $columns\n";
$w = $width * -1; $c = $columns;
while (<>) {
chomp;
if ( $c-- > 1 ) {
printf "%${w}s", $_;
next;
}
$c = $columns;
printf "%${w}s\n", $_;
}
print "\n";
java.io.IOException: Connection reset by peer
The other side has abruptly aborted the connection in midst of a transaction. That can have many causes which are not controllable from the server side on. E.g. the enduser decided to shutdown the client or change the server abruptly while still interacting with your server, or the client program has crashed, or the enduser's internet connection went down, or the enduser's machine crashed, etc, etc.
Quick fix, add this in your options:
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, false)
Now you have no idea what host you're actually connecting to, because cURL will not verify the certificate in any way. Hope you enjoy man-in-the-middle attacks!
Or just add it to your current function:
/**
* Get a web file (HTML, XHTML, XML, image, etc.) from a URL. Return an
* array containing the HTTP server response header fields and content.
*/
function get_web_page( $url )
{
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle all encodings
CURLOPT_USERAGENT => "spider", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // timeout on connect
CURLOPT_TIMEOUT => 120, // timeout on response
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_SSL_VERIFYPEER => false // Disabled SSL Cert checks
);
$ch = curl_init( $url );
curl_setopt_array( $ch, $options );
$content = curl_exec( $ch );
$err = curl_errno( $ch );
$errmsg = curl_error( $ch );
$header = curl_getinfo( $ch );
curl_close( $ch );
$header['errno'] = $err;
$header['errmsg'] = $errmsg;
$header['content'] = $content;
return $header;
}
If you want to do it right, you need something like this:
use autodie qw(open sysseek sysread truncate);
my $file = shift;
open my $fh, '+>>', $file;
my $pos = tell $fh;
sysseek $fh, $pos - 1, 0;
sysread $fh, my $buf, 1 or die 'No data to read?';
if($buf eq "\n"){
truncate $fh, $pos - 1;
}
We open the file for reading and appending; opening for appending means that we are already seek
ed to the end of the file. We then get the numerical position of the end of the file with tell
. We use that number to seek back one character, and then we read that one character. If it's a newline, we truncate the file to the character before that newline, otherwise, we do nothing.
This runs in constant time and constant space for any input, and doesn't require any more disk space, either.
The Color
structure is immutable (as all structures should really be), meaning that the values of its properties cannot be changed once that particular instance has been created.
Instead, you need to create a new instance of the structure with the property values that you want. Since you want to create a color using its component RGB values, you need to use the FromArgb
method:
Color myColor = Color.FromArgb(100, 150, 75);
I would defiantly give BlackFire a try.
There is this virtualBox I've put together using puphpet, to test different php frameworks which coms with BlackFire, please feel free to fork and/or distribute if required :)
Had similar problems recently. Would suggest you carefully check if the user you're connecting with has proper authorizations on the remote machine.
You can review permissions using the following command.
Set-PSSessionConfiguration -ShowSecurityDescriptorUI -Name Microsoft.PowerShell
Found this tip here (updated link, thanks "unbob"):
https://devblogs.microsoft.com/scripting/configure-remote-security-settings-for-windows-powershell/
It fixed it for me.
You can use title
attribute.
<img src="smiley.gif" title="Smiley face"/>
You can change the source of image as you want.
And as @Gray commented:
You can also use the title
on other things like <a ...
anchors, <p>
, <div>
, <input>
, etc.
See: this
Yes totally can, and pretty easily too. This is done by exposing your private variables and functions by returning the prototype object graph in the constructor. This is nothing new, but take a bit of js foo to understand the elegance of it. This way does not use global scoped, or weakmaps. It is a form of reflection built into the language. Depending on how you leverage this; one can either force an exception which interrupts the call stack, or bury the exception as an undefined
. This is demonstarted below, and can read more about these features here
class Clazz {_x000D_
constructor() {_x000D_
var _level = 1_x000D_
_x000D_
function _private(x) {_x000D_
return _level * x;_x000D_
}_x000D_
return {_x000D_
level: _level,_x000D_
public: this.private,_x000D_
public2: function(x) {_x000D_
return _private(x);_x000D_
},_x000D_
public3: function(x) {_x000D_
return _private(x) * this.public(x);_x000D_
},_x000D_
};_x000D_
}_x000D_
_x000D_
private(x) {_x000D_
return x * x;_x000D_
}_x000D_
}_x000D_
_x000D_
var clazz = new Clazz();_x000D_
_x000D_
console.log(clazz._level); //undefined_x000D_
console.log(clazz._private); // undefined_x000D_
console.log(clazz.level); // 1_x000D_
console.log(clazz.public(1)); //1_x000D_
console.log(clazz.public2(2)); //2_x000D_
console.log(clazz.public3(3)); //27_x000D_
console.log(clazz.private(0)); //error
_x000D_
To enable/disable simulator keyboard,
? + K (Ctrl + k)
To disable input from your keyboard,
iOS Simulator -> Hardware -> Keyboard -> Uncheck "Connect Hardware Keyboard"
You need to properly decode the source text. Most likely the source text is in UTF-8 format, not ASCII.
Because you do not provide any context or code for your question it is not possible to give a direct answer.
I suggest you study how unicode and character encoding is done in Python:
In addition to rupello's excellent answer, a "dirty" but very effective trick:
For all phones, any (local) network: Set up your PC to Man-In-The-Middle your mobile device.
Use Ettercap to do ARP spoofing between your mobile device and your router, and all your mobile's traffic will appear in Wireshark. See this tutorial for set-up details
pg_dump
does not work always.
Given that you have the same table ddl in the both dbs you could hack it from stdout and stdin as follows:
# grab the list of cols straight from bash
psql -d "$src_db" -t -c \
"SELECT column_name
FROM information_schema.columns
WHERE 1=1
AND table_name='"$table_to_copy"'"
# ^^^ filter autogenerated cols if needed
psql -d "$src_db" -c \
"copy ( SELECT col_1 , col2 FROM table_to_copy) TO STDOUT" |\
psql -d "$tgt_db" -c "\copy table_to_copy (col_1 , col2) FROM STDIN"
check this link. It has helped me with errno 150: http://verysimple.com/2006/10/22/mysql-error-number-1005-cant-create-table-mydbsql-328_45frm-errno-150/
On the top of my head two things come to mind.
I'm guessing the problem is with the set NULL on update (if my brains aren't on backwards today as they so often are...).
Edit: I missed the comments on your original post. Unsigned/not unsigned int columns maybe resolved your case. Hope my link helps someone in the future thought.
Ubuntu
sudo apt-get install php5-dev pecl imagemagick libmagickwand-dev
sudo pecl install imagick
sudo apt-get install php5-imagick
sudo service apache2 restart
Some dependencies will probably already be met but excluding the Apache service, that's everything required for PHP to use the Imagick
class.
For me, problem was Typo in location path.
Maybe first thing to check out for this kind of problem
Is path to project.
%hash = map { $_ => 1 } @array;
It's not as short as the "@hash{@array} = ..." solutions, but those ones require the hash and array to already be defined somewhere else, whereas this one can take an anonymous array and return an anonymous hash.
What this does is take each element in the array and pair it up with a "1". When this list of (key, 1, key, 1, key 1) pairs get assigned to a hash, the odd-numbered ones become the hash's keys, and the even-numbered ones become the respective values.
Your code is blanking out your file:
import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'wb') # opens file for writing (erases contents)
csv.writer(f, delimiter =' ',quotechar =',',quoting=csv.QUOTE_MINIMAL)
if you want to read the file in, you will need to use csv.reader and open the file for reading.
import csv
workingdir = "C:\Mer\Ven\sample"
csvfile = workingdir+"\test3.csv"
f=open(csvfile,'rb') # opens file for reading
reader = csv.reader(f)
for line in reader:
print line
If you want to write that back out to a new file with different delimiters, you can create a new file and specify those delimiters and write out each line (instead of printing the tuple).
So many answers, yet I can't find any solution that does efficiently what the title of the questions literally asks for (splitting on multiple possible separators—instead, many answers split on anything that is not a word, which is different). So here is an answer to the question in the title, that relies on Python's standard and efficient re
module:
>>> import re # Will be splitting on: , <space> - ! ? :
>>> filter(None, re.split("[, \-!?:]+", "Hey, you - what are you doing here!?"))
['Hey', 'you', 'what', 'are', 'you', 'doing', 'here']
where:
[…]
matches one of the separators listed inside,\-
in the regular expression is here to prevent the special interpretation of -
as a character range indicator (as in A-Z
),+
skips one or more delimiters (it could be omitted thanks to the filter()
, but this would unnecessarily produce empty strings between matched single-character separators), andfilter(None, …)
removes the empty strings possibly created by leading and trailing separators (since empty strings have a false boolean value).This re.split()
precisely "splits with multiple separators", as asked for in the question title.
This solution is furthermore immune to the problems with non-ASCII characters in words found in some other solutions (see the first comment to ghostdog74's answer).
The re
module is much more efficient (in speed and concision) than doing Python loops and tests "by hand"!
If you are trying something similar like source <( curl -sS $url )
and getting the (23) Failed writing body
error, it is because sourcing a process substitution doesn't work in bash 3.2
(the default for macOS).
Instead, you can use this workaround.
source /dev/stdin <<<"$( curl -sS $url )"
Use the function cast() to convert from timestamp to date
select to_char(cast(sysdate as date),'DD-MM-YYYY') from dual;
For more info of function cast oracle11g http://docs.oracle.com/cd/B28359_01/server.111/b28286/functions016.htm#SQLRF51256
if you are looking for a script to avoid submitting form when some errors found, this method should work
function verifyData(){
if (document.MyForm.FormInput.value.length == "") {
alert("Write something!");
}
else {
document.MyForm.submit();
}
}
change the Submit Button type to "button"
<input value="Save" type="button" onClick="verifyData()">
hope this help.
The simple solution is to put it in an iframe and hope that the user has a plug-in that supports it.
(I don't, the Acrobat plugin has been such a resource hog and source of instability that I make a point to remove it from any browser that it touches).
The complicated, but relative popular solution is to display it in a flash applet.
With Winforms you can use Form.BackColor to do this.
From within the Form's code:
BackColor = Color.LightPink;
If you mean a WPF Window you can use the Background property.
From within the Window's code:
Background = Brushes.LightPink;
If you're in charge (or have any control over the web service), get them to add a unique root element!
If you can't change that at all, then you can do a bit of regex or string-splitting to parse each and pass each element to your XML Reader.
Alternatively, you could manually add a junk root element, by prefixing an opening tag and suffixing a closing tag.
It's simple. Just change the port. Use 3268 instead of 389. If your domain name DOMAIN.LOCAL, in search put DC=DOMAIN,DC=LOCAL
Port 3268: This port is used for queries that are specifically targeted for the global catalog. LDAP requests sent to port 3268 can be used to search objects in the entire forest. However, only the attributes marked for replication to the global catalog can be returned.
Port 389: This port is used for requesting information from the Domain Controller. LDAP requests sent to port 389 can be used to search objects only within the global catalog’s home domain. However, the application can possible to obtain all of the attributes searched objects.
A friend function is not a member function, so the problem is that you declare operator<<
as a friend of A
:
friend ostream& operator<<(ostream&, A&);
then try to define it as a member function of the class logic
ostream& logic::operator<<(ostream& os, A& a)
^^^^^^^
Are you confused about whether logic
is a class or a namespace?
The error is because you've tried to define a member operator<<
taking two arguments, which means it takes three arguments including the implicit this
parameter. The operator can only take two arguments, so that when you write a << b
the two arguments are a
and b
.
You want to define ostream& operator<<(ostream&, const A&)
as a non-member function, definitely not as a member of logic
since it has nothing to do with that class!
std::ostream& operator<<(std::ostream& os, const A& a)
{
return os << a.number;
}
It's actually very similar to jQuery:
document.getElementsByClassName('class1 class2')
jq '.users[]|.first,.last' | paste - -
Just to add the information I was looking for: pragma mark
is Xcode specific, so if you deal with a C++ project that you open in different IDEs, it does not have any effect there. In Qt Creator, for example, it does not add categories for methods, nor generate any warnings/errors.
EDIT
#pragma
is a preprocessor directive which comes from C programming language. Its purpose is to specify implementation-dependent information to the compiler - that is, each compiler might choose to interpret this directive as it wants. That said, it is rather considered an extension which does not change/influence the code itself. So compilers might as well ignore it.
Xcode is an IDE which takes advantage of #pragma
and uses it in its own specific way. The point is, #pragma
is not Xcode and even Objective-C specific.
If folks want to read tags from the RedHat registry at https://registry.redhat.io/v2
then the steps are:
# example nodejs-12 image
IMAGE_STREAM=nodejs-12
REDHAT_REGISTRY_API="https://registry.redhat.io/v2/rhel8/$IMAGE_STREAM"
# Get an oAuth token based on a service account username and password https://access.redhat.com/articles/3560571
TOKEN=$(curl --silent -u "$REGISTRY_USER":"$REGISTRY_PASSWORD" "https://sso.redhat.com/auth/realms/rhcc/protocol/redhat-docker-v2/auth?service=docker-registry&client_id=curl&scope=repository:rhel:pull" | jq --raw-output '.token')
# Grab the tags
wget -q --header="Accept: application/json" --header="Authorization: Bearer $TOKEN" -O - "$REDHAT_REGISTRY_API/tags/list" | jq -r '."tags"[]'
If you want to compare what you have in your local openshift registry against what is in the upstream registry.redhat.com then here is a complete script.
If these are not your options
php.ini
.date_default_timezone
call.Instead of date
you could use gmdate
.
I have used gmdate( "Y" )
when I needed a year for a copyright snipplet.
This is how I solved this problem.
I first ran npm install @angular/core
.
Then I ran npm install --save
.
When both installs had successfully completed I ran npm serve
and received an error saying
"Versions of @angular/compiler-cli and typescript could not be determined.
The most common reason for this is a broken npm install.
Please make sure your package.json contains both @angular/compiler-cli and typescript in
devDependencies, then delete node_modules and package-lock.json (if you have one) and
run npm install again."
I then deleted my node_modules folder as well as my package-lock.json folder.
After I deleted those folders I ran npm install --save
once more.
I ran npm start
and received another error. This error said Error: Cannot find module '@angular-devkit/core'
.
I ran npm install @angular-devkit/core --save
.
Finally, I ran npm start
and the project started!
The best way is to simply use Convert.ToInt32
. It is fast and also rounds correctly.
Why make it more complicated?
It should be:
document.getElementById("placehere").appendChild(elem);
And place your div before your javascript, because if you don't, the javascript executes before the div exists. Or wait for it to load. So your code looks like this:
<html>
<body>
<script type="text/javascript">
window.onload=function(){
var elem = document.createElement("img");
elem.setAttribute("src", "http://img.zohostatic.com/discussions/v1/images/defaultPhoto.png");
elem.setAttribute("height", "768");
elem.setAttribute("width", "1024");
elem.setAttribute("alt", "Flower");
document.getElementById("placehere").appendChild(elem);
}
</script>
<div id="placehere">
</div>
</body>
</html>
To prove my point, see this with the onload and this without the onload. Fire up the console and you'll find an error stating that the div doesn't exist or cannot find appendChild method of null.
I ran into this exact same error message. I tried Aditi's example, and then I realized what the real issue was. (Because I had another apiEndpoint making a similar call that worked fine.) In this case The object in my list had not had an interface extracted from it yet. So because I apparently missed a step, when it went to do the bind to the
List<OfthisModelType>
It failed to deserialize.
If you see this issue, check to see if that could be the issue.
bcrypt
is a hashing algorithm which is scalable with hardware (via a configurable number of rounds). Its slowness and multiple rounds ensures that an attacker must deploy massive funds and hardware to be able to crack your passwords. Add to that per-password salts (bcrypt
REQUIRES salts) and you can be sure that an attack is virtually unfeasible without either ludicrous amount of funds or hardware.
bcrypt
uses the Eksblowfish algorithm to hash passwords. While the encryption phase of Eksblowfish and Blowfish are exactly the same, the key schedule phase of Eksblowfish ensures that any subsequent state depends on both salt and key (user password), and no state can be precomputed without the knowledge of both. Because of this key difference, bcrypt
is a one-way hashing algorithm. You cannot retrieve the plain text password without already knowing the salt, rounds and key (password). [Source]
Password hashing functions have now been built directly into PHP >= 5.5. You may now use password_hash()
to create a bcrypt
hash of any password:
<?php
// Usage 1:
echo password_hash('rasmuslerdorf', PASSWORD_DEFAULT)."\n";
// $2y$10$xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// For example:
// $2y$10$.vGA1O9wmRjrwAVXD98HNOgsNpDczlqm3Jq7KnEd1rVAGv3Fykk1a
// Usage 2:
$options = [
'cost' => 11
];
echo password_hash('rasmuslerdorf', PASSWORD_BCRYPT, $options)."\n";
// $2y$11$6DP.V0nO7YI3iSki4qog6OQI5eiO6Jnjsqg7vdnb.JgGIsxniOn4C
To verify a user provided password against an existing hash, you may use the password_verify()
as such:
<?php
// See the password_hash() example to see where this came from.
$hash = '$2y$07$BCryptRequires22Chrcte/VlQH0piJtjXl.0t1XkA8pw9dMXTpOq';
if (password_verify('rasmuslerdorf', $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
There is a compatibility library on GitHub created based on the source code of the above functions originally written in C, which provides the same functionality. Once the compatibility library is installed, usage is the same as above (minus the shorthand array notation if you are still on the 5.3.x branch).
You can use crypt()
function to generate bcrypt hashes of input strings. This class can automatically generate salts and verify existing hashes against an input. If you are using a version of PHP higher or equal to 5.3.7, it is highly recommended you use the built-in function or the compat library. This alternative is provided only for historical purposes.
class Bcrypt{
private $rounds;
public function __construct($rounds = 12) {
if (CRYPT_BLOWFISH != 1) {
throw new Exception("bcrypt not supported in this installation. See http://php.net/crypt");
}
$this->rounds = $rounds;
}
public function hash($input){
$hash = crypt($input, $this->getSalt());
if (strlen($hash) > 13)
return $hash;
return false;
}
public function verify($input, $existingHash){
$hash = crypt($input, $existingHash);
return $hash === $existingHash;
}
private function getSalt(){
$salt = sprintf('$2a$%02d$', $this->rounds);
$bytes = $this->getRandomBytes(16);
$salt .= $this->encodeBytes($bytes);
return $salt;
}
private $randomState;
private function getRandomBytes($count){
$bytes = '';
if (function_exists('openssl_random_pseudo_bytes') &&
(strtoupper(substr(PHP_OS, 0, 3)) !== 'WIN')) { // OpenSSL is slow on Windows
$bytes = openssl_random_pseudo_bytes($count);
}
if ($bytes === '' && is_readable('/dev/urandom') &&
($hRand = @fopen('/dev/urandom', 'rb')) !== FALSE) {
$bytes = fread($hRand, $count);
fclose($hRand);
}
if (strlen($bytes) < $count) {
$bytes = '';
if ($this->randomState === null) {
$this->randomState = microtime();
if (function_exists('getmypid')) {
$this->randomState .= getmypid();
}
}
for ($i = 0; $i < $count; $i += 16) {
$this->randomState = md5(microtime() . $this->randomState);
if (PHP_VERSION >= '5') {
$bytes .= md5($this->randomState, true);
} else {
$bytes .= pack('H*', md5($this->randomState));
}
}
$bytes = substr($bytes, 0, $count);
}
return $bytes;
}
private function encodeBytes($input){
// The following is code from the PHP Password Hashing Framework
$itoa64 = './ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$output = '';
$i = 0;
do {
$c1 = ord($input[$i++]);
$output .= $itoa64[$c1 >> 2];
$c1 = ($c1 & 0x03) << 4;
if ($i >= 16) {
$output .= $itoa64[$c1];
break;
}
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 4;
$output .= $itoa64[$c1];
$c1 = ($c2 & 0x0f) << 2;
$c2 = ord($input[$i++]);
$c1 |= $c2 >> 6;
$output .= $itoa64[$c1];
$output .= $itoa64[$c2 & 0x3f];
} while (true);
return $output;
}
}
You can use this code like this:
$bcrypt = new Bcrypt(15);
$hash = $bcrypt->hash('password');
$isGood = $bcrypt->verify('password', $hash);
Alternatively, you may also use the Portable PHP Hashing Framework.
Here is my solution for the round up/down problem
< .5 round down
> = .5 round up
import math
def _should_round_down(val: float):
if val < 0:
return ((val * -1) % 1) < 0.5
return (val % 1) < 0.5
def _round(val: float, ndigits=0):
if ndigits > 0:
val *= 10 ** (ndigits - 1)
is_positive = val > 0
tmp_val = val
if not is_positive:
tmp_val *= -1
rounded_value = math.floor(tmp_val) if _should_round_down(val) else math.ceil(tmp_val)
if not is_positive:
rounded_value *= -1
if ndigits > 0:
rounded_value /= 10 ** (ndigits - 1)
return rounded_value
# test
# nr = 12.2548
# for digit in range(0, 4):
# print("{} decimals : {} -> {}".format(digit, nr, _round(nr, digit)))
# output
# 0 decimals : 12.2548 -> 12
# 1 decimals : 12.2548 -> 12.0
# 2 decimals : 12.2548 -> 12.3
# 3 decimals : 12.2548 -> 12.25
I ran into the same situation where commands such as git diff origin
or git diff origin master
produced the error reported in the question, namely Fatal: ambiguous argument...
To resolve the situation, I ran the command
git symbolic-ref refs/remotes/origin/HEAD refs/remotes/origin/master
to set refs/remotes/origin/HEAD to point to the origin/master branch.
Before running this command, the output of git branch -a
was:
* master
remotes/origin/master
After running the command, the error no longer happened and the output of git branch -a
was:
* master
remotes/origin/HEAD -> origin/master
remotes/origin/master
(Other answers have already identified that the source of the error is HEAD not being set for origin. But I thought it helpful to provide a command which may be used to fix the error in question, although it may be obvious to some users.)
Additional information:
For anybody inclined to experiment and go back and forth between setting and unsetting refs/remotes/origin/HEAD, here are some examples.
To unset:
git remote set-head origin --delete
To set:
(additional ways, besides the way shown at the start of this answer)
git remote set-head origin master
to set origin/head explicitly
OR
git remote set-head origin --auto
to query the remote and automatically set origin/HEAD to the remote's current branch.
References:
git remote --help
see set-head descriptiongit symbolic-ref --help
As an additional reference for the other responses, instead of using "UTF-8" you can use:
HTTP.UTF_8
which is included since Java 4 as part of the org.apache.http.protocol library, which is included also since Android API 1.
Here's a list of things that are worth checking:
Is Suhosin installed?
ini_set
ini_set('memory_limit', '512'); // DIDN'T WORK
ini_set('memory_limit', '512MB'); // DIDN'T WORK
ini_set('memory_limit', '512M'); // OK - 512MB
ini_set('memory_limit', 512000000); // OK - 512MB
When an integer is used, the value is measured in bytes. Shorthand notation, as described in this FAQ, may also be used.
http://php.net/manual/en/ini.core.php#ini.memory-limit
Sets the value of the specified directive. This can not be used in .htaccess files. Any directive type set with php_admin_value can not be overridden by .htaccess or ini_set(). To clear a previously set value use none as the value.
Here is the string to access files in raw folder. Replace filename with name of your file.
android.resource://" + getPackageName() + "/" + R.raw.filename
I just wanted to add the fix I found for this issue. I'm not sure why this worked. I had the correct version of jstl (1.2) and also the correct version of servlet-api (2.5)
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
I also had the correct address in my page as suggested in this thread, which is
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
What fixed this issue for me was removing the scope tag from my xml file in the pom for my jstl 1.2 dependency. Again not sure why that fixed it but just in case someone is doing the spring with JPA and Hibernate tutorial on pluralsight and has their pom setup this way, try removing the scope tag and see if that fixes it. Like I said it worked for me.
It ought to be implemented in msysgit, but there are two downsides:
I did a quick search and there is work being actively done on this, see issue 224.
root@APPLICATIOSERVER:/var/www/html# php connectiontest.php 61e23468-949e-4103-8e08-9db09249e8s1 OpenSSL SSL_connect: SSL_ERROR_SYSCALL in connection to 10.172.123.1:80 root@APPLICATIOSERVER:/var/www/html#
Post declaring the proxy settings in the php script file issue has been fixed.
$proxy = '10.172.123.1:80'; curl_setopt($cSession, CURLOPT_PROXY, $proxy); // PROXY details with port
If searching for an element is important, I'd recommend std::set
instead of std::vector
. Using this:
std::find(vec.begin(), vec.end(), x)
runs in O(n) time, but std::set
has its own find()
member (ie. myset.find(x)
) which runs in O(log n) time - that's much more efficient with large numbers of elements
std::set
also guarantees all the added elements are unique, which saves you from having to do anything like if not contained then push_back()...
.
If you're looking for the equivalent of PHP's empty
function, check this out:
function empty(mixed_var) {
// example 1: empty(null);
// returns 1: true
// example 2: empty(undefined);
// returns 2: true
// example 3: empty([]);
// returns 3: true
// example 4: empty({});
// returns 4: true
// example 5: empty({'aFunc' : function () { alert('humpty'); } });
// returns 5: false
var undef, key, i, len;
var emptyValues = [undef, null, false, 0, '', '0'];
for (i = 0, len = emptyValues.length; i < len; i++) {
if (mixed_var === emptyValues[i]) {
return true;
}
}
if (typeof mixed_var === 'object') {
for (key in mixed_var) {
// TODO: should we check for own properties only?
//if (mixed_var.hasOwnProperty(key)) {
return false;
//}
}
return true;
}
return false;
}
Complete copy&paste recipe, just adding the commands in the comments (for the copy-paste solution), after testing them:
git filter-branch --tree-filter 'rm -rf node_modules' --prune-empty HEAD
echo node_modules/ >> .gitignore
git add .gitignore
git commit -m 'Removing node_modules from git history'
git gc
git push origin master --force
After this, you can remove the line "node_modules/" from .gitignore
In the layout set your input method options to search.
<EditText
android:imeOptions="actionSearch"
android:inputType="text" />
In the java add the editor action listener.
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
performSearch();
return true;
}
return false;
}
});
If using jruby, here is a code snippet to return an array of all tables in a db.
require "rubygems"
require "jdbc/mysql"
Jdbc::MySQL.load_driver
require "java"
def get_database_tables(connection, db_name)
md = connection.get_meta_data
rs = md.get_tables(db_name, nil, '%',["TABLE"])
tables = []
count = 0
while rs.next
tables << rs.get_string(3)
end #while
return tables
end
Another option, once inside the GDB shell, before running the program, you can do
(gdb) set args file1 file2
and inspect it with:
(gdb) show args
Put these classes into Color.py file near your test.py file and run test.py. I've tested these classes on Ubuntu Server 16.04 and Linux Mint 18.2 . All classes worked very good except GColor (RGB), that, it is usable in graphical terminal like Linux Mint terminal. Also, you can use these classes like this:
print(Formatting.Italic + ANSI_Compatible.Color(12) + "This is a " + Formatting.Bold + "test" + Formatting.Reset_Bold + "!" + ANSI_Compatible.END + Formatting.Reset)
print(Color.B_DarkGray + Color.F_LightBlue + "This is a " + Formatting.Bold + "test" + Formatting.Reset_Bold + "!" + Base.END)
Result:
Note: It's not working on Windows!
File Color.py :
class Base:
# Foreground:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
# Formatting
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
# End colored text
END = '\033[0m'
NC ='\x1b[0m' # No Color
class ANSI_Compatible:
END = '\x1b[0m'
# If Foreground is False that means color effect on Background
def Color(ColorNo, Foreground=True): # 0 - 255
FB_G = 38 # Effect on foreground
if Foreground != True:
FB_G = 48 # Effect on background
return '\x1b[' + str(FB_G) + ';5;' + str(ColorNo) + 'm'
class Formatting:
Bold = "\x1b[1m"
Dim = "\x1b[2m"
Italic = "\x1b[3m"
Underlined = "\x1b[4m"
Blink = "\x1b[5m"
Reverse = "\x1b[7m"
Hidden = "\x1b[8m"
# Reset part
Reset = "\x1b[0m"
Reset_Bold = "\x1b[21m"
Reset_Dim = "\x1b[22m"
Reset_Italic = "\x1b[23m"
Reset_Underlined = "\x1b[24"
Reset_Blink = "\x1b[25m"
Reset_Reverse = "\x1b[27m"
Reset_Hidden = "\x1b[28m"
class GColor: # Gnome supported
END = "\x1b[0m"
# If Foreground is False that means color effect on Background
def RGB(R, G, B, Foreground=True): # R: 0-255 , G: 0-255 , B: 0-255
FB_G = 38 # Effect on foreground
if Foreground != True:
FB_G = 48 # Effect on background
return "\x1b[" + str(FB_G) + ";2;" + str(R) + ";" + str(G) + ";" + str(B) + "m"
class Color:
# Foreground
F_Default = "\x1b[39m"
F_Black = "\x1b[30m"
F_Red = "\x1b[31m"
F_Green = "\x1b[32m"
F_Yellow = "\x1b[33m"
F_Blue = "\x1b[34m"
F_Magenta = "\x1b[35m"
F_Cyan = "\x1b[36m"
F_LightGray = "\x1b[37m"
F_DarkGray = "\x1b[90m"
F_LightRed = "\x1b[91m"
F_LightGreen = "\x1b[92m"
F_LightYellow = "\x1b[93m"
F_LightBlue = "\x1b[94m"
F_LightMagenta = "\x1b[95m"
F_LightCyan = "\x1b[96m"
F_White = "\x1b[97m"
# Background
B_Default = "\x1b[49m"
B_Black = "\x1b[40m"
B_Red = "\x1b[41m"
B_Green = "\x1b[42m"
B_Yellow = "\x1b[43m"
B_Blue = "\x1b[44m"
B_Magenta = "\x1b[45m"
B_Cyan = "\x1b[46m"
B_LightGray = "\x1b[47m"
B_DarkGray = "\x1b[100m"
B_LightRed = "\x1b[101m"
B_LightGreen = "\x1b[102m"
B_LightYellow = "\x1b[103m"
B_LightBlue = "\x1b[104m"
B_LightMagenta = "\x1b[105m"
B_LightCyan = "\x1b[106m"
B_White = "\x1b[107m"
And,
File test.py:
from Color import *
if __name__ == '__main__':
print("Base:")
print(Base.FAIL,"This is a test!", Base.END)
print("ANSI_Compatible:")
print(ANSI_Compatible.Color(120),"This is a test!", ANSI_Compatible.END)
print("Formatting:")
print(Formatting.Bold,"This is a test!", Formatting.Reset)
print("GColor:") # Gnome terminal supported
print(GColor.RGB(204,100,145),"This is a test!", GColor.END)
print("Color:")
print(Color.F_Cyan,"This is a test!",Color.F_Default)
Result:
On Ubuntu Server 16.04
On Linux Mint 18.2
Put this in an initializer
class Hash
def filter(*args)
return nil if args.try(:empty?)
if args.size == 1
args[0] = args[0].to_s if args[0].is_a?(Symbol)
self.select {|key| key.to_s.match(args.first) }
else
self.select {|key| args.include?(key)}
end
end
end
Then you can do
{a: "1", b: "b", c: "c", d: "d"}.filter(:a, :b) # => {a: "1", b: "b"}
or
{a: "1", b: "b", c: "c", d: "d"}.filter(/^a/) # => {a: "1"}
Yes it should be possible, even if the site is from another domain.
For example, in an HTML page on my site I have an iFrame whose contents are sourced from another website. The iFrame content is a single select field.
I need to be able to read the selected value on my site. In other words, I need to use the select list from another domain inside my own application. I do not have control over any server settings.
Initially therefore we might be tempted to do something like this (simplified):
HTML in my site:
<iframe name='select_frame' src='http://www.othersite.com/select.php?initial_name=jim'></iframe>
<input type='button' name='save' value='SAVE'>
HTML contents of iFrame (loaded from select.php
on another domain):
<select id='select_name'>
<option value='john'>John</option>
<option value='jim' selected>Jim</option>
</select>
jQuery:
$('input:button[name=save]').click(function() {
var name = $('iframe[name=select_frame]').contents().find('#select_name').val();
});
However, I receive this javascript error when I attempt to read the value:
Blocked a frame with origin "http://www.myownsite.com" from accessing a frame with origin "http://www.othersite.com". Protocols, domains, and ports must match.
To get around this problem, it seems that you can indirectly source the iFrame from a script in your own site, and have that script read the contents from the other site using a method like file_get_contents()
or curl
etc.
So, create a script (for example: select_local.php
in the current directory) on your own site with contents similar to this:
PHP content of select_local.php:
<?php
$url = "http://www.othersite.com/select.php?" . $_SERVER['QUERY_STRING'];
$html_select = file_get_contents($url);
echo $html_select;
?>
Also modify the HTML to call this local (instead of the remote) script:
<iframe name='select_frame' src='select_local.php?initial_name=jim'></iframe>
<input type='button' name='save' value='SAVE'>
Now your browser should think that it is loading the iFrame content from the same domain.
I got an error because DatePipe is not a provider, so it cannot be injected. One solution is to put it as a provider in your app module but my preferred solution was to instantiate it.
I looked at DatePipe's source code to see how it got the locale: https://github.com/angular/angular/blob/5.2.5/packages/common/src/pipes/date_pipe.ts#L15-L174
I wanted to use it within a pipe, so my example is within another pipe:
import { Pipe, PipeTransform, Inject, LOCALE_ID } from '@angular/core';
import { DatePipe } from '@angular/common';
@Pipe({
name: 'when',
})
export class WhenPipe implements PipeTransform {
static today = new Date((new Date).toDateString().split(' ').slice(1).join(' '));
datePipe: DatePipe;
constructor(@Inject(LOCALE_ID) private locale: string) {
this.datePipe = new DatePipe(locale);
}
transform(value: string | Date): string {
if (typeof(value) === 'string')
value = new Date(value);
return this.datePipe.transform(value, value < WhenPipe.today ? 'MMM d': 'shortTime')
}
}
The key here is importing Inject, and LOCALE_ID from angular's core, and then injecting that so you can give it to the DatePipe to instantiate it properly.
In your app module you could also add DatePipe to your providers array like this:
import { DatePipe } from '@angular/common';
@NgModule({
providers: [
DatePipe
]
})
Now you can just have it injected in your constructor where needed (like in cexbrayat's answer).
Either solution worked, I don't know which one angular would consider most "correct" but I chose to instantiate it manually since angular didn't provide datepipe as a provider itself.
I know this is an old question but since none of the answers mentioned the large object heap, this might be of use to others who find this question ...
Any memory allocation in .NET that is over 85,000 bytes comes from the large object heap (LOH) not the normal small object heap. Why does this matter? Because the large object heap is not compacted. Which means that the large object heap gets fragmented and in my experience this inevitably leads to out of memory errors.
In the original question the list has 50,000 items in it. Internally a list uses an array, and assuming 32 bit that requires 50,000 x 4bytes = 200,000 bytes (or double that if 64 bit). So that memory allocation is coming from the large object heap.
So what can you do about it?
If you are using a .net version prior to 4.5.1 then about all you can do about it is to be aware of the problem and try to avoid it. So, in this instance, instead of having a list of vehicles you could have a list of lists of vehicles, provided no list ever had more than about 18,000 elements in it. That can lead to some ugly code, but it is viable work around.
If you are using .net 4.5.1 or later then the behaviour of the garbage collector has changed subtly. If you add the following line where you are about to make large memory allocations:
System.Runtime.GCSettings.LargeObjectHeapCompactionMode = System.Runtime.GCLargeObjectHeapCompactionMode.CompactOnce;
it will force the garbage collector to compact the large object heap - next time only.
It might not be the best solution but the following has worked for me:
int tries = 0;
while (tries++ < 2)
{
try
{
. . some large allocation . .
return;
}
catch (System.OutOfMemoryException)
{
System.Runtime.GCSettings.LargeObjectHeapCompactionMode = System.Runtime.GCLargeObjectHeapCompactionMode.CompactOnce;
GC.Collect();
}
}
of course this only helps if you have the physical (or virtual) memory available.
Play released its module for dealing with JSON independently from Play Framework, Play WS
Made a blog post about that, check it out at http://pedrorijo.com/blog/scala-json/
Using case classes, and Play WS (already included in Play Framework) you case convert between json and case classes with a simple one-liner implicit
case class User(username: String, friends: Int, enemies: Int, isAlive: Boolean)
object User {
implicit val userJsonFormat = Json.format[User]
}
06/2013 :
public class Fibonaci{
static void fibonacci() {
int ptr1 = 1, ptr2 = 1, ptr3 = 0;
int temp = 0;
BufferedReader Data=new BufferedReader (new InputStreamReader(System.in));
try {
System.out.println("The Number Value's fib you required ? ");
ptr3 = Integer.parseInt(Data.readLine());
System.out.print(ptr1 + " " + ptr2 + " ");
for (int i = 0; i < ptr3; i++) {
System.out.print(ptr1 + ptr2 + " ");
temp = ptr1;
ptr1 = ptr2;
ptr2 = temp + ptr2;
}
} catch(IOException err) {
System.out.println("Error!" + err);
} catch(NumberFormatException err) {
System.out.println("Invald Input!");
}
}
public static void main(String[]args)throws Exception{
Fibonaci.fibonacci();
}
}
You can do like this.
Use the to_datetime
function, specifying a format to match your data.
raw_data['Mycol'] = pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')
I made this library to do this.
https://github.com/fx-kirin/add_parent_path
# Just add parent path
add_parent_path(1)
# Append to syspath and delete when the exist of with statement.
with add_parent_path(1):
# Import modules in the parent path
pass
Using TimeUnit.SECONDS.sleep(1);
or Thread.sleep(1000);
Is acceptable way to do it. In both cases you have to catch InterruptedException
which makes your code Bulky.There is an Open Source java library called MgntUtils (written by me) that provides utility that already deals with InterruptedException
inside. So your code would just include one line:
TimeUtils.sleepFor(1, TimeUnit.SECONDS);
See the javadoc here. You can access library from Maven Central or from Github. The article explaining about the library could be found here
If you are using Android Studio 3.0 or above make sure your project build.gradle should have content similar to-
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.1'
}
}
allprojects {
repositories {
google()
jcenter()
}
}
Note- position really matters add google() before jcenter()
And for below Android Studio 3.0 and starting from support libraries 26.+ your project build.gradle must look like this-
allprojects {
repositories {
jcenter()
maven {
url "https://maven.google.com"
}
}
}
check these links below for more details-
There is also an alternate solution for those who aren't afraid of using hex editors (e.g. XVI32) [thanks to Trevor for this]: in the unpacked 1 installer executable (jdk-8uXX-windows-i586.exe
in case of JDK) simply replace all occurrences of RegDeleteKeyExA
(the name of API found in "new" ADVAPI32.DLL
) with RegDeleteKeyA
(legacy API name), followed by two hex '00's (to preserve padding/segmentation boundaries). The installer will complain about unsupported Windows version, but will work nevertheless.
For reference, the raw hex strings will be:
52 65 67 44 65 6C 65 74 65 4B 65 79 45 78 41
replaced with
52 65 67 44 65 6C 65 74 65 4B 65 79 41 00 00
Note: this procedure applies to both offline (standalone) and online (downloader) package.
1: some newer installer versions are packed with UPX - you'd need to unpack them first, otherwise you simply won't be able to find the hex string required
If you want to specify a list of files on the command line, and get the whole thing done in a single atomic command, try:
git apply --3way <(git show -- list-of-files)
--3way
: If a patch does not apply cleanly, Git will create a merge conflict so you can run git mergetool
. Omitting --3way
will make Git give up on patches which don't apply cleanly.
Abridged from: XML, Escaping
There are five predefined entities:
< represents "<"
> represents ">"
& represents "&"
' represents '
" represents "
"All permitted Unicode characters may be represented with a numeric character reference." For example:
中
Most of the control characters and other Unicode ranges are specifically excluded, meaning (I think) they can't occur either escaped or direct:
If you use the following to change the port or host:
if __name__ == '__main__':
app.run(host='0.0.0.0', port=80)
use the following code to start the server (my main entrance for flask is app.py):
python app.py
instead of using:
flask run
I'd like to point out 2 more options:
For x64 install zlib1g-dev
.
sudo apt-get install zlib1g-dev
I don't need all the x86 libs ;)
Indeed, just as commented by Tim Williams, the way to make it work is pre-formatting as text. Thus, to do it all via VBA, just do that:
Cells(1, 1).NumberFormat = "@"
Cells(1, 1).Value = "1234,56"
It's just what it says:
inputFile = open((x), encoding = "utf8", "r")
You have specified encoding
as a keyword argument, but "r"
as a positional argument. You can't have positional arguments after keyword arguments. Perhaps you wanted to do:
inputFile = open((x), "r", encoding = "utf8")
return
in function return execution back to caller and exit
from function terminates the program.
in main
function return 0
or exit(0)
are same but if you write exit(0)
in different function then you program will exit from that position.
returning different values like return 1
or return -1
means that program is returning error .
When exit(0)
is used to exit from program, destructors for locally scoped non-static objects are not called. But destructors are called if return 0 is used.
This is a nudity detector. I haven't tried it. It's the only OSS one I could find.
You can try this way:
open('u.item', encoding='utf8', errors='ignore')
Kibana is also a good solution. It is a data visualization platform for Elastic.If installed it runs by default on port 5601.
Out of the many things it provides. It has "Dev Tools" where we can do your debugging.
For example you can check your available indexes here using the command
GET /_cat/indices
A simple solution of error is that you first need to change the folder directory in command prompt. By default in command prompt or in terminal(Inside Android studio in the bottom)tab the path is set to C:\Users#Name of your PC that you selected\AndroidStudioProjects#app name\flutter_app> Change accordingly:- C:\Users#Name of your PC that you selected\AndroidStudioProjects#app name\flutter_app>cd\