I do not recall my original use case for this mechanism. Nowadays, I cannot think of any valid use case.
Your client should be able to detect when the connection is lost and allow you to re-create the connection. If it important that part of program logic is executed using the same connection, then use transactions.
tl;dr; Do not use this method.
A pragmatic solution is to force MySQL to keep the connection alive:
setInterval(function () {
db.query('SELECT 1');
}, 5000);
I prefer this solution to connection pool and handling disconnect because it does not require to structure your code in a way thats aware of connection presence. Making a query every 5 seconds ensures that the connection will remain alive and PROTOCOL_CONNECTION_LOST
does not occur.
Furthermore, this method ensures that you are keeping the same connection alive, as opposed to re-connecting. This is important. Consider what would happen if your script relied on LAST_INSERT_ID()
and mysql connection have been reset without you being aware about it?
However, this only ensures that connection time out (wait_timeout
and interactive_timeout
) does not occur. It will fail, as expected, in all others scenarios. Therefore, make sure to handle other errors.
The following query is very helpful
select * from
(select count(*) used from pg_stat_activity) q1,
(select setting::int res_for_super from pg_settings where name=$$superuser_reserved_connections$$) q2,
(select setting::int max_conn from pg_settings where name=$$max_connections$$) q3;
I am using this, try it in playground. Define the base urls as Struct in Constants
struct Constants {
struct APIDetails {
static let APIScheme = "https"
static let APIHost = "restcountries.eu"
static let APIPath = "/rest/v1/alpha/"
}
}
private func createURLFromParameters(parameters: [String:Any], pathparam: String?) -> URL {
var components = URLComponents()
components.scheme = Constants.APIDetails.APIScheme
components.host = Constants.APIDetails.APIHost
components.path = Constants.APIDetails.APIPath
if let paramPath = pathparam {
components.path = Constants.APIDetails.APIPath + "\(paramPath)"
}
if !parameters.isEmpty {
components.queryItems = [URLQueryItem]()
for (key, value) in parameters {
let queryItem = URLQueryItem(name: key, value: "\(value)")
components.queryItems!.append(queryItem)
}
}
return components.url!
}
let url = createURLFromParameters(parameters: ["fullText" : "true"], pathparam: "IN")
//Result url= https://restcountries.eu/rest/v1/alpha/IN?fullText=true
Dont write with stability stable
in the command ,
in your composer.json file, put
"minimum-stability": "stable"
before the closing curly bracket.
The <input type="button">
is just a button and won't do anything by itself.
The <input type="submit">
, when inside a form element, will submit the form when clicked.
Another useful 'special' button is the <input type="reset">
that will clear the form.
I have an Activity that extends ListActivity.
I tried doing something like this in onCreate:
ListView listView = getListView();
listView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Log.i("Hello!", "Y u no see me?");
}
});
But that didn't work.
Instead I simply needed to override onListItemClick:
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Log.i("Hello!", "Clicked! YAY!");
}
Demo: http://www.jqueryscript.net/demo/jQuery-Plugin-For-Fixed-Table-Header-Footer-Columns-TableHeadFixer/
HTML
<h2>TableHeadFixer Fix Left Column</h2>
<div id="parent">
<table id="fixTable" class="table">
<thead>
<tr>
<th>Ano</th>
<th>Jan</th>
<th>Fev</th>
<th>Mar</th>
<th>Abr</th>
<th>Maio</th>
<th>Total</th>
</tr>
</thead>
<tbody>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
<tr>
<td>2012</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>110.00</td>
<td>550.00</td>
</tr>
</tbody>
</table>
</div>
JS
$(document).ready(function() {
$("#fixTable").tableHeadFixer({"head" : false, "right" : 1});
});
CSS
#parent {
height: 300px;
}
#fixTable {
width: 1800px !important;
}
You can also do this.
//find the index of the CompanyName column
int columnIndex = thisReader.GetOrdinal("CompanyName");
//Get the value of the column. Will throw if the value is null.
string companyName = thisReader.GetString(columnIndex);
MY OWN SOLUTION
I created a new component
called test
in this folder:
I also created a mock called test.json
in the assests
folder created by angular cli
(important):
This mock looks like this:
[
{
"id": 1,
"name": "Item 1"
},
{
"id": 2,
"name": "Item 2"
},
{
"id": 3,
"name": "Item 3"
}
]
In the controller of my component test
import
follow rxjs
like this
import 'rxjs/add/operator/map'
This is important, because you have to map
your response
from the http get
call, so you get a json
and can loop it in your ngFor
. Here is my code how I load the mock data. I used http
get
and called my path to the mock with this path this.http.get("/assets/mock/test/test.json")
. After this i map
the response and subscribe
it. Then I assign it to my variable items
and loop it with ngFor
in my template
. I also export the type. Here is my whole controller code:
import { Component, OnInit } from "@angular/core";
import { Http, Response } from "@angular/http";
import 'rxjs/add/operator/map'
export type Item = { id: number, name: string };
@Component({
selector: "test",
templateUrl: "./test.component.html",
styleUrls: ["./test.component.scss"]
})
export class TestComponent implements OnInit {
items: Array<Item>;
constructor(private http: Http) {}
ngOnInit() {
this.http
.get("/assets/mock/test/test.json")
.map(data => data.json() as Array<Item>)
.subscribe(data => {
this.items = data;
console.log(data);
});
}
}
And my loop in it's template
:
<div *ngFor="let item of items">
{{item.name}}
</div>
It works as expected! I can now add more mock files in the assests folder and just change the path to get it as json
. Notice that you have also to import the HTTP
and Response
in your controller. The same in you app.module.ts (main) like this:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule, JsonpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { TestComponent } from './components/molecules/test/test.component';
@NgModule({
declarations: [
AppComponent,
TestComponent
],
imports: [
BrowserModule,
HttpModule,
JsonpModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
public void ReadXmlFile()
{
string path = HttpContext.Current.Server.MapPath("~/App_Data"); // Finds the location of App_Data on server.
XmlTextReader reader = new XmlTextReader(System.IO.Path.Combine(path, "XMLFile7.xml")); //Combines the location of App_Data and the file name
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element:
break;
case XmlNodeType.Text:
columnNames.Add(reader.Value);
break;
case XmlNodeType.EndElement:
break;
}
}
}
You can avoid the first statement and just specify the path name in constructor of XmlTextReader.
Mhh.. I think @Damian asks for remove undefined field (property) from an JS object
.
Then, I would simply do :
for (const i in myObj)
if (typeof myObj[i] === 'undefined')
delete myObj[i];
Short and efficient solution, in (vanilla) JS ! Example :
const myObj = {_x000D_
a: 1,_x000D_
b: undefined,_x000D_
c: null, _x000D_
d: 'hello world'_x000D_
};_x000D_
_x000D_
for (const i in myObj) _x000D_
if (typeof myObj[i] === 'undefined') _x000D_
delete myObj[i]; _x000D_
_x000D_
console.log(myObj);
_x000D_
what I'm doing wrong here?
Almost everything.
$today = date('Y-m-d'); // no need for strtotime
$sth = $db->prepare("SELECT id_email FROM db WHERE hardcopy = '1' AND hardcopy_date <= :today AND hardcopy_sent = '0' ORDER BY id_email ASC");
$sth->bindParam(':today',$today); // no need for PDO::PARAM_STR
$sth->execute(); // no need for if
$this->id_email = $sth->fetchAll(PDO::FETCH_COLUMN); // no need for while
return count($this->id_email); // no need for the everything else
effectively, you always have your fetched data (in this case in $this->id_email
variable) to tell whether your query returned anything or not. Read more in my article on PDO.
Kotlin Solution:
For custom class save in onSaveInstanceState
you can be converted your class to JSON
string and restore it with Gson
convertion and for single String, Double, Int, Long
value save and restore as following. The following example is for Fragment
and Activity
:
For Activity:
For put data in saveInstanceState
:
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
//for custom class-----
val gson = Gson()
val json = gson.toJson(your_custom_class)
outState.putString("CUSTOM_CLASS", json)
//for single value------
outState.putString("MyString", stringValue)
outState.putBoolean("MyBoolean", true)
outState.putDouble("myDouble", doubleValue)
outState.putInt("MyInt", intValue)
}
Restore data:
override fun onRestoreInstanceState(savedInstanceState: Bundle) {
super.onRestoreInstanceState(savedInstanceState)
//for custom class restore
val json = savedInstanceState?.getString("CUSTOM_CLASS")
if (!json!!.isEmpty()) {
val gson = Gson()
testBundle = gson.fromJson(json, Session::class.java)
}
//for single value restore
val myBoolean: Boolean = savedInstanceState?.getBoolean("MyBoolean")
val myDouble: Double = savedInstanceState?.getDouble("myDouble")
val myInt: Int = savedInstanceState?.getInt("MyInt")
val myString: String = savedInstanceState?.getString("MyString")
}
You can restore it on Activity onCreate
also.
For fragment:
For put class in saveInstanceState
:
override fun onSaveInstanceState(outState: Bundle) {
super.onSaveInstanceState(outState)
val gson = Gson()
val json = gson.toJson(customClass)
outState.putString("CUSTOM_CLASS", json)
}
Restore data:
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
//for custom class restore
if (savedInstanceState != null) {
val json = savedInstanceState.getString("CUSTOM_CLASS")
if (!json!!.isEmpty()) {
val gson = Gson()
val customClass: CustomClass = gson.fromJson(json, CustomClass::class.java)
}
}
// for single value restore
val myBoolean: Boolean = savedInstanceState.getBoolean("MyBoolean")
val myDouble: Double = savedInstanceState.getDouble("myDouble")
val myInt: Int = savedInstanceState.getInt("MyInt")
val myString: String = savedInstanceState.getString("MyString")
}
For switching to the database.
By:
use {your_database_name} example:
use friends
where friends
is the name of your database.
Then write:
db.getCollectionNames()
show collections
This will give you the name of collections.
Option 1 is to use display:table-cell
. You need to unfloat the Bootstrap col-* using float:none
..
.center {
display:table-cell;
vertical-align:middle;
float:none;
}
Option 2 is display:flex
to vertical align the row with flexbox:
.row.center {
display: flex;
align-items: center;
}
http://www.bootply.com/7rAuLpMCwr
Vertical centering is very different in Bootstrap 4. See this answer for Bootstrap 4 https://stackoverflow.com/a/41464397/171456
Express.js is a framework used for Node and it is most commonly used as a web application for node js.
Here is a link to a video on how to quickly set up a node app with express https://www.youtube.com/watch?v=QEcuSSnqvck
Like other answers pointed out, you might find it easier to work with an array.
If not:
var alerts = {
1: {app:'helloworld',message:'message'},
2: {app:'helloagain',message:'another message'}
}
// Get the current size of the object
size = Object.keys(alerts).length
//add a new alert
alerts[size + 1] = {app:'Your new app', message:'your new message'}
//Result:
console.log(alerts)
{
1: {app:'helloworld',message:'message'},
2: {app:'helloagain',message:'another message'}
3: {app: "Another hello",message: "Another message"}
}
try it:
I assume this is a one-off data scrubbing exercise. Once done, ensure you add database constraints to prevent bad data in the future e.g.
ALTER TABLE Customer ADD
CONSTRAINT customer_names__whitespace
CHECK (
Names NOT LIKE ' %'
AND Names NOT LIKE '% '
AND Names NOT LIKE '% %'
);
Also consider disallowing other characters (tab, carriage return, line feed, etc) that may cause problems.
It may also be a good time to split those Names into family_name
, first_name
, etc :)
Another tip from my side:
In order to set the window's width to let's say exactly 80 columns, use
80 CTRL+W |
In order to set it to maximum width, just omit the preceding number:
CTRL+W |
Here is a more polished version of the accepted answer. It accepts only timestamps and returns a relative date or a formatted date string for everything +/-2 days
<?php
/**
* Relative time
*
* date Format http://php.net/manual/en/function.date.php
* strftime Format http://php.net/manual/en/function.strftime.php
* latter can be used with setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');
*
* @param timestamp $target
* @param timestamp $base start time, defaults to time()
* @param string $format use date('Y') or strftime('%Y') format string
* @return string
*/
function relative_time($target, $base = NULL, $format = 'Y-m-d H:i:s')
{
if(is_null($base)) {
$base = time();
}
$baseDate = new DateTime();
$targetDate = new DateTime();
$baseDate->setTimestamp($base);
$targetDate->setTimestamp($target);
// don't modify original dates
$baseDateTemp = clone $baseDate;
$targetDateTemp = clone $targetDate;
// normalize times -> reset to midnight that day
$baseDateTemp = $baseDateTemp->modify('midnight');
$targetDateTemp = $targetDateTemp->modify('midnight');
$interval = (int) $baseDateTemp->diff($targetDateTemp)->format('%R%a');
d($baseDate->format($format));
switch($interval) {
case 0:
return (string) 'today';
break;
case -1:
return (string) 'yesterday';
break;
case 1:
return (string) 'tomorrow';
break;
default:
if(strpos($format,'%') !== false )
{
return (string) strftime($format, $targetDate->getTimestamp());
}
return (string) $targetDate->format($format);
break;
}
}
setlocale(LC_ALL, 'de_DE@euro', 'de_DE', 'deu_deu');
echo relative_time($weather->time, null, '%A, %#d. %B'); // Montag, 6. August
echo relative_time($weather->time, null, 'l, j. F'); // Monday, 6. August
Strings are immutable, so using
public string GenerateString()
{
return
"abc" +
"def";
}
will slow you performance - each of those values is a string literal which must be concatenated at runtime - bad news if you reuse the method/property/whatever alot...
Store your string literals in resources is a good idea...
public string GenerateString()
{
return Resources.MyString;
}
That way it is localisable and the code is tidy (although performance is pretty terrible).
You can use .loc
to select the specific columns with all rows and then pull that. An example is below:
pandas.merge(dataframe1, dataframe2.iloc[:, [0:5]], how='left', on='key')
In this example, you are merging dataframe1 and dataframe2. You have chosen to do an outer left join on 'key'. However, for dataframe2 you have specified .iloc
which allows you to specific the rows and columns you want in a numerical format. Using :
, your selecting all rows, but [0:5]
selects the first 5 columns. You could use .loc
to specify by name, but if your dealing with long column names, then .iloc
may be better.
Instead of adding onSubmit event, you can prevent the default action for submit button.
So, in the following html:
<form name="form" action="insert.php" method="post">
<input type='submit' />
</form>?
first, prevent submit button action. Then make the ajax call asynchronously, and submit the form when the password is correct.
$('input[type=submit]').click(function(e) {
e.preventDefault(); //prevent form submit when button is clicked
var password = $.trim($('#employee_password').val());
$.ajax({
type: "POST",
url: "checkpass.php",
data: "password="+password,
success: function(html) {
var arr=$.parseJSON(html);
var $form = $('form');
if(arr == "Successful")
{
$form.submit(); //submit the form if the password is correct
}
}
});
});????????????????????????????????
You can refer to server examples in Fine Uploader, which has django version. https://github.com/FineUploader/server-examples/tree/master/python/django-fine-uploader
It's very elegant and most important of all, it provides featured js lib. Template is not included in server-examples, but you can find demo on its website. Fine Uploader: http://fineuploader.com/demos.html
views.py
UploadView dispatches post and delete request to respective handlers.
class UploadView(View):
@csrf_exempt
def dispatch(self, *args, **kwargs):
return super(UploadView, self).dispatch(*args, **kwargs)
def post(self, request, *args, **kwargs):
"""A POST request. Validate the form and then handle the upload
based ont the POSTed data. Does not handle extra parameters yet.
"""
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
handle_upload(request.FILES['qqfile'], form.cleaned_data)
return make_response(content=json.dumps({ 'success': True }))
else:
return make_response(status=400,
content=json.dumps({
'success': False,
'error': '%s' % repr(form.errors)
}))
def delete(self, request, *args, **kwargs):
"""A DELETE request. If found, deletes a file with the corresponding
UUID from the server's filesystem.
"""
qquuid = kwargs.get('qquuid', '')
if qquuid:
try:
handle_deleted_file(qquuid)
return make_response(content=json.dumps({ 'success': True }))
except Exception, e:
return make_response(status=400,
content=json.dumps({
'success': False,
'error': '%s' % repr(e)
}))
return make_response(status=404,
content=json.dumps({
'success': False,
'error': 'File not present'
}))
forms.py
class UploadFileForm(forms.Form):
""" This form represents a basic request from Fine Uploader.
The required fields will **always** be sent, the other fields are optional
based on your setup.
Edit this if you want to add custom parameters in the body of the POST
request.
"""
qqfile = forms.FileField()
qquuid = forms.CharField()
qqfilename = forms.CharField()
qqpartindex = forms.IntegerField(required=False)
qqchunksize = forms.IntegerField(required=False)
qqpartbyteoffset = forms.IntegerField(required=False)
qqtotalfilesize = forms.IntegerField(required=False)
qqtotalparts = forms.IntegerField(required=False)
Packaged artifacts contain a META-INF/maven/${groupId}/${artifactId}/pom.properties
file which content looks like:
#Generated by Maven
#Sun Feb 21 23:38:24 GMT 2010
version=2.5
groupId=commons-lang
artifactId=commons-lang
Many applications use this file to read the application/jar version at runtime, there is zero setup required.
The only problem with the above approach is that this file is (currently) generated during the package
phase and will thus not be present during tests, etc (there is a Jira issue to change this, see MJAR-76). If this is an issue for you, then the approach described by Alex is the way to go.
No.
Sometimes you can quote the filename.
"C:\Program Files\Something"
Some programs will tolerate the quotes. Since you didn't provide any specific program, it's impossible to tell if quotes will work for you.
No. JavaScript is automatically garbage collected; the object's memory will be reclaimed only if the GC decides to run and the object is eligible for collection.
Seeing as that will happen automatically as required, what would be the purpose of reclaiming the memory explicitly?
Switching to yarn solved the issue for me.
One solution would be to use the plt.legend
function, even if you don't want an actual legend. You can specify the placement of the legend box by using the loc
keyterm. More information can be found at this website but I've also included an example showing how to place a legend:
ax.scatter(xa,ya, marker='o', s=20, c="lightgreen", alpha=0.9)
ax.scatter(xb,yb, marker='o', s=20, c="dodgerblue", alpha=0.9)
ax.scatter(xc,yc marker='o', s=20, c="firebrick", alpha=1.0)
ax.scatter(xd,xd,xd, marker='o', s=20, c="goldenrod", alpha=0.9)
line1 = Line2D(range(10), range(10), marker='o', color="goldenrod")
line2 = Line2D(range(10), range(10), marker='o',color="firebrick")
line3 = Line2D(range(10), range(10), marker='o',color="lightgreen")
line4 = Line2D(range(10), range(10), marker='o',color="dodgerblue")
plt.legend((line1,line2,line3, line4),('line1','line2', 'line3', 'line4'),numpoints=1, loc=2)
Note that because loc=2
, the legend is in the upper-left corner of the plot. And if the text overlaps with the plot, you can make it smaller by using legend.fontsize
, which will then make the legend smaller.
Add --force to your command line if you are sure you want to push. E.g. use git push origin --force
(I recommend the command line as you will find much more support from other users with the command line. Also this may not be possible with SmartGit.) See this site for more information: http://help.github.com/remotes/
Use System.currentTimeMillis() or System.nanoTime() if you want even more precise reading. Usually, milliseconds is precise enough if you need to output the value to the user. Moreover, System.nanoTime()
may return negative values, thus it may be possible that, if you're using that method, the return value is not correct.
A general and wide use would be to use milliseconds :
long start = System.currentTimeMillis();
...
long end = System.currentTimeMillis();
NumberFormat formatter = new DecimalFormat("#0.00000");
System.out.print("Execution time is " + formatter.format((end - start) / 1000d) + " seconds");
Note that nanoseconds are usually used to calculate very short and precise program executions, such as unit testing and benchmarking. Thus, for overall program execution, milliseconds are preferable.
Use this because whenever transaction open more than one transaction then below will work SELECT * FROM sys.sysprocesses WHERE open_tran <> 0
This has been used above but not mentioned exclusively.
setCropToPadding(boolean);
If true, the image will be cropped to fit within its padding.
This will make the ImageView
source to fit within the padding's added to its background.
Via XML it can be done as below-
android:cropToPadding="true"
import java.util.Scanner;
class my{
public static void main(String args[])
{
Scanner x=new Scanner(System.in);
double a,b,c=0,d;
d=1;
d=d/10;
int e,z=0;
System.out.print("Enter no:");
a=x.nextInt();
for(b=1;b<=a/2;b++)
{
if(b*b==a)
{
c=b;
break;
}
else
{
if(b*b>a)
break;
}
}
b--;
if(c==0)
{
for(e=1;e<=15;e++)
{
while(b*b<=a && z==0)
{
if(b*b==a){c=b;z=1;}
else
{
b=b+d; //*d==0.1 first time*//
if(b*b>=a){z=1;b=b-d;}
}
}
d=d/10;
z=0;
}
c=b;
}
System.out.println("Squre root="+c);
}
}
This refreshes the calculation better than Range(A:B).Calculate
:
Public Sub UpdateMyFunctions()
Dim myRange As Range
Dim rng As Range
' Assume the functions are in this range A1:B10.
Set myRange = ActiveSheet.Range("A1:B10")
For Each rng In myRange
rng.Formula = rng.Formula
Next
End Sub
this work for me on galaxy note its show contacts, file managers installed on device, gallery, music player
private void openFile(Int CODE) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.setType("*/*");
startActivityForResult(intent, CODE);
}
here get path in onActivityResult
of activity.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
String Fpath = data.getDataString();
// do somthing...
super.onActivityResult(requestCode, resultCode, data);
}
Add white-space: nowrap;
:
.garage-title {
clear: both;
display: inline-block;
overflow: hidden;
white-space: nowrap;
}
hi i'm using ruby on rails for csv generation. In our application we plan to go for the multi language(I18n) and we faced an issue while viewing I18n content in the CSV file of windows excel.
Was fine with Linux (Ubuntu) and mac.
We identified that windows excel need to be imported the data again to view the actual data. While import we will get more options to choose character set.
But this can’t be educated for each and every user, so solution we looking for is to open just by double click.
Then we identified the way of showing data by open mode and bom in windows excel with the help of aghuddleston gist. Added at reference.
Example I18n content
In Mac and Linux
Swedish : Förnamn English : First name
In Windows
Swedish : Förnamn English : First name
def user_information_report(report_file_path, user_id)
user = User.find(user_id)
I18n.locale = user.current_lang
open_mode = "w+:UTF-16LE:UTF-8"
bom = "\xEF\xBB\xBF"
body user, open_mode, bom
end
def headers
headers = [
"ID", "SDN ID",
I18n.t('sys_first_name'), I18n.t('sys_last_name'), I18n.t('sys_dob'),
I18n.t('sys_gender'), I18n.t('sys_email'), I18n.t('sys_address'),
I18n.t('sys_city'), I18n.t('sys_state'), I18n.t('sys_zip'),
I18n.t('sys_phone_number')
]
end
def body tenant, open_mode, bom
File.open(report_file_path, open_mode) do |f|
csv_file = CSV.generate(col_sep: "\t") do |csv|
csv << headers
tenant.patients.find_each(batch_size: 10) do |patient|
csv << [
patient.id, patient.patientid,
patient.first_name, patient.last_name, "#{patient.dob}",
"#{translate_gender(patient.gender)}", patient.email, "#{patient.address_1.to_s} #{patient.address_2.to_s}",
"#{patient.city}", "#{patient.state}", "#{patient.zip}",
"#{patient.phone_number}"
]
end
end
f.write bom
f.write(csv_file)
end
end
Important things to note here is open mode and bom
open_mode = "w+:UTF-16LE:UTF-8"
bom = "\xEF\xBB\xBF"
Before writing the CSV insert BOM
f.write bom
f.write(csv_file)
Windows and Mac
File can be opened directly by double clicking.
Linux (ubuntu)
While opening a file ask for the separator options -> choose “TAB”
Please perform the following two steps only to get rid of this error.
1. Clean Project using Product -> clean.
2. Run the Project.
Now try to add/Connect the actions or outlets.
Working Fine for me for many times.
You can also put DOM elements, like div
on top of the canvas that would represent your canvas elements and be positioned the same way.
Now you can attach event listeners to these divs and run the necessary actions.
You can use kill -0
for checking whether a particular pid is running or not.
Assuming, you have list of pid
numbers in a file called pid
in pwd
while true;
do
if [ -s pid ] ; then
for pid in `cat pid`
do
echo "Checking the $pid"
kill -0 "$pid" 2>/dev/null || sed -i "/^$pid$/d" pid
done
else
echo "All your process completed" ## Do what you want here... here all your pids are in finished stated
break
fi
done
I had to use nl2br to display the carriage returns correctly and it worked for me:
<?php
echo nl2br(file_get_contents( "filename.php" )); // get the contents, and echo it out.
?>
PHP 7.1.0 has introduced the iterable
pseudo-type and the is_iterable()
function, which is specially designed for such a purpose:
This […] proposes a new
iterable
pseudo-type. This type is analogous tocallable
, accepting multiple types instead of one single type.
iterable
accepts anyarray
or object implementingTraversable
. Both of these types are iterable usingforeach
and can be used withyield
from within a generator.
function foo(iterable $iterable) {
foreach ($iterable as $value) {
// ...
}
}
This […] also adds a function
is_iterable()
that returns a boolean:true
if a value is iterable and will be accepted by theiterable
pseudo-type,false
for other values.
var_dump(is_iterable([1, 2, 3])); // bool(true)
var_dump(is_iterable(new ArrayIterator([1, 2, 3]))); // bool(true)
var_dump(is_iterable((function () { yield 1; })())); // bool(true)
var_dump(is_iterable(1)); // bool(false)
var_dump(is_iterable(new stdClass())); // bool(false)
You can also use the function is_array($var)
to check if the passed variable is an array:
<?php
var_dump( is_array(array()) ); // true
var_dump( is_array(array(1, 2, 3)) ); // true
var_dump( is_array($_SERVER) ); // true
?>
Read more in How to check if a variable is an array in PHP?
Use these Kotlin extensions:
/**
* Converts Pixel to DP.
*/
val Int.pxToDp: Int
get() = (this / Resources.getSystem().displayMetrics.density).toInt()
/**
* Converts DP to Pixel.
*/
val Int.dpToPx: Int
get() = (this * Resources.getSystem().displayMetrics.density).toInt()
If using the above solution of two <VirtualHost *:80>
blocks with different ServerName
s...
<VirtualHost *:80>
ServerName example.com
Redirect permanent / http://www.example.com/
</VirtualHost>
<VirtualHost *:80>
ServerName www.example.com
</VirtualHost>
... then you must set NameVirtualHost On
as well.
If you don't do this, Apache doesn't allow itself to use the different ServerName
s to distinguish the blocks, so you get this error message:
[warn] _default_ VirtualHost overlap on port 80, the first has precedence
...and either no redirection happens, or you have an infinite redirection loop, depending on which block you put first.
<div style="text-align: center; border-top: 1px solid black">
<div style="display: inline-block; position: relative; top: -10px; background-color: white; padding: 0px 10px">text</div>
</div>
try this : here select is your select element
let select = document.getElementsByClassName('lstSelected')[0],
options = select.options,
len = options.length,
data='',
i=0;
while (i<len){
if (options[i].selected)
data+= "&" + select.name + '=' + options[i].value;
i++;
}
return data;
Data is in the form of query string i.e.name=value&name=anotherValue
Hope this will help...
mdpi is the reference density -- that is, 1 px on an mdpi display is equal to 1 dip. The ratio for asset scaling is:
ldpi | mdpi | hdpi | xhdpi | xxhdpi | xxxhdpi
0.75 | 1 | 1.5 | 2 | 3 | 4
Although you don't really need to worry about tvdpi unless you're developing specifically for Google TV or the original Nexus 7 -- but even Google recommends simply using hdpi assets. You probably don't need to worry about xxhdpi either (although it never hurts, and at least the launcher icon should be provided at xxhdpi), and xxxhdpi is just a constant in the source code right now (no devices use it, nor do I expect any to for a while, if ever), so it's safe to ignore as well.
What this means is if you're doing a 48dip image and plan to support up to xhdpi resolution, you should start with a 96px image (144px if you want native assets for xxhdpi) and make the following images for the densities:
ldpi | mdpi | hdpi | xhdpi | xxhdpi | xxxhdpi
36 x 36 | 48 x 48 | 72 x 72 | 96 x 96 | 144 x 144 | 192 x 192
And these should display at roughly the same size on any device, provided you've placed these in density-specific folders (e.g. drawable-xhdpi, drawable-hdpi, etc.)
For reference, the pixel densities for these are:
ldpi | mdpi | hdpi | xhdpi | xxhdpi | xxxhdpi
120 | 160 | 240 | 320 | 480 | 640
#include <omp.h>
double start = omp_get_wtime();
// code
double finish = omp_get_wtime();
double total_time = finish - start;
I add my answer, similar to others but maybe it will be the quickest one to read and implement.
NOTE: Rebase is not needed in this case.
Assume I have a repo1
and two branches master
and dev-user
.
dev-user
is a branch done at a certain state of master
.
Now assume that both dev-user
and master
advance.
At some point I want dev-user
to get all the commits made in master
.
How do I do it?
I go first in my repository root folder
cd name_of_the_repository
then
git checkout master
git pull
git checkout dev-user
git pull
git merge master
git push
I hope this helps someone else in the same situation.
The functionality is indeed similar (apart from the calling semantics, where call-template
requires a name
attribute and a corresponding names template).
However, the parser will not execute the same way.
From MSDN:
Unlike
<xsl:apply-templates>
,<xsl:call-template>
does not change the current node or the current node-list.
File.Create(string)
returns an instance of the FileStream
class. You can call the Stream.Close()
method on this object in order to close it and release resources that it's using:
var myFile = File.Create(myPath);
myFile.Close();
However, since FileStream
implements IDisposable
, you can take advantage of the using
statement (generally the preferred way of handling a situation like this). This will ensure that the stream is closed and disposed of properly when you're done with it:
using (var myFile = File.Create(myPath))
{
// interact with myFile here, it will be disposed automatically
}
If you prefer a one-liner:
matched_lines = [line for line in my_string.split('\n') if "substring" in line]
This uses the standard CSS border and a pseudo element+overflow:hidden. In the example you get three different 2px dashed borders: normal, spaced like a 5px, spaced like a 10px. Is actually 10px with only 10-8=2px visible.
div.two{border:2px dashed #FF0000}_x000D_
_x000D_
div.five:before {_x000D_
content: "";_x000D_
position: absolute;_x000D_
border: 5px dashed #FF0000;_x000D_
top: -3px;_x000D_
bottom: -3px;_x000D_
left: -3px;_x000D_
right: -3px;_x000D_
}_x000D_
_x000D_
div.ten:before {_x000D_
content: "";_x000D_
position: absolute;_x000D_
border: 10px dashed #FF0000;_x000D_
top: -8px;_x000D_
bottom: -8px;_x000D_
left: -8px;_x000D_
right: -8px;_x000D_
}_x000D_
_x000D_
div.odd:before {left:0;right:0;border-radius:60px}_x000D_
_x000D_
div {_x000D_
overflow: hidden;_x000D_
position: relative;_x000D_
_x000D_
_x000D_
text-align:center;_x000D_
padding:10px;_x000D_
margin-bottom:20px;_x000D_
}
_x000D_
<div class="two">Kupo nuts here</div>_x000D_
<div class="five">Kupo nuts<br/>here</div>_x000D_
<div class="ten">Kupo<br/>nuts<br/>here</div>_x000D_
<div class="ten odd">Kupo<br/>nuts<br/>here</div>
_x000D_
Applied to small elements with big rounded corners may make for some fun effects.
The php mysql api is deprecated. It's kaput --- going away -- not to be used, finito.
If you have a modern version of PHP (> 5.6) then Wordpress should automatically switch to make use of mysqli. That should be your first attempt.
If you can not update your php, rather than attempting to resurrect something that php no longer supports, just patch your wordpress: http://wordpress.org/plugins/mysqli/
If you're using Selenium with Firefox you should be able to use EXSLT extensions, and regexp:test()
Does this work for you?
String expr = "//*[regexp:test(@id, 'sometext[0-9]+_text')]";
driver.findElement(By.xpath(expr));
General Syntax:
7z a archive_name target parameters
Check your 7-Zip dir. Depending on the release you have, 7z may be replaced with 7za in the syntax.
Parameters:
Eg. This will prompt for a PW and hide file structures:
7z a archive_name target -p -mhe=on
Eg. No prompt, visible file structure:
7z a archive_name target -pPUT_PASSWORD_HERE
And so on. If you leave target blank, 7z will assume * in current directory and it will recurs directories by default.
What you are after is called partial function application.
Don't be fooled by those that don't understand the subtle difference between that and currying, they are different.
Partial function application can be used to implement, but is not currying. Here is a quote from a blog post on the difference:
Where partial application takes a function and from it builds a function which takes fewer arguments, currying builds functions which take multiple arguments by composition of functions which each take a single argument.
This has already been answered, see this question for your answer: How can I pre-set arguments in JavaScript function call?
Example:
var fr = partial(f, 1, 2, 3);
// now, when you invoke fr() it will invoke f(1,2,3)
fr();
Again, see that question for the details.
To validate for only letters and spaces, try this
String name1_exp = "^[a-zA-Z]+[\-'\s]?[a-zA-Z ]+$";
Firstly you have to create state in app.js as below
.state('login', {
url: '/',
templateUrl: 'views/login.html',
controller: 'LoginCtrl'
})
and use below code in controller
$location.path('login');
Hope this will help you
Python 3.8 one-liner if you don't care to write your own algorithm or use libraries:
l = [1,2,3,2,1,5,6,5,5,5]
res = [(x, count) for x, g in groupby(sorted(l)) if (count := len(list(g))) > 1]
print(res)
Prints item and count:
[(1, 2), (2, 2), (5, 4)]
groupby
takes a grouping function so you can define your groupings in different ways and return additional Tuple
fields as needed.
This question has already been answered for the original poster, but in case someone encounters this in an MS-Test project:
from within Visual Studio, click the Test menu -> Test Settings -> Default Processor Architecture and ensure that the architecture matches that of the other assembly that you're referencing. If the other assembly is x64 and your test settings are x86, you may experience the symptoms that the original poster had.
If you have the table definition to have an IDENTITY column e.g. IDENTITY(1,1) then don't include MyId in your INSERT INTO statement. The point of IDENTITY is it gives it the next unused value as the primary key value.
insert into MYDB.dbo.MainTable (MyFirstName, MyLastName, MyAddress, MyPort)
values(@myFirstName, @myLastName, @myAddress, @myPort)
There is then no need to pass the @MyId parameter into your stored procedure either. So change it to:
CREATE PROCEDURE [dbo].[sp_Test]
@myFirstName nvarchar(50)
,@myLastName nvarchar(50)
,@myAddress nvarchar(MAX)
,@myPort int
AS
If you want to know what the ID of the newly inserted record is add
SELECT @@IDENTITY
to the end of your procedure. e.g. http://msdn.microsoft.com/en-us/library/ms187342.aspx
You will then be able to pick this up in which ever way you are calling it be it SQL or .NET.
P.s. a better way to show you table definision would have been to script the table and paste the text into your stackoverflow browser window because your screen shot is missing the column properties part where IDENTITY is set via the GUI. To do that right click the table 'Script Table as' --> 'CREATE to' --> Clipboard. You can also do File or New Query Editor Window (all self explanitory) experient and see what you get.
Another thing you can do is to:
Item
model that returns the category name and ReadOnlyField
.Your model would look like this.
class Item(models.Model):
name = models.CharField(max_length=100)
category = models.ForeignKey(Category, related_name='items')
def __unicode__(self):
return self.name
@property
def category_name(self):
return self.category.name
Your serializer would look like this. Note that the serializer will automatically get the value of the category_name
model property by naming the field with the same name.
class ItemSerializer(serializers.ModelSerializer):
category_name = serializers.ReadOnlyField()
class Meta:
model = Item
You can get the introduction of the article in Wikipedia by querying pages such as https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro=&explaintext=&titles=java. You just need to parse the json file and the result is plain text which has been cleaned including removing links and references.
Give another go at force removing the brewed version of git
brew uninstall --force git
Then cleanup any older versions and clear the brew cache
brew cleanup -s git
Remove any dead symlinks
brew cleanup --prune-prefix
Then try reinstalling git
brew install git
If that doesn't work, I'd remove that installation of Homebrew altogether and reinstall it. If you haven't placed anything else in your brew --prefix
directory (/usr/local
by default), you can simply rm -rf $(brew --prefix)
. Otherwise the Homebrew wiki recommends using a script at https://gist.github.com/mxcl/1173223#file-uninstall_homebrew-sh
Specifically, if you are dealing with a UserForm, then you might try the Repaint method. You might encounter an issue with DoEvents if you are using event triggers in your form. For instance, any keys pressed while a function is running will be sent by DoEvents The keyboard input will be processed before the screen is updated, so if you are changing cells on a spreadsheet by holding down one of the arrow keys on the keyboard, then the cell change event will keep firing before the main function finishes.
A UserForm will not be refreshed in some cases, because DoEvents will fire the events; however, Repaint will update the UserForm and the user will see the changes on the screen even when another event immediately follows the previous event.
In the UserForm code it is as simple as:
Me.Repaint
Since no one has mentioned this yet, about the only way to get smart printf
statements is to use the ternary operator:
printf("%d item%s", count, count > 1 ? "s\n" : "\n");
Caveat: There are some differences in operator precedence when you move from C to C++ and may be surprised by the subtle bug(s) that arise thereof.
Seems to me like you want to create a property.
public int MyProperty
{
get { return _myProperty; }
set
{
_myProperty = value;
if (_myProperty == 1)
{
// DO SOMETHING HERE
}
}
}
private int _myProperty;
This allows you to run some code any time the property value changes. You could raise an event here, if you wanted.
Swift 5, Alamofire, host
//Session reference
var alamofireSessionManager: Session!
func checkHostReachable(completionHandler: @escaping (_ isReachable:Bool) -> Void) {
let configuration = URLSessionConfiguration.default
configuration.timeoutIntervalForRequest = 1
configuration.timeoutIntervalForResource = 1
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
alamofireSessionManager = Session(configuration: configuration)
alamofireSessionManager.request("https://google.com").response { response in
completionHandler(response.response?.statusCode == 200)
}
}
//using
checkHostReachable() { (isReachable) in
print("isReachable:\(isReachable)")
}
Data contract: It specifies that your entity class is ready for Serialization process.
Data members: It specifies that the particular field is part of the data contract and it can be serialized.
Yes, assignment will just copy the value of l1
(which is a reference) to l2
. They will both refer to the same object.
Creating a shallow copy is pretty easy though:
List<Integer> newList = new ArrayList<>(oldList);
(Just as one example.)
I think Buu's digest cycle watch is genius. Thanks for sharing. As others have noted $interval also causes the digest cycle to run. We could for the purpose of auto logging the user out use setInterval which will not cause a digest loop.
app.run(function($rootScope) {
var lastDigestRun = new Date();
setInterval(function () {
var now = Date.now();
if (now - lastDigestRun > 10 * 60 * 1000) {
//logout
}
}, 60 * 1000);
$rootScope.$watch(function() {
lastDigestRun = new Date();
});
});
CSS only solution for modern browsers
@keyframes slidein {
0% {margin-left:1500px;}
100% {margin-left:0px;}
}
.note {
animation-name: slidein;
animation-duration: .9s;
display: block;
}
Since you've got an array, what you really want is Array#slice
, not split
.
rest = ex.slice(1 .. -1)
# or
rest = ex[1 .. -1]
@Html.TextAreaFor(model => model.Text)
Wrap the name in a span, give it a class and assign a style to that class:
<td><span class="names">Name text you want bold</span> rest of your text</td>
style:
.names { font-weight: bold; }
Since AngularJS 1.3.4 you can use $setDirty()
on fields (source). For example, for each field with error and marked required you can do the following:
angular.forEach($scope.form.$error.required, function(field) {
field.$setDirty();
});
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
System.out.println(sdf.format(date));
std::min_element(vec.begin(), vec.end())
- for std::vector
std::min_element(v, v+n)
- for array
std::min_element( std::begin(v), std::end(v) )
- added C++11 version from comment by @JamesKanze
def transpose_finite_iterable(iterable):
return zip(*iterable) # `itertools.izip` for Python 2 users
works fine for finite iterable (e.g. sequences like list
/tuple
/str
) of (potentially infinite) iterables which can be illustrated like
| |a_00| |a_10| ... |a_n0| |
| |a_01| |a_11| ... |a_n1| |
| |... | |... | ... |... | |
| |a_0i| |a_1i| ... |a_ni| |
| |... | |... | ... |... | |
where
n in N
,a_ij
corresponds to j
-th element of i
-th iterable,and after applying transpose_finite_iterable
we get
| |a_00| |a_01| ... |a_0i| ... |
| |a_10| |a_11| ... |a_1i| ... |
| |... | |... | ... |... | ... |
| |a_n0| |a_n1| ... |a_ni| ... |
Python example of such case where a_ij == j
, n == 2
>>> from itertools import count
>>> iterable = [count(), count()]
>>> result = transpose_finite_iterable(iterable)
>>> next(result)
(0, 0)
>>> next(result)
(1, 1)
But we can't use transpose_finite_iterable
again to return to structure of original iterable
because result
is an infinite iterable of finite iterables (tuple
s in our case):
>>> transpose_finite_iterable(result)
... hangs ...
Traceback (most recent call last):
File "...", line 1, in ...
File "...", line 2, in transpose_finite_iterable
MemoryError
So how can we deal with this case?
deque
After we take a look at docs of itertools.tee
function, there is Python recipe that with some modification can help in our case
def transpose_finite_iterables(iterable):
iterator = iter(iterable)
try:
first_elements = next(iterator)
except StopIteration:
return ()
queues = [deque([element])
for element in first_elements]
def coordinate(queue):
while True:
if not queue:
try:
elements = next(iterator)
except StopIteration:
return
for sub_queue, element in zip(queues, elements):
sub_queue.append(element)
yield queue.popleft()
return tuple(map(coordinate, queues))
let's check
>>> from itertools import count
>>> iterable = [count(), count()]
>>> result = transpose_finite_iterables(transpose_finite_iterable(iterable))
>>> result
(<generator object transpose_finite_iterables.<locals>.coordinate at ...>, <generator object transpose_finite_iterables.<locals>.coordinate at ...>)
>>> next(result[0])
0
>>> next(result[0])
1
Now we can define general function for working with iterables of iterables ones of which are finite and another ones are potentially infinite using functools.singledispatch
decorator like
from collections import (abc,
deque)
from functools import singledispatch
@singledispatch
def transpose(object_):
"""
Transposes given object.
"""
raise TypeError('Unsupported object type: {type}.'
.format(type=type))
@transpose.register(abc.Iterable)
def transpose_finite_iterables(object_):
"""
Transposes given iterable of finite iterables.
"""
iterator = iter(object_)
try:
first_elements = next(iterator)
except StopIteration:
return ()
queues = [deque([element])
for element in first_elements]
def coordinate(queue):
while True:
if not queue:
try:
elements = next(iterator)
except StopIteration:
return
for sub_queue, element in zip(queues, elements):
sub_queue.append(element)
yield queue.popleft()
return tuple(map(coordinate, queues))
def transpose_finite_iterable(object_):
"""
Transposes given finite iterable of iterables.
"""
yield from zip(*object_)
try:
transpose.register(abc.Collection, transpose_finite_iterable)
except AttributeError:
# Python3.5-
transpose.register(abc.Mapping, transpose_finite_iterable)
transpose.register(abc.Sequence, transpose_finite_iterable)
transpose.register(abc.Set, transpose_finite_iterable)
which can be considered as its own inverse (mathematicians call this kind of functions "involutions") in class of binary operators over finite non-empty iterables.
As a bonus of singledispatch
ing we can handle numpy
arrays like
import numpy as np
...
transpose.register(np.ndarray, np.transpose)
and then use it like
>>> array = np.arange(4).reshape((2,2))
>>> array
array([[0, 1],
[2, 3]])
>>> transpose(array)
array([[0, 2],
[1, 3]])
Since transpose
returns iterators and if someone wants to have a tuple
of list
s like in OP -- this can be made additionally with map
built-in function like
>>> original = [('a', 1), ('b', 2), ('c', 3), ('d', 4)]
>>> tuple(map(list, transpose(original)))
(['a', 'b', 'c', 'd'], [1, 2, 3, 4])
I've added generalized solution to lz
package from 0.5.0
version which can be used like
>>> from lz.transposition import transpose
>>> list(map(tuple, transpose(zip(range(10), range(10, 20)))))
[(0, 1, 2, 3, 4, 5, 6, 7, 8, 9), (10, 11, 12, 13, 14, 15, 16, 17, 18, 19)]
There is no solution (at least obvious) for handling potentially infinite iterable of potentially infinite iterables, but this case is less common though.
If you don't have access to sysjobs table (someone elses server etc) you might be have or be allowed access to sysjobs_view
SELECT *
from msdb..sysjobs_view s
left join master.sys.syslogins l on s.owner_sid = l.sid
or
SELECT *, SUSER_SNAME(s.owner_sid) AS owner
from msdb..sysjobs_view s
if you want to write in column:
for x in np.nditer(a.T, order='C'):
file.write(str(x))
file.write("\n")
Here 'a' is the name of numpy array and 'file' is the variable to write in a file.
If you want to write in row:
writer= csv.writer(file, delimiter=',')
for x in np.nditer(a.T, order='C'):
row.append(str(x))
writer.writerow(row)
I have just fixed using following steps, It may help you.
Step: 1
Step: 2
Step: 3
Step: 4
Step: 5
Then run following query.
ALTER DATABASE YourDBName
SET MULTI_USER
WITH ROLLBACK IMMEDIATE
GO
Enjoy...!
Is null an instance of anything?
No, there is no type which null
is an instanceof
.
instanceof
RelationalExpression: RelationalExpression instanceof ReferenceType
At run time, the result of the
instanceof
operator istrue
if the value of the RelationalExpression is notnull
and the reference could be cast to the ReferenceType without raising aClassCastException
. Otherwise the result isfalse
.
This means that for any type E
and R
, for any E o
, where o == null
, o instanceof R
is always false
.
What set does 'null' belong to?
There is also a special null type, the type of the expression
null
, which has no name. Because the null type has no name, it is impossible to declare a variable of the null type or to cast to the null type. Thenull
reference is the only possible value of an expression of null type. Thenull
reference can always be cast to any reference type. In practice, the programmer can ignore the null type and just pretend thatnull
is merely a special literal that can be of any reference type.
What is null?
As the JLS quote above says, in practice you can simply pretend that it's "merely a special literal that can be of any reference type".
In Java, null == null
(this isn't always the case in other languages). Note also that by contract, it also has this special property (from java.lang.Object
):
public boolean equals(Object obj)
For any non-
null
reference valuex
,x.equals(null)
shouldreturn false
.
It is also the default value (for variables that have them) for all reference types:
- Each class variable, instance variable, or array component is initialized with a default value when it is created:
- For all reference types, the default value is
null
.
How this is used varies. You can use it to enable what is called lazy initialization of fields, where a field would have its initial value of null
until it's actually used, where it's replaced by the "real" value (which may be expensive to compute).
There are also other uses. Let's take a real example from java.lang.System
:
public static Console console()
Returns: The system console, if any, otherwise
null
.
This is a very common use pattern: null
is used to denote non-existence of an object.
Here's another usage example, this time from java.io.BufferedReader
:
public String readLine() throws IOException
Returns: A
String
containing the contents of the line, not including any line-termination characters, ornull
if the end of the stream has been reached.
So here, readLine()
would return instanceof String
for each line, until it finally returns a null
to signify the end. This allows you to process each line as follows:
String line;
while ((line = reader.readLine()) != null) {
process(line);
}
One can design the API so that the termination condition doesn't depend on readLine()
returning null
, but one can see that this design has the benefit of making things concise. Note that there is no problem with empty lines, because an empty line "" != null
.
Let's take another example, this time from java.util.Map<K,V>
:
V get(Object key)
Returns the value to which the specified key is mapped, or
null
if this map contains no mapping for the key.If this map permits
null
values, then a return value ofnull
does not necessarily indicate that the map contains no mapping for the key; it's also possible that the map explicitly maps the key tonull
. ThecontainsKey
operation may be used to distinguish these two cases.
Here we start to see how using null
can complicate things. The first statement says that if the key isn't mapped, null
is returned. The second statement says that even if the key is mapped, null
can also be returned.
In contrast, java.util.Hashtable
keeps things simpler by not permitting null
keys and values; its V get(Object key)
, if returns null
, unambiguously means that the key isn't mapped.
You can read through the rest of the APIs and find where and how null
is used. Do keep in mind that they aren't always the best practice examples.
Generally speaking, null
are used as a special value to signify:
How is it represented in the memory?
In Java? None of your concern. And it's best kept that way.
null
a good thing?This is now borderline subjective. Some people say that null
causes many programmer errors that could've been avoided. Some say that in a language that catches NullPointerException
like Java, it's good to use it because you will fail-fast on programmer errors. Some people avoid null
by using Null object pattern, etc.
This is a huge topic on its own, so it's best discussed as answer to another question.
I will end this with a quote from the inventor of null
himself, C.A.R Hoare (of quicksort fame):
I call it my billion-dollar mistake. It was the invention of the
null
reference in 1965. At that time, I was designing the first comprehensive type system for references in an object oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn't resist the temptation to put in anull
reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.
The video of this presentation goes deeper; it's a recommended watch.
And with the new string formatting method...
f = open('{0}.csv'.format(name), 'wb')
Using Visual Studio
This gives details about each assembly, app domain and has a few options to load symbols (i.e. pdb files that contain debug information).
Using Process Explorer
If you want an external tool you can use the Process Explorer (freeware, published by Microsoft)
Click on a process and it will show a list with all the assemblies used. The tool is pretty good as it shows other information such as file handles etc.
Programmatically
Check this SO question that explains how to do it.
To add on to what Rob has mentioned. Setting break points in your application allows for the step-by-step processing of the stack. This enables the developer to use the debugger to see at what exact point the method is doing something that was unanticipated.
Since Rob has used the NullPointerException
(NPE) to illustrate something common, we can help to remove this issue in the following manner:
if we have a method that takes parameters such as: void (String firstName)
In our code we would want to evaluate that firstName
contains a value, we would do this like so: if(firstName == null || firstName.equals("")) return;
The above prevents us from using firstName
as an unsafe parameter. Therefore by doing null checks before processing we can help to ensure that our code will run properly. To expand on an example that utilizes an object with methods we can look here:
if(dog == null || dog.firstName == null) return;
The above is the proper order to check for nulls, we start with the base object, dog in this case, and then begin walking down the tree of possibilities to make sure everything is valid before processing. If the order were reversed a NPE could potentially be thrown and our program would crash.
Like there was discussed above OS could kill the APPLICATION without any notification (there is no onDestroy event) so there is no way to save these global variables.
SharedPreferences could be a solution EXCEPT you have COMPLEX STRUCTURED variables (in my case I had integer array to store the IDs that the user has already handled). The problem with the SharedPreferences is that it is hard to store and retrieve these structures each time the values needed.
In my case I had a background SERVICE so I could move this variables to there and because the service has onDestroy event, I could save those values easily.
I think the answer of Curt is correct, however, what if you want to add a class to a div that already has a class declared in the ASP.NET code.
Here is my solution for that, it is a generic method so you can call it directly as this:
Asp Net Div declaration:
<div id="divButtonWrapper" runat="server" class="text-center smallbutton fixPad">
Code to add class:
divButtonWrapper.AddClassToHtmlControl("nameOfYourCssClass")
Generic class:
public static class HtmlGenericControlExtensions
{
public static void AddClassToHtmlControl(this HtmlGenericControl htmlGenericControl, string className)
{
if (string.IsNullOrWhiteSpace(className))
return;
htmlGenericControl
.Attributes.Add("class", string.Join(" ", htmlGenericControl
.Attributes["class"]
.Split(' ')
.Except(new[] { "", className })
.Concat(new[] { className })
.ToArray()));
}
}
Don't agree with post above. I have a Hero with only English available and I want Spanish.
I installed MoreLocale 2, and it has lots of different languages (Dutch among them). I choose Spanish, Sense UI restarted and EVERYTHING in my phone changed to Spanish: menus, settings, etc. The keyboard predictive text defaulted to Spanish and started suggesting words in Spanish. This means, somewhere within the OS there is a Spanish dictionary hidden and MoreLocale made it available.
The problem is that English is still the only option available in keyboard input language so I can switch to English but can't switch back to Spanish unless I restart Sense UI, which takes a couple of minutes so not a very practical solution.
Still looking for an easier way to do it so please help.
I've created SQLite databases up to 3.5GB in size with no noticeable performance issues. If I remember correctly, I think SQLite2 might have had some lower limits, but I don't think SQLite3 has any such issues.
According to the SQLite Limits page, the maximum size of each database page is 32K. And the maximum pages in a database is 1024^3. So by my math that comes out to 32 terabytes as the maximum size. I think you'll hit your file system's limits before hitting SQLite's!
On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.
Source: Reading and Writing Files
You Need to write a custom Deserializer and then loop it and get the values of the hasmap.
Custom Deserializer:-
public class UserDetailsDeserializer implements JsonDeserializer<AllUserDetailsKeyModel> {
/*
bebebejunskjd:{
"email": "[email protected]",
"mobileNum": "12345678",
"password": "1234567",
"username": "akhil"}*/
@Override public AllUserDetailsKeyModel deserialize(JsonElement json, Type typeOfT,
JsonDeserializationContext context) throws JsonParseException {
final JsonObject jsonObject = json.getAsJsonObject();
Gson gson = new Gson();
Type AllUserDetailsResponseModel =
new TypeToken<HashMap<String, AllUserDetailsResponseModel>>(){}.getType();
HashMap<String, AllUserDetailsResponseModel> user =
gson.fromJson(jsonObject, AllUserDetailsResponseModel);
AllUserDetailsKeyModel result = new AllUserDetailsKeyModel();
result.setResult(user);
return result;
}
}
The code in comments is my object model and u should replaceAllUserDetailsKeyModel with your model class and add this to the rest client like below:-
private Converter.Factory createGsonConverter() {
GsonBuilder gsonBuilder = new GsonBuilder();
gsonBuilder.registerTypeAdapter(AllUserDetailsKeyModel.class, new UserDetailsDeserializer());
Gson gson = gsonBuilder.create();
return GsonConverterFactory.create(gson);
}
This the custom Convertor for Retrofit.
In your onResponse you just loop with hasmaps and get value by key and my model class looks like below:-
public class AllUserDetailsKeyModel {
private Map<String, AllUserDetailsResponseModel> result;
public Map<String, AllUserDetailsResponseModel> getResult() {
return result;
}
public void setResult(Map<String, AllUserDetailsResponseModel> result) {
this.result = result;
}
}
probably you need to give a Type T where T is your data Type and my model consists only of a hashmap and getters and setters for that.
And finally set Custom Convertor to retrofit like below:- .addConverterFactory(createGsonConverter())
Let me know if you need more clarifications.
You can perform bulk insert using mongoose, as the highest score answer. But the example cannot work, it should be:
/* a humongous amount of potatos */
var potatoBag = [{name:'potato1'}, {name:'potato2'}];
var Potato = mongoose.model('Potato', PotatoSchema);
Potato.collection.insert(potatoBag, onInsert);
function onInsert(err, docs) {
if (err) {
// TODO: handle error
} else {
console.info('%d potatoes were successfully stored.', docs.length);
}
}
Don't use a schema instance for the bulk insert, you should use a plain map object.
You need to use a back_inserter
:
std::copy(input.begin(), input.end(), std::back_inserter(output));
std::copy
doesn't add elements to the container into which you are inserting: it can't; it only has an iterator into the container. Because of this, if you pass an output iterator directly to std::copy
, you must make sure it points to a range that is at least large enough to hold the input range.
std::back_inserter
creates an output iterator that calls push_back
on a container for each element, so each element is inserted into the container. Alternatively, you could have created a sufficient number of elements in the std::vector
to hold the range being copied:
std::vector<double> output(input.size());
std::copy(input.begin(), input.end(), output.begin());
Or, you could use the std::vector
range constructor:
std::vector<double> output(input.begin(), input.end());
From the friendly Wikipedia:
The stdlib.h and stddef.h header files define a datatype called size_t which is used to represent the size of an object. Library functions that take sizes expect them to be of type size_t, and the sizeof operator evaluates to size_t.
The actual type of size_t is platform-dependent; a common mistake is to assume size_t is the same as unsigned int, which can lead to programming errors, particularly as 64-bit architectures become more prevalent.
Also, check Why size_t matters
You can do it without having to create a real Hibernate mapping. Try this:
SELECT * FROM Employee e, Team t WHERE e.Id_team=t.Id_team
The beauty of C++, like C, is that the sized of these things are implementation-defined, so there's no correct answer without your specifying the compiler you're using. Are those two the same? Yes. "long long" is a synonym for "long long int", for any compiler that will accept both.
First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.
Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.
Instead, I would move all of the "application" content to a separate component, like a JPanel
for example and simply move this between the applet or frame as required...
ps- You can use f.setLocationRelativeTo(null)
to center the window on the screen ;)
Updated
You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...
Within the constructor of GalzyTable2
you are doing...
JApplet app = new JApplet(); add(app); app.init(); app.start();
...Why are you adding another applet to an applet??
Case in point...
Within the main
method, you are trying to add the instance of JFrame
to itself...
f.getContentPane().add(f, button2);
Instead, create yourself a class that extends from something like JPanel
, add your UI logical to this, using compound components if required.
Then, add this panel to whatever top level container you need.
Take the time to read through Creating a GUI with Swing
Updated with example
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException; public class GalaxyTable2 extends JPanel { private static final int PREF_W = 700; private static final int PREF_H = 600; String[] columnNames = {"Phone Name", "Brief Description", "Picture", "price", "Buy"}; // Create image icons ImageIcon Image1 = new ImageIcon( getClass().getResource("s1.png")); ImageIcon Image2 = new ImageIcon( getClass().getResource("s2.png")); ImageIcon Image3 = new ImageIcon( getClass().getResource("s3.png")); ImageIcon Image4 = new ImageIcon( getClass().getResource("s4.png")); ImageIcon Image5 = new ImageIcon( getClass().getResource("note.png")); ImageIcon Image6 = new ImageIcon( getClass().getResource("note2.png")); ImageIcon Image7 = new ImageIcon( getClass().getResource("note3.png")); Object[][] rowData = { {"Galaxy S", "3G Support,CPU 1GHz", Image1, 120, false}, {"Galaxy S II", "3G Support,CPU 1.2GHz", Image2, 170, false}, {"Galaxy S III", "3G Support,CPU 1.4GHz", Image3, 205, false}, {"Galaxy S4", "4G Support,CPU 1.6GHz", Image4, 230, false}, {"Galaxy Note", "4G Support,CPU 1.4GHz", Image5, 190, false}, {"Galaxy Note2 II", "4G Support,CPU 1.6GHz", Image6, 190, false}, {"Galaxy Note 3", "4G Support,CPU 2.3GHz", Image7, 260, false},}; MyTable ss = new MyTable( rowData, columnNames); // Create a table JTable jTable1 = new JTable(ss); public GalaxyTable2() { jTable1.setRowHeight(70); add(new JScrollPane(jTable1), BorderLayout.CENTER); JPanel buttons = new JPanel(); JButton button = new JButton("Home"); buttons.add(button); JButton button2 = new JButton("Confirm"); buttons.add(button2); add(buttons, BorderLayout.SOUTH); } @Override public Dimension getPreferredSize() { return new Dimension(PREF_W, PREF_H); } public void actionPerformed(ActionEvent e) { new AMainFrame7().setVisible(true); } public static void main(String[] args) { EventQueue.invokeLater(new Runnable() { @Override public void run() { try { UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName()); } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) { ex.printStackTrace(); } JFrame frame = new JFrame("Testing"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(new GalaxyTable2()); frame.pack(); frame.setLocationRelativeTo(null); frame.setVisible(true); } }); } }
You also seem to have a lack of understanding about how to use layout managers.
Take the time to read through Creating a GUI with Swing and Laying components out in a container
Really stupid question: Are you sure the string is being truncated, and not just broken at the linebreak you specify (and possibly not showing in your interface)? Ie, do you expect the field to show as
This will be inserted \n This will not be
or
This will be inserted
This will not be
Also, what interface are you using? Is it possible that something along the way is eating your backslashes?
This is not possible now, but there is a work around. You can engage with the user in the public realm and ask them to send you private messages, but you can't send private messages back, only public ones. Of course, this all depends on if the user gives you the correct permissions.
If you have given permission to access a person's friends, you can then theoretically post on that users wall with references to each one of the friends, asking them to publicly interact with you and then potentially privately message you.
Get Friends
#if authenticated
https://graph.facebook.com/me/friends
http://developers.facebook.com/docs/reference/api/user/
Post in the Public Domain
http://developers.facebook.com/docs/reference/api/status/
Get Messages sent to that user (if given permission)
http://developers.facebook.com/docs/reference/api/message/
I think i get the problem :
Once you make the div fade out you aren't exiting the function : fadeout calls itself again over even after opacity has become 0
if(element.style.opacity < 0.0) {
return;
}
And do the same for fadein too
Use the wait
built-in:
process1 &
process2 &
process3 &
process4 &
wait
process5 &
process6 &
process7 &
process8 &
wait
For the above example, 4 processes process1
... process4
would be started in the background, and the shell would wait until those are completed before starting the next set.
From the GNU manual:
wait [jobspec or pid ...]
Wait until the child process specified by each process ID pid or job specification jobspec exits and return the exit status of the last command waited for. If a job spec is given, all processes in the job are waited for. If no arguments are given, all currently active child processes are waited for, and the return status is zero. If neither jobspec nor pid specifies an active child process of the shell, the return status is 127.
try this method
<script type="text/javascript">
function set(value) {
return value;
}
alert(set(@Html.Raw(Json.Encode(Model.Message)))); // Message set from controller
alert(set(@Html.Raw(Json.Encode(ViewBag.UrMessage))));
</script>
Thanks
FileSaver.js should be able to help you here.
var canvas = document.getElementById("my-canvas");
// draw to canvas...
canvas.toBlob(function(blob) {
saveAs(blob, "pretty image.png");
});
Convert your x-axis data from text to datetime.datetime
, use datetime.strptime
:
>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
datetime.datetime(2012, 5, 31, 19, 0)
This is an example of how to plot data once you have an array of datetimes:
import matplotlib.pyplot as plt
import datetime
import numpy as np
x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)
plt.plot(x,y)
plt.show()
For Windows:
Open Command Prompt and
type: netstat -a -o -n
Find the PID of the process that you want to kill.
Type: taskkill /F /PID 16876
This one 16876 - is the PID for the process that I want to kill - in that case, the process is 4200 - check the attached file.you can give any port number.
Now, Type : ng serve
to start your angular app at the same port 4200
If you don't want the last \t after the last element, you have to use the index to check, but remember that this only "works" (i.e. is O(n)) when lists implements the RandomAccess.
List<String> list = new ArrayList<String>();
list.add("one");
list.add("two");
list.add("three");
StringBuilder sb = new StringBuilder(list.size() * apprAvg); // every apprAvg > 1 is better than none
for (int i = 0; i < list.size(); i++) {
sb.append(list.get(i));
if (i < list.size() - 1) {
sb.append("\t");
}
}
System.out.println(sb.toString());
For playing sound in java, you can refer to the following code.
import java.io.*;
import java.net.URL;
import javax.sound.sampled.*;
import javax.swing.*;
// To play sound using Clip, the process need to be alive.
// Hence, we use a Swing application.
public class SoundClipTest extends JFrame {
public SoundClipTest() {
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setTitle("Test Sound Clip");
this.setSize(300, 200);
this.setVisible(true);
try {
// Open an audio input stream.
URL url = this.getClass().getClassLoader().getResource("gameover.wav");
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
// Get a sound clip resource.
Clip clip = AudioSystem.getClip();
// Open audio clip and load samples from the audio input stream.
clip.open(audioIn);
clip.start();
} catch (UnsupportedAudioFileException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (LineUnavailableException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new SoundClipTest();
}
}
iOS Simulator > Menu Bar > Debug > Open System Log
Old ways:
iOS Simulator prints its logs directly to stdout, so you can see the logs mixed up with system logs.
Open the Terminal and type: tail -f /var/log/system.log
Then run the simulator.
EDIT:
This stopped working on Mavericks/Xcode 5. Now you can access the simulator logs in its own folder: ~/Library/Logs/iOS Simulator/<sim-version>/system.log
You can either use the Console.app to see this, or just do a tail (iOS 7.0.3 64 bits for example):
tail -f ~/Library/Logs/iOS\ Simulator/7.0.3-64/system.log
EDIT 2:
They are now located in ~/Library/Logs/CoreSimulator/<simulator-hash>/system.log
tail -f ~/Library/Logs/CoreSimulator/<simulator-hash>/system.log
My method of doing this has been to create an inherited class that explicitly implements IDisposable. This is useful for folks who use the gui to add the service reference ( Add Service Reference ). I just drop this class in the project making the service reference and use it instead of the default client:
using System;
using System.ServiceModel;
using MyApp.MyService; // The name you gave the service namespace
namespace MyApp.Helpers.Services
{
public class MyServiceClientSafe : MyServiceClient, IDisposable
{
void IDisposable.Dispose()
{
if (State == CommunicationState.Faulted)
{
Abort();
}
else if (State != CommunicationState.Closed)
{
Close();
}
// Further error checks and disposal logic as desired..
}
}
}
Note: This is just a simple implementation of dispose, you can implement more complex dispose logic if you like.
You can then replace all your calls made with the regular service client with the safe clients, like this:
using (MyServiceClientSafe client = new MyServiceClientSafe())
{
var result = client.MyServiceMethod();
}
I like this solution as it does not require me to have access to the Interface definitions and I can use the using
statement as I would expect while allowing my code to look more or less the same.
You will still need to handle the exceptions which can be thrown as pointed out in other comments in this thread.
You should use the following code :
Class2 cls2 = new Class2();
cls2.UpdateEmployee();
In case you don't want to create a new instance to call the method, you can decalre the method as static
and then you can just call Class2.UpdateEmployee()
.
None of the other answers worked for me on MacOS Sierra 10.12.4
Here is what I had to do:
git config --global --unset user.password
Then run your git command (ex. git push) and reenter your username and password.
This works better in my case if you have object or multi-dimensional array. It will shows only first items, other will be just ignored in loop.
.filter('limitItems', function () {
return function (items) {
var result = {}, i = 1;
angular.forEach(items, function(value, key) {
if (i < 5) {
result[key] = value;
}
i = i + 1;
});
return result;
};
});
Change 5 on what you want.
Use Awk.
awk '{ print length }' abc.txt
span
s are by default displayed inline, which means they don't have a height and width.
Try adding a display: block
to your span.
Since Python 3.3, you can use the class ExitStack
from the contextlib
module to safely
open an arbitrary number of files.
It can manage a dynamic number of context-aware objects, which means that it will prove especially useful if you don't know how many files you are going to handle.
In fact, the canonical use-case that is mentioned in the documentation is managing a dynamic number of files.
with ExitStack() as stack:
files = [stack.enter_context(open(fname)) for fname in filenames]
# All opened files will automatically be closed at the end of
# the with statement, even if attempts to open files later
# in the list raise an exception
If you are interested in the details, here is a generic example in order to explain how ExitStack
operates:
from contextlib import ExitStack
class X:
num = 1
def __init__(self):
self.num = X.num
X.num += 1
def __repr__(self):
cls = type(self)
return '{cls.__name__}{self.num}'.format(cls=cls, self=self)
def __enter__(self):
print('enter {!r}'.format(self))
return self.num
def __exit__(self, exc_type, exc_value, traceback):
print('exit {!r}'.format(self))
return True
xs = [X() for _ in range(3)]
with ExitStack() as stack:
print(len(stack._exit_callbacks)) # number of callbacks called on exit
nums = [stack.enter_context(x) for x in xs]
print(len(stack._exit_callbacks))
print(len(stack._exit_callbacks))
print(nums)
Output:
0
enter X1
enter X2
enter X3
3
exit X3
exit X2
exit X1
0
[1, 2, 3]
If you want to do it via setAttribute
you would change the style
attribute like so:
element.setAttribute('style','transform:rotate(90deg); -webkit-transform: rotate(90deg)') //etc
This would be helpful if you want to reset all other inline style and only set your needed style properties' values again, BUT in most cases you may not want that. That's why everybody advised to use this:
element.style.transform = 'rotate(90deg)';
element.style.webkitTransform = 'rotate(90deg)';
The above is equivalent to
element.style['transform'] = 'rotate(90deg)';
element.style['-webkit-transform'] = 'rotate(90deg)';
Simply Refer this URL and download and save required dll files @ this location:
C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\PublicAssemblies
URL is: https://github.com/NN---/vssdk2013/find/master
I faced this problem when I tried to build and install my app to a Android 8.1.0 (API 26)phone.
The only reason is that I added android:hasCode="false"
to the application
tag in the manifest
file. However, it worked on API 24 with the same code when I tried several months ago (STRANGE?).
After removing that attribute, the problem disappears.
; For Windows Users to back to temp directory
set backup
set backupdir=C:\WINDOWS\Temp
set backupskip=C:\WINDOWS\Temp\*
set directory=C:\WINDOWS\Temp
set writebackup
The way to do this in 2019+ is to use DeviceOrientation
API. This works in most modern browsers on desktop and mobile.
window.addEventListener("deviceorientation", handleOrientation, true);
After registering your event listener (in this case, a JavaScript function called handleOrientation()), your listener function periodically gets called with updated orientation data.
The orientation event contains four values:
DeviceOrientationEvent.absolute
DeviceOrientationEvent.alpha
DeviceOrientationEvent.beta
DeviceOrientationEvent.gamma
The event handler function can look something like this:
function handleOrientation(event) { var absolute = event.absolute; var alpha = event.alpha; var beta = event.beta; var gamma = event.gamma; // Do stuff with the new orientation data }
Please follow below step to do some processing after Application Context get loaded i.e application is ready to serve.
Create below annotation i.e
@Retention(RetentionPolicy.RUNTIME) @Target(value= {ElementType.METHOD, ElementType.TYPE}) public @interface AfterApplicationReady {}
2.Create Below Class which is a listener which get call on application ready state.
@Component
public class PostApplicationReadyListener implements ApplicationListener<ApplicationReadyEvent> {
public static final Logger LOGGER = LoggerFactory.getLogger(PostApplicationReadyListener.class);
public static final String MODULE = PostApplicationReadyListener.class.getSimpleName();
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
try {
ApplicationContext context = event.getApplicationContext();
String[] beans = context.getBeanNamesForAnnotation(AfterAppStarted.class);
LOGGER.info("bean found with AfterAppStarted annotation are : {}", Arrays.toString(beans));
for (String beanName : beans) {
Object bean = context.getBean(beanName);
Class<?> targetClass = AopUtils.getTargetClass(bean);
Method[] methods = targetClass.getMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(AfterAppStartedComplete.class)) {
LOGGER.info("Method:[{} of Bean:{}] found with AfterAppStartedComplete Annotation.", method.getName(), beanName);
Method currentMethod = bean.getClass().getMethod(method.getName(), method.getParameterTypes());
LOGGER.info("Going to invoke method:{} of bean:{}", method.getName(), beanName);
currentMethod.invoke(bean);
LOGGER.info("Invocation compeleted method:{} of bean:{}", method.getName(), beanName);
}
}
}
} catch (Exception e) {
LOGGER.warn("Exception occured : ", e);
}
}
}
Finally when you start your Spring application just before log stating application started your listener will be called.
You can create a base class in your application that inherits from System.Web.UI.Page. Let all your pages inherit from the newly created base class. Add a property or a variable to your base class with propected access modifier, so that it will be accessed from all your pages in the application.
Sorry for delay, but I will try to make perfect form :)
I will added Count validation steps and check every time not .val()
. Check .length
, because I think is better pattern in your case. Of course remove unbind
function.
Of course source code:
// Prevent form submit if any entrees are missing
$('form').submit(function(e){
e.preventDefault();
var formIsValid = true;
// Count validation steps
var validationLoop = 0;
// Cycle through each Attendee Name
$('[name="atendeename[]"]', this).each(function(index, el){
// If there is a value
if ($(el).val().length > 0) {
validationLoop++;
// Find adjacent entree input
var entree = $(el).next('input');
var entreeValue = entree.val();
// If entree is empty, don't submit form
if (entreeValue.length === 0) {
alert('Please select an entree');
entree.focus();
formIsValid = false;
return false;
}
}
});
if (formIsValid && validationLoop > 0) {
alert("Correct Form");
return true;
} else {
return false;
}
});
For me, I just re-installed the react-scripts instead of react-scripts --save.
Sorting list of dicts using below will sort list in descending order on first column as salary and second column as age
d=[{'salary':123,'age':23},{'salary':123,'age':25}]
d=sorted(d, key=lambda i: (i['salary'], i['age']),reverse=True)
Output: [{'salary': 123, 'age': 25}, {'salary': 123, 'age': 23}]
function validatePhone(txtPhone) {
var a = document.getElementById(txtPhone).value;
var filter = /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/;
if (filter.test(a)) {
return true;
}
else {
return false;
}
}
this.setState(
{
originId: input.originId,
destinationId: input.destinationId,
radius: input.radius,
search: input.search
},
function() { console.log("setState completed", this.state) }
)
this might be helpful
You could try:
$j('div.contextualError.ckgcellphone').css('display')
If you use ng-model, you don't want to also use ng-checked. Instead just initialize the model variable to true. Normally you would do this in a controller that is managing your page (add one). In your fiddle I just did the initialization in an ng-init attribute for demonstration purposes.
<div ng-app="">
Send to Office: <input type="checkbox" ng-model="checked" ng-init="checked=true"><br/>
<select id="transferTo" ng-disabled="checked">
<option>Tech1</option>
<option>Tech2</option>
</select>
</div>
Since I have recently developed an Android application using gyroscope data (steady compass), I tried to collect a list with such devices. This is not an exhaustive list at all, but it is what I have so far:
*** Phones:
*** Tablets:
Hope the list keeps growing and hope that gyros will be soon available on mid and low price smartphones.
context.Widgets.RemoveRange(context.Widgets.Where(w => w.WidgetId == widgetId).ToList()); db.SaveChanges();
THX for this question! Works good for me on all popular browsers:
function openNewBackgroundTab(){
var a = document.createElement("a");
a.href = window.location.pathname;
var evt = document.createEvent("MouseEvents");
//the tenth parameter of initMouseEvent sets ctrl key
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0,
true, false, false, false, 0, null);
a.dispatchEvent(evt);
}
var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
if(!is_chrome)
{
var url = window.location.pathname;
var win = window.open(url, '_blank');
} else {
openNewBackgroundTab();
}
- (void)GetCurrentTimeStamp
{
NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
[objDateformat setDateFormat:@"yyyy-MM-dd"];
NSString *strTime = [objDateformat stringFromDate:[NSDate date]];
NSString *strUTCTime = [self GetUTCDateTimeFromLocalTime:strTime];//You can pass your date but be carefull about your date format of NSDateFormatter.
NSDate *objUTCDate = [objDateformat dateFromString:strUTCTime];
long long milliseconds = (long long)([objUTCDate timeIntervalSince1970] * 1000.0);
NSString *strTimeStamp = [Nsstring stringwithformat:@"%lld",milliseconds];
NSLog(@"The Timestamp is = %@",strTimestamp);
}
- (NSString *) GetUTCDateTimeFromLocalTime:(NSString *)IN_strLocalTime
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *objDate = [dateFormatter dateFromString:IN_strLocalTime];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
NSString *strDateTime = [dateFormatter stringFromDate:objDate];
return strDateTime;
}
NOTE :- The Timestamp must be in UTC Zone, So I convert our local Time to UTC Time.
An enhanced for
loop is just limiting the number of parameters inside the parenthesis.
for (int i = 0; i < myArray.length; i++) {
System.out.println(myArray[i]);
}
Can be written as:
for (int myValue : myArray) {
System.out.println(myValue);
}
The right answer (using Python 2.7 and later, since check_output()
was introduced then) is:
py2output = subprocess.check_output(['python','py2.py','-i', 'test.txt'])
To demonstrate, here are my two programs:
py2.py:
import sys
print sys.argv
py3.py:
import subprocess
py2output = subprocess.check_output(['python', 'py2.py', '-i', 'test.txt'])
print('py2 said:', py2output)
Running it:
$ python3 py3.py
py2 said: b"['py2.py', '-i', 'test.txt']\n"
Here's what's wrong with each of your versions:
py2output = subprocess.check_output([str('python py2.py '),'-i', 'test.txt'])
First, str('python py2.py')
is exactly the same thing as 'python py2.py'
—you're taking a str
, and calling str
to convert it to an str
. This makes the code harder to read, longer, and even slower, without adding any benefit.
More seriously, python py2.py
can't be a single argument, unless you're actually trying to run a program named, say, /usr/bin/python\ py2.py
. Which you're not; you're trying to run, say, /usr/bin/python
with first argument py2.py
. So, you need to make them separate elements in the list.
Your second version fixes that, but you're missing the '
before test.txt'
. This should give you a SyntaxError
, probably saying EOL while scanning string literal
.
Meanwhile, I'm not sure how you found documentation but couldn't find any examples with arguments. The very first example is:
>>> subprocess.check_output(["echo", "Hello World!"])
b'Hello World!\n'
That calls the "echo"
command with an additional argument, "Hello World!"
.
Also:
-i is a positional argument for argparse, test.txt is what the -i is
I'm pretty sure -i
is not a positional argument, but an optional argument. Otherwise, the second half of the sentence makes no sense.
Another way to go about it, besides the nice answers already mentioned, depends upon the fact that you can pass optional named arguments by position. For example,
def f(x,y=None):
print(x)
if y is not None:
print(y)
Yields
In [11]: f(1,2)
1
2
In [12]: f(1)
1
You need to add the package containing the executable pg_config.
A prior answer should have details you need: pg_config executable not found
You can place your json to js file and save it to global variable. It is not asynchronous, but it can help.
Structure in C
First you need to declare your structure:
struct mystruct{
char element_1,
char element_2
};
Instantiate C structure
Once you declared your structure , you can instantiate a variable that has as type your structure using either:
mystruct struct_example;
or :
mystruct* struct_example;
For the first use case you can access the varaiable eleemnet using the following syntax: struct_example.element_1 = 5;
For the second use case which is having a pointer to variable of type your structure, to be able to access the variable structure you need an arrow:
struct_example->element_1 = 5;
As far as I can see it on the website of that paginations plugin, the plugin itself doesn't do the actual pagination. The only thing it does is display a row of numbers, and display the correct buttons depending on the page you're on.
However, to actually paginate, you have to write the appropriate Javascript yourself. This should be placed in stead of this Javascript:
function test(pageNumber)
{
var page="#page-id-"+pageNumber;
$('.select').hide()
$(page).show()
}
Which is code I'm guessing you've copy-pasted from somewhere but at the moment doesn't really do anything. If you don't know Javascript, going with another library that actually does pagination of a table is something you probably want to do.
It is not possible, since all classes in the package might not be loaded, while you always knows package of a class.
In my experience with regex you really need to focus on what EXACTLY you are trying to match, rather than what NOT to match.
for example
\d{2}
[1-9][0-9]
The first expression will match any 2 digits....and the second will match 1 digit from 1 to 9 and 1 digit - any digit. So if you type 07 the first expression will validate it, but the second one will not.
See this for advanced reference:
http://www.regular-expressions.info/refadv.html
EDITED:
^((?!my string).)*$
Is the regular expression for does not contain "my string".
A logical address is the address at which an item (memory cell, storage element, network host) appears to reside from the perspective of an executing application program.
I found out that with MySQL probably the correct query is the following:
SELECT SUBSTRING( FROM_UNIXTIME( CEILING( timestamp /300 ) *300,
'%Y-%m-%d %H:%i:%S' ) , 1, 19 ) AS ts_CEILING,
SUM(value)
FROM group_interval
GROUP BY SUBSTRING( FROM_UNIXTIME( CEILING( timestamp /300 ) *300,
'%Y-%m-%d %H:%i:%S' ) , 1, 19 )
ORDER BY SUBSTRING( FROM_UNIXTIME( CEILING( timestamp /300 ) *300,
'%Y-%m-%d %H:%i:%S' ) , 1, 19 ) DESC
Let me know what you think.
If you are using Moment.js then you can use there built in Duration
object
const duration = moment.duration(4825, 'seconds');
const h = duration.hours(); // 1
const m = duration.minutes(); // 20
const s = duration.seconds(); // 25
I got the same error, what worked for me is:
Let me clarify two points here :
(a = 'b',c)
in function.
The correct order of defining parameter in function are :(a,b,c)
(a = 'b',r= 'j')
(*args)
(**kwargs)
def example(a, b, c=None, r="w" , d=[], *ae, **ab):
(a,b)
are positional parameter
(c=none)
is optional parameter
(r="w")
is keyword parameter
(d=[])
is list parameter
(*ae)
is keyword-only
(*ab)
is var-keyword parameter
so first re-arrange your parameters
so second remove this "len1 = hgt"
it's not allowed in python.
keep in mind the difference between argument and parameters.
I would just use a value in the querystring to pass the required information to the next page.
SWIFT 2.0 code to present the current week starting from monday.
@IBAction func show(sender: AnyObject) {
// Getting Days of week corresponding to their dateFormat
let calendar = NSCalendar.currentCalendar()
let dayInt: Int!
var weekDate: [String] = []
var i = 2
print("Dates corresponding to days are")
while((dayInt - dayInt) + i < 9)
{
let weekFirstDate = calendar.dateByAddingUnit(.Day, value: (-dayInt+i), toDate: NSDate(), options: [])
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEEE dd MMMM"
let dayOfWeekString = dateFormatter.stringFromDate(weekFirstDate!)
weekDate.append(dayOfWeekString)
i++
}
for i in weekDate
{
print(i) //Printing the day stored in array
}
}
// function to get week day
func getDayOfWeek(today:String)->Int {
let formatter = NSDateFormatter()
formatter.dateFormat = "MMM-dd-yyyy"
let todayDate = formatter.dateFromString(today)!
let myCalendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)!
let myComponents = myCalendar.components(.Weekday, fromDate: todayDate)
let weekDay = myComponents.weekday
return weekDay
}
@IBAction func DateTitle(sender: AnyObject) {
// Getting currentDate and weekDay corresponding to it
let currentDate = NSDate()
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MMM-dd-yyyy"
let dayOfWeekStrings = dateFormatter.stringFromDate(currentDate)
dayInt = getDayOfWeek(dayOfWeekStrings)
}
Have you tried the Generate Scripts
(Right click, tasks, generate scripts) option in SQL Management Studio? Does that produce what you mean by a "SQL File"?
After running into the same issue - here're some of my thoughts:
As it affects only Chrome (other browsers work fine with VideoForEverybody solution) the solution I've used is:
for every mp4 file, create a Theora encoded mp4 file (example.mp4 -> example_c.mp4) apply following js:
if (window.chrome)
$("[type=video\\\/mp4]").each(function()
{
$(this).attr('src', $(this).attr('src').replace(".mp4", "_c.mp4"));
});
Unfortunately it's a bad Chrome hack, but hey, at least it works.
Source: user: eithedog
This also can help: chrome could play html5 mp4 video but html5test said chrome did not support mp4 video codec
Also check your version of crome here: html5test
In my case, I commited a spell mistake in @Named("beanName"), it was suppose to be "beanName", but I wrote "beanNam", for example.
In our case, deletion was not possible due to already having an app that we were in pre-release. The fix was not to delete but rather to edit each section, including version number, that needed to change for the new candidate.
It stands for Representational State Transfer and it can mean a lot of things, but usually when you are talking about APIs and applications, you are talking about REST as a way to do web services or get programs to talk over the web.
REST is basically a way of communicating between systems and does much of what SOAP RPC was designed to do, but while SOAP generally makes a connection, authenticates and then does stuff over that connection, REST works pretty much the same way that that the web works. You have a URL and when you request that URL you get something back. This is where things start getting confusing because people describe the web as a the largest REST application and while this is technically correct it doesn't really help explain what it is.
In a nutshell, REST allows you to get two applications talking over the Internet using tools that are similar to what a web browser uses. This is much simpler than SOAP and a lot of what REST does is says, "Hey, things don't have to be so complex."
Worth reading:
You can flip both vertical and horizontal at the same time
-moz-transform: scaleX(-1) scaleY(-1);
-o-transform: scaleX(-1) scaleY(-1);
-webkit-transform: scaleX(-1) scaleY(-1);
transform: scaleX(-1) scaleY(-1);
And with the transition property you can get a cool flip
-webkit-transition: transform .4s ease-out 0ms;
-moz-transition: transform .4s ease-out 0ms;
-o-transition: transform .4s ease-out 0ms;
transition: transform .4s ease-out 0ms;
transition-property: transform;
transition-duration: .4s;
transition-timing-function: ease-out;
transition-delay: 0ms;
Actually it flips the whole element, not just the background-image
SNIPPET
function flip(){_x000D_
var myDiv = document.getElementById('myDiv');_x000D_
if (myDiv.className == 'myFlipedDiv'){_x000D_
myDiv.className = '';_x000D_
}else{_x000D_
myDiv.className = 'myFlipedDiv';_x000D_
}_x000D_
}
_x000D_
#myDiv{_x000D_
display:inline-block;_x000D_
width:200px;_x000D_
height:20px;_x000D_
padding:90px;_x000D_
background-color:red;_x000D_
text-align:center;_x000D_
-webkit-transition:transform .4s ease-out 0ms;_x000D_
-moz-transition:transform .4s ease-out 0ms;_x000D_
-o-transition:transform .4s ease-out 0ms;_x000D_
transition:transform .4s ease-out 0ms;_x000D_
transition-property:transform;_x000D_
transition-duration:.4s;_x000D_
transition-timing-function:ease-out;_x000D_
transition-delay:0ms;_x000D_
}_x000D_
.myFlipedDiv{_x000D_
-moz-transform:scaleX(-1) scaleY(-1);_x000D_
-o-transform:scaleX(-1) scaleY(-1);_x000D_
-webkit-transform:scaleX(-1) scaleY(-1);_x000D_
transform:scaleX(-1) scaleY(-1);_x000D_
}
_x000D_
<div id="myDiv">Some content here</div>_x000D_
_x000D_
<button onclick="flip()">Click to flip</button>
_x000D_
In addition to all the mentions of StopIteration, the Python "for" loop simply does what you want:
>>> it = iter("hello")
>>> for i in it:
... print i
...
h
e
l
l
o
Here's a minimal set of instructions for upgrading to Python 3 using MacPorts:
sudo port install py37-pip
sudo port select --set pip pip37
sudo port select --set pip3 pip37
sudo pip install numpy, scipy, matplotlib
I ran some old code and it works again after this upgrade.
The most upVoted answer seems working but become hectic for developers to see their minor changes after couple of minutes. I solved this issue by following these steps: 1- Push my code to bitbucket/github repo ( to view the changes later ) 2- cut paste android folder to any safe location for recovery 3- delete the android folder from my project 4- run react-native upgrade 5- Now, I see all the changes between the previous and the lastest build (using VsCode) 6- I found the issue in build.gradle file in these lines of code.
ext {
buildToolsVersion = "28.0.2"
minSdkVersion = 16
compileSdkVersion = 28
targetSdkVersion = 27
supportLibVersion = "28.0.0"
}
7- I copied these lines ( generated by react-native upgrade script and delete the android folder again. 8- Then I cut paste android folder back in my project folder which I Cut Pasted in step 2. 9 - Replace build.gradle files lines with the copied ones. 10- Now It works as normal.
Hope this will help you.
If you are searching by the fieldname1
value, try this:
var r = exitDictionary
.Select(i => i.Value).Cast<Dictionary<string, object>>()
.Where(d => d.ContainsKey("fieldname1"))
.Select(d => d["fieldname1"]).Cast<List<Dictionary<string, string>>>()
.SelectMany(d1 =>
d1
.Where(d => d.ContainsKey("valueTitle"))
.Select(d => d["valueTitle"])
.Where(v => v != null)).ToList();
If you are looking by the type of the value in the subDictionary
(Dictionary<string, object>
explicitly), you may do this:
var r = exitDictionary
.Select(i => i.Value).Cast<Dictionary<string, object>>()
.SelectMany(d=>d.Values)
.OfType<List<Dictionary<string, string>>>()
.SelectMany(d1 =>
d1
.Where(d => d.ContainsKey("valueTitle"))
.Select(d => d["valueTitle"])
.Where(v => v != null)).ToList();
Both alternatives will return:
title1
title2
title3
title1
title2
title3
*/5 * * * *
means every 5 minutes
5 * * * *
means the 5th minute of every hour
There are multiple options, none being simple "one shot" full text solution:
Key name pattern search: Searching for keys starting with some string- if you design key names carefully, then you may have rather quick solution.
Search metadata attached to keys: when posting a file to AWS S3, you may process the content, extract some meta information and attach this meta information in form of custom headers into the key. This allows you to fetch key names and headers without need to fetch complete content. The search has to be done sequentialy, there is no "sql like" search option for this. With large files this could save a lot of network traffic and time.
Store metadata on SimpleDB: as previous point, but with storing the metadata on SimpleDB. Here you have sql like select statements. In case of large data sets you may hit SimpleDB limits, which can be overcome (partition metadata across multiple SimpleDB domains), but if you go really far, you may need to use another metedata type of database.
Sequential full text search of the content - processing all the keys one by one. Very slow, if you have too many keys to process.
We are storing 1440 versions of a file a day (one per minute) for couple of years, using versioned bucket, it is easily possible. But getting some older version takes time, as one has to sequentially go version by version. Sometime I use simple CSV index with records, showing publication time plus version id, having this, I could jump to older version rather quickly.
As you see, AWS S3 is not on it's own designed for full text searches, it is simple storage service.
As someone who's spent a bit of time optimizing MD5 performance, I thought I'd supply more of a technical explanation than the benchmarks provided here, to anyone who happens to find this in the future.
MD5 does less "work" than SHA1 (e.g. fewer compression rounds), so one may think it should be faster. However, the MD5 algorithm is mostly one big dependency chain, which means that it doesn't exploit modern superscalar processors particularly well (i.e. exhibits low instructions-per-clock). SHA1 has more parallelism available, so despite needing more "computational work" done, it often ends up being faster than MD5 on modern superscalar processors.
If you do the MD5 vs SHA1 comparison on older processors or ones with less superscalar "width" (such as a Silvermont based Atom CPU), you'll generally find MD5 is faster than SHA1.
SHA2 and SHA3 are even more compute intensive than SHA1, and generally much slower.
One thing to note, however, is that some new x86 and ARM CPUs have instructions to accelerate SHA1 and SHA256, which obviously helps these algorithms greatly if the instructions are being used.
As an aside, SHA256 and SHA512 performance may exhibit similarly curious behaviour. SHA512 does more "work" than SHA256, however a key difference between the two is that SHA256 operates using 32-bit words, whilst SHA512 operates using 64-bit words. As such, SHA512 will generally be faster than SHA256 on a platform with a 64-bit word size, as it's processing twice the amount of data at once. Conversely, SHA256 should outperform SHA512 on a platform with a 32-bit word size.
Note that all of the above only applies to single buffer hashing (by far the most common use case). If you're fancy and computing multiple hashes in parallel, i.e. a multi-buffer SIMD approach, the behaviour changes somewhat.
The Node.js Documentation offers a very elegant example using the Readline module.
Example: Read File Stream Line-by-Line
const fs = require('fs');
const readline = require('readline');
const rl = readline.createInterface({
input: fs.createReadStream('sample.txt'),
crlfDelay: Infinity
});
rl.on('line', (line) => {
console.log(`Line from file: ${line}`);
});
Note: we use the crlfDelay option to recognize all instances of CR LF ('\r\n') as a single line break.
try using the css pseudoclass :focus
input[type="button"], input[type="button"]:focus {
/* your style goes here */
}
edit as for links and onclick events use (you shouldn’t use inline javascript eventhandlers, but for the sake of simplicity i will use them here):
<a href="some/page.php" title="perform some js action" onclick="callFunction(this.href);return false;">watch and learn</a>
with this.href you can even access the target of the link in your function. return false
will just prevent browsers from following the link when clicked.
if javascript is disabled the link will work as a normal link and just load some/page.php
—if you want your link to be dead when js is disabled use href="#"
wait until the process is over ...
while(webview.getProgress()< 100){}
progressBar.setVisibility(View.GONE);
Try this:
public void ringtone(){
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
}
Not sure about "Best Practices" for memory leaks in python, but python should clear it's own memory by it's garbage collector. So mainly I would start by checking for circular list of some short, since they won't be picked up by the garbage collector.
hasOwnProperty
is a normal JavaScript function that takes a string argument.
When you call shape1.hasOwnProperty(name)
you are passing it the value of the name
variable (which doesn't exist), just as it would if you wrote alert(name)
.
You need to call hasOwnProperty
with a string containing name
, like this: shape1.hasOwnProperty("name")
.
Google TOS have been relaxed a bit in April 2014. Now it states:
"Don’t misuse our Services. For example, don’t interfere with our Services or try to access them using a method other than the interface and the instructions that we provide."
So the passage about "automated means" and scripts is gone now. It evidently still is not the desired (by google) way of accessing their services, but I think it is now formally open to interpretation of what exactly an "interface" is and whether it makes any difference as of how exactly returned HTML is processed (rendered or parsed). Anyhow, I have written a Java convenience library and it is up to you to decide whether to use it or not:
Aside from getting decode
and encode
backwards, I think part of the answer here is actually don't use the ascii
encoding. It's probably not what you want.
To begin with, think of str
like you would a plain text file. It's just a bunch of bytes with no encoding actually attached to it. How it's interpreted is up to whatever piece of code is reading it. If you don't know what this paragraph is talking about, go read Joel's The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets right now before you go any further.
Naturally, we're all aware of the mess that created. The answer is to, at least within memory, have a standard encoding for all strings. That's where unicode
comes in. I'm having trouble tracking down exactly what encoding Python uses internally for sure, but it doesn't really matter just for this. The point is that you know it's a sequence of bytes that are interpreted a certain way. So you only need to think about the characters themselves, and not the bytes.
The problem is that in practice, you run into both. Some libraries give you a str
, and some expect a str
. Certainly that makes sense whenever you're streaming a series of bytes (such as to or from disk or over a web request). So you need to be able to translate back and forth.
Enter codecs
: it's the translation library between these two data types. You use encode
to generate a sequence of bytes (str
) from a text string (unicode
), and you use decode
to get a text string (unicode
) from a sequence of bytes (str
).
For example:
>>> s = "I look like a string, but I'm actually a sequence of bytes. \xe2\x9d\xa4"
>>> codecs.decode(s, 'utf-8')
u"I look like a string, but I'm actually a sequence of bytes. \u2764"
What happened here? I gave Python a sequence of bytes, and then I told it, "Give me the unicode
version of this, given that this sequence of bytes is in 'utf-8'
." It did as I asked, and those bytes (a heart character) are now treated as a whole, represented by their Unicode codepoint.
Let's go the other way around:
>>> u = u"I'm a string! Really! \u2764"
>>> codecs.encode(u, 'utf-8')
"I'm a string! Really! \xe2\x9d\xa4"
I gave Python a Unicode string, and I asked it to translate the string into a sequence of bytes using the 'utf-8'
encoding. So it did, and now the heart is just a bunch of bytes it can't print as ASCII; so it shows me the hexadecimal instead.
We can work with other encodings, too, of course:
>>> s = "I have a section \xa7"
>>> codecs.decode(s, 'latin1')
u'I have a section \xa7'
>>> codecs.decode(s, 'latin1')[-1] == u'\u00A7'
True
>>> u = u"I have a section \u00a7"
>>> u
u'I have a section \xa7'
>>> codecs.encode(u, 'latin1')
'I have a section \xa7'
('\xa7'
is the section character, in both
Unicode and Latin-1.)
So for your question, you first need to figure out what encoding your str
is in.
Did it come from a file? From a web request? From your database? Then the source determines the encoding. Find out the encoding of the source and use that to translate it into a unicode
.
s = [get from external source]
u = codecs.decode(s, 'utf-8') # Replace utf-8 with the actual input encoding
Or maybe you're trying to write it out somewhere. What encoding does the destination expect? Use that to translate it into a str
. UTF-8 is a good choice for plain text documents; most things can read it.
u = u'My string'
s = codecs.encode(u, 'utf-8') # Replace utf-8 with the actual output encoding
[Write s out somewhere]
Are you just translating back and forth in memory for interoperability or something? Then just pick an encoding and stick with it; 'utf-8'
is probably the best choice for that:
u = u'My string'
s = codecs.encode(u, 'utf-8')
newu = codecs.decode(s, 'utf-8')
In modern programming, you probably never want to use the 'ascii'
encoding for any of this. It's an extremely small subset of all possible characters, and no system I know of uses it by default or anything.
Python 3 does its best to make this immensely clearer simply by changing the names. In Python 3, str
was replaced with bytes
, and unicode
was replaced with str
.
int64_t delayInSeconds = 0.6;
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
do something to the button(s)
});
'lib/
's parent directory must be in sys.path
.
Your 'lib/__init__.py
' might look like this:
from . import settings # or just 'import settings' on old Python versions
class Helper(object):
pass
Then the following example should work:
from lib.settings import Values
from lib import Helper
__init__.py
defines how your package looks from outside. If you need to use Helper
in settings.py
then define Helper
in a different file e.g., 'lib/helper.py
'.
. | `-- import_submodule.py `-- lib |-- __init__.py |-- foo | |-- __init__.py | `-- someobject.py |-- helper.py `-- settings.py 2 directories, 6 files
The command:
$ python import_submodule.py
Output:
settings
helper
Helper in lib.settings
someobject
Helper in lib.foo.someobject
# ./import_submodule.py
import fnmatch, os
from lib.settings import Values
from lib import Helper
print
for root, dirs, files in os.walk('.'):
for f in fnmatch.filter(files, '*.py'):
print "# %s/%s" % (os.path.basename(root), f)
print open(os.path.join(root, f)).read()
print
# lib/helper.py
print 'helper'
class Helper(object):
def __init__(self, module_name):
print "Helper in", module_name
# lib/settings.py
print "settings"
import helper
class Values(object):
pass
helper.Helper(__name__)
# lib/__init__.py
#from __future__ import absolute_import
import settings, foo.someobject, helper
Helper = helper.Helper
# foo/someobject.py
print "someobject"
from .. import helper
helper.Helper(__name__)
# foo/__init__.py
import someobject
From windows cmd you can use start
:
"dev": "start npm run start-watch && start npm run wp-server"
Every command launched this way starts in its own window.
3.545555555 to get 3.54. Try Following for this:
DecimalFormat df = new DecimalFormat("#.##");
df.setRoundingMode(RoundingMode.FLOOR);
double result = new Double(df.format(3.545555555);
This will give= 3.54!
If you will change the ID then Toggle will not working same problem was with me i just change
<div class="collapse navbar-collapse" id="defaultNavbar1">
<ul class="nav navbar-nav">
id="defaultNavbar1" then toggle is working
This example allows you to get more information when there is an error in your code. Basically, it buffers messages and only outputs those at a certain log level (e.g. Warn) unless a certain condition is met (e.g. there has been an error, so the log level is >= Error), then it will output more info (e.g. all messages from log levels >= Trace). Because the messages are buffered, this lets you gather trace information about what happened before an Error or ErrorException was logged - very useful!
I adapted this one from an example in the source code. I was thrown at first because I left out the AspNetBufferingWrapper
(since mine isn't an ASP app) - it turns out that the PostFilteringWrapper requires some buffered target. Note that the target-ref
element used in the above-linked example cannot be used in NLog 1.0 (I am using 1.0 Refresh for a .NET 4.0 app); it is necessary to put your target inside the wrapper block. Also note that the logic syntax (i.e. greater-than or less-than symbols, < and >) has to use the symbols, not the XML escapes for those symbols (i.e. >
and <
) or else NLog will error.
app.config:
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
</configSections>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
throwExceptions="true" internalLogToConsole="true" internalLogLevel="Warn" internalLogFile="nlog.log">
<variable name="appTitle" value="My app"/>
<variable name="csvPath" value="${specialfolder:folder=Desktop:file=${appTitle} log.csv}"/>
<targets async="true">
<!--The following will keep the default number of log messages in a buffer and write out certain levels if there is an error and other levels if there is not. Messages that appeared before the error (in code) will be included, since they are buffered.-->
<wrapper-target xsi:type="BufferingWrapper" name="smartLog">
<wrapper-target xsi:type="PostFilteringWrapper">
<!--<target-ref name="fileAsCsv"/>-->
<target xsi:type="File" fileName="${csvPath}"
archiveAboveSize="4194304" concurrentWrites="false" maxArchiveFiles="1" archiveNumbering="Sequence"
>
<layout xsi:type="CsvLayout" delimiter="Tab" withHeader="false">
<column name="time" layout="${longdate}" />
<column name="level" layout="${level:upperCase=true}"/>
<column name="message" layout="${message}" />
<column name="callsite" layout="${callsite:includeSourcePath=true}" />
<column name="stacktrace" layout="${stacktrace:topFrames=10}" />
<column name="exception" layout="${exception:format=ToString}"/>
<!--<column name="logger" layout="${logger}"/>-->
</layout>
</target>
<!--during normal execution only log certain messages-->
<defaultFilter>level >= LogLevel.Warn</defaultFilter>
<!--if there is at least one error, log everything from trace level-->
<when exists="level >= LogLevel.Error" filter="level >= LogLevel.Trace" />
</wrapper-target>
</wrapper-target>
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="smartLog"/>
</rules>
</nlog>
</configuration>
Zero and None both treated as same for if block, below code should work fine.
if number or number==0:
return True
For MySql 5.6 installed from DMG on Mavericks
sudo ln -s /usr/local/mysql-5.6.14-osx10.7-x86_64/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib
In addition to the 3 floated column structure (which I would suggest as well), you have to insert a clearfix to prevent layoutproblems with elements after the columncontainer (keep the columncontainer in the flow, so to speak...).
<div id="contentBox" class="clearfix">
....
</div>
CSS:
.clearfix { zoom: 1; }
.clearfix:before, .clearfix:after { content: "\0020"; display: block; height: 0; overflow: hidden; }
.clearfix:after { clear: both; }
Keep() method marks the specified key in the dictionary for retention
You can use Keep() when prevent/hold the value depends on additional logic.
when you read TempData one’s and want to hold for another request then use keep method, so TempData can available for next request as above example.
Here is a way to easily escape & char in oracle DB
set escape '\\'
and within query write like
'ERRORS &\\\ PERFORMANCE';
Set private int selected_position = -1;
to prevent from any item being selected on start.
@Override
public void onBindViewHolder(final OrdersHolder holder, final int position) {
final Order order = orders.get(position);
holder.bind(order);
if(selected_position == position){
//changes background color of selected item in RecyclerView
holder.itemView.setBackgroundColor(Color.GREEN);
} else {
holder.itemView.setBackgroundColor(Color.TRANSPARENT);
//this updated an order property by status in DB
order.setProductStatus("0");
}
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//status switch and DB update
if (order.getProductStatus().equals("0")) {
order.setProductStatus("1");
notifyItemChanged(selected_position);
selected_position = position;
notifyItemChanged(selected_position);
} else {
if (order.getProductStatus().equals("1")){
//calls for interface implementation in
//MainActivity which opens a new fragment with
//selected item details
listener.onOrderSelected(order);
}
}
}
});
}
As you specify in your attrs.xml
your adSize attribute belongs to the namespace com.google.ads.AdView
. Try to change:
android:adUnitId="a14bd6d2c63e055" android:adSize="BANNER"
to
ads:adUnitId="a14bd6d2c63e055" ads:adSize="BANNER"
and it should work.
MonoDevelop, the IDE associated with Mono Project should be enough for C# development on Linux. Now I don't know any good profilers and other tools for C# development on Linux. But then again mind you, that C# is a language more native to windows. You are better developing C# apps for windows than for linux.
EDIT: When you download MonoDevelop from the Ubuntu Software Center, it will contain pretty much everything you need to get started right away (Compiler, Runtime Environment, IDE). If you would like more information, see the following links:
Instead of an annoying confirmation popup, it would be nice to delay leaving just a bit (matter of milliseconds) to manage successfully posting the unsaved data to the server, which I managed for my site using writing dummy text to the console like this:
window.onbeforeunload=function(e){
// only take action (iterate) if my SCHEDULED_REQUEST object contains data
for (var key in SCHEDULED_REQUEST){
postRequest(SCHEDULED_REQUEST); // post and empty SCHEDULED_REQUEST object
for (var i=0;i<1000;i++){
// do something unnoticable but time consuming like writing a lot to console
console.log('buying some time to finish saving data');
};
break;
};
}; // no return string --> user will leave as normal but data is send to server
Edit: See also Synchronous_AJAX and how to do that with jquery
To summarize the below posts a bit:
If all you care about is if at least one matching row is in the DB then use exists
as it is the most efficient way of checking this: it will return true as soon as it finds at least one matching row whereas count
, etc will find all matching rows.
If you actually need to use the data for processing or if the query has side effects, or if you need to know the actual total number of rows then checking the ROWCOUNT
or count
is probably the best way on hand.
Deleting node_modules
and package-lock.json
and npm i
solve the issue for me.
Logging has greatly improved in heroku!
$ heroku logs -n 500
Better!
$ heroku logs --tail
references: http://devcenter.heroku.com/articles/logging
UPDATED
These are no longer add-ons, but part of the default functionality :)
Reading the original comment, rutherford is looking for a cross-browser way to wrap unbroken text (inferred by his use of word-wrap for IE, designed to break unbroken strings).
/* Source: http://snipplr.com/view/10979/css-cross-browser-word-wrap */
.wordwrap {
white-space: pre-wrap; /* CSS3 */
white-space: -moz-pre-wrap; /* Firefox */
white-space: -pre-wrap; /* Opera <7 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* IE */
}
I've used this class for a bit now, and works like a charm. (note: I've only tested in FireFox and IE)
You can also use Url.Action for the path instead like so:
$.ajax({
url: "@Url.Action("Holiday", "Calendar", new { area = "", year= (val * 1) + 1 })",
type: "GET",
success: function (partialViewResult) {
$("#refTable").html(partialViewResult);
}
});
Try this code
document.onreadystatechange = function () {
if (document.readyState == "interactive") {
initApplication();
}
}
visit https://developer.mozilla.org/en-US/docs/DOM/document.readyState for more details
I would not recommend changing the actual bootstrap CSS files. If you do not want to use Jako's first solution you can create a custom bootstrap style sheet with one of the available Bootstrap theme generator (Bootstrap theme generators). That way you can use 1 style sheet with all of the default Bootstrap CSS with just the one change to it that you want. With a Bootstrap theme generator you do not need to write any CSS. You only need to set the hex values for the color you want for the body (Scaffolding; bodyBackground).
Addition to @BalusC 's answer. You also need to set width of headers. In my case, below css can only apply to my table's column width.
.myTable td:nth-child(1),.myTable th:nth-child(1) {
width: 20px;
}
I experienced a similar problem lately after i created a maven project, the maven dependencies folder did not appear in the project structure.To solve this simply add any dependency in the pom file, such as in code below, or right-click on the project and go to maven and select add dependency, search for any dependency such as junit
add this, and the maven dependency should appear on your project structure now.
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.2.9.RELEASE</version>
<scope>runtime</scope>
</dependency>
</dependencies>
If you are generating Notification from a Service that is started in the foreground using
startForeground(NOTIFICATION_ID, notificationBuilder.build());
Then issuing
notificationManager.cancel(NOTIFICATION_ID);
does't work canceling the Notification & notification still appears in the status bar. In this particular case, you will solve these by 2 ways:
1> Using stopForeground( false ) inside service:
stopForeground( false );
notificationManager.cancel(NOTIFICATION_ID);
2> Destroy that service class with calling activity:
Intent i = new Intent(context, Service.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
if(ServiceCallingActivity.activity != null) {
ServiceCallingActivity.activity.finish();
}
context.stopService(i);
Second way prefer in music player notification more because thay way not only notification remove but remove player also...!!
You can do something like this:
public class Example
{
public String name;
public String location;
public String[] getExample()
{
String ar[] = new String[2];
ar[0]= name;
ar[1] = location;
return ar; //returning two values at once
}
}