Although the order does not matter as the dictionary is hashmap. It depends on the order how it is pushed in:
s = 'abbc'
a = 'cbab'
def load_dict(s):
dict_tmp = {}
for ch in s:
if ch in dict_tmp.keys():
dict_tmp[ch]+=1
else:
dict_tmp[ch] = 1
return dict_tmp
dict_a = load_dict(a)
dict_s = load_dict(s)
print('for string %s, the keys are %s'%(s, dict_s.keys()))
print('for string %s, the keys are %s'%(a, dict_a.keys()))
output:
for string abbc, the keys are dict_keys(['a', 'b', 'c'])
for string cbab, the keys are dict_keys(['c', 'b', 'a'])
I had the same thing. All came down to a "d" instead of a "D" in a tag name in the schema.
from urllib.request import Request, urlopen
url="https://svnweb.freebsd.org/csrg/share/dict/words?revision=61569&view=co"
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
web_byte = urlopen(req).read()
webpage = web_byte.decode('utf-8')
print(webpage)
Randomizing the first 500 words
from urllib.request import Request, urlopen
import random
url="https://svnweb.freebsd.org/csrg/share/dict/words?revision=61569&view=co"
req = Request(url, headers={'User-Agent': 'Mozilla/5.0'})
web_byte = urlopen(req).read()
webpage = web_byte.decode('utf-8')
first500 = webpage[:500].split("\n")
random.shuffle(first500)
print(first500)
Output
['abnegation', 'able', 'aborning', 'Abigail', 'Abidjan', 'ablaze', 'abolish', 'abbe', 'above', 'abort', 'aberrant', 'aboriginal', 'aborigine', 'Aberdeen', 'Abbott', 'Abernathy', 'aback', 'abate', 'abominate', 'AAA', 'abc', 'abed', 'abhorred', 'abolition', 'ablate', 'abbey', 'abbot', 'Abelson', 'ABA', 'Abner', 'abduct', 'aboard', 'Abo', 'abalone', 'a', 'abhorrent', 'Abelian', 'aardvark', 'Aarhus', 'Abe', 'abjure', 'abeyance', 'Abel', 'abetting', 'abash', 'AAAS', 'abdicate', 'abbreviate', 'abnormal', 'abject', 'abacus', 'abide', 'abominable', 'abode', 'abandon', 'abase', 'Ababa', 'abdominal', 'abet', 'abbas', 'aberrate', 'abdomen', 'abetted', 'abound', 'Aaron', 'abhor', 'ablution', 'abeyant', 'about']
I think token should be handled just like password. As such, they should be encrypted in DB.
I'n doing something like this to generate a unique new token for a model:
key = ActiveSupport::KeyGenerator
.new(Devise.secret_key)
.generate_key("put some random or the name of the key")
loop do
raw = SecureRandom.urlsafe_base64(nil, false)
enc = OpenSSL::HMAC.hexdigest('SHA256', key, raw)
break [raw, enc] unless Model.exist?(token: enc)
end
I have changed the order of included projects (Eclipse / Configure Build Path / Order and Export). I have moved my two dependent projects to the top of the "Order and Export" list. It solved the problem "NoClassDefFoundError".
It is strange for me. I didn't heard about the importance of the order of included libraries and projects. Android + Eclipse is fun :)
Most straightforward option:
plot(var1[var3<155],var2[var3<155])
It does not look good because of code redundancy, but is ok for fastn
dirty hacking.
awk -F: '{print $2}' <<< $var
You need to slightly modify your compare
function and use functools.cmp_to_key
to pass it to sorted
. Example code:
import functools
lst = [list(range(i, i+5)) for i in range(5, 1, -1)]
def fitness(item):
return item[0]+item[1]+item[2]+item[3]+item[4]
def compare(item1, item2):
return fitness(item1) - fitness(item2)
sorted(lst, key=functools.cmp_to_key(compare))
Output:
[[2, 3, 4, 5, 6], [3, 4, 5, 6, 7], [4, 5, 6, 7, 8], [5, 6, 7, 8, 9]]
Works :)
I solved a similar issue by just deleting the .git
folder from my project and reintegrating with version control through IntelliJ.
Note: The .git
folder is hidden. You can view it in the terminal with ls -a
, and then remove it using rm -rf .git
.
I'm actually using this method and it works perfectly. I was 'inspired' by the code written by Aeonhack here.
Public Event MyEvent()
Protected Overrides Sub Dispose(ByVal disposing As Boolean)
If MyEventEvent IsNot Nothing Then
For Each d In MyEventEvent.GetInvocationList ' If this throws an exception, try using .ToArray
RemoveHandler MyEvent, d
Next
End If
End Sub
The field MyEventEvent is hidden, but it does exist.
Debugging, you can see how d.target
is the object actually handling the event, and d.method
its method. You only have to remove it.
It works great. No more objects not being GC'ed because of the event handlers.
The screen widths Bootstrap v3.x uses are as follows:
Extra small devices
Phones (<768px)
/ .col-xs-
Small devices
Tablets (=768px)
/ .col-sm-
Medium devices
Desktops (=992px)
/ .col-md-
Large devices
Desktops (=1200px)
/ .col-lg-
So, these are good to use and work well in practice.
I found that I couldn't use multiple databases within the same database model when using EF. But in linq2sql I could just by prefixing the schema names with database names.
This was one of the reasons I originally began working with linq2sql. I do not know if EF has yet allowed this functionality, but I remember reading that it was intended for it not to allow this.
You can use opendir()
and check if ENOENT == errno
on failure:
#include <dirent.h>
#include <errno.h>
DIR* dir = opendir("mydir");
if (dir) {
/* Directory exists. */
closedir(dir);
} else if (ENOENT == errno) {
/* Directory does not exist. */
} else {
/* opendir() failed for some other reason. */
}
If your datetime object represents UTC time, don't use time.mktime, as it assumes the tuple is in your local timezone. Instead, use calendar.timegm:
>>> import datetime, calendar
>>> d = datetime.datetime(1970, 1, 1, 0, 1, 0)
>>> calendar.timegm(d.timetuple())
60
You can use "Gena" library. It closely resembles stl::vector
in pure C89.
From the README, it features:
vec[k][j]
;You can check it out here:
Python has importing and namespacing, which are good. In Python you can import into the current namespace, like:
>>> from test import disp
>>> disp('World!')
Or with a namespace:
>>> import test
>>> test.disp('World!')
How about?
DF$Den<-ifelse (is.na(DF$Denial1) | is.na(DF$Denial2) | is.na(DF$Denial3), "0", "1")
Also constructor based initialisation will not work as intended whenever some kind of proxying or remoting is involved.
The ct will get called whenever an EJB gets deserialized, and whenever a new proxy gets created for it...
You can refer to this site it will give you a explanation which one is better as i know {{}} this is slower than ng-bind.
http://corpus.hubwiz.com/2/angularjs/16125872.html refer this site.
It's also a good idea to mark the DOCUMENT
as optional. Per the Angular docs:
Document might not be available in the Application Context when Application and Rendering Contexts are not the same (e.g. when running the application into a Web Worker).
Here's an example of using the DOCUMENT
to see whether the browser has SVG support:
import { Optional, Component, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common'
...
constructor(@Optional() @Inject(DOCUMENT) document: Document) {
this.supportsSvg = !!(
document &&
document.createElementNS &&
document.createElementNS('http://www.w3.org/2000/svg', 'svg').createSVGRect
);
In DOS you couldn't use environment variables on the command line, only in batch files, where they used the %
sign as a delimiter. If you wanted a literal %
sign in a batch file, e.g. in an echo
statement, you needed to double it.
This carried over to Windows NT which allowed environment variables on the command line, however for backwards compatibility you still need to double your %
signs in a .cmd file.
You probably want to round the double to 5 decimals or so before comparing since a double can contain very small decimal parts if you have done some calculations with it.
double d = 10.0;
d /= 3.0; // d should be something like 3.3333333333333333333333...
d *= 3.0; // d is probably something like 9.9999999999999999999999...
// d should be 10.0 again but it is not, so you have to use rounding before comparing
d = myRound(d, 5); // d is something like 10.00000
if (fmod(d, 1.0) == 0)
// No decimals
else
// Decimals
If you are using C++ i don't think there is a round-function, so you have to implement it yourself like in: http://www.cplusplus.com/forum/general/4011/
I have the same problem with you when I implement OpenCV 2.4.11 on VS 2015. I tried to solve this problem by three methods one by one but they didn't work:
Finally I solved this problem by reinstalling VS2015 with selecting all the options that can be installed, it takes a lot space but it really works.
That .toggle()
method was removed from jQuery in version 1.9. You can do this instead:
$(document).ready(function() {
$('#showmenu').click(function() {
$('.menu').slideToggle("fast");
});
});
Demo: http://jsfiddle.net/APA2S/1/
...but as with the code in your question that would slide up or down. To slide left or right you can do the following:
$(document).ready(function() {
$('#showmenu').click(function() {
$('.menu').toggle("slide");
});
});
Demo: http://jsfiddle.net/APA2S/2/
Noting that this requires jQuery-UI's slide effect, but you added that tag to your question so I assume that is OK.
For those who want to round up a / b
and get integer:
Another variant using integer division is
def int_ceil(a, b):
return (a - 1) // b + 1
>>> int_ceil(19, 5)
4
>>> int_ceil(20, 5)
4
>>> int_ceil(21, 5)
5
SAP released SAP Crystal Reports, developer version for Microsoft Visual Studio
To integrate “SAP Crystal Reports, developer version for Microsoft Visual Studio” you must run the Install Executable. Running the MSI will not fully integrate Crystal Reports into VS. MSI files by definition are for runtime distribution only.
New In SP25 Release
Visual Studio 2019, Addressed incidents, Win10 1809, Security update
/**
* Singleton class
*
*/
final class UserFactory
{
/**
* Call this method to get singleton
*
* @return UserFactory
*/
public static function Instance()
{
static $inst = null;
if ($inst === null) {
$inst = new UserFactory();
}
return $inst;
}
/**
* Private ctor so nobody else can instantiate it
*
*/
private function __construct()
{
}
}
To use:
$fact = UserFactory::Instance();
$fact2 = UserFactory::Instance();
$fact == $fact2;
But:
$fact = new UserFactory()
Throws an error.
See http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static to understand static variable scopes and why setting static $inst = null;
works.
Just remember that modifying the padding or margins on any bootstrap grid elements is likely to create overflowing elements at some point at lower screen-widths.
If that happens just remember to use CSS media queries and only include the margins at screen-widths that can handle it.
In keeping with the mobile-first approach of the framework you are working within (bootstrap) it is better to add the padding at widths which can handle it, rather than excluding it at widths which can't.
@media (min-width: 992px){
.navbar li {
margin-left : 1em;
margin-right : 1em;
}
}
In HTML the style tag has the following syntax:
style="property1:value1;property2:value2"
so in your case:
<h2 style="text-align:center;font-family:tahoma">TITLE</h2>
Hope this helps.
If you are getting these type of errors when running mongod from command line or running mongodb server,
then follow these steps,
AppDelegate.swift
func createDatabase()
{
var path:Array=NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let directory:String=path[0]
let DBpath=(directory as NSString).appendingPathComponent("Food.sqlite")
print(DBpath)
if (FileManager.default.fileExists(atPath: DBpath))
{
print("Successfull database create")
}
else
{
let pathfrom:String=(Bundle.main.resourcePath! as NSString).appendingPathComponent("Food.sqlite")
var success:Bool
do {
try FileManager.default.copyItem(atPath: pathfrom, toPath: DBpath)
success = true
} catch _ {
success = false
}
if !success
{
print("database not create ")
}
else
{
print("Successfull database new create")
}
}
}
Database.swift
import UIKit
class database: NSObject
{
func databasePath() -> NSString
{
var path:Array=NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)
let directory:String=path[0]
let DBpath=(directory as NSString).appendingPathComponent("Food.sqlite")
if (FileManager.default.fileExists(atPath: DBpath))
{
return DBpath as NSString
}
return DBpath as NSString
}
func ExecuteQuery(_ str:String) -> Bool
{
var result:Bool=false
let DBpath:String=self.databasePath() as String
var db: OpaquePointer? = nil
var stmt:OpaquePointer? = nil
let strExec=str.cString(using: String.Encoding.utf8)
if (sqlite3_open(DBpath, &db)==SQLITE_OK)
{
if (sqlite3_prepare_v2(db, strExec! , -1, &stmt, nil) == SQLITE_OK)
{
if (sqlite3_step(stmt) == SQLITE_DONE)
{
result=true
}
}
sqlite3_finalize(stmt)
}
sqlite3_close(db)
return result
}
func SelectQuery(_ str:String) -> Array<Dictionary<String,String>>
{
var result:Array<Dictionary<String,String>>=[]
let DBpath:String=self.databasePath() as String
var db: OpaquePointer? = nil
var stmt:OpaquePointer? = nil
let strExec=str.cString(using: String.Encoding.utf8)
if ( sqlite3_open(DBpath,&db) == SQLITE_OK)
{
if (sqlite3_prepare_v2(db, strExec! , -1, &stmt, nil) == SQLITE_OK)
{
while (sqlite3_step(stmt) == SQLITE_ROW)
{
var i:Int32=0
let icount:Int32=sqlite3_column_count(stmt)
var dict=Dictionary<String, String>()
while i < icount
{
let strF=sqlite3_column_name(stmt, i)
let strV = sqlite3_column_text(stmt, i)
let rFiled:String=String(cString: strF!)
let rValue:String=String(cString: strV!)
//let rValue=String(cString: UnsafePointer<Int8>(strV!))
dict[rFiled] = rValue
i += 1
}
result.insert(dict, at: result.count)
}
sqlite3_finalize(stmt)
}
sqlite3_close(db)
}
return result
}
func AllSelectQuery(_ str:String) -> Array<Model>
{
var result:Array<Model>=[]
let DBpath:String=self.databasePath() as String
var db: OpaquePointer? = nil
var stmt:OpaquePointer? = nil
let strExec=str.cString(using: String.Encoding.utf8)
if ( sqlite3_open(DBpath,&db) == SQLITE_OK)
{
if (sqlite3_prepare_v2(db, strExec! , -1, &stmt, nil) == SQLITE_OK)
{
while (sqlite3_step(stmt) == SQLITE_ROW)
{
let mod=Model()
mod.id=String(cString: sqlite3_column_text(stmt, 0))
mod.image=String(cString: sqlite3_column_text(stmt, 1))
mod.name=String(cString: sqlite3_column_text(stmt, 2))
mod.foodtype=String(cString: sqlite3_column_text(stmt, 3))
mod.vegtype=String(cString: sqlite3_column_text(stmt, 4))
mod.details=String(cString: sqlite3_column_text(stmt, 5))
result.insert(mod, at: result.count)
}
sqlite3_finalize(stmt)
}
sqlite3_close(db)
}
return result
}
}
Model.swift
import UIKit
class Model: NSObject
{
var uid:Int = 0
var id:String = ""
var image:String = ""
var name:String = ""
var foodtype:String = ""
var vegtype:String = ""
var details:String = ""
var mealtype:String = ""
var date:String = ""
}
Access database :
let DB=database()
var mod=Model()
database Query fire :
var DailyResult:Array<Model> = DB.AllSelectQuery("select * from food where foodtype == 'Sea Food' ORDER BY name ASC")
If you don't care about the locale issue, you can set PERL_BADLANG=0
. Of course, this could result in incorrect localisation.
In case of Angular 7.x you can get the native element and its id or properties.
myClickHandler($event) {
this.selectedElement = <Element>$event.target;
console.log(this.selectedElement.id)
this.selectedElement.classList.remove('some-class');
}
html:
<div class="list-item" (click)="myClickHandler($event)">...</div>
This sort of approach should work.
var plugin_exists = true;
try {
// some code that requires that plugin here
} catch(err) {
plugin_exists = false;
}
you can also use this to read all the lines in the file one by one then print i
#include <iostream>
#include <fstream>
using namespace std;
bool check_file_is_empty ( ifstream& file){
return file.peek() == EOF ;
}
int main (){
string text[256];
int lineno ;
ifstream file("text.txt");
int num = 0;
while (!check_file_is_empty(file))
{
getline(file , text[num]);
num++;
}
for (int i = 0; i < num ; i++)
{
cout << "\nthis is the text in " << "line " << i+1 << " :: " << text[i] << endl ;
}
system("pause");
return 0;
}
hope this could help you :)
Just another possibility: Spring initializes bean by type not by name if you don't define bean with a name, which is ok if you use it by its type:
Producer:
@Service
public void FooServiceImpl implements FooService{}
Consumer:
@Autowired
private FooService fooService;
or
@Autowired
private void setFooService(FooService fooService) {}
but not ok if you use it by name:
ApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
ctx.getBean("fooService");
It would complain: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'fooService' is defined
In this case, assigning name to @Service("fooService")
would make it work.
There is no standard support for renaming properties in JavaScriptSerializer
however you can quite easily add your own:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Script.Serialization;
using System.Reflection;
public class JsonConverter : JavaScriptConverter
{
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
List<MemberInfo> members = new List<MemberInfo>();
members.AddRange(type.GetFields());
members.AddRange(type.GetProperties().Where(p => p.CanRead && p.CanWrite && p.GetIndexParameters().Length == 0));
object obj = Activator.CreateInstance(type);
foreach (MemberInfo member in members)
{
JsonPropertyAttribute jsonProperty = (JsonPropertyAttribute)Attribute.GetCustomAttribute(member, typeof(JsonPropertyAttribute));
if (jsonProperty != null && dictionary.ContainsKey(jsonProperty.Name))
{
SetMemberValue(serializer, member, obj, dictionary[jsonProperty.Name]);
}
else if (dictionary.ContainsKey(member.Name))
{
SetMemberValue(serializer, member, obj, dictionary[member.Name]);
}
else
{
KeyValuePair<string, object> kvp = dictionary.FirstOrDefault(x => string.Equals(x.Key, member.Name, StringComparison.InvariantCultureIgnoreCase));
if (!kvp.Equals(default(KeyValuePair<string, object>)))
{
SetMemberValue(serializer, member, obj, kvp.Value);
}
}
}
return obj;
}
private void SetMemberValue(JavaScriptSerializer serializer, MemberInfo member, object obj, object value)
{
if (member is PropertyInfo)
{
PropertyInfo property = (PropertyInfo)member;
property.SetValue(obj, serializer.ConvertToType(value, property.PropertyType), null);
}
else if (member is FieldInfo)
{
FieldInfo field = (FieldInfo)member;
field.SetValue(obj, serializer.ConvertToType(value, field.FieldType));
}
}
public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
{
Type type = obj.GetType();
List<MemberInfo> members = new List<MemberInfo>();
members.AddRange(type.GetFields());
members.AddRange(type.GetProperties().Where(p => p.CanRead && p.CanWrite && p.GetIndexParameters().Length == 0));
Dictionary<string, object> values = new Dictionary<string, object>();
foreach (MemberInfo member in members)
{
JsonPropertyAttribute jsonProperty = (JsonPropertyAttribute)Attribute.GetCustomAttribute(member, typeof(JsonPropertyAttribute));
if (jsonProperty != null)
{
values[jsonProperty.Name] = GetMemberValue(member, obj);
}
else
{
values[member.Name] = GetMemberValue(member, obj);
}
}
return values;
}
private object GetMemberValue(MemberInfo member, object obj)
{
if (member is PropertyInfo)
{
PropertyInfo property = (PropertyInfo)member;
return property.GetValue(obj, null);
}
else if (member is FieldInfo)
{
FieldInfo field = (FieldInfo)member;
return field.GetValue(obj);
}
return null;
}
public override IEnumerable<Type> SupportedTypes
{
get
{
return new[] { typeof(DataObject) };
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property)]
public class JsonPropertyAttribute : Attribute
{
public JsonPropertyAttribute(string name)
{
Name = name;
}
public string Name
{
get;
set;
}
}
The DataObject
class then becomes:
public class DataObject
{
[JsonProperty("user_id")]
public int UserId { get; set; }
[JsonProperty("detail_level")]
public DetailLevel DetailLevel { get; set; }
}
I appreicate this might be a little late but thought other people wanting to use the JavaScriptSerializer
rather than the DataContractJsonSerializer
might appreciate it.
Here's a really simple & concise ES6 function to do this:
const titleCase = (str) => {
return str.replace(/\w\S*/g, (t) => { return t.charAt(0).toUpperCase() + t.substr(1).toLowerCase() });
}
export default titleCase;
Works well included in a utilities
folder and used as follows:
import titleCase from './utilities/titleCase.js';
const string = 'my title & string';
console.log(titleCase(string)); //-> 'My Title & String'
If you don't want to make the button a separate image, you can use the <area>
tag. This is done by using html similar to this:
<img src="imgsrc" width="imgwidth" height="imgheight" alt="alttext" usemap="#mapname">
<map name="mapname">
<area shape="rect" coords="see note 1" href="link" alt="alttext">
</map>
Note 1: The coords=" "
attribute must be formatted in this way: coords="x1,y1,x2,y2"
where:
x1=top left X coordinate
y1=top left Y coordinate
x2=bottom right X coordinate
y2=bottom right Y coordinate
Note 2: The usemap="#mapname"
attribute must include the #
.
EDIT:
I looked at your code and added in the <map>
and <area>
tags where they should be. I also commented out some parts that were either overlapping the image or seemed there for no use.
<div class="flexslider">
<ul class="slides" runat="server" id="Ul">
<li class="flex-active-slide" style="background: url("images/slider-bg-1.jpg") no-repeat scroll 50% 0px transparent; width: 100%; float: left; margin-right: -100%; position: relative; display: list-item;">
<div class="container">
<div class="sixteen columns contain"></div>
<img runat="server" id="imgSlide1" style="top: 1px; right: -19px; opacity: 1;" class="item" src="./test.png" data-topimage="7%" height="358" width="728" usemap="#imgmap" />
<map name="imgmap">
<area shape="rect" coords="48,341,294,275" href="http://www.example.com/">
</map>
<!--<a href="#" style="display:block; background:#00F; width:356px; height:66px; position:absolute; left:1px; top:-19px; left: 162px; top: 279px;"></a>-->
</div>
</li>
</ul>
</div>
<!-- <ul class="flex-direction-nav">
<li><a class="flex-prev" href="#"><i class="icon-angle-left"></i></a></li>
<li><a class="flex-next" href="#"><i class="icon-angle-right"></i></a></li>
</ul> -->
Notes:
coord="48,341,294,275"
is in reference to your screenshot you posted.src="./test.png"
is the location and name of the screenshot you posted on my computer.href="http://www.example.com/"
is an example link.Try following css with addition of white-space
:
span {
display: block;
word-wrap:break-word;
width: 50px;
white-space: normal
}
Every answer seems to suggest that you need to use secure hashes to do the job but all of these are tuned to be slow to force a bruteforce attacker to have lots of computing power and depending on your needs this may not be the best solution.
There are algorithms specifically designed to hash files as fast as possible to check integrity and comparison (murmur
, XXhash
...). Obviously these are not designed for security as they don't meet the requirements of a secure hash algorithm (i.e. randomness) but have low collision rates for large messages. This features make them ideal if you are not looking for security but speed.
Examples of this algorithms and comparison can be found in this excellent answer: Which hashing algorithm is best for uniqueness and speed?.
As an example, we at our Q&A site use murmur3
to hash the images uploaded by the users so we only store them once even if users upload the same image in several answers.
The lambda you are passing to forEach()
is evaluated for each element received from the stream. The iteration itself is not visible from within the scope of the lambda, so you cannot continue
it as if forEach()
were a C preprocessor macro. Instead, you can conditionally skip the rest of the statements in it.
I was running PHPUnit tests on PHP5, and then, I needed to support PHP7 as well. This is what I did:
In composer.json:
"phpunit/phpunit": "~4.8|~5.7"
In my PHPUnit bootstrap file (in my case, /tests/bootstrap.php
):
// PHPUnit 6 introduced a breaking change that
// removed PHPUnit_Framework_TestCase as a base class,
// and replaced it with \PHPUnit\Framework\TestCase
if (!class_exists('\PHPUnit_Framework_TestCase') && class_exists('\PHPUnit\Framework\TestCase'))
class_alias('\PHPUnit\Framework\TestCase', '\PHPUnit_Framework_TestCase');
In other words, this will work for tests written originally for PHPUnit 4 or 5, but then needed to work on PHPUnit 6 as well.
I fond that executing click()
event on a
element inside a for loop
for multiple files download works only for limited number of files (10 files in my case). The only reason that would explain this behavior that made sense to me, was speed/intervals of downloads executed by click()
events.
I figure out that, if I slow down execution of click()
event, then I will be able to downloads all files.
This is solution that worked for me.
var urls = [
'http://example.com/file1',
'http://example.com/file2',
'http://example.com/file3'
]
var interval = setInterval(download, 300, urls);
function download(urls) {
var url = urls.pop();
var a = document.createElement("a");
a.setAttribute('href', url);
a.setAttribute('download', '');
a.setAttribute('target', '_blank');
a.click();
if (urls.length == 0) {
clearInterval(interval);
}
}
I execute download event click()
every 300ms. When there is no more files to download urls.length == 0
then, I execute clearInterval
on interval
function to stop downloads.
You can now simply get a list of event listeners bound to an object by using the javascript function getEventListeners().
For example type the following in the dev tools console:
// Get all event listners bound to the document object
getEventListeners(document);
Update 2019
In Bootstrap 4, flexbox can be used to get a full height layout that fills the remaining space.
First of all, the container (parent) needs to be full height:
Option 1_ Add a class for min-height: 100%;
. Remember that min-height will only work if the parent has a defined height:
html, body {
height: 100%;
}
.min-100 {
min-height: 100%;
}
https://codeply.com/go/dTaVyMah1U
Option 2_ Use vh
units:
.vh-100 {
min-height: 100vh;
}
https://codeply.com/go/kMahVdZyGj
Also of Bootstrap 4.1, the vh-100
and min-vh-100
classes are included in Bootstrap so there is no need to for the extra CSS
Then, use flexbox direction column d-flex flex-column
on the container, and flex-grow-1
on any child divs (ie: row
) that you want to fill the remaining height.
Also see:
Bootstrap 4 Navbar and content fill height flexbox
Bootstrap - Fill fluid container between header and footer
How to make the row stretch remaining height
SWIFT 4
//First get the nsObject by defining as an optional AnyObject
let nsObject: AnyObject? = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as AnyObject
//Then just cast the object as a String, but be careful, you may want to double check for nil
let version = nsObject as! String
Yea, this was a pain for me as well.
So what i did was find the "Start Wampserver", just hit the start button and type it in.
Then right click on it , select properties. I set it to run in XP servive pack 3 on the capatability tab. I also checked the box "Run this program as an administrator".
Then I right clicked the WAMPSERVER on the System Tray, and re-started all services. This worked perfect for me, hope this will help you as well.
Rob
You could use addEventListener to add as many listeners as you want.
document.getElementById("Save").addEventListener('click',function ()
{
alert("hello");
//validation code to see State field is mandatory.
} );
Also add script
tag after the element to make sure Save
element is loaded at the time when script runs
Rather than moving script tag you could call it when dom is loaded. Then you should place your code inside the
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("Save").addEventListener('click',function ()
{
alert("hello");
//validation code to see State field is mandatory.
} );
});
with tempa as
(
select value,row_number() over (order by value) as Rn,/* Assigning a
row_number */
count(value) over () as Cnt /*Taking total count of the values */
from numbers
where value is not null /* Excluding the null values */
),
tempb as
(
/* Since we don't know whether the number of rows is odd or even, we shall
consider both the scenarios */
select round(cnt/2) as Ref from tempa where mod(cnt,2)=1
union all
select round(cnt/2) a Ref from tempa where mod(cnt,2)=0
union all
select round(cnt/2) + 1 as Ref from tempa where mod(cnt,2)=0
)
select avg(value) as Median_Value
from tempa where rn in
( select Ref from tempb);
This error message happens either because your ProfileDto
class is not registered in the JAXB Content, or the class using it does not use @XmlSeeAlso(ProfileDto.class)
to make processable by JAXB.
About your comment:
I was under the impression the annotations was only needed when the referenced class was a sub-class.
No, they are also needed when not declared in the JAXB context or, for example, when the only class having a static reference to it has this reference annotated with @XmlTransient
. I maintain a tutorial here.
Use par(las=1)
.
See ?par
:
las
numeric in {0,1,2,3}; the style of axis labels.
0: always parallel to the axis [default],
1: always horizontal,
2: always perpendicular to the axis,
3: always vertical.
Your original problem was that you were checking if the list was null, which it would never be because you instantiated it with List<Integer> numbers = new ArrayList<Integer>();
. However, you have updated your code to use the List.isEmpty()
method to properly check if the list is empty.
The problem now is that you are never actually sending an empty list to giveList()
. In your do-while loop, you add any input number to the list, even if it is -1. To prevent -1 being added, change the do-while loop to only add numbers if they are not -1. Then, the list will be empty if the user's first input number is -1.
do {
number = Integer.parseInt(JOptionPane.showInputDialog("Enter a number (-1 to stop)"));
/* Change this line */
if (number != -1) numbers.add(number);
} while (number != -1);
Good'ol javascript:
var m = "Hello World";
var k = m.split(' '); // I have used space, you can use any thing.
for(i=0;i<k.length;i++)
alert(k[i]);
You just put them in __init__.py.
So with test/classes.py being:
class A(object): pass
class B(object): pass
... and test/__init__.py being:
from classes import *
class Helper(object): pass
You can import test and have access to A, B and Helper
>>> import test
>>> test.A
<class 'test.classes.A'>
>>> test.B
<class 'test.classes.B'>
>>> test.Helper
<class 'test.Helper'>
I tried hard, but this seems to work (assuming \r
is biting you here):
printf "\r" | egrep -xv "[[:space:]]*"
Include the attribute Method="text" on the xsl:output tag and include newlines in your literal content in the XSL at the appropriate points. If you prefer to keep the source code of your XSL tidy use the entity
where you want a new line.
The general consensus answer above seems to have have a compatibility issue with CORS support. In order to use the HttpContext.Current.User.Identity.Name attribute you must disable anonymous authentication in order to force Windows authentication to provide the authenticated user information. Unfortunately, I believe you must have anonymous authentication enabled in order to process the pre-flight OPTIONS request in a CORS scenario.
You can get around this by leaving anonymous authentication enabled and using the HttpContext.Current.Request.LogonUserIdentity attribute instead. This will return the authenticated user information (assuming you are in an intranet scenario) even with anonymous authentication enabled. The attribute returns a WindowsUser data structure and both are defined in the System.Web namespace
using System.Web;
WindowsIdentity user;
user = HttpContext.Current.Request.LogonUserIdentity;
I fount a very simple solution:
<dependency>
<groupId>com.cedarsoftware</groupId>
<artifactId>json-io</artifactId>
<version>4.5.0</version>
</dependency>
Java code:
import com.cedarsoftware.util.io.JsonWriter;
//...
String jsonString = "json_string_plain_text";
System.out.println(JsonWriter.formatJson(jsonString));
To list only the containers SHA1:
docker ps -aq --no-trunc
That way, you can use the list of all containers for other commands (which accept multiple container ids as parameters).
For example, to list only the name of all containers (since docker ps
list only their names with other information):
docker inspect --format='{{.Name}}' $(sudo docker ps -aq --no-trunc)
In case you use jQuery on the client side, you may be interested in this blog post that provides code how to globally extend jQuery's $.parseJSON()
function to automatically convert dates for you.
You don't have to change existing code in case of adding this code. It doesn't affect existing calls to $.parseJSON()
, but if you start using $.parseJSON(data, true)
, dates in data
string will be automatically converted to Javascript dates.
It supports Asp.net date strings: /Date(2934612301)/
as well as ISO strings 2010-01-01T12_34_56-789Z
. The first one is most common for most used back-end web platform, the second one is used by native browser JSON support (as well as other JSON client side libraries like json2.js).
Anyway. Head over to blog post to get the code. http://erraticdev.blogspot.com/2010/12/converting-dates-in-json-strings-using.html
You can add a wrapper around promise functionality to return an Observable to observer.
import { of, Observable, defer } from 'rxjs';
import { map } from 'rxjs/operators';
function getTodos$(): Observable<any> {
return defer(()=>{
return fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => {
return json;
})
});
}
getTodos$().
subscribe(
(next)=>{
console.log('Data is:', next);
}
)
System.out.println(Normalizer.normalize("àèé", Normalizer.Form.NFD).replaceAll("\\p{InCombiningDiacriticalMarks}+", ""));
worked for me. The output of the snippet above gives "aee" which is what I wanted, but
System.out.println(Normalizer.normalize("àèé", Normalizer.Form.NFD).replaceAll("[^\\p{ASCII}]", ""));
didn't do any substitution.
Possible with HTML5.
In general it is safer to work on copies than on original data frames, except when you know that you won't be needing the original anymore and want to proceed with the manipulated version. Normally, you would still have some use for the original data frame to compare with the manipulated version, etc. Therefore, most people work on copies and merge at the end.
Code behind solution
private void Button1_Click(object sender, RoutedEventArgs e)
{
System.Text.StringBuilder myStringBuilder = new System.Text.StringBuilder();
myStringBuilder.Append("Orange").AppendLine();
myStringBuilder.Append("").AppendLine();
myStringBuilder.Append("Apple").AppendLine();
myStringBuilder.Append("Banana").AppendLine();
myStringBuilder.Append("").AppendLine();
myStringBuilder.Append("Plum").AppendLine();
TextBox1.Text = myStringBuilder.ToString();
}
Additionally, if using WildFly/JBoss, set the logging level of org.hibernate to DEBUG
You're not running a module -- you're running subroutines/functions that happen to be stored in modules.
If you put the code in a standalone module and don't specify scope in the definitions of your subroutines/functions, they will be public by default, and callable from anywhere within your application. This means that you can call them with RunCode in a macro, from the class modules of forms/reports, from standalone class modules, or for the functions, from SQL (with some caveats).
Given that you were trying to implement in VBA something that you felt was too complicated for SQL, SQL is the likely context in which you want to execute the code. So, you should just be able to call your function within the SQL statement:
SELECT MyTable.PersonID, MyTable.FirstName, MyTable.LastName, FormatAddress([Address], [City], [State], [Zip], [Country]) As Address
FROM MyTable;
That SQL calls a public function called FormatAddress() that takes as arguments the components of an address and formats them appropriately. It's a trivial example as you likely would not need a VBA function for that purpose, but the point is that this is how you call functions from within a SQL statement.
Subroutines (i.e., code that returns no value) are not callable from within SQL statements.
You can right click the project file, select "Unload project" then you can open the file directly for editing by selecting "Edit project name.csproj".
You will have to load the project back after you have saved your changes in order for it to compile.
See How to: Unload and Reload Projects on MSDN.
Since project files are XML files, you can also simply edit them using any text editor that supports Unicode (notepad, notepad++ etc...)
However, I would be very reluctant to edit these files by hand - use the Solution explorer for this if at all possible. If you have errors and you know how to fix them manually, go ahead, but be aware that you can completely ruin the project file if you don't know exactly what you are doing.
TextView t2 = (TextView) findViewById(R.id.textviewidname);
t2.setMovementMethod(LinkMovementMethod.getInstance());
and
<string name="google_stackoverflow"><a href="https://stackoverflow.com/questions/9852184/android-textview-hyperlink?rq=1">google stack overflow</a></string>
The link is, "Android: textview hyperlink"
and the tag is, "google stack overflow"
Define the first code block in your java and the second code block in your strings.xml file. Also, be sure to reference the id of the textView from your page layout in your java.
You can essentially do this 2 ways:
Add a file called .htaccess
in your root folder, and add something like this:
RewriteEngine on
RewriteRule ^/?Some-text-goes-here/([0-9]+)$ /picture.php?id=$1
This will tell Apache to enable mod_rewrite for this folder, and if it gets asked a URL matching the regular expression it rewrites it internally to what you want, without the end user seeing it. Easy, but inflexible, so if you need more power:
Put the following in your .htaccess instead: (note the leading slash)
FallbackResource /index.php
This will tell it to run your index.php
for all files it cannot normally find in your site. In there you can then for example:
$path = ltrim($_SERVER['REQUEST_URI'], '/'); // Trim leading slash(es)
$elements = explode('/', $path); // Split path on slashes
if(empty($elements[0])) { // No path elements means home
ShowHomepage();
} else switch(array_shift($elements)) // Pop off first item and switch
{
case 'Some-text-goes-here':
ShowPicture($elements); // passes rest of parameters to internal function
break;
case 'more':
...
default:
header('HTTP/1.1 404 Not Found');
Show404Error();
}
This is how big sites and CMS-systems do it, because it allows far more flexibility in parsing URLs, config and database dependent URLs etc. For sporadic usage the hardcoded rewrite rules in .htaccess
will do fine though.
Generally i prefer the lambda syntax with LINQ, but Join
is one example where i prefer the query syntax - purely for readability.
Nonetheless, here is the equivalent of your above query (i think, untested):
var query = db.Categories // source
.Join(db.CategoryMaps, // target
c => c.CategoryId, // FK
cm => cm.ChildCategoryId, // PK
(c, cm) => new { Category = c, CategoryMaps = cm }) // project result
.Select(x => x.Category); // select result
You might have to fiddle with the projection depending on what you want to return, but that's the jist of it.
I have used following code to read "xls and xlsx" :
include 'PHPExcel/IOFactory.php';
$location='sample-excel-files.xlsx';
$objPHPExcel = PHPExcel_IOFactory::load($location);
$sheet = $objPHPExcel->getSheet(0);
$total_rows = $sheet->getHighestRow();
$total_columns = $sheet->getHighestColumn();
$set_excel_query_all=array();
for($row =2; $row <= $total_rows; $row++) {
$singlerow = $sheet->rangeToArray('A' . $row . ':' . $total_columns . $row, NULL, TRUE, FALSE);
$single_row=$singlerow[0];
$set_excel_query['store_id']=$single_row[0];
$set_excel_query['employee_uid']=$single_row[1];
$set_excel_query['opus_id']=$single_row[2];
$set_excel_query['item_description']=$single_row[3];
if($single_row[4])
{
$set_excel_query['opus_transaction_date']= date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($single_row[4]));
}
$set_excel_query['opus_transaction_num']=$single_row[5];
$set_excel_query['opus_invoice_num']=$single_row[6];
$set_excel_query['customer_name']=$single_row[7];
$set_excel_query['mobile_num']=$single_row[8];
$set_excel_query['opus_amount']=$single_row[9];
$set_excel_query['rq4_amount']=$single_row[10];
$set_excel_query['difference']=$single_row[11];
$set_excel_query['ocomment']=$single_row[12];
$set_excel_query['mark_delete']=$single_row[13];
if($single_row[14])
{
$set_excel_query['upload_date']= date('Y-m-d', PHPExcel_Shared_Date::ExcelToPHP($single_row[14]));
}
$set_excel_query_all[]=$set_excel_query;
}
print_r($set_excel_query_all);
In the .service file under the [Unit] section:
[Unit]
Description=My Website
After=syslog.target network.target mongodb.service
The important part is the mongodb.service
The manpage describes it however due to formatting it's not as clear on first sight
As of Django 2.1, a new built in template tag has been introduced specifically for this use case: json_script
.
https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#json-script
The new tag will safely serialize template values and protects against XSS.
Django docs excerpt:
Safely outputs a Python object as JSON, wrapped in a tag, ready for use with JavaScript.
Delegate[] dary = TermCheckScore.GetInvocationList();
if ( dary != null )
{
foreach ( Delegate del in dary )
{
TermCheckScore -= ( Action ) del;
}
}
This is weird. I don't know why this was happening with me while generating signed apk but below steps worked for me.
That's it.
You can use:
select *
from
sys.procedures
where
name like '%name_of_proc%'
if you need the code you can look in the syscomments table
select text
from
syscomments c
inner join sys.procedures p on p.object_id = c.object_id
where
p.name like '%name_of_proc%'
Edit Update:
you can can also use the ansi standard version
SELECT *
FROM
INFORMATION_SCHEMA.ROUTINES
WHERE
ROUTINE_NAME LIKE '%name_of_proc%'
You 100% can do this on the server side...
Protected Sub Button3_Click(sender As Object, e As System.EventArgs)
MesgBox("Test")
End Sub
Private Sub MesgBox(ByVal sMessage As String)
Dim msg As String
msg = "<script language='javascript'>"
msg += "alert('" & sMessage & "');"
msg += "</script>"
Response.Write(msg)
End Sub
here is actually a whole slew of ways to go about this http://www.sislands.com/coin70/week1/dialogbox.htm
Or if you like to mix outputs (stdout & stderr) in one single file you may want to use:
command > merged-output.txt 2>&1
Not exactly the case of this question but can be helpful. I got this exception when i call mkdirs() on new file instead of its parent
File file = new java.io.File(path);
//file.mkdirs(); // wrong!
file.getParentFile().mkdirs(); // correct!
if (!file.exists()) {
file.createNewFile();
}
For Python 3.x
import urllib.request
from urllib.error import HTTPError
try:
urllib.request.urlretrieve(url, fullpath)
except urllib.error.HTTPError as err:
print(err.code)
Getting one char from string at specified index
Dim pos As Integer
Dim outStr As String
pos = 2
Dim outStr As String
outStr = Left(Mid("abcdef", pos), 1)
outStr="b"
If primary key is not already defined on parent table then this issue may arise. Please try to define the primary key on existing table. For eg:
ALTER TABLE table_name
ADD PRIMARY KEY (the_column_which_is_primary_key);
I tried to start my binary, compiled with Qt 5.7
, on Ubuntu 16.04 LTS where Qt 5.5
is preinstalled. It didn't work.
At first, I inspected the binary itself with ldd
as was suggested here, and "satisfied" all "not found" dependencies. Then this notorious This application failed to start because it could not find or load the Qt platform plugin "xcb"
error was thrown.
Firstly you should create platforms
directory where your binary is, because it is the place where Qt looks for XCB library. Copy libqxcb.so
there. I wonder why authors of other answers didn't mention this.
Then you may want to run your binary with QT_DEBUG_PLUGINS=1
environment variable set to check which dependencies of libqxcb.so
are not "satisfied". (You may also use ldd
for this as suggested in the accepted answer).
The command output may look like this:
me@xerus:/media/sf_Qt/Package$ LD_LIBRARY_PATH=. QT_DEBUG_PLUGINS=1 ./Binary
QFactoryLoader::QFactoryLoader() checking directory path "/media/sf_Qt/Package/platforms" ...
QFactoryLoader::QFactoryLoader() looking at "/media/sf_Qt/Package/platforms/libqxcb.so"
Found metadata in lib /media/sf_Qt/Package/platforms/libqxcb.so, metadata=
{
"IID": "org.qt-project.Qt.QPA.QPlatformIntegrationFactoryInterface.5.3",
"MetaData": {
"Keys": [
"xcb"
]
},
"className": "QXcbIntegrationPlugin",
"debug": false,
"version": 329472
}
Got keys from plugin meta data ("xcb")
loaded library "/media/sf_Qt/Package/platforms/libqxcb.so"
QLibraryPrivate::loadPlugin failed on "/media/sf_Qt/Package/platforms/libqxcb.so" : "Cannot load library /media/sf_Qt/Package/platforms/libqxcb.so: (/usr/lib/x86_64-linux-gnu/libQt5DBus.so.5: version `Qt_5' not found (required by ./libQt5XcbQpa.so.5))"
This application failed to start because it could not find or load the Qt platform plugin "xcb"
in "".
Available platform plugins are: xcb.
Reinstalling the application may fix this problem.
Aborted (core dumped)
Note the failing libQt5DBus.so.5
library. Copy it to your libraries path, in my case it was the same directory where my binary is (hence LD_LIBRARY_PATH=.
). Repeat this process until all dependencies are satisfied.
P.S. thanks to the author of this answer for QT_DEBUG_PLUGINS=1
.
Works in both with postgresql and Oracle
SELECT ename, sal, round(((sal * .15 + comm) /12),2)
FROM emp where job = 'SALESMAN'
int height(Node* root) {
if(root==NULL) return -1;
return max(height(root->left),height(root->right))+1;
}
Take of maximum height from left and right subtree and add 1 to it.This also handles the base case(height of Tree with 1 node is 0).
A tail recursion is a recursive function where the function calls itself at the end ("tail") of the function in which no computation is done after the return of recursive call. Many compilers optimize to change a recursive call to a tail recursive or an iterative call.
Consider the problem of computing factorial of a number.
A straightforward approach would be:
factorial(n):
if n==0 then 1
else n*factorial(n-1)
Suppose you call factorial(4). The recursion tree would be:
factorial(4)
/ \
4 factorial(3)
/ \
3 factorial(2)
/ \
2 factorial(1)
/ \
1 factorial(0)
\
1
The maximum recursion depth in the above case is O(n).
However, consider the following example:
factAux(m,n):
if n==0 then m;
else factAux(m*n,n-1);
factTail(n):
return factAux(1,n);
Recursion tree for factTail(4) would be:
factTail(4)
|
factAux(1,4)
|
factAux(4,3)
|
factAux(12,2)
|
factAux(24,1)
|
factAux(24,0)
|
24
Here also, maximum recursion depth is O(n) but none of the calls adds any extra variable to the stack. Hence the compiler can do away with a stack.
DELETE FROM ... WHERE id=...;
protected function templateRemove($id){
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('XXXBundle:Templates')->findOneBy(array('id' => $id));
if ($entity != null){
$em->remove($entity);
$em->flush();
}
}
It's fairly easy to use label
, You can break the outer loop from inner loop using the label, Consider the example below,
public class Breaking{
public static void main(String[] args) {
outerscope:
for (int i=0; i < 5; i++) {
for (int j=0; j < 5; j++) {
if (condition) {
break outerscope;
}
}
}
}
}
Another approach is to use the breaking variable/flag to keep track of required break. consider the following example.
public class Breaking{
public static void main(String[] args) {
boolean isBreaking = false;
for (int i=0; i < 5; i++) {
for (int j=0; j < 5; j++) {
if (condition) {
isBreaking = true;
break;
}
}
if(isBreaking){
break;
}
}
}
}
However, I prefer using the first approach.
Try this:
$('[id$=lblVessel]').text("NewText");
The id$=
will match the elements that end with that text, which is how ASP.NET auto-generates IDs. You can make it safer using span[id=$=lblVessel]
but usually this isn't necessary.
here is direct link for api 17 documentation. Just extract at under docs folder. Hope it helps.
https://dl-ssl.google.com/android/repository/docs-17_r02.zip (129 MB)
You can use the RedirectToAction()
method, then the action you redirect to can return a View. The easiest way to do this is:
return RedirectToAction("Index", model);
Then in your Index method, return the view you want.
I'm using this to detect bots:
if (preg_match('/bot|crawl|curl|dataprovider|search|get|spider|find|java|majesticsEO|google|yahoo|teoma|contaxe|yandex|libwww-perl|facebookexternalhit/i', $_SERVER['HTTP_USER_AGENT'])) {
// is bot
}
In addition I use a whitelist to block unwanted bots:
if (preg_match('/apple|baidu|bingbot|facebookexternalhit|googlebot|-google|ia_archiver|msnbot|naverbot|pingdom|seznambot|slurp|teoma|twitter|yandex|yeti/i', $_SERVER['HTTP_USER_AGENT'])) {
// allowed bot
}
An unwanted bot (= false-positive user) is then able to solve a captcha to unblock himself for 24 hours. And as no one solves this captcha, I know it does not produce false-positives. So the bot detection seem to work perfectly.
Note: My whitelist is based on Facebooks robots.txt.
Locking on the this pointer can be bad if you are locking over a shared resource. A shared resource can be a static variable or a file on your computer - i.e. something that is shared between all users of the class. The reason is that the this pointer will contain a different reference to a location in memory each time your class is instantiated. So, locking over this in once instance of a class is different than locking over this in another instance of a class.
Check out this code to see what I mean. Add the following code to your main program in a Console application:
static void Main(string[] args)
{
TestThreading();
Console.ReadLine();
}
public static void TestThreading()
{
Random rand = new Random();
Thread[] threads = new Thread[10];
TestLock.balance = 100000;
for (int i = 0; i < 10; i++)
{
TestLock tl = new TestLock();
Thread t = new Thread(new ThreadStart(tl.WithdrawAmount));
threads[i] = t;
}
for (int i = 0; i < 10; i++)
{
threads[i].Start();
}
Console.Read();
}
Create a new class like the below.
class TestLock
{
public static int balance { get; set; }
public static readonly Object myLock = new Object();
public void Withdraw(int amount)
{
// Try both locks to see what I mean
// lock (this)
lock (myLock)
{
Random rand = new Random();
if (balance >= amount)
{
Console.WriteLine("Balance before Withdrawal : " + balance);
Console.WriteLine("Withdraw : -" + amount);
balance = balance - amount;
Console.WriteLine("Balance after Withdrawal : " + balance);
}
else
{
Console.WriteLine("Can't process your transaction, current balance is : " + balance + " and you tried to withdraw " + amount);
}
}
}
public void WithdrawAmount()
{
Random rand = new Random();
Withdraw(rand.Next(1, 100) * 100);
}
}
Here is a run of the program locking on this.
Balance before Withdrawal : 100000
Withdraw : -5600
Balance after Withdrawal : 94400
Balance before Withdrawal : 100000
Balance before Withdrawal : 100000
Withdraw : -5600
Balance after Withdrawal : 88800
Withdraw : -5600
Balance after Withdrawal : 83200
Balance before Withdrawal : 83200
Withdraw : -9100
Balance after Withdrawal : 74100
Balance before Withdrawal : 74100
Withdraw : -9100
Balance before Withdrawal : 74100
Withdraw : -9100
Balance after Withdrawal : 55900
Balance after Withdrawal : 65000
Balance before Withdrawal : 55900
Withdraw : -9100
Balance after Withdrawal : 46800
Balance before Withdrawal : 46800
Withdraw : -2800
Balance after Withdrawal : 44000
Balance before Withdrawal : 44000
Withdraw : -2800
Balance after Withdrawal : 41200
Balance before Withdrawal : 44000
Withdraw : -2800
Balance after Withdrawal : 38400
Here is a run of the program locking on myLock.
Balance before Withdrawal : 100000
Withdraw : -6600
Balance after Withdrawal : 93400
Balance before Withdrawal : 93400
Withdraw : -6600
Balance after Withdrawal : 86800
Balance before Withdrawal : 86800
Withdraw : -200
Balance after Withdrawal : 86600
Balance before Withdrawal : 86600
Withdraw : -8500
Balance after Withdrawal : 78100
Balance before Withdrawal : 78100
Withdraw : -8500
Balance after Withdrawal : 69600
Balance before Withdrawal : 69600
Withdraw : -8500
Balance after Withdrawal : 61100
Balance before Withdrawal : 61100
Withdraw : -2200
Balance after Withdrawal : 58900
Balance before Withdrawal : 58900
Withdraw : -2200
Balance after Withdrawal : 56700
Balance before Withdrawal : 56700
Withdraw : -2200
Balance after Withdrawal : 54500
Balance before Withdrawal : 54500
Withdraw : -500
Balance after Withdrawal : 54000
As other have answered, the result is exactly the same, None
is returned in all cases.
The difference is stylistic, but please note that PEP8 requires the use to be consistent:
Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. If any return statement returns an expression, any return statements where no value is returned should explicitly state this as return None, and an explicit return statement should be present at the end of the function (if reachable).
Yes:
def foo(x): if x >= 0: return math.sqrt(x) else: return None def bar(x): if x < 0: return None return math.sqrt(x)
No:
def foo(x): if x >= 0: return math.sqrt(x) def bar(x): if x < 0: return return math.sqrt(x)
https://www.python.org/dev/peps/pep-0008/#programming-recommendations
Basically, if you ever return non-None
value in a function, it means the return value has meaning and is meant to be caught by callers. So when you return None
, it must also be explicit, to convey None
in this case has meaning, it is one of the possible return values.
If you don't need return at all, you function basically works as a procedure instead of a function, so just don't include the return
statement.
If you are writing a procedure-like function and there is an opportunity to return earlier (i.e. you are already done at that point and don't need to execute the remaining of the function) you may use empty an return
s to signal for the reader it is just an early finish of execution and the None
value returned implicitly doesn't have any meaning and is not meant to be caught (the procedure-like function always returns None
anyway).
It seems like you have it worked out, but for others looking for this answer, an easy way to do this is by printing to stderr. You can do that like this:
from __future__ import print_function # In python 2.7
import sys
@app.route('/button/')
def button_clicked():
print('Hello world!', file=sys.stderr)
return redirect('/')
Flask will display things printed to stderr in the console. For other ways of printing to stderr, see this stackoverflow post
You can use this code line in view(form)
<?= $form->field($model, 'hidden1')->hiddenInput(['value'=>'your_value'])->label(false) ?>
Please refere this as example
If your need to pass currant date and time as hidden input : Model attribute is 'created_on' and its value is retrieve from date('Y-m-d H:i:s') , just like:"2020-03-10 09:00:00"
<?= $form->field($model, 'created_on')->hiddenInput(['value'=>date('Y-m-d H:i:s')])->label(false) ?>
I had a similar issue; turns out it was case-sensitivity issue. So, make sure you use the proper case.
This would work:
declare @test varchar(100)
set @test = 'this is a test'
while charindex(' ',@test ) > 0
begin
set @test = replace(@test, ' ', ' ')
end
select @test
How does the virtual keyword work?
Assume that Man is a base class, Indian is derived from man.
Class Man
{
public:
virtual void do_work()
{}
}
Class Indian : public Man
{
public:
void do_work()
{}
}
Declaring do_work() as virtual simply means: which do_work() to call will be determined ONLY at run-time.
Suppose I do,
Man *man;
man = new Indian();
man->do_work(); // Indian's do work is only called.
If virtual is not used, the same is statically determined or statically bound by the compiler, depending on what object is calling. So if an object of Man calls do_work(), Man's do_work() is called EVEN THOUGH IT POINTS TO AN INDIAN OBJECT
I believe that the top voted answer is misleading - Any method whether or not virtual can have an overridden implementation in the derived class. With specific reference to C++ the correct difference is run-time (when virtual is used) binding and compile-time (when virtual is not used but a method is overridden and a base pointer is pointed at a derived object) binding of associated functions.
There seems to be another misleading comment that says,
"Justin, 'pure virtual' is just a term (not a keyword, see my answer below) used to mean "this function cannot be implemented by the base class."
THIS IS WRONG! Purely virtual functions can also have a body AND CAN BE IMPLEMENTED! The truth is that an abstract class' pure virtual function can be called statically! Two very good authors are Bjarne Stroustrup and Stan Lippman.... because they wrote the language.
I fixed this problem by editing config.inc.php
file which is in phpmyadmin
folder:
specifically changed $cfg['Servers'][$i]['host'] = 'localhost'
to $cfg['Servers'][$i]['host'] = '127.0.0.1'
They're not recommended because it's a PITA if you ever have to move your code to a server where it's not supported (and you can't enable it). As you say, lots of shared hosts do support shorttags but "lots" isn't all of them. If you want to share your scripts, it's best to use the full syntax.
I agree that <?
and <?=
are easier on programmers than <?php
and <?php echo
but it is possible to do a bulk find-and-replace as long as you use the same form each time (and don't chuck in spaces (eg: <? php
or <? =
)
I don't buy readability as a reason at all. Most serious developers have the option of syntax highlighting available to them.
As ThiefMaster mentions in the comments, as of PHP 5.4, <?= ... ?>
tags are supported everywhere, regardless of shorttags settings. This should mean they're safe to use in portable code but that does mean there's then a dependency on PHP 5.4+. If you want to support pre-5.4 and can't guarantee shorttags, you'll still need to use <?php echo ... ?>
.
Also, you need to know that ASP tags <% , %> , <%= , and script tag are removed from PHP 7. So if you would like to support long-term portable code and would like switching to the most modern tools consider changing that parts of code.
You can use REQUEST_TIME
from the $_SERVER
superglobal array. From the documentation:
REQUEST_TIME
The timestamp of the start of the request. (Available since PHP 5.1.0.)
REQUEST_TIME_FLOAT
The timestamp of the start of the request, with microsecond precision. (Available since PHP 5.4.0.)
This way you don't need to save a timestamp at the beginning of your script. You can simply do:
<?php
// Do stuff
usleep(mt_rand(100, 10000));
// At the end of your script
$time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];
echo "Did stuff in $time seconds\n";
?>
Here, $time
would contain the time elapsed since the start of the script in seconds, with microseconds precision (eg. 1.341
for 1 second and 341 microseconds)
PHP documentation: $_SERVER
variables and microtime
function
There are many ways you can import Text file to the current sheet. Here are three (including the method that you are using above)
Cells.Copy
Using a QueryTable
Here is a simple macro that I recorded. Please amend it to suit your needs.
Sub Sample()
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;C:\Sample.txt", Destination:=Range("$A$1") _
)
.Name = "Sample"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End Sub
Open the text file in memory
Sub Sample()
Dim MyData As String, strData() As String
Open "C:\Sample.txt" For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
strData() = Split(MyData, vbCrLf)
End Sub
Once you have the data in the array you can export it to the current sheet.
Using the method that you are already using
Sub Sample()
Dim wbI As Workbook, wbO As Workbook
Dim wsI As Worksheet
Set wbI = ThisWorkbook
Set wsI = wbI.Sheets("Sheet1") '<~~ Sheet where you want to import
Set wbO = Workbooks.Open("C:\Sample.txt")
wbO.Sheets(1).Cells.Copy wsI.Cells
wbO.Close SaveChanges:=False
End Sub
FOLLOWUP
You can use the Application.GetOpenFilename
to choose the relevant file. For example...
Sub Sample()
Dim Ret
Ret = Application.GetOpenFilename("Prn Files (*.prn), *.prn")
If Ret <> False Then
With ActiveSheet.QueryTables.Add(Connection:= _
"TEXT;" & Ret, Destination:=Range("$A$1"))
'~~> Rest of the code
End With
End If
End Sub
I use this to solve it, go to cmd line
devenv.exe /setup /resetuserdata /resetsettings
Just to add to Jon's coding if you needed to take it a step further, and do more than just one column you can add something like
Dim copyRange2 As Range
Dim copyRange3 As Range
Set copyRange2 =src.Range("B2:B" & lastRow)
Set copyRange3 =src.Range("C2:C" & lastRow)
copyRange2.SpecialCells(xlCellTypeVisible).Copy tgt.Range("B12")
copyRange3.SpecialCells(xlCellTypeVisible).Copy tgt.Range("C12")
put these near the other codings that are the same you can easily change the Ranges as you need.
I only add this because it was helpful for me. I'd assume Jon already knows this but for those that are less experienced sometimes it's helpful to see how to change/add/modify these codings. I figured since Ruya didn't know how to manipulate the original coding it could be helpful if one ever needed to copy over only 2 visibile columns, or only 3, etc. You can use this same coding, add in extra lines that are almost the same and then the coding is copying over whatever you need.
I don't have enough reputation to reply to Jon's comment directly so I have to post as a new comment, sorry.
When you first instantiate the $objPHPExcel, it already has a single sheet (sheet 0); you're then adding a new sheet (which will become sheet 1), but setting active sheet to sheet $i (when $i is 0)... so you're renaming and populating the original worksheet created when you instantiated $objPHPExcel rather than the one you've just added... this is your title "0".
You're also using the createSheet() method, which both creates a new worksheet and adds it to the workbook... but you're also adding it again yourself which is effectively adding the sheet in two position.
So first iteration, you already have sheet0, add a new sheet at both indexes 1 and 2, and edit/title sheet 0. Second iteration, you add a new sheet at both indexes 3 and 4, and edit/title sheet 1, but because you have the same sheet at indexes 1 and 2 this effectively writes to the sheet at index 2. Third iteration, you add a new sheet at indexes 5 and 6, and edit/title sheet 2, overwriting your earlier editing/titleing of sheet 1 which acted against sheet 2 instead.... and so on
NetBeans 8.0.2 (PHP) has two problems: the SubVersion client and the Twig templates. In order to drastically improve overall performance, a) disable teh "Twig Templates" plugin (this will also deactivate Symphony2, in case you may require it) and b) override the SVN client with this switch:
run.args.extra=-J-DsvnClientAdapterFactory=commandline
^ project.properties lets one define the CLI arguments individually (which may also make sense with RAM settings and other customization). guess one could re-enable Twig once that linked bug-report has been closed. re-scanning isn't really the issue, while the rescan performs as it should ...in a timely manner.
Just was testing some more and noticed, that on Linux it runs way smoother with the Oracle JDK than the (common) OpenJDK - have seen there is even one version of NetBeans bundled with it.
You don't need both hibernate.cfg.xml
and persistence.xml
in this case. Have you tried removing hibernate.cfg.xml
and mapping everything in persistence.xml
only?
But as the other answer also pointed out, this is not okay like this:
@Id
@JoinColumn(name = "categoria")
private String id;
Didn't you want to use @Column
instead?
request.stream
is the stream of raw data passed to the application by the WSGI server. No parsing is done when reading it, although you usually want request.get_data()
instead.
data = request.stream.read()
The stream will be empty if it was previously read by request.data
or another attribute.
The correct way to format a date to return "2012-12-29" is with the script from JavaScript Date Format:
var d1 = new Date();
return d1.format("dd-m-yy");
This code does NOT work:
var d1 = new Date();
d1.toString('yyyy-MM-dd');
Using Java 8:
private static Comparator<String> nullSafeStringComparator = Comparator
.nullsFirst(String::compareToIgnoreCase);
private static Comparator<Metadata> metadataComparator = Comparator
.comparing(Metadata::getName, nullSafeStringComparator)
.thenComparing(Metadata::getValue, nullSafeStringComparator);
public int compareTo(Metadata that) {
return metadataComparator.compare(this, that);
}
Here is a helper function to perform a simple Cartesian product with two data frames. The internal logic handles using an internal key, and avoids mangling any columns that happen to be named "key" from either side.
import pandas as pd
def cartesian(df1, df2):
"""Determine Cartesian product of two data frames."""
key = 'key'
while key in df1.columns or key in df2.columns:
key = '_' + key
key_d = {key: 0}
return pd.merge(
df1.assign(**key_d), df2.assign(**key_d), on=key).drop(key, axis=1)
# Two data frames, where the first happens to have a 'key' column
df1 = pd.DataFrame({'number':[1, 2], 'key':[3, 4]})
df2 = pd.DataFrame({'digit': [5, 6]})
cartesian(df1, df2)
shows:
number key digit
0 1 3 5
1 1 3 6
2 2 4 5
3 2 4 6
Pull "pulls" the div towards the left of the browser and and Push "pushes" the div away from left of browser.
Like:
So basically in a 3 column layout of any web page the "Main Body" appears at the "Center" and in "Mobile" view the "Main Body" appears at the "Top" of the page. This is mostly desired by everyone with 3 column layout.
<div class="container">
<div class="row">
<div id="content" class="col-lg-4 col-lg-push-4 col-sm-12">
<h2>This is Content</h2>
<p>orem Ipsum ...</p>
</div>
<div id="sidebar-left" class="col-lg-4 col-sm-6 col-lg-pull-4">
<h2>This is Left Sidebar</h2>
<p>orem Ipsum...</p>
</div>
<div id="sidebar-right" class="col-lg-4 col-sm-6">
<h2>This is Right Sidebar</h2>
<p>orem Ipsum.... </p>
</div>
</div>
</div>
You can view it here: http://jsfiddle.net/DrGeneral/BxaNN/1/
Hope it helps
I would remove them. In my book, dead code like that should be considered errors because it makes you do a double-take and ask yourself "How would I ever execute that line?"
This works for me as of Mongoose v4.7.0
:
mongoose.connection.dropDatabase();
I am using xampp. For me best option is to change environment variables. Environment variable changing window is shared by @Abu Bakr in this thread
I change the path value as C:\xampp\mysql\bin; and it is working nice
when you want to get all image from folder then use glob()
built in function which help to get all image . But when you get all then sometime need to check that all is valid so in this case this code help you. this code will also check that it is image
$all_files = glob("mytheme/images/myimages/*.*");
for ($i=0; $i<count($all_files); $i++)
{
$image_name = $all_files[$i];
$supported_format = array('gif','jpg','jpeg','png');
$ext = strtolower(pathinfo($image_name, PATHINFO_EXTENSION));
if (in_array($ext, $supported_format))
{
echo '<img src="'.$image_name .'" alt="'.$image_name.'" />'."<br /><br />";
} else {
continue;
}
}
for more information
This question is old, but I wanted to add my two-cents. I read the question as " I want to run a query to my [my]SQL database and store the returned data as Pandas data structure [DataFrame]."
From the code it looks like you mean mysql database and assume you mean pandas DataFrame.
import MySQLdb as mdb
import pandas.io.sql as sql
from pandas import *
conn = mdb.connect('<server>','<user>','<pass>','<db>');
df = sql.read_frame('<query>', conn)
For example,
conn = mdb.connect('localhost','myname','mypass','testdb');
df = sql.read_frame('select * from testTable', conn)
This will import all rows of testTable into a DataFrame.
use some thing like
import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
//method to convert Document to String
public String getStringFromDocument(Document doc)
{
try
{
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
return writer.toString();
}
catch(TransformerException ex)
{
ex.printStackTrace();
return null;
}
}
Bash script to convert each page of a PDF into its own SVG file.
#!/bin/bash
#
# Make one PDF per page using PDF toolkit.
# Convert this PDF to SVG using inkscape
#
inputPdf=$1
pageCnt=$(pdftk $inputPdf dump_data | grep NumberOfPages | cut -d " " -f 2)
for i in $(seq 1 $pageCnt); do
echo "converting page $i..."
pdftk ${inputPdf} cat $i output ${inputPdf%%.*}_${i}.pdf
inkscape --without-gui "--file=${inputPdf%%.*}_${i}.pdf" "--export-plain-svg=${inputPdf%%.*}_${i}.svg"
done
To generate in png, use --export-png
, etc...
Yet, another solution is to use a :before
pseudo element with a border-radius: 50%
. This will work in all browsers, including IE 8 and up.
Using the em
unit allows responsiveness to font size changes. You can test this, by resizing your jsFiddle window.
ul {
list-style: none;
line-height: 1em;
font-size: 3vw;
}
ul li:before {
content: "";
line-height: 1em;
width: .5em;
height: .5em;
background-color: red;
float: left;
margin: .25em .25em 0;
border-radius: 50%;
}
You can even play with the box-shadow
to create some nice shadows, something that will not look nice with the content: "• "
solution.
I know this is an old post but I've just signed up for Azure and I get 25,000 emails a month for free via SendGrid. These instructions are excellent, I was up and running in minutes:
How to Send Email Using SendGrid with Azure
Azure customers can unlock 25,000 free emails each month.
microlog4android works for me but the documentation is pretty poor. All they need to add is a this is a quick start tutorial.
Here is a quick tutorial I found.
Add the following static variable in your main Activity:
private static final Logger logger = LoggerFactory.getLogger();
Add the following to your onCreate()
method:
PropertyConfigurator.getConfigurator(this).configure();
Create a file named microlog.properties
and store it in assets
directory
Edit the microlog.properties
file as follows:
microlog.level=DEBUG
microlog.appender=LogCatAppender;FileAppender
microlog.formatter=PatternFormatter
microlog.formatter.PatternFormatter.pattern=%c [%P] %m %T
Add logging statements like this:
logger.debug("M4A");
For each class you create a logger object as specified in 1)
6.You may be add the following permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Here is the source for tutorial
I know it's a bit too late, but maybe someone is looking for easy way to access appsettings in .net core app. in API constructor add the following:
public class TargetClassController : ControllerBase
{
private readonly IConfiguration _config;
public TargetClassController(IConfiguration config)
{
_config = config;
}
[HttpGet("{id:int}")]
public async Task<ActionResult<DTOResponse>> Get(int id)
{
var config = _config["YourKeySection:key"];
}
}
For primitive types (e.g. numbers, booleans, strings, etc.), there is no difference between toBe
and toEqual
; either one will work for 5
, true
, or "the cake is a lie"
.
To understand the difference between toBe
and toEqual
, let's imagine three objects.
var a = { bar: 'baz' },
b = { foo: a },
c = { foo: a };
Using a strict comparison (===
), some things are "the same":
> b.foo.bar === c.foo.bar
true
> b.foo.bar === a.bar
true
> c.foo === b.foo
true
But some things, even though they are "equal", are not "the same", since they represent objects that live in different locations in memory.
> b === c
false
Jasmine's toBe
matcher is nothing more than a wrapper for a strict equality comparison
expect(c.foo).toBe(b.foo)
is the same thing as
expect(c.foo === b.foo).toBe(true)
Don't just take my word for it; see the source code for toBe.
But b
and c
represent functionally equivalent objects; they both look like
{ foo: { bar: 'baz' } }
Wouldn't it be great if we could say that b
and c
are "equal" even if they don't represent the same object?
Enter toEqual
, which checks "deep equality" (i.e. does a recursive search through the objects to determine whether the values for their keys are equivalent). Both of the following tests will pass:
expect(b).not.toBe(c);
expect(b).toEqual(c);
Hope that helps clarify some things.
As Thomas Owens pointed out, simply concatenating the files will leave multiple ID3 headers scattered throughout the resulting concatenated file - so the time/bitrate info will be wildly wrong.
You're going to need to use a tool which can combine the audio data for you.
mp3wrap would be ideal for this - it's designed to join together MP3 files, without needing to decode + re-encode the data (which would result in a loss of audio quality) and will also deal with the ID3 tags intelligently.
The resulting file can also be split back into its component parts using the mp3splt tool - mp3wrap adds information to the IDv3 comment to allow this.
Something like this
string find = "item_manuf_id = 'some value'";
DataRow[] foundRows = table.Select(find);
To access named elements placed in a form, it is a good practice to use the form
object itself.
To access an arbitrary element in the DOM tree that may on occasion be found within a form, use getElementById
and the element's id
.
Because the dataset
property wasn't supported by Internet Explorer until version 11, you may want to use getAttribute()
instead:
document.getElementById("the-span").addEventListener("click", function(){
console.log(this.getAttribute('data-type'));
});
In short:
Source: code.
I'd rather recommend you to use Volley to make GET, PUT, POST... requests.
First, add dependency in your gradle file.
compile 'com.he5ed.lib:volley:android-cts-5.1_r4'
Now, use this code snippet to make requests.
RequestQueue queue = Volley.newRequestQueue(getApplicationContext());
StringRequest postRequest = new StringRequest( com.android.volley.Request.Method.POST, mURL,
new Response.Listener<String>()
{
@Override
public void onResponse(String response) {
// response
Log.d("Response", response);
}
},
new Response.ErrorListener()
{
@Override
public void onErrorResponse(VolleyError error) {
// error
Log.d("Error.Response", error.toString());
}
}
) {
@Override
protected Map<String, String> getParams()
{
Map<String, String> params = new HashMap<String, String>();
//add your parameters here as key-value pairs
params.put("username", username);
params.put("password", password);
return params;
}
};
queue.add(postRequest);
Rails 4:
def change
change_column_null(:users, :admin, false )
end
You can chain class selectors without a space between them:
.a.b {
color: #666;
}
Note that, if it matters to you, IE6 treats .a.b
as .b
, so in that browser both div.a.b
and div.b
will have gray text. See this answer for a comparison between proper browsers and IE6.
I am on Mac Os. In my case, my host file was black. I added following entries (these entries should be there by default, but they weren't).
##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting. Do not change this entry.
##
127.0.0.1 localhost
255.255.255.255 broadcasthost
::1 localhost
After re-running android studio, it prompted the sdk download.
You should be using where
, select
is a projection that returns the output of the statement, thus why you get boolean values. where
is a filter that keeps the structure of the dataframe, but only keeps data where the filter works.
Along the same line though, per the documentation, you can write this in 3 different ways
// The following are equivalent:
peopleDf.filter($"age" > 15)
peopleDf.where($"age" > 15)
peopleDf($"age" > 15)
Besides the GUI-based tools mentioned in the other answers, there are a few command line tools which can transform the original PDF source code into a different representation which lets you inspect the (now modified file) with a text editor. All of the tools below work on Linux, Mac OS X, other Unix systems or Windows.
qpdf
(my favorite)Use qpdf to uncompress (most) object's streams and also dissect ObjStm
objects into individual indirect objects:
qpdf --qdf --object-streams=disable orig.pdf uncompressed-qpdf.pdf
qpdf
describes itself as a tool that does "structural, content-preserving transformations on PDF files".
Then just open + inspect the uncompressed-qpdf.pdf
file in your favorite text editor. Most of the previously compressed (and hence, binary) bytes will now be plain text.
mutool
There is also the mutool
command line tool which comes bundled with the MuPDF PDF viewer (which is a sister product to Ghostscript, made by the same company, Artifex). The following command does also uncompress streams and makes them more easy to inspect through a text editor:
mutool clean -d orig.pdf uncompressed-mutool.pdf
podofouncompress
PoDoFo is an FreeSoftware/OpenSource library to work with the PDF format and it includes a few command line tools, including podofouncompress
. Use it like this to uncompress PDF streams:
podofouncompress orig.pdf uncompressed-podofo.pdf
peepdf.py
PeePDF is a Python-based tool which helps you to explore PDF files. Its original purpose was for research and dissection of PDF-based malware, but I find it useful also to investigate the structure of completely benign PDF files.
It can be used interactively to "browse" the objects and streams contained in a PDF.
I'll not give a usage example here, but only a link to its documentation:
pdfid.py
and pdf-parser.py
pdfid.py
and pdf-parser.py
are two PDF tools by Didier Stevens written in Python.
Their background is also to help explore malicious PDFs -- but I also find it useful to analyze the structure and contents of benign PDF files.
Here is an example how I would extract the uncompressed stream of PDF object no. 5 into a *.dump file:
pdf-parser.py -o 5 -f -d obj5.dump my.pdf
Please note that some binary parts inside a PDF are not necessarily uncompressible (or decode-able into human readable ASCII code), because they are embedded and used in their native format inside PDFs. Such PDF parts are JPEG images, fonts or ICC color profiles.
If you compare above tools and the command line examples given, you will discover that they do NOT all produce identical outputs. The effort of comparing them for their differences in itself can help you to better understand the nature of the PDF syntax and file format.
I saw this when I was trying to access the members.
My struct was this:
struct test {
int a;
int b;
};
struct test testvar;
Normally we access structure members as
testvar.a;
testvar.b;
I mistook testvar to be a pointer and did this.
testvar->a;
That's when I saw this error.
request for member ‘a’ in something not a structure or union
I had this info message "No Spring WebApplicationInitializer types detected on classpath" while deploying a WAR with spring integration beans in WebLogic server. Actually, I could observe that the servlet URL returned 404 Not Found and beside that info message with a negative tone "No Spring ...etc" in Server logs, nothing else was seemingly in error in my spring config; no build or deployment errors, no complaints. Indeed, I suspected that the beans.xml (spring context XML) was actually not picked up at all and that was bound to the very specific organizing of artefacts in Oracle's jDeveloper. The solution is to play carefully with the 'contributors' and 'filters' for the WEB-INF/classes category when you edit your deployment profile under the 'deployment' topic in project properties.
Precisely, I would advise to name your spring context by the jDeveloper default "beans.xml" and place it side by side to the WEB-INF subdirectory itself (under your web Apllication source path, e.g. like <...your project path>/public_html/). Then in the WEB-INF/classes category (when editing the deployment profile) your can check the Project HTML root directory in the 'contributor' list, and then select the beans.xml in filters, and then ensure your web.xml features a context-param value like classpath:beans.xml.
Once that was fixed, I was able to progress and after some more bean config changes and implementations, the message "No Spring WebApplicationInitializer types detected on classpath" came back! Actually, I did not notice when and why exactly it came back. This second time, I added a
public class HttpGatewayInit implements WebApplicationInitializer { ... }
which implements empty inherited methods, and the whole application works fine!
...If you feel that java EE development has been getting a bit too crazy with cascades of XML configuration files (some edited manually, others through wizards) intepreted by cascades of variant initializers, let me insist that I fully share your point.
Use "&
" instead of "&".
Easiest solution is to create the column using the correct data type: DATE
For example:
Create table:
create table test_date (mydate date);
Insert row:
insert into test_date values (to_date('01-01-2011','dd-mm-yyyy'));
To get the month and year, do as follows:
select to_char(mydate, 'MM-YYYY') from test_date;
Your result will be as follows: 01-2011
Another cool function to use is "EXTRACT"
select extract(year from mydate) from test_date;
This will return: 2011
This error could caused by a username with Chinese characters.
Will something like this work for you? What this does is query the content resolver to find the file path data that is stored for that content entry
public static String getRealPathFromUri(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
This will end up giving you an absolute file path that you can construct a file uri from
You can try this.
Return types using arrow notation is the same as previous answers:
const sum = (a: number, b: number) : number => a + b;
I think ("\") may be causing the problem because \ is the escape character. change it to ("\\")
This might help someone on ubuntu. No promises.
sudo apt-get install libcurl3 php5-dev libcurl4-gnutls-dev libmagic-dev
sudo apt-get install php-http make
sudo pecl install pecl_http
And adding "extension=http.so"
to php.ini (Normally located at /etc/php5/apache2/php.ini
)
Then restart Apache (sudo service apache2 restart
).
If in doubt, check your apache logs:
sudo su --
cd /var/log/apache2
tail -25 error.log
Is http.so starting or failing?
Another method without having to update your Python code at all, would be to redirect via the console.
Basically, have your Python script print()
as usual, then call the script from the command line and use command line redirection. Like this:
$ python ./myscript.py > output.txt
Your output.txt
file will now contain all output from your Python script.
Edit:
To address the comment; for Windows, change the forward-slash to a backslash.
(i.e. .\myscript.py
)
<script>
var name=document.getElementById("name").value;
var address= document.getElementById("address").value;
var age= document.getElementById("age").value;
$.ajax({
type:"GET",
url:"http://hostname/projectfolder/webservicename.php?callback=jsondata&web_name="+name+"&web_address="+address+"&web_age="+age,
crossDomain:true,
dataType:'jsonp',
success: function jsondata(data)
{
var parsedata=JSON.parse(JSON.stringify(data));
var logindata=parsedata["Status"];
if("sucess"==logindata)
{
alert("success");
}
else
{
alert("failed");
}
}
});
<script>
You need to use web services. In the above code I have php web service to be used which has a callback function which is optional. Assuming you know HTML5 I did not post the html code. In the url you can send the details to the web server.
You can't float or set the width of an inline element. Remove display: inline;
from both classes and your markup should present fine.
EDIT: You can set the width, but it will cause the element to be rendered as a block.
This is an updated version for .NET 4.5 and newer using async/await and IEnumerables:
public static class CompressionExtensions
{
public static async Task<IEnumerable<byte>> Zip(this object obj)
{
byte[] bytes = obj.Serialize();
using (MemoryStream msi = new MemoryStream(bytes))
using (MemoryStream mso = new MemoryStream())
{
using (var gs = new GZipStream(mso, CompressionMode.Compress))
await msi.CopyToAsync(gs);
return mso.ToArray().AsEnumerable();
}
}
public static async Task<object> Unzip(this byte[] bytes)
{
using (MemoryStream msi = new MemoryStream(bytes))
using (MemoryStream mso = new MemoryStream())
{
using (var gs = new GZipStream(msi, CompressionMode.Decompress))
{
// Sync example:
//gs.CopyTo(mso);
// Async way (take care of using async keyword on the method definition)
await gs.CopyToAsync(mso);
}
return mso.ToArray().Deserialize();
}
}
}
public static class SerializerExtensions
{
public static byte[] Serialize<T>(this T objectToWrite)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(stream, objectToWrite);
return stream.GetBuffer();
}
}
public static async Task<T> _Deserialize<T>(this byte[] arr)
{
using (MemoryStream stream = new MemoryStream())
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
await stream.WriteAsync(arr, 0, arr.Length);
stream.Position = 0;
return (T)binaryFormatter.Deserialize(stream);
}
}
public static async Task<object> Deserialize(this byte[] arr)
{
object obj = await arr._Deserialize<object>();
return obj;
}
}
With this you can serialize everything BinaryFormatter
supports, instead only of strings.
Edit:
In case, you need take care of Encoding
, you could just use Convert.ToBase64String(byte[])...
With the constructor:
// create a vector with 20 integer elements
std::vector<int> arr(20);
for(int x = 0; x < 20; ++x)
arr[x] = x;
CodePen Working Example
For more GitHub repo
<!DOCTYPE html>
<html>
<head>
<title>Count Up Numbers Example</title>
<script src="https://code.jquery.com/jquery-2.2.4.js" integrity="sha256-iT6Q9iMJYuQiMWNd9lDyBUStIq/8PuOW33aOqmvFpqI=" crossorigin="anonymous"></script>
<style type="text/css">
/*
Courtesy: abcc.com
https://abcc.com/en
https://abcc.com/en/at-mining
*/
.rewards {
background-color: #160922;
}
.th-num-bold {
font-family: "Arial" ;
}
.ff-arial {
font-family: "Arial" ;
}
.scroll-wrap .scroll-exchange-fee .exchange_time {
color: hsla(0,0%,100%,.7);
font-size: 13px;
}
.f14 {
font-size: 14px;
}
.flex {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
}
.jcsb {
-ms-flex-pack: justify!important;
-webkit-box-pack: justify!important;
justify-content: space-between!important;
}
.aic {
-ms-flex-align: center!important;
-webkit-box-align: center!important;
align-items: center!important;
}
li {
list-style: none;
}
.pull-left {
float: left!important;
}
.rewards-wrap {
height: 100%;
}
.at-equity-wrap .rewards .calculate_container {
-webkit-box-shadow: rgba(0,0,0,.03) 0 5px 10px 0;
background: url(https://s.abcc.com/portal/static/img/home-bg-pc.c9207cd.png);
background-repeat: no-repeat;
background-size: 1440px 100%;
box-shadow: 0 5px 10px 0 rgba(0,0,0,.03);
margin: 0 auto;
max-width: 1200px;
overflow: hidden;
position: relative;
}
.rewards-pc-wrap .current-profit .point {
color: #fff;
font-size: 25px;
}
.rewards-pc-wrap .current-profit .integer {
color: #fff;
font-size: 45px;
}
.rewards-pc-wrap .current-profit .decimal {
color: #fff;
font-size: 25px;
}
.rewards-pc-wrap .current-profit .unit {
color: #fff;
font-size: 24px;
margin-right: 5px;
margin-top: 18px;
}
.rewards-pc-wrap .yesterday-profit .point {
color: #fff;
font-size: 25px;
}
.rewards-pc-wrap .yesterday-profit .integer {
color: #fff;
font-size: 45px;
}
.rewards-pc-wrap .yesterday-profit .decimal {
color: #fff;
font-size: 25px;
}
.rewards-pc-wrap .yesterday-profit .unit {
color: #fff;
font-size: 24px;
margin-right: 5px;
margin-top: 18px;
}
.rewards-pc-wrap .profit-rate-100 .point {
color: #fff;
font-size: 25px;
}
.rewards-pc-wrap .profit-rate-100 .integer {
color: #fff;
font-size: 45px;
}
.rewards-pc-wrap .profit-rate-100 .decimal {
color: #fff;
font-size: 25px;
}
.rewards-pc-wrap .profit-rate-100 .unit {
color: #fff;
font-size: 24px;
margin-right: 5px;
margin-top: 18px;
}
.rewards-pc-wrap .total-profit .point {
color: #fff;
font-size: 25px;
}
.rewards-pc-wrap .total-profit .integer {
color: #fff;
font-size: 45px;
}
.rewards-pc-wrap .total-profit .decimal {
color: #fff;
font-size: 25px;
}
.rewards-pc-wrap .total-profit .unit {
color: #fff;
font-size: 24px;
margin-right: 5px;
margin-top: 18px;
}
.rewards-pc-wrap {
height: 400px;
margin-left: 129px;
padding-top: 100px;
width: 630px;
}
.itm-rv {
-ms-flex: 1;
-webkit-box-flex: 1;
flex: 1;
font-family: "Arial";
}
.fb {
font-weight: 700;
}
.main-p {
color: hsla(0,0%,100%,.7);
font-size: 13px;
margin-bottom: 8px;
margin-top: 10px;
}
.sub-p {
color: hsla(0,0%,100%,.5);
font-size: 12px;
margin-top: 12px;
}
.fb-r {
font-weight: 300;
}
.price-btc {
color: hsla(0,0%,100%,.5);
font-size: 13px;
margin-top: 10px;
}
</style>
</head>
<body>
<div class="at-equity-wrap">
<div class="rewards" >
<div class="calculate_container">
<div class="rewards-wrap">
<div class="flex jcc aic">
<div class="rewards-pc-wrap slideInUp" id="nuBlock">
<div class="flex jcsb aic">
<div class="itm-rv" style="margin-right: 60px;">
<div class="current-profit th-num-bold fb"><span class="unit pull-left">$</span> <span class="integer" id="cr_prft_int" >0</span> <span class="point">.</span> <span class="decimal" id="cr_prft_dcml" >00</span></div>
<p class="main-p">Platform Rewards to Be Distributed Today</p>
<p class="sub-p fb-r">Total circulating KAT eligible for rewards:100,000,000</p>
</div>
<div class="itm-rv">
<div class="profit-rate-100 th-num-bold"><span class="unit pull-left">$</span> <span class="integer" id="dly_prft_int" >0</span> <span class="point">.</span><span class="decimal" id="dly_prft_dcml" >00</span></div>
<p class="main-p">Daily Rewards of 1000 KAT</p>
<div class="profit-rate sub-p fb-r"><span >Daily KAT Rewards Rate</span> <span class="integer">0</span> <span class="decimal">.00</span> <span class="unit">%</span></div>
</div>
</div>
<div class="flex jcsb aic" style="margin-top: 40px;">
<div class="itm-rv" style="margin-right: 60px;">
<div class="yesterday-profit th-num-bold fb'"><span class="unit pull-left">$</span> <span class="integer" id="ytd_prft_int" >0</span> <span class="point">.</span><span class="decimal" id="ytd_prft_dcml" >00</span></div>
<div class="price-btc fb-r">/ 0.00000000 BTC</div>
<p class="main-p fb-r">Platform Rewards Distributed Yesterday</p>
</div>
<div class="itm-rv">
<div class="total-profit th-num-bold fb'"><span class="unit pull-left">$</span> <span class="integer" id="ttl_prft_int" >0</span> <span class="point">.</span><span class="decimal" id="ttl_prft_dcml" >00</span></div>
<div class="price-btc fb-r">/ 0.00000000 BTC</div>
<p class="main-p fb-r">Cumulative Platform Rewards Distributed</p>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
</body>
<script type="text/javascript">
$(document).on('ready', function(){
setTimeout(function(){
cr_countUp();
dly_countUp();
ytd_countUp();
ttl_countUp();
}, 2000);
});
unit = "$";
var cr_data, dly_data, ytd_data, ttl_data;
cr_data = dly_data = ytd_data = ttl_data = ["670.0000682", "670.002", "660.000068", "660.002", "650.000000063", "650.01", "640.00000006", "640.01", "630.0000000602", "630.01", "620.0000000622", "620.01", "610.00000016", "610.002", "600.00000015998", "600.002", "590.00000094", "590.002", "580.0000009", "580.002", "760.0000682", "760.002", "660.000068", "660.002", "560.000000063", "560.01", "460.00000006", "460.01", "360.0000000602", "360.01", "260.0000000622", "260.01", "160.00000016", "160.002", "060.00000015998", "060.002", "950.00000094", "950.002", "850.0000009", "850.002"];
cr_start = 0;
cr_stop = cr_data.length - 1;
cr_nu = 20;
function cr_countUp(){
setTimeout(function(){
$("#cr_prft_int").text(cr_data[cr_start].split(".")[0]);
$("#cr_prft_dcml").text(cr_data[cr_start].split(".")[1]);
if(cr_start < cr_stop){
cr_start += 1;
cr_countUp();
}
}, cr_nu);
}
dly_start = 0;
dly_stop = dly_data.length - 1;
dly_nu = 20;
function dly_countUp(){
setTimeout(function(){
$("#dly_prft_int").text(dly_data[dly_start].split(".")[0]);
$("#dly_prft_dcml").text(dly_data[dly_start].split(".")[1]);
if(dly_start < dly_stop){
dly_start += 1;
dly_countUp();
}
}, dly_nu);
}
ytd_start = 0;
ytd_stop = ytd_data.length - 1;
ytd_nu = 20;
function ytd_countUp(){
setTimeout(function(){
$("#ytd_prft_int").text(ytd_data[ytd_start].split(".")[0]);
$("#ytd_prft_dcml").text(ytd_data[ytd_start].split(".")[1]);
if(ytd_start < ytd_stop){
ytd_start += 1;
ytd_countUp();
}
}, ytd_nu);
}
ttl_start = 0;
ttl_stop = ttl_data.length - 1;
ttl_nu = 20;
function ttl_countUp(){
setTimeout(function(){
$("#ttl_prft_int").text(ttl_data[ttl_start].split(".")[0]);
$("#ttl_prft_dcml").text(ttl_data[ttl_start].split(".")[1]);
if(ttl_start < ttl_stop){
ttl_start += 1;
ttl_countUp();
}
}, ttl_nu);
}
</script>
</html>
I think you can achieve it by using the below code
Model::get(['ColumnName'])->toArray();
Hi For jQuery You can only use like this
Use async and type="text/javascript" only
Given:
A_1 = [10 200 7 150]';
A_2 = [0.001 0.450 0.007 0.200]';
(As others have already pointed out) There are tools to simply compute correlation, most obviously corr
:
corr(A_1, A_2); %Returns 0.956766573975184 (Requires stats toolbox)
You can also use base Matlab's corrcoef
function, like this:
M = corrcoef([A_1 A_2]): %Returns [1 0.956766573975185; 0.956766573975185 1];
M(2,1); %Returns 0.956766573975184
Which is closely related to the cov
function:
cov([condition(A_1) condition(A_2)]);
As you almost get to in your original question, you can scale and adjust the vectors yourself if you want, which gives a slightly better understanding of what is going on. First create a condition function which subtracts the mean, and divides by the standard deviation:
condition = @(x) (x-mean(x))./std(x); %Function to subtract mean AND normalize standard deviation
Then the correlation appears to be (A_1 * A_2)/(A_1^2), like this:
(condition(A_1)' * condition(A_2)) / sum(condition(A_1).^2); %Returns 0.956766573975185
By symmetry, this should also work
(condition(A_1)' * condition(A_2)) / sum(condition(A_2).^2); %Returns 0.956766573975185
And it does.
I believe, but don't have the energy to confirm right now, that the same math can be used to compute correlation and cross correlation terms when dealing with multi-dimensiotnal inputs, so long as care is taken when handling the dimensions and orientations of the input arrays.
zsh has a builtin command emulate
which can emulate different shells by setting the appropriate options, although csh will never be fully emulated.
emulate bash
perform commands
emulate -R zsh
The -R flag restores all the options to their default values for that shell.
See: zsh manual
I've pushed django-pdb
to PyPI.
It's a simple app that means you don't need to edit your source code every time you want to break into pdb.
Installation is just...
pip install django-pdb
'django_pdb'
to your INSTALLED_APPS
You can now run: manage.py runserver --pdb
to break into pdb at the start of every view...
bash: manage.py runserver --pdb
Validating models...
0 errors found
Django version 1.3, using settings 'testproject.settings'
Development server is running at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
GET /
function "myview" in testapp/views.py:6
args: ()
kwargs: {}
> /Users/tom/github/django-pdb/testproject/testapp/views.py(7)myview()
-> a = 1
(Pdb)
And run: manage.py test --pdb
to break into pdb on test failures/errors...
bash: manage.py test testapp --pdb
Creating test database for alias 'default'...
E
======================================================================
>>> test_error (testapp.tests.SimpleTest)
----------------------------------------------------------------------
Traceback (most recent call last):
File ".../django-pdb/testproject/testapp/tests.py", line 16, in test_error
one_plus_one = four
NameError: global name 'four' is not defined
======================================================================
> /Users/tom/github/django-pdb/testproject/testapp/tests.py(16)test_error()
-> one_plus_one = four
(Pdb)
The project's hosted on GitHub, contributions are welcome of course.
Building on Cheyenne Forbes' answer, and one I found here via fcalderan: Just disable scroll not hide it? and to fix Hallodom's issue of the scrollbar disappearing
CSS:
.preventscroll{
position: fixed;
overflow-y:scroll;
}
JS:
whatever.onclick = function(){
$('body').addClass('preventscroll');
}
whatevertoclose.onclick = function(){
$('body').removeClass('preventscroll');
}
This code does jump you to the top of the page, but I think that fcalderan's code has a workaround.
If you use Sqlite's REGEXP support ( see the answer at Problem with regexp python and sqlite for how to do that ) , then you can do it easily in one clause:
SELECT word FROM table WHERE word NOT REGEXP '[abc]';
You could add a calculated column that includes only the date without the time. Between the two options, I'd go with the BETWEEN
operator because it's 'cleaner' to me and should make better use of indexes. Comparing execution plans would seem to indicate that BETWEEN
would be faster; however, in actual testing they performed the same.
Queue
is an interface that extends Collection
in Java. It has all the functions needed to support FIFO
architecture.
For concrete implementation you may use LinkedList
. LinkedList implements Deque
which in turn implements Queue
. All of these are a part of java.util
package.
For details about method with sample example you can refer FIFO based Queue implementation in Java.
PS: Above link goes to my personal blog that has additional details on this.
For what it's worth, here is my way:
List<string> list = new List<string>(new string[] { "cat", "Dog", "parrot", "dog", "parrot", "goat", "parrot", "horse", "goat" });
Dictionary<string, int> wordCount = new Dictionary<string, int>();
//count them all:
list.ForEach(word =>
{
string key = word.ToLower();
if (!wordCount.ContainsKey(key))
wordCount.Add(key, 0);
wordCount[key]++;
});
//remove words appearing only once:
wordCount.Keys.ToList().FindAll(word => wordCount[word] == 1).ForEach(key => wordCount.Remove(key));
Console.WriteLine(string.Format("Found {0} duplicates in the list:", wordCount.Count));
wordCount.Keys.ToList().ForEach(key => Console.WriteLine(string.Format("{0} appears {1} times", key, wordCount[key])));
You dont need this line: setContentView(txtCambiado);
This is the solution for me
File currentDir = new File("");
New, Edited Answer:
Add this in viewDidLayoutSubviews
SWIFT
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let indexPath = IndexPath(item: 12, section: 0)
self.collectionView.scrollToItem(at: indexPath, at: [.centeredVertically, .centeredHorizontally], animated: true)
}
Normally, .centerVertically
is the case
ObjC
-(void)viewDidLayoutSubviews {
[super viewDidLayoutSubviews];
NSIndexPath *indexPath = [NSIndexPath indexPathForItem:12 inSection:0];
[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically | UICollectionViewScrollPositionCenteredHorizontally animated:NO];
}
Old answer working for older iOS
Add this in viewWillAppear
:
[self.view layoutIfNeeded];
[self.collectionView scrollToItemAtIndexPath:indexPath atScrollPosition:UICollectionViewScrollPositionCenteredVertically animated:NO];
Try writing it in a new file..
f = open(filename, 'r+')
f2= open(filename2,'a+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.close()
f2.write(text)
fw.close()
After Pulling hair for a long time,I finally found an issue.I've selected wrong certificate while creating Provisioning Profile,By selecting right one,It helped for me.In your case,If it is multiple then You have to try and select one by one to get this issue solved.
Or just use a regular for loop instead of foreach. A for loop is slightly faster (though you won't notice the difference except in very time critical code).
Try using a ConcurrentHashMap
instead of a plain HashMap
As pointed out by in the comments, this answers is outdated. youcompleteme
now supports python3 and jedi-vim
no longer breaks the undo history.
Original answer below.
AFAIK there are three options, each with its disadvantages:
Python 3 and undo history (gundo!) are a must for me, so options 1 and 2 are out.
If it is a 2 byte string you can do something like in this concrete example where I switch on ISO639-2 language codes.
LANIDX_TYPE LanCodeToIdx(const char* Lan)
{
if(Lan)
switch(Lan[0]) {
case 'A': switch(Lan[1]) {
case 'N': return LANIDX_AN;
case 'R': return LANIDX_AR;
}
break;
case 'B': switch(Lan[1]) {
case 'E': return LANIDX_BE;
case 'G': return LANIDX_BG;
case 'N': return LANIDX_BN;
case 'R': return LANIDX_BR;
case 'S': return LANIDX_BS;
}
break;
case 'C': switch(Lan[1]) {
case 'A': return LANIDX_CA;
case 'C': return LANIDX_CO;
case 'S': return LANIDX_CS;
case 'Y': return LANIDX_CY;
}
break;
case 'D': switch(Lan[1]) {
case 'A': return LANIDX_DA;
case 'E': return LANIDX_DE;
}
break;
case 'E': switch(Lan[1]) {
case 'L': return LANIDX_EL;
case 'N': return LANIDX_EN;
case 'O': return LANIDX_EO;
case 'S': return LANIDX_ES;
case 'T': return LANIDX_ET;
case 'U': return LANIDX_EU;
}
break;
case 'F': switch(Lan[1]) {
case 'A': return LANIDX_FA;
case 'I': return LANIDX_FI;
case 'O': return LANIDX_FO;
case 'R': return LANIDX_FR;
case 'Y': return LANIDX_FY;
}
break;
case 'G': switch(Lan[1]) {
case 'A': return LANIDX_GA;
case 'D': return LANIDX_GD;
case 'L': return LANIDX_GL;
case 'V': return LANIDX_GV;
}
break;
case 'H': switch(Lan[1]) {
case 'E': return LANIDX_HE;
case 'I': return LANIDX_HI;
case 'R': return LANIDX_HR;
case 'U': return LANIDX_HU;
}
break;
case 'I': switch(Lan[1]) {
case 'S': return LANIDX_IS;
case 'T': return LANIDX_IT;
}
break;
case 'J': switch(Lan[1]) {
case 'A': return LANIDX_JA;
}
break;
case 'K': switch(Lan[1]) {
case 'O': return LANIDX_KO;
}
break;
case 'L': switch(Lan[1]) {
case 'A': return LANIDX_LA;
case 'B': return LANIDX_LB;
case 'I': return LANIDX_LI;
case 'T': return LANIDX_LT;
case 'V': return LANIDX_LV;
}
break;
case 'M': switch(Lan[1]) {
case 'K': return LANIDX_MK;
case 'T': return LANIDX_MT;
}
break;
case 'N': switch(Lan[1]) {
case 'L': return LANIDX_NL;
case 'O': return LANIDX_NO;
}
break;
case 'O': switch(Lan[1]) {
case 'C': return LANIDX_OC;
}
break;
case 'P': switch(Lan[1]) {
case 'L': return LANIDX_PL;
case 'T': return LANIDX_PT;
}
break;
case 'R': switch(Lan[1]) {
case 'M': return LANIDX_RM;
case 'O': return LANIDX_RO;
case 'U': return LANIDX_RU;
}
break;
case 'S': switch(Lan[1]) {
case 'C': return LANIDX_SC;
case 'K': return LANIDX_SK;
case 'L': return LANIDX_SL;
case 'Q': return LANIDX_SQ;
case 'R': return LANIDX_SR;
case 'V': return LANIDX_SV;
case 'W': return LANIDX_SW;
}
break;
case 'T': switch(Lan[1]) {
case 'R': return LANIDX_TR;
}
break;
case 'U': switch(Lan[1]) {
case 'K': return LANIDX_UK;
case 'N': return LANIDX_UN;
}
break;
case 'W': switch(Lan[1]) {
case 'A': return LANIDX_WA;
}
break;
case 'Z': switch(Lan[1]) {
case 'H': return LANIDX_ZH;
}
break;
}
return LANIDX_UNDEFINED;
}
LANIDX_* being constant integers used to index in arrays.
Windows - set environment variable permanently:
setx ANDROID_HOME "C:\Program Files\Android\android-sdk"
or
setx ANDROID_HOME "C:\Program Files (x86)\Android\android-sdk"
Haven't seen a solution with margin
in any of these answers yet, so here is my solution to this problem.
This solution only works if you know the width of your image.
<div>
<img src="https://placehold.it/80x80">
<span>This is my very long text what should align. This is my very long text what should align.</span>
</div>
div {
overflow:hidden;
}
img {
width:80px
margin-right:20px;
display:inline-block;
vertical-align:middle;
}
span {
width:100%;
margin-right:-100px;
padding-right:100px;
display:inline-block;
vertical-align:middle;
box-sizing:border-box;
-moz-box-sizing:border-box;
-webkit-box-sizing:border-box;
}
What you want is charAt
.
var x = 'some string';
alert(x.charAt(0)); // alerts 's'
If you are using some trackers like google analytics
or amplitude
and you are trying to release your app in another platforms other than Google Play
, this errors appears for users. So there are two possible solutions:
Google Play
The following command will create a copy in a new window. So you can continue see both original file and the new file.
:w {newfilename} | sp #
DateTime
doesn't have a default key as an input. The default key should be an input to the Column
function. Try this:
import datetime
from sqlalchemy import Column, Integer, DateTime
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
class Test(Base):
__tablename__ = 'test'
id = Column(Integer, primary_key=True)
created_date = Column(DateTime, default=datetime.datetime.utcnow)
The advice you were given is flawed. Unconditionally setting GIT_AUTHOR_DATE in an --env-filter
would rewrite the date of every commit. Also, it would be unusual to use git commit inside --index-filter
.
You are dealing with multiple, independent problems here.
Each commit has two dates: the author date and the committer date. You can override each by supplying values through the environment variables GIT_AUTHOR_DATE and GIT_COMMITTER_DATE for any command that writes a new commit. See “Date Formats” in git-commit(1) or the below:
Git internal format = <unix timestamp> <time zone offset>, e.g. 1112926393 +0200
RFC 2822 = e.g. Thu, 07 Apr 2005 22:13:13 +0200
ISO 8601 = e.g. 2005-04-07T22:13:13
The only command that writes a new commit during normal use is git commit. It also has a --date
option that lets you directly specify the author date. Your anticipated usage includes git filter-branch --env-filter
also uses the environment variables mentioned above (these are part of the “env” after which the option is named; see “Options” in git-filter-branch(1) and the underlying “plumbing” command git-commit-tree(1).
If your repository is very simple (i.e. you only have a single branch, no tags), then you can probably use git rebase to do the work.
In the following commands, use the object name (SHA-1 hash) of the commit instead of “A”. Do not forget to use one of the “date override” methods when you run git commit.
---A---B---C---o---o---o master
git checkout master
git checkout A~0
git add path/to/file
git commit --date='whenever'
git tag ,new-commit -m'delete me later'
git checkout -
git rebase --onto ,new-commit A
git tag -d ,new-commit
---A---N (was ",new-commit", but we delete the tag)
\
B'---C'---o---o---o master
If you wanted to update A to include the new file (instead of creating a new commit where it was added), then use git commit --amend
instead of git commit
. The result would look like this:
---A'---B'---C'---o---o---o master
The above works as long as you can name the commit that should be the parent of your new commit. If you actually want your new file to be added via a new root commit (no parents), then you need something a bit different:
B---C---o---o---o master
git checkout master
git checkout --orphan new-root
git rm -rf .
git add path/to/file
GIT_AUTHOR_DATE='whenever' git commit
git checkout -
git rebase --root --onto new-root
git branch -d new-root
N (was new-root, but we deleted it)
\
B'---C'---o---o---o master
git checkout --orphan
is relatively new (Git 1.7.2), but there are other ways of doing the same thing that work on older versions of Git.
If your repository is more complex (i.e. it has more than one ref (branches, tags, etc.)), then you will probably need to use git filter-branch. Before using git filter-branch, you should make a backup copy of your entire repository. A simple tar archive of your entire working tree (including the .git directory) is sufficient. git filter-branch does make backup refs, but it is often easier to recover from a not-quite-right filtering by just deleting your .git
directory and restoring it from your backup.
Note: The examples below use the lower-level command git update-index --add
instead of git add
. You could use git add, but you would first need to copy the file from some external location to the expected path (--index-filter
runs its command in a temporary GIT_WORK_TREE that is empty).
If you want your new file to be added to every existing commit, then you can do this:
new_file=$(git hash-object -w path/to/file)
git filter-branch \
--index-filter \
'git update-index --add --cacheinfo 100644 '"$new_file"' path/to/file' \
--tag-name-filter cat \
-- --all
git reset --hard
I do not really see any reason to change the dates of the existing commits with --env-filter 'GIT_AUTHOR_DATE=…'
. If you did use it, you would have make it conditional so that it would rewrite the date for every commit.
If you want your new file to appear only in the commits after some existing commit (“A”), then you can do this:
file_path=path/to/file
before_commit=$(git rev-parse --verify A)
file_blob=$(git hash-object -w "$file_path")
git filter-branch \
--index-filter '
if x=$(git rev-list -1 "$GIT_COMMIT" --not '"$before_commit"') &&
test -n "$x"; then
git update-index --add --cacheinfo 100644 '"$file_blob $file_path"'
fi
' \
--tag-name-filter cat \
-- --all
git reset --hard
If you want the file to be added via a new commit that is to be inserted into the middle of your history, then you will need to generate the new commit prior to using git filter-branch and add --parent-filter
to git filter-branch:
file_path=path/to/file
before_commit=$(git rev-parse --verify A)
git checkout master
git checkout "$before_commit"
git add "$file_path"
git commit --date='whenever'
new_commit=$(git rev-parse --verify HEAD)
file_blob=$(git rev-parse --verify HEAD:"$file_path")
git checkout -
git filter-branch \
--parent-filter "sed -e s/$before_commit/$new_commit/g" \
--index-filter '
if x=$(git rev-list -1 "$GIT_COMMIT" --not '"$new_commit"') &&
test -n "$x"; then
git update-index --add --cacheinfo 100644 '"$file_blob $file_path"'
fi
' \
--tag-name-filter cat \
-- --all
git reset --hard
You could also arrange for the file to be first added in a new root commit: create your new root commit via the “orphan” method from the git rebase section (capture it in new_commit
), use the unconditional --index-filter
, and a --parent-filter
like "sed -e \"s/^$/-p $new_commit/\""
.
select
ROW_NUMBER() Over (Order by CustomerID) As [S.N.],
CustomerID ,
CustomerName,
Address,
City,
State,
ZipCode
from Customers;
Do you mean elif
?
Have you tried using ASP.NET MVC TempData ?
ASP.NET MVC TempData dictionary is used to share data between controller actions. The value of TempData persists until it is read or until the current user’s session times out. Persisting data in TempData is useful in scenarios such as redirection, when values are needed beyond a single request.
The code would be something like this:
[HttpPost]
public ActionResult ApplicationPoolsUpdate(ServiceViewModel viewModel)
{
XDocument updatedResultsDocument = myService.UpdateApplicationPools();
TempData["doc"] = updatedResultsDocument;
return RedirectToAction("UpdateConfirmation");
}
And in the ApplicationPoolController:
public ActionResult UpdateConfirmation()
{
if (TempData["doc"] != null)
{
XDocument updatedResultsDocument = (XDocument) TempData["doc"];
...
return View();
}
}
As Joshua Bloch notes in Effective Java:
You can use an Enum if all your constants are related (like planet names), put the constant values in classes they are related to (if you have access to them), or use a non instanciable utility class (define a private default constructor).
class SomeConstants
{
// Prevents instanciation of myself and my subclasses
private SomeConstants() {}
public final static String TOTO = "toto";
public final static Integer TEN = 10;
//...
}
Then, as already stated, you can use static imports to use your constants.
Thank you #DangerDave this solved my problem on Magento 2, and this is how I did
I am on a vps
root@myvps [~]# cd /var/lib/mysql/mydatabasename/
root@myvps [~]# ls
check for tables with no .frm fie (only .idb) and delete them,
rm customer_grid_flat.ibd
System will regenerate tables after running index:reindex command
Here's JMarsh's Visual Studio macro modified to generate a constructor based on the fields and properties in the class.
Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE100
Imports System.Diagnostics
Imports System.Collections.Generic
Public Module ConstructorEditor
Public Sub AddConstructorFromFields()
Dim classInfo As CodeClass2 = GetClassElement()
If classInfo Is Nothing Then
System.Windows.Forms.MessageBox.Show("No class was found surrounding the cursor. Make sure that this file compiles and try again.", "Error")
Return
End If
' Setting up undo context. One Ctrl+Z undoes everything
Dim closeUndoContext As Boolean = False
If DTE.UndoContext.IsOpen = False Then
closeUndoContext = True
DTE.UndoContext.Open("AddConstructorFromFields", False)
End If
Try
Dim dataMembers As List(Of DataMember) = GetDataMembers(classInfo)
AddConstructor(classInfo, dataMembers)
Finally
If closeUndoContext Then
DTE.UndoContext.Close()
End If
End Try
End Sub
Private Function GetClassElement() As CodeClass2
' Returns a CodeClass2 element representing the class that the cursor is within, or null if there is no class
Try
Dim selection As TextSelection = DTE.ActiveDocument.Selection
Dim fileCodeModel As FileCodeModel2 = DTE.ActiveDocument.ProjectItem.FileCodeModel
Dim element As CodeElement2 = fileCodeModel.CodeElementFromPoint(selection.TopPoint, vsCMElement.vsCMElementClass)
Return element
Catch
Return Nothing
End Try
End Function
Private Function GetDataMembers(ByVal classInfo As CodeClass2) As System.Collections.Generic.List(Of DataMember)
Dim dataMembers As List(Of DataMember) = New List(Of DataMember)
Dim prop As CodeProperty2
Dim v As CodeVariable2
For Each member As CodeElement2 In classInfo.Members
prop = TryCast(member, CodeProperty2)
If Not prop Is Nothing Then
dataMembers.Add(DataMember.FromProperty(prop.Name, prop.Type))
End If
v = TryCast(member, CodeVariable2)
If Not v Is Nothing Then
If v.Name.StartsWith("_") And Not v.IsConstant Then
dataMembers.Add(DataMember.FromPrivateVariable(v.Name, v.Type))
End If
End If
Next
Return dataMembers
End Function
Private Sub AddConstructor(ByVal classInfo As CodeClass2, ByVal dataMembers As List(Of DataMember))
' Put constructor after the data members
Dim position As Object = dataMembers.Count
' Add new constructor
Dim ctor As CodeFunction2 = classInfo.AddFunction(classInfo.Name, vsCMFunction.vsCMFunctionConstructor, vsCMTypeRef.vsCMTypeRefVoid, position, vsCMAccess.vsCMAccessPublic)
For Each dataMember As DataMember In dataMembers
ctor.AddParameter(dataMember.NameLocal, dataMember.Type, -1)
Next
' Assignments
Dim startPoint As TextPoint = ctor.GetStartPoint(vsCMPart.vsCMPartBody)
Dim point As EditPoint = startPoint.CreateEditPoint()
For Each dataMember As DataMember In dataMembers
point.Insert(" " + dataMember.Name + " = " + dataMember.NameLocal + ";" + Environment.NewLine)
Next
End Sub
Class DataMember
Public Name As String
Public NameLocal As String
Public Type As Object
Private Sub New(ByVal name As String, ByVal nameLocal As String, ByVal type As Object)
Me.Name = name
Me.NameLocal = nameLocal
Me.Type = type
End Sub
Shared Function FromProperty(ByVal name As String, ByVal type As Object)
Dim nameLocal As String
If Len(name) > 1 Then
nameLocal = name.Substring(0, 1).ToLower + name.Substring(1)
Else
nameLocal = name.ToLower()
End If
Return New DataMember(name, nameLocal, type)
End Function
Shared Function FromPrivateVariable(ByVal name As String, ByVal type As Object)
If Not name.StartsWith("_") Then
Throw New ArgumentException("Expected private variable name to start with underscore.")
End If
Dim nameLocal As String = name.Substring(1)
Return New DataMember(name, nameLocal, type)
End Function
End Class
End Module
The naive solution, of course, is to write a function for each enumeration that performs the conversion to string:
enum OS_type { Linux, Apple, Windows };
inline const char* ToString(OS_type v)
{
switch (v)
{
case Linux: return "Linux";
case Apple: return "Apple";
case Windows: return "Windows";
default: return "[Unknown OS_type]";
}
}
This, however, is a maintenance disaster. With the help of the Boost.Preprocessor library, which can be used with both C and C++ code, you can easily take advantage of the preprocessor and let it generate this function for you. The generation macro is as follows:
#include <boost/preprocessor.hpp>
#define X_DEFINE_ENUM_WITH_STRING_CONVERSIONS_TOSTRING_CASE(r, data, elem) \
case elem : return BOOST_PP_STRINGIZE(elem);
#define DEFINE_ENUM_WITH_STRING_CONVERSIONS(name, enumerators) \
enum name { \
BOOST_PP_SEQ_ENUM(enumerators) \
}; \
\
inline const char* ToString(name v) \
{ \
switch (v) \
{ \
BOOST_PP_SEQ_FOR_EACH( \
X_DEFINE_ENUM_WITH_STRING_CONVERSIONS_TOSTRING_CASE, \
name, \
enumerators \
) \
default: return "[Unknown " BOOST_PP_STRINGIZE(name) "]"; \
} \
}
The first macro (beginning with X_
) is used internally by the second. The second macro first generates the enumeration, then generates a ToString
function that takes an object of that type and returns the enumerator name as a string (this implementation, for obvious reasons, requires that the enumerators map to unique values).
In C++ you could implement the ToString
function as an operator<<
overload instead, but I think it's a bit cleaner to require an explicit "ToString
" to convert the value to string form.
As a usage example, your OS_type
enumeration would be defined as follows:
DEFINE_ENUM_WITH_STRING_CONVERSIONS(OS_type, (Linux)(Apple)(Windows))
While the macro looks at first like it is a lot of work, and the definition of OS_type
looks rather foreign, remember that you have to write the macro once, then you can use it for every enumeration. You can add additional functionality to it (e.g., a string-form to enum conversion) without too much trouble, and it completely solves the maintenance problem, since you only have to provide the names once, when you invoke the macro.
The enumeration can then be used as if it were defined normally:
#include <iostream>
int main()
{
OS_type t = Windows;
std::cout << ToString(t) << " " << ToString(Apple) << std::endl;
}
The code snippets in this post, beginning with the #include <boost/preprocessor.hpp>
line, can be compiled as posted to demonstrate the solution.
This particular solution is for C++ as it uses C++-specific syntax (e.g., no typedef enum
) and function overloading, but it would be straightforward to make this work with C as well.
If you have reason to avoid the use of the datetime
module, then these functions will work.
def is_leap_year(year):
""" if year is a leap year return True
else return False """
if year % 100 == 0:
return year % 400 == 0
return year % 4 == 0
def doy(Y,M,D):
""" given year, month, day return day of year
Astronomical Algorithms, Jean Meeus, 2d ed, 1998, chap 7 """
if is_leap_year(Y):
K = 1
else:
K = 2
N = int((275 * M) / 9.0) - K * int((M + 9) / 12.0) + D - 30
return N
def ymd(Y,N):
""" given year = Y and day of year = N, return year, month, day
Astronomical Algorithms, Jean Meeus, 2d ed, 1998, chap 7 """
if is_leap_year(Y):
K = 1
else:
K = 2
M = int((9 * (K + N)) / 275.0 + 0.98)
if N < 32:
M = 1
D = N - int((275 * M) / 9.0) + K * int((M + 9) / 12.0) + 30
return Y, M, D
It's been a while, but last time I had something similar:
ROLLBACK TRAN
or trying to
COMMIT
what had allready been done free'd everything up so I was able to clear things out and start again.
Alternatively, when you want to save individual R objects, I recommend using saveRDS
.
You can save R objects using saveRDS
, then load them into R with a new variable name using readRDS
.
Example:
# Save the city object
saveRDS(city, "city.rds")
# ...
# Load the city object as city
city <- readRDS("city.rds")
# Or with a different name
city2 <- readRDS("city.rds")
But when you want to save many/all your objects in your workspace, use Manetheran's answer.
You need to set line-height.
<div style="border: 1px solid red;">
<span style="font-size: 38px; vertical-align:middle; float:left; line-height: 38px">Hejsan</span>
<span style="font-size: 13px; vertical-align:middle; float:right; line-height: 38px">svejsan</span>
<div style="clear: both;"></div>
class StudentAdapter extends BaseAdapter {
ArrayList<LichHocDTO> studentList;
private void capNhatDuLieu(ArrayList<LichHocDTO> list){
this.studentList.clear();
this.studentList.addAll(list);
this.notifyDataSetChanged();
}
}
You can try. It work for me
User this function:-
function dateRange($first, $last, $step = '+1 day', $format = 'Y-m-d' ) {
$dates = array();
$current = strtotime($first);
$last = strtotime($last);
while( $current <= $last ) {
$dates[] = date($format, $current);
$current = strtotime($step, $current);
}
return $dates;
}
Usage / function call:-
Increase by one day:-
dateRange($start, $end); //increment is set to 1 day.
Increase by Month:-
dateRange($start, $end, "+1 month");//increase by one month
use third parameter if you like to set date format:-
dateRange($start, $end, "+1 month", "Y-m-d H:i:s");//increase by one month and format is mysql datetime
x^y
is not "x
to the power of y
". It's "x
XOR y
".
During development / testing of new releases, the cache can be a problem because the browser, the server and even sometimes the 3G telco (if you do mobile deployment) will cache the static content (e.g. JS, CSS, HTML, img). You can overcome this by appending version number, random number or timestamp to the URL e.g: JSP: <script src="js/excel.js?time=<%=new java.util.Date()%>"></script>
In case you're running pure HTML (instead of server pages JSP, ASP, PHP) the server won't help you. In browser, links are loaded before the JS runs, therefore you have to remove the links and load them with JS.
// front end cache bust
var cacheBust = ['js/StrUtil.js', 'js/protos.common.js', 'js/conf.js', 'bootstrap_ECP/js/init.js'];
for (i=0; i < cacheBust.length; i++){
var el = document.createElement('script');
el.src = cacheBust[i]+"?v=" + Math.random();
document.getElementsByTagName('head')[0].appendChild(el);
}