1) "container" is a class and not an ID 2) .container - set z-index and display: none in your CSS and not inline unless there is a really good reason to do so. Demo@fiddle
$("#button").click(function() {
$(".container").css("opacity", 0.2);
$("#loading-img").css({"display": "block"});
});
CSS:
#loading-img {
background: url(http://web.bogdanteodoru.com/wp-content/uploads/2012/01/bouncy-css3-loading-animation.jpg) center center no-repeat; /* different for testing purposes */
display: none;
height: 100px; /* for testing purposes */
z-index: 12;
}
And a demo with animated image.
I got the error because of a clumsy typo:
This errors:
knitr::opts_chunk$seet(echo = FALSE)
Error: attempt to apply non-function
After correcting the typo, it works:
knitr::opts_chunk$set(echo = FALSE)
This is what i do and it's in my opinion simplest way to do this. define an object manager for your new customized model then define your model.
from django.db import models
from django.contrib.auth.models import PermissionsMixin, AbstractBaseUser, BaseUserManager
class User_manager(BaseUserManager):
def create_user(self, username, email, gender, nickname, password):
email = self.normalize_email(email)
user = self.model(username=username, email=email, gender=gender, nickname=nickname)
user.set_password(password)
user.save(using=self.db)
return user
def create_superuser(self, username, email, gender, password, nickname=None):
user = self.create_user(username=username, email=email, gender=gender, nickname=nickname, password=password)
user.is_superuser = True
user.is_staff = True
user.save()
return user
class User(PermissionsMixin, AbstractBaseUser):
username = models.CharField(max_length=32, unique=True, )
email = models.EmailField(max_length=32)
gender_choices = [("M", "Male"), ("F", "Female"), ("O", "Others")]
gender = models.CharField(choices=gender_choices, default="M", max_length=1)
nickname = models.CharField(max_length=32, blank=True, null=True)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)
REQUIRED_FIELDS = ["email", "gender"]
USERNAME_FIELD = "username"
objects = User_manager()
def __str__(self):
return self.username
Dont forget to add this line of code in your settings.py
:
AUTH_USER_MODEL = 'YourApp.User'
This is what i do and it always works.
:w
- Write a file.
!sudo
- Call shell sudo command.
tee
- The output of write (vim :w) command redirected using tee. The % is nothing but current file name i.e. /etc/apache2/conf.d/mediawiki.conf. In other words tee command is run as root and it takes standard input and write it to a file represented by %. However, this will prompt to reload file again (hit L to load changes in vim itself):
You can't change the color of the line (you can't specify different foreground colors for the same element, and the text and its decoration form a single element). However there are some tricks:
a:link, a:visited {text-decoration: none; color: red; border-bottom: 1px solid #006699; }
a:hover, a:active {text-decoration: none; color: red; border-bottom: 1px solid #1177FF; }
Also you can make some cool effects this way:
a:link {text-decoration: none; color: red; border-bottom: 1px dashed #006699; }
Hope it helps.
In concept of immutable data, maybe this is a better way:
class TempClass {
val list: List<Int> by lazy {
listOf<Int>()
}
fun doSomething() {
list += 10
list -= 10
}
}
I don't think min/max validations attribute exist. I would use something like
[Range(1, Int32.MaxValue)]
for minimum value 1 and
[Range(Int32.MinValue, 10)]
for maximum value 10
If you want 08:30 ( HH:MM) format then try this,
SELECT EmplID
, EmplName
, InTime
, [TimeOut]
, [DateVisited]
, RIGHT('0' + CONVERT(varchar(3),DATEDIFF(minute,InTime, TimeOut)/60),2) + ':' +
RIGHT('0' + CONVERT(varchar(2),DATEDIFF(minute,InTime,TimeOut)%60),2)
as TotalHours from times Order By EmplID, DateVisited
This needs to be done on the server-side, where the cookie was issued.
@wdavo is correct. The same is also true for functions.
If you override a base function, like Update, then in your subclass you need:
new void Update()
{
//do stufff
}
Without the new at the start of the function decleration you will get the warning flag.
Recently, I have seen this problem too. Below, you have my solution:
Or it can be a genuine network issue. Restart your network-manager using sudo service network-manager restart
or fix it up
I have just received this error after switching from HTTPS to SSH (for my origin remote). To fix, I simply ran the following command (for each repo):
ssh -T [email protected]
Upon receiving a successful response, I could fetch/push to the repo with ssh.
I took that command from Git's Testing your SSH connection guide, which is part of the greater Connecting to GitHub with with SSH guide.
I'm on 4.4.2, and calling overridePendingTransition(0, 0) in the launching activity's onCreate() will disable the starting animation (calling overridePendingTransition(0, 0) immediately after startActivity() did NOT work). As noted in another answer, calling overridePendingTransition(0, 0) after finish() disables the closing animation.
Btw, I found that setting the style with "android:windowAnimationStyle">@null (another answer mentioned here) caused a crash when my launching activity tried to set the action bar title. Debugging further, I discovered that somehow this causes window.hasFeature(Window.FEATURE_ACTION_BAR) to fail in the Activity's initActionBar().
Google's new Maven repo is required for the latest support library that is compatible with Android 8.0. Just update your Google's Maven repository like below:
To add them to your build, add maven.google.com
to the Maven repositories in your module-level build.gradle
file:
repositories {
maven {
url 'https://maven.google.com'
// Alternative URL is 'https://dl.google.com/dl/android/maven2/'
}
}
Alternative you can update build.gradle
file like this:
repositories {
jcenter()
google()
}
Then add the desired library to your dependencies block. For example, the cardview library looks like this:
dependencies {
compile 'com.android.support:cardview-v7:26.1.0'
}
<?php if($condition) : ?>
<a href="http://yahoo.com">This will only display if $condition is true</a>
<?php endif; ?>
By request, here's elseif and else (which you can also find in the docs)
<?php if($condition) : ?>
<a href="http://yahoo.com">This will only display if $condition is true</a>
<?php elseif($anotherCondition) : ?>
more html
<?php else : ?>
even more html
<?php endif; ?>
It's that simple.
The HTML will only be displayed if the condition is satisfied.
do not forget to insert (or unCommanet) this line at the beginning of your pod file:
platform :iOS, '9.0'
that saves my day
I mostly agree with the accepted answer, but there is a C++11 option that has not been covered in existing answers:
Example:
struct sandwich {
// Factory methods.
static sandwich ham();
static sandwich spam();
// Move constructor.
sandwich(sandwich &&);
// etc.
};
Then you can construct objects on the stack:
sandwich mine{sandwich::ham()};
As subobjects of other things:
auto lunch = std::make_pair(sandwich::spam(), apple{});
Or dynamically allocated:
auto ptr = std::make_shared<sandwich>(sandwich::ham());
When might I use this?
If, on a public constructor, it is not possible to give meaningful initialisers for all class members without some preliminary calculation, then I might convert that constructor to a static method. The static method performs the preliminary calculations, then returns a value result via a private constructor which just does a member-wise initialisation.
I say 'might' because it depends on which approach gives the clearest code without being unnecessarily inefficient.
Sharding is horizontal(row wise) database partitioning as opposed to vertical(column wise) partitioning which is Normalization. It separates very large databases into smaller, faster and more easily managed parts called data shards. It is a mechanism to achieve distributed systems.
Why do we need distributed systems?
You can read more here: Advantages of Distributed database
How sharding help achieve distributed system?
You can partition a search index into N partitions and load each index on a separate server. If you query one server, you will get 1/Nth of the results. So to get complete result set, a typical distributed search system use an aggregator that will accumulate results from each server and combine them. An aggregator also distribute query onto each server. This aggregator program is called MapReduce in big data terminology. In other words, Distributed Systems = Sharding + MapReduce (Although there are other things too).
I ran into this problem with my new Nexus 4 and an APK built with Adobe AIR. I already had android:installLocation="preferExternal" in my manifest. I noticed I was also calling adb install
with the -s
option (Install package on the shared mass storage such as sdcard.) which seemed like overkill.
Removing the -s
flag from adb install
fixed the issue for me.
Probably you didn't provide an argument on the command line. In that case, sys.argv
only contains one value, but it would have to have two in order to provide values for both user_name
and script
.
line2 = "hello 12 hi 89"
temp1 = re.findall(r'\d+', line2) # through regular expression
res2 = list(map(int, temp1))
print(res2)
Hi ,
you can search all the integers in the string through digit by using findall expression .
In the second step create a list res2 and add the digits found in string to this list
hope this helps
Regards, Diwakar Sharma
If you look at the code for the component you can see that it uses the className
prop passed to it to combine with the row
class to get the resulting set of classes (<Row className="aaa bbb"...
works).Also, if you provide the id
prop like <Row id="444" ...
it will actually set the id attribute for the element.
class Element
{
public string Company;
public string TypeOfInvestment;
public decimal Worth;
}
class Program
{
static void Main(string[] args)
{
List<Element> elements = new List<Element>()
{
new Element { Company = "JPMORGAN CHASE",TypeOfInvestment = "Stocks", Worth = 96983 },
new Element { Company = "AMER TOWER CORP",TypeOfInvestment = "Securities", Worth = 17141 },
new Element { Company = "ORACLE CORP",TypeOfInvestment = "Assets", Worth = 59372 },
new Element { Company = "PEPSICO INC",TypeOfInvestment = "Assets", Worth = 26516 },
new Element { Company = "PROCTER & GAMBL",TypeOfInvestment = "Stocks", Worth = 387050 },
new Element { Company = "QUASLCOMM INC",TypeOfInvestment = "Bonds", Worth = 196811 },
new Element { Company = "UTD TECHS CORP",TypeOfInvestment = "Bonds", Worth = 257429 },
new Element { Company = "WELLS FARGO-NEW",TypeOfInvestment = "Bank Account", Worth = 106600 },
new Element { Company = "FEDEX CORP",TypeOfInvestment = "Stocks", Worth = 103955 },
new Element { Company = "CVS CAREMARK CP",TypeOfInvestment = "Securities", Worth = 171048 },
};
//Group by on multiple column in LINQ (Query Method)
var query = from e in elements
group e by new{e.TypeOfInvestment,e.Company} into eg
select new {eg.Key.TypeOfInvestment, eg.Key.Company, Points = eg.Sum(rl => rl.Worth)};
foreach (var item in query)
{
Console.WriteLine(item.TypeOfInvestment.PadRight(20) + " " + item.Points.ToString());
}
//Group by on multiple column in LINQ (Lambda Method)
var CompanyDetails =elements.GroupBy(s => new { s.Company, s.TypeOfInvestment})
.Select(g =>
new
{
company = g.Key.Company,
TypeOfInvestment = g.Key.TypeOfInvestment,
Balance = g.Sum(x => Math.Round(Convert.ToDecimal(x.Worth), 2)),
}
);
foreach (var item in CompanyDetails)
{
Console.WriteLine(item.TypeOfInvestment.PadRight(20) + " " + item.Balance.ToString());
}
Console.ReadLine();
}
}
function valid(id)
{
var textVal=document.getElementById(id).value;
if (!textVal.match("Tryit")
{
alert("Field says Tryit");
return false;
}
else
{
return true;
}
}
Use this for expressing things
I use following code, found somewhere in the internet don't remember the source though.
var allText;
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function () {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
allText = rawFile.responseText;
}
}
}
rawFile.send(null);
return JSON.parse(allText);
As of recently, there is another way - using Glide's Generated API. It takes some initial work but then gives you all the power of Glide with the flexibility to do anything because you writhe the actual code so I think it's a good solution for the long run. Plus, the usage is very simple and neat.
First, setup Glide version 4+:
implementation 'com.github.bumptech.glide:glide:4.6.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.6.1'
Then create Glid's app module class to trigger the annotation processing:
@GlideModule
public final class MyAppGlideModule extends AppGlideModule {}
Then create the Glide extension which actually does the work. You can customize it to do whatever you want:
@GlideExtension
public class MyGlideExtension {
private MyGlideExtension() {}
@NonNull
@GlideOption
public static RequestOptions roundedCorners(RequestOptions options, @NonNull Context context, int cornerRadius) {
int px = Math.round(cornerRadius * (context.getResources().getDisplayMetrics().xdpi / DisplayMetrics.DENSITY_DEFAULT));
return options.transforms(new RoundedCorners(px));
}
}
After adding these files, build your project.
Then use it in your code like this:
GlideApp.with(this)
.load(imageUrl)
.roundedCorners(getApplicationContext(), 5)
.into(imageView);
You can get it like this:
SELECT TOP 1 CR
FROM tbl
ORDER BY len(CR) DESC
but i'm sure, there is a more elegant way to do it
Having an application called site
can reproduce this issue either.
This will work for a number greater than 0. You don't need to convert the number into string:
function convertNumberToDigitArray(number) {
const arr = [];
while (number > 0) {
let lastDigit = number % 10;
arr.push(lastDigit);
number = Math.floor(number / 10);
}
return arr;
}
Here is my code, this flips on hover and flips back off-hover.
CSS:
.flip-container {
background: transparent;
display: inline-block;
}
.flip-this {
position: relative;
width: 100%;
height: 100%;
transition: transform 0.6s;
transform-style: preserve-3d;
}
.flip-container:hover .flip-this {
transition: 0.9s;
transform: rotateY(180deg);
}
HTML:
<div class="flip-container">
<div class="flip-this">
<img width="100" alt="Godot icon" src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/6a/Godot_icon.svg/512px-Godot_icon.svg.png">
</div>
</div>
What types of files is not mentioned. If they're media files, go ahead with flat files. You probably just need a DB for tags and some way to associate the "external BLOBs" to the records in the DB. But if full text search is something you need, there's no other way to go but migrate to a full DB.
Another thing, your filesystem might provide the ceiling as far as number of physical files are concerned.
As mentioned by other answers, as of now android studio does not provide this out of the box. However, there are ways to do this easily.
As mentioned by @Elad Lavi, you should consider cloud hosting of your source code. Checkout github, bitbucket, gitlab, etc. All these provide private repositories, some free, some not.
If all you want is to just zip the sources, you can achieve this using git's git archive
. Here are the steps:
git init # on the root of the project folder
git add . # note: android studio already created .gitignore
git commit -m 'ready to zip sources'
git archive HEAD --format=zip > /tmp/archive.zip
Note: If you intend to send this by email, you have to remove gradlew.bat from zip file.
Both these solutions are possible thanks to VCS like git.
You find the differences explained in the detailed PHP manual on the page of require
:
require
is identical toinclude
except upon failure it will also produce a fatalE_COMPILE_ERROR
level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING
) which allows the script to continue.
See @efritz's answer for an example
You can do it in a hackish way. Careful using the sqlcmd
hack. If the data has double quotes or commas you will run into trouble.
You can use a simple script to do it properly:
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Data Exporter '
' '
' Description: Allows the output of data to CSV file from a SQL '
' statement to either Oracle, SQL Server, or MySQL '
' Author: C. Peter Chen, http://dev-notes.com '
' Version Tracker: '
' 1.0 20080414 Original version '
' 1.1 20080807 Added email functionality '
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
option explicit
dim dbType, dbHost, dbName, dbUser, dbPass, outputFile, email, subj, body, smtp, smtpPort, sqlstr
'''''''''''''''''
' Configuration '
'''''''''''''''''
dbType = "oracle" ' Valid values: "oracle", "sqlserver", "mysql"
dbHost = "dbhost" ' Hostname of the database server
dbName = "dbname" ' Name of the database/SID
dbUser = "username" ' Name of the user
dbPass = "password" ' Password of the above-named user
outputFile = "c:\output.csv" ' Path and file name of the output CSV file
email = "[email protected]" ' Enter email here should you wish to email the CSV file (as attachment); if no email, leave it as empty string ""
subj = "Email Subject" ' The subject of your email; required only if you send the CSV over email
body = "Put a message here!" ' The body of your email; required only if you send the CSV over email
smtp = "mail.server.com" ' Name of your SMTP server; required only if you send the CSV over email
smtpPort = 25 ' SMTP port used by your server, usually 25; required only if you send the CSV over email
sqlStr = "select user from dual" ' SQL statement you wish to execute
'''''''''''''''''''''
' End Configuration '
'''''''''''''''''''''
dim fso, conn
'Create filesystem object
set fso = CreateObject("Scripting.FileSystemObject")
'Database connection info
set Conn = CreateObject("ADODB.connection")
Conn.ConnectionTimeout = 30
Conn.CommandTimeout = 30
if dbType = "oracle" then
conn.open("Provider=MSDAORA.1;User ID=" & dbUser & ";Password=" & dbPass & ";Data Source=" & dbName & ";Persist Security Info=False")
elseif dbType = "sqlserver" then
conn.open("Driver={SQL Server};Server=" & dbHost & ";Database=" & dbName & ";Uid=" & dbUser & ";Pwd=" & dbPass & ";")
elseif dbType = "mysql" then
conn.open("DRIVER={MySQL ODBC 3.51 Driver}; SERVER=" & dbHost & ";PORT=3306;DATABASE=" & dbName & "; UID=" & dbUser & "; PASSWORD=" & dbPass & "; OPTION=3")
end if
' Subprocedure to generate data. Two parameters:
' 1. fPath=where to create the file
' 2. sqlstr=the database query
sub MakeDataFile(fPath, sqlstr)
dim a, showList, intcount
set a = fso.createtextfile(fPath)
set showList = conn.execute(sqlstr)
for intcount = 0 to showList.fields.count -1
if intcount <> showList.fields.count-1 then
a.write """" & showList.fields(intcount).name & ""","
else
a.write """" & showList.fields(intcount).name & """"
end if
next
a.writeline ""
do while not showList.eof
for intcount = 0 to showList.fields.count - 1
if intcount <> showList.fields.count - 1 then
a.write """" & showList.fields(intcount).value & ""","
else
a.write """" & showList.fields(intcount).value & """"
end if
next
a.writeline ""
showList.movenext
loop
showList.close
set showList = nothing
set a = nothing
end sub
' Call the subprocedure
call MakeDataFile(outputFile,sqlstr)
' Close
set fso = nothing
conn.close
set conn = nothing
if email <> "" then
dim objMessage
Set objMessage = CreateObject("CDO.Message")
objMessage.Subject = "Test Email from vbs"
objMessage.From = email
objMessage.To = email
objMessage.TextBody = "Please see attached file."
objMessage.AddAttachment outputFile
objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = smtp
objMessage.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = smtpPort
objMessage.Configuration.Fields.Update
objMessage.Send
end if
'You're all done!! Enjoy the file created.
msgbox("Data Writer Done!")
Also, what helped me understand this particular scenario that you described is the Promise API documentation, specifically where it explains how the promised returned by the then
method will be resolved differently depending on what the handler fn returns:
if the handler function:
- returns a value, the promise returned by then gets resolved with the returned value as its value;
- throws an error, the promise returned by then gets rejected with the thrown error as its value;
- returns an already resolved promise, the promise returned by then gets resolved with that promise's value as its value;
- returns an already rejected promise, the promise returned by then gets rejected with that promise's value as its value.
- returns another pending promise object, the resolution/rejection of the promise returned by then will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the value of the promise returned by then will be the same as the value of the promise returned by the handler.
@jason-mccreary is totally right. Besides I recommend you this code to get more info in case of malfunction:
$rest = curl_exec($crl);
if ($rest === false)
{
// throw new Exception('Curl error: ' . curl_error($crl));
print_r('Curl error: ' . curl_error($crl));
}
curl_close($crl);
print_r($rest);
EDIT 1
To debug you can set CURLOPT_HEADER
to true to check HTTP response with firebug::net or similar.
curl_setopt($crl, CURLOPT_HEADER, true);
EDIT 2
About Curl error: SSL certificate problem, verify that the CA cert is OK
try adding this headers (just to debug, in a production enviroment you should keep these options in true
):
curl_setopt($crl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($crl, CURLOPT_SSL_VERIFYPEER, false);
You have to use the encoding "Windows-1252".
header('Content-Encoding: Windows-1252');
header('Content-type: text/csv; charset=Windows-1252');
header("Content-Disposition: attachment; filename={$filename}");
Maybe you have to convert your strings:
private function convertToWindowsCharset($string) {
$encoding = mb_detect_encoding($string);
return iconv($encoding, "Windows-1252", $string);
}
Here's a good tutorial on what crontab is and how to use it on Ubuntu. Your crontab line will look something like this:
00 00 * * * ruby path/to/your/script.rb
(00 00
indicates midnight--0 minutes and 0 hours--and the *
s mean every day of every month.)
Syntax: mm hh dd mt wd command mm minute 0-59 hh hour 0-23 dd day of month 1-31 mt month 1-12 wd day of week 0-7 (Sunday = 0 or 7) command: what you want to run all numeric values can be replaced by * which means all
MAY BE INTERESTING TO YOU:
In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
Once string object is created its data or state can't be changed but a new string object is created.
It's called spread attributes and its aim is to make the passing of props easier.
Let us imagine that you have a component that accepts N number of properties. Passing these down can be tedious and unwieldy if the number grows.
<Component x={} y={} z={} />
Thus instead you do this, wrap them up in an object and use the spread notation
var props = { x: 1, y: 1, z:1 };
<Component {...props} />
which will unpack it into the props on your component, i.e., you "never" use {... props}
inside your render()
function, only when you pass the props down to another component. Use your unpacked props as normal this.props.x
.
And if you want to vary the speed and include callbacks simply add them like this :
jQuery.fn.extend({
slideRightShow: function(speed,callback) {
return this.each(function() {
$(this).show('slide', {direction: 'right'}, speed, callback);
});
},
slideLeftHide: function(speed,callback) {
return this.each(function() {
$(this).hide('slide', {direction: 'left'}, speed, callback);
});
},
slideRightHide: function(speed,callback) {
return this.each(function() {
$(this).hide('slide', {direction: 'right'}, speed, callback);
});
},
slideLeftShow: function(speed,callback) {
return this.each(function() {
$(this).show('slide', {direction: 'left'}, speed, callback);
});
}
});
Windows / OS X:
For multi-line selection, Ctrl+Alt+Down / ?+Alt+Shift+Down will extend your selection or cursor position to the next line. Ctrl+Right / ?+Right will move to the end of each line, no matter how long. To escape the multi-line selection, hit Esc.
See the VS Code keybindings (OS sensitive)
you can throw
as object
throw ({message: 'This Failed'})
then for example in your try/catch
try {
//
} catch(e) {
console.log(e); //{message: 'This Failed'}
console.log(e.message); //This Failed
}
or just throw a string error
throw ('Your error')
try {
//
} catch(e) {
console.log(e); //Your error
}
throw new Error //only accept a string
window.location.reload() // without passing true as argument
works for me.
You have to put the selector.xml file in the drwable folder.
Then write:
android:background="@drawable/selector"
.
This takes care of the pressed and focussed states.
I prefer location.assign(url);
Complete syntax example:
document.location.assign('https://www.urltodocument.com/document.pdf');
These are the steps I followed to install mongoDB on windows 7
download the .msi file from the mongodb site--> https://www.mongodb.com/download-center?jmp=nav#community and run it
Wherever your mondoDb is downloaded (generally in the c drive Program Files folder), go to that folder and wherever is the bin folder in that same folder create your data folder and your log folder
3.Inside your data folder create your db folder
The structure would look something like this
Now open command prompt as administrator.
change your file path and enter the bin folder.( in this case it would be c>program files>MongoDB>bin> )
Type in the following command : mongod --directoryperdb --dbpath "C:/Program Files\MongoDB\data" --logpath "C:\Program Files\MongoDB\log\mongo.log" --logappend --rest --install
This would set the logpath and database path. Lastly run net start MongoDB . Hope this helps.
Actually, there is one that works flawlessly:
display: flex; flex-direction: column;
as long as you can live with supporting only IE10 and up
.container {_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
background: #ddd;_x000D_
width: 15em;_x000D_
}_x000D_
_x000D_
.square {_x000D_
margin: 15px;_x000D_
height: 3em;_x000D_
background: yellow;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="square"></div>_x000D_
<div class="square"></div>_x000D_
<div class="square"></div>_x000D_
</div>_x000D_
<div class="container">_x000D_
<div class="square"></div>_x000D_
<div class="square"></div>_x000D_
<div class="square"></div>_x000D_
</div>
_x000D_
In addition to the correct answer by mdma, you can also use the mail command as follows:
mail [email protected] -s"Subject Here" -a"Content-Type: text/html; charset=\"us-ascii\""
you will get what you're looking for. Don't forget to put <HTML>
and </HTML>
in the email. Here's a quick script I use to email a daily report in HTML:
#!/bin/sh
(cat /path/to/tomorrow.txt mysql -h mysqlserver -u user -pPassword Database -H -e "select statement;" echo "</HTML>") | mail [email protected] -s"Tomorrow's orders as of now" -a"Content-Type: text/html; charset=\"us-ascii\""
you can do like this
<a href="http://www.w3c.org/" target="_blank">W3C Home Page</a>
find this page
http://www.corelangs.com/html/links/new-window.html
goreb
Below will reinitialize your local repo; also clearing remote repos (ie origin):
git init
Then below, will create 'origin' if it doesn't exist:
git remote add origin [repo-url]
Else, you can use the set-url
subcommand to edit an existing remote:
git remote set-url origin [repo-url]
Also, you can check existing remotes with
git remote -v
Hope this helps!
Swift version : This presents a ViewController which is embedded in a Navigation Controller.
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
// Identify the bundle by means of a class in that bundle.
let storyboard = UIStoryboard(name: "Storyboard", bundle: NSBundle(forClass: SettingsViewController.self))
// Instance of ViewController that is in the storyboard.
let settingViewController = storyboard.instantiateViewControllerWithIdentifier("SettingsVC")
let navController = UINavigationController(rootViewController: settingViewController)
presentViewController(navController, animated: true, completion: nil)
}
Simply declare length to be a cons, if it is not then you should be allocating memory dynamically
The below command worked for me
sudo service postgresql restart
You might be better off using a ListView with a CursorAdapter (or SimpleCursorAdapter).
These are built to show rows from a sqlite database and allow refreshing with minimal programming on your part.
Edit - here is a tutorial involving SimpleCursorAdapter and ListView including sample code.
You can create an Answer in Mockito. Let's assume, we have an interface named Application with a method myFunction.
public interface Application {
public String myFunction(String abc);
}
Here is the test method with a Mockito answer:
public void testMyFunction() throws Exception {
Application mock = mock(Application.class);
when(mock.myFunction(anyString())).thenAnswer(new Answer<String>() {
@Override
public String answer(InvocationOnMock invocation) throws Throwable {
Object[] args = invocation.getArguments();
return (String) args[0];
}
});
assertEquals("someString",mock.myFunction("someString"));
assertEquals("anotherString",mock.myFunction("anotherString"));
}
Since Mockito 1.9.5 and Java 8, you can also use a lambda expression:
when(myMock.myFunction(anyString())).thenAnswer(i -> i.getArguments()[0]);
Thought I'll add this one to the mix:
Collections.addAll(result, preprocessor.preprocess(lines));
This is the change that Intelli recommends.
from the javadocs:
Adds all of the specified elements to the specified collection._x000D_
Elements to be added may be specified individually or as an array._x000D_
The behavior of this convenience method is identical to that of_x000D_
<tt>c.addAll(Arrays.asList(elements))</tt>, but this method is likely_x000D_
to run significantly faster under most implementations._x000D_
_x000D_
When elements are specified individually, this method provides a_x000D_
convenient way to add a few elements to an existing collection:_x000D_
<pre>_x000D_
Collections.addAll(flavors, "Peaches 'n Plutonium", "Rocky Racoon");_x000D_
</pre>
_x000D_
It is not so easy to give out specific addresses to people say for a conference or a specific project or product. It could be more secure to prevent hacking such as SQL injection attacks etc.
Now that opts
is deprecated in ggplot2
package, function theme
should be used instead:
library(grid) # for unit()
... + theme(legend.key.height=unit(3,"line"))
... + theme(legend.key.width=unit(3,"line"))
NoneType
is simply the type of the None
singleton:
>>> type(None)
<type 'NoneType'>
From the latter link above:
None
The sole value of the type
NoneType
.None
is frequently used to represent the absence of a value, as when default arguments are not passed to a function. Assignments toNone
are illegal and raise aSyntaxError
.
In your case, it looks like one of the items you are trying to concatenate is None
, hence your error.
Assuming you are talking about this js in browser environment (unlike others like nodejs), Unfortunately I think what you are trying to do isn't possible simply because this is not the way it is supposed to work.
Html pages are delivered to the browser via HTTP Protocol, which is a 'stateless' protocol. If you still needed to pass values in between pages, there could be 3 approaches:
window
objectuse the val() function
this should be good
$(document).ready(function() {
$('input:radio').change(function() {
alert('ole');
});
});
I had to run the following command:
sudo apt-get autoremove phpmyadmin
Then I cleared my cache and it worked!
This error comes when you append this line os.path.join(os.path.dirname(__file__))
in python interactive shell.
Python Shell
doesn't detect current file path in __file__
and it's related to your filepath
in which you added this line
So you should write this line os.path.join(os.path.dirname(__file__))
in file.py
. and then run python file.py
, It works because it takes your filepath.
First of all, you should be using json.loads
, not json.dumps
. loads
converts JSON source text to a Python value, while dumps
goes the other way.
After you fix that, based on the JSON snippet at the top of your question, readable_json
will be a list, and so readable_json['firstName']
is meaningless. The correct way to get the 'firstName'
field of every element of a list is to eliminate the playerstuff = readable_json['firstName']
line and change for i in playerstuff:
to for i in readable_json:
.
I prefer TIMESTAMPDIFF because you can easily change the unit if need be.
UPDATED:
TO NOT HAVE ANY
b
and quotes at first and endHow to convert
bytes
as seen to strings, even in weird situations.
As your code may have unrecognizable characters to 'utf-8'
encoding,
it's better to use just str without any additional parameters:
some_bad_bytes = b'\x02-\xdfI#)'
text = str( some_bad_bytes )[2:-1]
print(text)
Output: \x02-\xdfI
if you add 'utf-8'
parameter, to these specific bytes, you should receive error.
As PYTHON 3 standard says, text
would be in utf-8 now with no concern.
Adding /
after /preference
solved the problem for me:
@Test
public void circularViewPathIssue() throws Exception {
mockMvc.perform(get("/preference/"))
.andDo(print());
}
Tips in order of Importance:
-Tip#1 Always remember to declare your destructors "virtual".
-Tip#2 Use RAII
-Tip#3 Use boost's smartpointers
-Tip#4 Don't write your own buggy Smartpointers, use boost (on a project I'm on right now I can't use boost, and I've suffered having to debug my own smart pointers, I would definately not take the same route again, but then again right now I can't add boost to our dependencies)
-Tip#5 If its some casual/non-performance critical (as in games with thousands of objects) work look at Thorsten Ottosen's boost pointer container
-Tip#6 Find a leak detection header for your platform of choice such as Visual Leak Detection's "vld" header
I can't believe there's no BitSet
solution.
A BitSet
is an abstraction over a set of bits so we don't have to use boolean[]
for more advanced interactions anymore, because it already contains most of the needed methods. It's also pretty fast in batch operations since it internally uses long
values to store the bits and doesn't therefore check every bit separately like we do with boolean[]
.
BitSet myBitSet = new BitSet(10);
// fills the bitset with ten true values
myBitSet.set(0, 10);
For your particular case, I'd use cardinality()
:
if (myBitSet.cardinality() == myBitSet.size()) {
// do something, there are no false bits in the bitset
}
Another alternative is using Guava:
return Booleans.contains(myArray, true);
The variable
left of the :
is a parameter name. The use of variable
on the right is making use of the parameter.
Means almost exactly the same as:
def some_method(variable):
return variable[0]
Solution 1: I changed src subfolder names, manifest file, activity headers and run/debug configuration. And still got building errors. If your project is not so big, just create a new project, copy-paste old files and change package names in headers of .java files and android manifest.
Solution 2: Inside IntelliJ 12, goto someFile.java and find your old package name
package com.myself.project2
click to which word that you want to change. Press Shift+F6.
Dialog comes, type new name.
Then goto Run/Edit configurations. Inside Launch radio button change package name to new one. It should work.
Other renaming options of IntelliJ are: http://www.jetbrains.com/idea/webhelp/rename-refactorings.html
Invoke mysql with the -N
(the alias for -N
is --skip-column-names
) option:
mysql -N ...
use testdb;
select * from names;
+------+-------+
| 1 | pete |
| 2 | john |
| 3 | mike |
+------+-------+
3 rows in set (0.00 sec)
Credit to ErichBSchulz for pointing out the -N alias.
To remove the grid (the vertical and horizontal lines) around the results use -s
(--silent
). Columns are separated with a TAB
character.
mysql -s ...
use testdb;
select * from names;
id name
1 pete
2 john
3 mike
To output the data with no headers and no grid just use both -s
and -N
.
mysql -sN ...
from pathlib import Path
import os
sorted(Path('./').iterdir(), key=lambda t: t.stat().st_mtime)
or
sorted(Path('./').iterdir(), key=os.path.getmtime)
or
sorted(os.scandir('./'), key=lambda t: t.stat().st_mtime)
where m time is modified time.
From C++ Primer:
The istringstream type reads a string, ostringstream writes a string, and stringstream reads and writes the string.
I come across some cases where it is both convenient and concise to use stringstream.
It is from one of the solutions for this leetcode problem. It demonstrates a very suitable case where the use of stringstream is efficient and concise.
Suppose a
and b
are complex numbers expressed in string format, we want to get the result of multiplication of a
and b
also in string format. The code is as follows:
string a = "1+2i", b = "1+3i";
istringstream sa(a), sb(b);
ostringstream out;
int ra, ia, rb, ib;
char buff;
// only read integer values to get the real and imaginary part of
// of the original complex number
sa >> ra >> buff >> ia >> buff;
sb >> rb >> buff >> ib >> buff;
out << ra*rb-ia*ib << '+' << ra*ib+ia*rb << 'i';
// final result in string format
string result = out.str()
It is also from a leetcode problem that requires you to simplify the given path string, one of the solutions using stringstream is the most elegant that I have seen:
string simplifyPath(string path) {
string res, tmp;
vector<string> stk;
stringstream ss(path);
while(getline(ss,tmp,'/')) {
if (tmp == "" or tmp == ".") continue;
if (tmp == ".." and !stk.empty()) stk.pop_back();
else if (tmp != "..") stk.push_back(tmp);
}
for(auto str : stk) res += "/"+str;
return res.empty() ? "/" : res;
}
Without the use of stringstream, it would be difficult to write such concise code.
The Chr
function in VB.NET converts the integer back to the character:
Dim i As Integer = Asc("x") ' Convert to ASCII integer.
Dim x As Char = Chr(i) ' Convert ASCII integer to char.
Make sure you wrap the condition in the correct precedence
ng-disabled="((!product.img) || (!product.name))"
Yes if you are using Python 3.3+. You can use the built-in unittest.mock
to assert method called. For Python 2.6+ use the rolling backport Mock
, which is the same thing.
Here is a quick example in your case:
from unittest.mock import MagicMock
aw = aps.Request("nv1")
aw.Clear = MagicMock()
aw2 = aps.Request("nv2", aw)
assert aw.Clear.called
There is actually a way to have a shell in the container.
Assume your /root/run.sh
launches the process, process manager (supervisor), or whatever.
Create /root/runme.sh
with some gnu-screen tricks:
# Spawn a screen with two tabs
screen -AdmS 'main' /root/run.sh
screen -S 'main' -X screen bash -l
screen -r 'main'
Now, you have your daemons in tab 0, and an interactive shell in tab 1. docker attach
at any time to see what's happening inside the container.
Another advice is to create a "development bundle" image on top of the production image with all the necessary tools, including this screen trick.
select t1.rowInt,t1.Value,t2.Value-t1.Value as diff
from (select * from myTable) as t1,
(select * from myTable where rowInt!=1
union all select top 1 rowInt=COUNT(*)+1,Value=0 from myTable) as t2
where t1.rowInt=t2.rowInt-1
In my machine (Ubuntu 14.04 and Genymotion 2.5.2) the source of the problem was that, I had 2 adb files of different versions.
(Before, narrowing down this problem source, I already had Genymotion's Settings > "Use custom Android SDK tools" referring to my machine's installed Android SDK directory as advised by Aditya Kresna Permana. I also tried with killing and starting the adb server and few other solutions from around the web).
Then saw, that running adb version
from my Android SDK installation directory “~/Android/Sdk/platform-tools” produced - "Android Debug Bridge version 1.0.32"
But, adb version
command from “/usr/bin” directory produced- “Android Debug Bridge version 1.0.31"
So just followed - http://bernaerts.dyndns.org/linux/74-ubuntu/328-ubuntu-trusty-android-adb-fastboot-qtadb to update the adb in “/usr/bin”
# adb version
Android Debug Bridge version 1.0.31
# wget -O - https://skia.googlesource.com/skia/+archive/cd048d18e0b81338c1a04b9749a00444597df394/platform_tools/android/bin/linux.tar.gz | tar -zxvf - adb
# sudo mv adb /usr/bin/adb
# sudo chmod +x /usr/bin/adb
# adb version
Android Debug Bridge version 1.0.32
And now running adb devices
works perfectly as expected.
And it also solved the associated problem that, before my PhoneGap (Cordova) app was not getting integrated with the Genymotion's virtual device. Now obviously that problem solved as well.
From the fine manual.
You must own the table to use ALTER TABLE.
Or be a database superuser.
ERROR: must be owner of relation contact
PostgreSQL error messages are usually spot on. This one is spot on.
Simple definitions for overloading and overriding
Overloading (Compile Time Polymorphism):: Functions with same name and different parameters
public class A
{
public void print(int x, int y)
{
Console.WriteLine("Parent Method");
}
}
public class B : A
{
public void child()
{
Console.WriteLine("Child Method");
}
public void print(float x, float y)
{
Console.WriteLine("Overload child method");
}
}
Overriding (Run Time Polymorphism):: Functions in the extended class with same name and same parameters as in the base class, but with different behaviors.
public class A
{
public virtual void print()
{
Console.WriteLine("Parent Method");
}
}
public class B : A
{
public void child()
{
Console.WriteLine("Child Method");
}
public override void print()
{
Console.WriteLine("Overriding child method");
}
}
You could attach to the KeyDown event and then query the database for that portion of the text that the user has already entered. For example, if the user enters "T", search for things that start with "T". Then, when they enter the next letter, for example "e", search for things in the table that start with "Te".
The available items could be displayed in a "floating" ListBox, for example. You would need to place the ListBox just beneath the TextBox so that they can see the entries available, then remove the ListBox when they're done typing.
This can be done using list comprehensions as defined in PEP 202
[w.strip() for w in ['this\n', 'is\n', 'a\n', 'list\n', 'of\n', 'words\n']]
It is only required if you aren't using the default values for version
and encoding
(which you are in that example).
works with bash and sh both:
touch /tmp/testfile
sleep 10 && rm /tmp/testfile &
until ! [ -f /tmp/testfile ]
do
echo "testfile still exist..."
sleep 1
done
echo "now testfile is deleted.."
As far as your question goes: no, if activating from .ini
is not enough and you can't upgrade PHP, there's not much you can do. Some modules, but not all, can be added without recompilation (zypper install php5-soap
, yum install php-soap
). If it is not enough, try installing some PEAR class for interpreted SOAP support (NuSOAP, etc.).
In general, the double-dash --switches
are designed to be used when recompiling PHP from scratch.
You would download the PHP source package (as a compressed .tgz
tarball, say), expand it somewhere and then, e.g. under Linux, run the configure script
./configure --prefix ...
The configure
command used by your PHP may be shown with phpinfo()
. Repeating it identical should give you an exact copy of the PHP you now have installed. Adding --enable-soap
will then enable SOAP in addition to everything else.
That said, if you aren't familiar with PHP recompilation, don't do it. It also requires several ancillary libraries that you might, or might not, have available - freetype
, gd
, libjpeg
, XML
, expat
, and so on and so forth (it's not enough they are installed; they must be a developer version, i.e. with headers and so on; in most distributions, having libjpeg
installed might not be enough, and you might need libjpeg-dev
also).
I have to keep a separate virtual machine with everything installed for my recompilation purposes.
I found that user controls can exist in the same project.
As others have mentioned, AutoToolboxPopulate must be set to True.
Create the desired user control.
Select Build Solution.
If the new user control doesn't show up in the toolbox, close/open Visual Studio.
If the user controls still aren't showing up in the toolbox, right click on the toolbox and select Reset Toolbox. Then select Build Solution. If they still aren't there, restart Visual Studio.
There must not be any build errors when the solution is built, otherwise new toolbox items will not be added to the toolbox.
It is not working because you have to declare which global variables you'll be accessing:
$data = 'My data';
function menugen() {
global $data; // <-- Add this line
echo "[" . $data . "]";
}
menugen();
Otherwise you can access it as $GLOBALS['data']
. See Variable scope.
Even if a little off-topic, I'd suggest you avoid using globals at all and prefer passing as parameters.
date()
itself is only for formatting, but it accepts a second parameter.
date("F j, Y", time() - 60 * 60 * 24);
To keep it simple I just subtract 24 hours from the unix timestamp.
A modern oop-approach is using DateTime
$date = new DateTime();
$date->sub(new DateInterval('P1D'));
echo $date->format('F j, Y') . "\n";
Or in your case (more readable/obvious)
$date = new DateTime();
$date->add(DateInterval::createFromDateString('yesterday'));
echo $date->format('F j, Y') . "\n";
(Because DateInterval
is negative here, we must add()
it here)
See also: DateTime::sub()
and DateInterval
Having this problem before I found out my own lazy solution (based on other people suggestions). It should be helpful if your <head>
contents go through php interpreter.
To force downloading file every time you make changes to it, you could add file byte size of this file after question mark sign at the end.
<link rel="stylesheet" type="text/css" href="styles.css?<?=filesize('styles.css');?>">
EDIT: As suggested in comments, filemtime()
is actually a better solution as long as your files have properly updated modify time (I, myself, have experienced such issues in the past, while working with remote files):
<link rel="stylesheet" type="text/css" href="styles.css?<?=filemtime('styles.css');?>">
Looks like you have an extra parenthesis.
The following portion is parsed as an assignment so the interpreter/compiler will look for a semi-colon or attempt to insert one if certain conditions are met.
foob_name = $this.attr('name').replace(/\[(\d+)\]/, function($0, $1) {
return '[' + (+$1 + 1) + ']';
})
<MyComponent text={<span>This is <strong>not</strong> working.</span>} />
and then in your component you can do prop checking like so:
import React from 'react';
export default class MyComponent extends React.Component {
static get propTypes() {
return {
text: React.PropTypes.object, // if you always want react components
text: React.PropTypes.any, // if you want both text or react components
}
}
}
Make sure you choose only one prop type.
I faced this error (errno 121) but it was caused by mysql-created intermediate tables that had been orphaned, preventing me from altering a table even though no such constraint name existed across any of my tables. At some point, my MySQL had crashed or failed to cleanup an intermediate table (table name starting with a #sql-) which ended up presenting me with an error such as: Can't create table '#sql-' (errno 121) when trying to run an ALTER TABLE with certain constraint names.
According to the docs at http://dev.mysql.com/doc/refman/5.7/en/innodb-troubleshooting-datadict.html , you can search for these orphan tables with:
SELECT * FROM INFORMATION_SCHEMA.INNODB_SYS_TABLES WHERE NAME LIKE '%#sql%';
The version I was working with was 5.1, but the above command only works on versions >= 5.6 (manual is incorrect about it working for 5.5 or earlier, because INNODB_SYS_TABLES does not exist in such versions). I was able to find the orphaned temporary table (which did not match the one named in the message) by searching my mysql data directory in command line:
find . -iname '#*'
After discovering the filename, such as #sql-9ad_15.frm, I was able to drop that orphaned table in MySQL:
USE myschema;
DROP TABLE `#mysql50##sql-9ad_15`;
After doing so, I was then able to successfully run my ALTER TABLE.
For completeness, as per the MySQL documentation linked, "the #mysql50# prefix tells MySQL to ignore file name safe encoding introduced in MySQL 5.1."
<div>
<img src="whatever it is" class="image-crop">
</div>
/*mobile code*/
.image-crop{
width:100%;
max-height: auto;
}
/*desktop code*/
@media screen and (min-width: 640px) {
.image-crop{
width:100%;
max-height: 140px;
}
For anyone still having this problem: Use NuGet to install: Microsoft.EntityFrameworkCore.Proxies
This problem is related to the use of Castle Proxy with EFCore.
Of course, the following code won't give you random numbers but pseudo random number. Use the following code
#define QUICK_RAND(m,n) m + ( std::rand() % ( (n) - (m) + 1 ) )
For example:
int myRand = QUICK_RAND(10, 20);
You must call
srand(time(0)); // Initialize random number generator.
otherwise the numbers won't be near random.
If I understand the goal is to insert a new record to a table but if the data is already on the table: skip it! Here is my answer:
INSERT INTO tbl_member
(Field1,Field2,Field3,...)
SELECT a.Field1,a.Field2,a.Field3,...
FROM (SELECT Field1 = [NewValueField1], Field2 = [NewValueField2], Field3 = [NewValueField3], ...) AS a
LEFT JOIN tbl_member AS b
ON a.Field1 = b.Field1
WHERE b.Field1 IS NULL
The record to be inserted is in the new value fields.
it works :
export PATH=/home/yourUserName/anaconda3/bin:$PATH
after that run anaconda-navigator
command. remember anaconda can't in Sudo mode, so don't use sudo at all.
Just run the command:
php artisan migrate:refresh --seed
You could try a setInterval, if you know the exact length of the sound. You could have the setInterval play the sound every x seconds. X would be the length of your sound.
You can use a CASE
statement.
SELECT
CASE WHEN currate.currentrate IS NULL THEN 1 ELSE currate.currentrate END
FROM ...
After hours of finding ways on how to get the data from the row selected on a WPF DataGrid Control, as I was using MongoDB. I found this post and used Tony's answer. I revised the code to be relevant to my project. Maybe someone can use this to get an idea.
private void selectionChanged(object sender, SelectionChangedEventArgs e)
{
facultyData row = (facultyData)facultyDataGrid.SelectedItem;
facultyID_Textbox.Text = row.facultyID;
lastName_TextBox.Text = row.lastName;
firstName_TextBox.Text = row.firstName;
middleName_TextBox.Text = row.middleName;
age_TextBox.Text = row.age.ToString();
}
}
class facultyData
{
public ObjectId _id { get; set; }
public string facultyID { get; set; }
public string acadYear { get; set; }
public string program { get; set; }
}
Use .loc
for label based indexing:
df.loc[df.A==0, 'B'] = np.nan
The df.A==0
expression creates a boolean series that indexes the rows, 'B'
selects the column. You can also use this to transform a subset of a column, e.g.:
df.loc[df.A==0, 'B'] = df.loc[df.A==0, 'B'] / 2
I don't know enough about pandas internals to know exactly why that works, but the basic issue is that sometimes indexing into a DataFrame returns a copy of the result, and sometimes it returns a view on the original object. According to documentation here, this behavior depends on the underlying numpy behavior. I've found that accessing everything in one operation (rather than [one][two]) is more likely to work for setting.
How many thousands of users?
I've run some TCP/IP client/server connection tests in the past on Windows 2003 Server and managed more than 70,000 connections on a reasonably low spec VM. (see here for details: http://www.lenholgate.com/blog/2005/10/the-64000-connection-question.html). I would be extremely surprised if Windows 2008 Server is limited to less than 2003 Server and, IMHO, the posting that Cloud links to is too vague to be much use. This kind of question comes up a lot, I blogged about why I don't really think that it's something that you should actually worry about here: http://www.serverframework.com/asynchronousevents/2010/12/one-million-tcp-connections.html.
Personally I'd test it and see. Even if there is no inherent limit in the Windows 2008 Server version that you intend to use there will still be practical limits based on memory, processor speed and server design.
If you want to run some 'generic' tests you can use my multi-client connection test and the associated echo server. Detailed here: http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html and here: http://www.lenholgate.com/blog/2005/11/simple-echo-servers.html. These are what I used to run my own tests for my server framework and these are what allowed me to create 70,000 active connections on a Windows 2003 Server VM with 760MB of memory.
Edited to add details from the comment below...
If you're already thinking of multiple servers I'd take the following approach.
Use the free tools that I link
to and prove to yourself that you
can create a reasonable number of
connections onto your target OS
(beware of the Windows limits on
dynamic ports which may cause your
client connections to fail, search
for MAX_USER_PORT
).
during development regularly test your actual server with test clients that can create connections and actually 'do something' on the server. This will help to prevent you building the server in ways that restrict its scalability. See here: http://www.serverframework.com/asynchronousevents/2010/10/how-to-support-10000-or-more-concurrent-tcp-connections-part-2-perf-tests-from-day-0.html
This might be a very late reply but it is working for us. We are using the same gallery provided by Android, just that, we have adjusted the left margin such a way that the screens left end is considered as Gallery's center. That really worked well for us.
You can use git show
with a path from the root of the repository (./
or ../
for relative pathing):
$ git show REVISION:path/to/file
Replace REVISION
with your actual revision (could be a Git commit SHA, a tag name, a branch name, a relative commit name, or any other way of identifying a commit in Git)
For example, to view the version of file <repository-root>/src/main.c
from 4 commits ago, use:
$ git show HEAD~4:src/main.c
Git for Windows requires forward slashes even in paths relative to the current directory. For more information, check out the man page for git-show
.
EditText ein=(EditText)findViewById(R.id.edittext1);
TextView t=new TextView(this);
t.setText("Your Text is="+ein.getText());
setContentView(t);
After much testing, I have verified that the original question is already right; missing just a couple of settings:
container_row
MUST have position: relative;
position: absolute; left:0;
container_row
should have additional styling:
height:x; line-height:x; vertical-align:middle;
text-align:center;
could, also, help.Map reduce is a framework that was developed to process massive amounts of data efficiently. For example, if we have 1 million records in a dataset, and it is stored in a relational representation - it is very expensive to derive values and perform any sort of transformations on these.
For Example In SQL, Given the Date of Birth, to find out How many people are of age > 30 for a million records would take a while, and this would only increase in order of magnitute when the complexity of the query increases. Map Reduce provides a cluster based implementation where data is processed in a distributed manner
Here is a wikipedia article explaining what map-reduce
is all about
Another good example is Finding Friends via map reduce can be a powerful example to understand the concept, and a well used use-case.
Personally, found this link quite useful to understand the concept
Copying the explanation provided in the blog (In case the link goes stale)
Finding Friends
MapReduce is a framework originally developed at Google that allows for easy large scale distributed computing across a number of domains. Apache Hadoop is an open source implementation.
I'll gloss over the details, but it comes down to defining two functions: a map function and a reduce function. The map function takes a value and outputs key:value pairs. For instance, if we define a map function that takes a string and outputs the length of the word as the key and the word itself as the value then map(steve) would return 5:steve and map(savannah) would return 8:savannah. You may have noticed that the map function is stateless and only requires the input value to compute it's output value. This allows us to run the map function against values in parallel and provides a huge advantage. Before we get to the reduce function, the mapreduce framework groups all of the values together by key, so if the map functions output the following key:value pairs:
3 : the 3 : and 3 : you 4 : then 4 : what 4 : when 5 : steve 5 : where 8 : savannah 8 : research
They get grouped as:
3 : [the, and, you] 4 : [then, what, when] 5 : [steve, where] 8 : [savannah, research]
Each of these lines would then be passed as an argument to the reduce function, which accepts a key and a list of values. In this instance, we might be trying to figure out how many words of certain lengths exist, so our reduce function will just count the number of items in the list and output the key with the size of the list, like:
3 : 3 4 : 3 5 : 2 8 : 2
The reductions can also be done in parallel, again providing a huge advantage. We can then look at these final results and see that there were only two words of length 5 in our corpus, etc...
The most common example of mapreduce is for counting the number of times words occur in a corpus. Suppose you had a copy of the internet (I've been fortunate enough to have worked in such a situation), and you wanted a list of every word on the internet as well as how many times it occurred.
The way you would approach this would be to tokenize the documents you have (break it into words), and pass each word to a mapper. The mapper would then spit the word back out along with a value of
1
. The grouping phase will take all the keys (in this case words), and make a list of 1's. The reduce phase then takes a key (the word) and a list (a list of 1's for every time the key appeared on the internet), and sums the list. The reducer then outputs the word, along with it's count. When all is said and done you'll have a list of every word on the internet, along with how many times it appeared.Easy, right? If you've ever read about mapreduce, the above scenario isn't anything new... it's the "Hello, World" of mapreduce. So here is a real world use case (Facebook may or may not actually do the following, it's just an example):
Facebook has a list of friends (note that friends are a bi-directional thing on Facebook. If I'm your friend, you're mine). They also have lots of disk space and they serve hundreds of millions of requests everyday. They've decided to pre-compute calculations when they can to reduce the processing time of requests. One common processing request is the "You and Joe have 230 friends in common" feature. When you visit someone's profile, you see a list of friends that you have in common. This list doesn't change frequently so it'd be wasteful to recalculate it every time you visited the profile (sure you could use a decent caching strategy, but then I wouldn't be able to continue writing about mapreduce for this problem). We're going to use mapreduce so that we can calculate everyone's common friends once a day and store those results. Later on it's just a quick lookup. We've got lots of disk, it's cheap.
Assume the friends are stored as Person->[List of Friends], our friends list is then:
A -> B C D B -> A C D E C -> A B D E D -> A B C E E -> B C D
Each line will be an argument to a mapper. For every friend in the list of friends, the mapper will output a key-value pair. The key will be a friend along with the person. The value will be the list of friends. The key will be sorted so that the friends are in order, causing all pairs of friends to go to the same reducer. This is hard to explain with text, so let's just do it and see if you can see the pattern. After all the mappers are done running, you'll have a list like this:
For map(A -> B C D) : (A B) -> B C D (A C) -> B C D (A D) -> B C D For map(B -> A C D E) : (Note that A comes before B in the key) (A B) -> A C D E (B C) -> A C D E (B D) -> A C D E (B E) -> A C D E For map(C -> A B D E) : (A C) -> A B D E (B C) -> A B D E (C D) -> A B D E (C E) -> A B D E For map(D -> A B C E) : (A D) -> A B C E (B D) -> A B C E (C D) -> A B C E (D E) -> A B C E And finally for map(E -> B C D): (B E) -> B C D (C E) -> B C D (D E) -> B C D Before we send these key-value pairs to the reducers, we group them by their keys and get: (A B) -> (A C D E) (B C D) (A C) -> (A B D E) (B C D) (A D) -> (A B C E) (B C D) (B C) -> (A B D E) (A C D E) (B D) -> (A B C E) (A C D E) (B E) -> (A C D E) (B C D) (C D) -> (A B C E) (A B D E) (C E) -> (A B D E) (B C D) (D E) -> (A B C E) (B C D)
Each line will be passed as an argument to a reducer. The reduce function will simply intersect the lists of values and output the same key with the result of the intersection. For example, reduce((A B) -> (A C D E) (B C D)) will output (A B) : (C D) and means that friends A and B have C and D as common friends.
The result after reduction is:
(A B) -> (C D) (A C) -> (B D) (A D) -> (B C) (B C) -> (A D E) (B D) -> (A C E) (B E) -> (C D) (C D) -> (A B E) (C E) -> (B D) (D E) -> (B C)
Now when D visits B's profile, we can quickly look up
(B D)
and see that they have three friends in common,(A C E)
.
From what I understand of the scikit-image docs (http://scikit-image.org/docs/dev/index.html), imshow() takes a ndarray as an argument, and not a dictionary:
http://scikit-image.org/docs/dev/api/skimage.io.html?highlight=imshow#skimage.io.imshow
Maybe if you post the whole stack trace, we could see that the TypeError comes somewhere deep from imshow().
The reason it invokes the method immediately and pressing the button does nothing is that action(somenumber)
is evaluated and its return value is attributed as the command for the button. So if action
prints something to tell you it has run and returns None
, you just run action
to evaluate its return value and given None
as the command for the button.
To have buttons to call functions with different arguments you can use global variables, although I can't recommend it:
import Tkinter as Tk
frame = Tk.Frame(width=5, height=2, bd=1, relief=Tk.SUNKEN)
frame.grid(row=2,column=2)
frame.pack(fill=Tk.X, padx=5, pady=5)
def action():
global output
global variable
output.insert(Tk.END,variable.get())
button = Tk.Button(master=frame, text='press', command=action)
button.pack()
variable = Tk.Entry(master=frame)
variable.pack()
output = Tk.Text(master=frame)
output.pack()
if __name__ == '__main__':
Tk.mainloop()
What I would do is make a class
whose objects would contain every variable required and methods to change those as needed:
import Tkinter as Tk
class Window:
def __init__(self):
self.frame = Tk.Frame(width=5, height=2, bd=1, relief=Tk.SUNKEN)
self.frame.grid(row=2,column=2)
self.frame.pack(fill=Tk.X, padx=5, pady=5)
self.button = Tk.Button(master=self.frame, text='press', command=self.action)
self.button.pack()
self.variable = Tk.Entry(master=self.frame)
self.variable.pack()
self.output = Tk.Text(master=self.frame)
self.output.pack()
def action(self):
self.output.insert(Tk.END,self.variable.get())
if __name__ == '__main__':
window = Window()
Tk.mainloop()
We can also use str_extract
from stringr
years<-c("20 years old", "1 years old")
as.integer(stringr::str_extract(years, "\\d+"))
#[1] 20 1
If there are multiple numbers in the string and we want to extract all of them, we may use str_extract_all
which unlike str_extract
returns all the macthes.
years<-c("20 years old and 21", "1 years old")
stringr::str_extract(years, "\\d+")
#[1] "20" "1"
stringr::str_extract_all(years, "\\d+")
#[[1]]
#[1] "20" "21"
#[[2]]
#[1] "1"
For me the problem was that changing the value for this field didn`t work:
$('#cardNumber').val(maskNumber);
None of the solutions above worked for me so I investigated further and found:
According to DOM Level 2 Event Specification: The change event occurs when a control loses the input focus and its value has been modified since gaining focus. That means that change event is designed to fire on change by user interaction. Programmatic changes do not cause this event to be fired.
The solution was to add the trigger function and cause it to trigger change event like this:
$('#cardNumber').val(maskNumber).trigger('change');
This can be achieved through LINQ with grouping, here a list of items pointed as a data source to the actual grid view. Sample pseudo code which could help coding the actual.
var tabelDetails =(from li in dc.My_table
join m in dc.Table_One on li.ID equals m.ID
join c in dc.Table_two on li.OtherID equals c.ID
where //Condition
group new { m, li, c } by new
{
m.ID,
m.Name
} into g
select new
{
g.Key.ID,
Name = g.Key.FullName,
sponsorBonus= g.Where(s => s.c.Name == "sponsorBonus").Count(),
pairingBonus = g.Where(s => s.c.Name == "pairingBonus").Count(),
staticBonus = g.Where(s => s.c.Name == "staticBonus").Count(),
leftBonus = g.Where(s => s.c.Name == "leftBonus").Count(),
rightBonus = g.Where(s => s.c.Name == "rightBonus").Count(),
Total = g.Count() //Row wise Total
}).OrderBy(t => t.Name).ToList();
tabelDetails.Insert(tabelDetails.Count(), new //This data will be the last row of the grid
{
Name = "Total", //Column wise total
sponsorBonus = tabelDetails.Sum(s => s.sponsorBonus),
pairingBonus = tabelDetails.Sum(s => s.pairingBonus),
staticBonus = tabelDetails.Sum(s => s.staticBonus),
leftBonus = tabelDetails.Sum(s => s.leftBonus),
rightBonus = tabelDetails.Sum(s => s.rightBonus ),
Total = tabelDetails.Sum(s => s.Total)
});
I needed to template a few files with minimal tooling and for me the issue with above sed -e '/../r file.txt
is that it only appends the file after it prints out the rest of the match, it doesn't replace it.
This doesn't do it (all matches are replaced and pattern matching continues from same point)
#!/bin/bash
TEMPDIR=$(mktemp -d "${TMPDIR:-/tmp/}$(basename $0).XXXXXXXXXXXX")
# remove on exit
trap "rm -rf $TEMPDIR" EXIT
DCTEMPLATE=$TEMPDIR/dctemplate.txt
DCTEMPFILE=$TEMPDIR/dctempfile.txt
# template that will replace
printf "0replacement
1${SHELL} data
2anotherlinenoEOL" > $DCTEMPLATE
# test data
echo -e "xxy \n987 \nxx xx\n yz yxxyy" > $DCTEMPFILE
# print original for debug
echo "---8<--- $DCTEMPFILE"
cat $DCTEMPFILE
echo "---8<--- $DCTEMPLATE"
cat $DCTEMPLATE
echo "---8<---"
# replace 'xx' -> contents of $DCTEMPFILE
perl -e "our \$fname = '${DCTEMPLATE}';" -pe 's/xx/`cat $fname`/eg' ${DCTEMPFILE}
Get Date::Manip from CPAN, then:
use Date::Manip;
$string = '18-Sep-2008 20:09'; # or a wide range of other date formats
$unix_time = UnixDate( ParseDate($string), "%s" );
edit:
Date::Manip is big and slow, but very flexible in parsing, and it's pure perl. Use it if you're in a hurry when you're writing code, and you know you won't be in a hurry when you're running it.
e.g. Use it to parse command line options once on start-up, but don't use it parsing large amounts of data on a busy web server.
See the authors comments.
(Thanks to the author of the first comment below)
Remember: import UIKit
Swift:
UIDevice.currentDevice().name
Swift 3, 4, 5:
UIDevice.current.name
Tried with all the methods but nothing worked
I got one reference from git hub.
To use type script imports with nodejs, i installed below packages.
1. npm i typescript
2. npm i ts-node
Won't require type: module in package.json
E:g
{
"name": "my-app",
"version": "0.0.1",
"description": "",
"scripts": {
},
"dependencies": {
"knex": "^0.16.3",
"pg": "^7.9.0",
"ts-node": "^8.1.0",
"typescript": "^3.3.4000"
}
}
Create an XML file named border.xml in the drawable folder and put the following code in it.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="rectangle">
<solid android:color="#FF0000" />
</shape>
</item>
<item android:left="5dp" android:right="5dp" android:top="5dp" >
<shape android:shape="rectangle">
<solid android:color="#000000" />
</shape>
</item>
</layer-list>
Then add a background to your linear layout like this:
android:background="@drawable/border"
EDIT :
This XML was tested with a galaxy s running GingerBread 2.3.3 and ran perfectly as shown in image below:
ALSO
tested with galaxy s 3 running JellyBean 4.1.2 and ran perfectly as shown in image below :
Finally its works perfectly with all APIs
EDIT 2 :
It can also be done using a stroke to keep the background as transparent while still keeping a border except at the bottom with the following code.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:left="0dp" android:right="0dp" android:top="0dp"
android:bottom="-10dp">
<shape android:shape="rectangle">
<stroke android:width="10dp" android:color="#B22222" />
</shape>
</item>
</layer-list>
hope this help .
As written, you're performing integer arithmetic, which automatically just truncates any decimal results. To perform floating point arithmetic, either change the constants to be floating point values:
int a = round(59.0 / 4);
Or cast them to a float
or other floating point type:
int a = round((float)59 / 4);
Either way, you need to do the final rounding with the round()
function in the math.h
header, so be sure to #include <math.h>
and use a C99 compatible compiler.
If you want to get the indices of the largest n
numbers in a list called data
, you can use Pandas sort_values
:
pd.Series(data).sort_values(ascending=False).index[0:n]
new way to do it in rails 3.1 is SomeModel.limit(5).order('id desc')
Well, as others have stated, ambiguity in type is the issue. So the answer is no, C# doesn't let that happen because it's a strongly typed language, and it deals only with compile time known types. The compiler could have been designed to infer it as of type object
, but the designers chose to avoid the extra complexity (in C# null
has no type).
One alternative is
var foo = new { }; //anonymous type
Again note that you're initializing to a compile time known type, and at the end its not null
, but anonymous object. It's only a few lines shorter than new object()
. You can only reassign the anonymous type to foo
in this one case, which may or may not be desirable.
Initializing to null
with type not being known is out of question.
Unless you're using dynamic
.
dynamic foo = null;
//or
var foo = (dynamic)null; //overkill
Of course it is pretty useless, unless you want to reassign values to foo
variable. You lose intellisense support as well in Visual Studio.
Lastly, as others have answered, you can have a specific type declared by casting;
var foo = (T)null;
So your options are:
//initializes to non-null; I like it; cant be reassigned a value of any type
var foo = new { };
//initializes to non-null; can be reassigned a value of any type
var foo = new object();
//initializes to null; dangerous and finds least use; can be reassigned a value of any type
dynamic foo = null;
var foo = (dynamic)null;
//initializes to null; more conventional; can be reassigned a value of any type
object foo = null;
//initializes to null; cannot be reassigned a value of any type
var foo = (T)null;
Deleting the .user file is exactly what fixed the problem for me. Lightning strike near the office shut my PC down and corrupted my .user file and project wouldn't load. I opened the file in Notepad++ and the "spaces" turned out to be [NULL] characters. Deleted the .user file and the file loaded!
source https://forums.asp.net/t/1491251.aspx?Can+t+load+project+because+root+element+is+missing+
Use SQL Server Migration Assistant (SSMA)
In addition to MySQL it supports Oracle, Sybase and MS Access.
It appears to be quite smart and capable of handling even nontrivial transfers. It also got some command line interface (in addition to GUI) so theoretically it can be integrated into some batch load process.
This the current download link for MySQL version https://www.microsoft.com/en-us/download/details.aspx?id=54257
The current (June 2016) stable version 6.0.1 crashes with the current (5.3.6) MySQL ODBC driver while transferring data. Everything 64 bit. The 5.3 version with the 5.1.13 ODBC driver works fine.
I get same problem in Entity Framewrok and I solved it by under steps :
1-Open your Model.edmx 2-change a table place (for do change in cs file) 3-save it
I hope help you
Its a common error which happens when we try to access a database which doesn't exist. So create the database using
CREATE DATABASE blog_development;
The error commonly occours when we have dropped the database using
DROP DATABASE blog_development;
and then try to access the database.
Both are 0-based, but the start is inclusive and the end is exclusive. This ensures the resulting string is of length start - end
.
To make life easier for substring
operation, imagine that characters are between indexes.
0 1 2 3 4 5 6 7 8 9 10 <- available indexes for substring
u n i v E R S i t y
? ?
start end --> range of "E R S"
Quoting the docs:
The substring begins at the specified
beginIndex
and extends to the character at indexendIndex - 1
. Thus the length of the substring isendIndex-beginIndex
.
In simple terms,
SNS - sends messages to the subscriber using push mechanism and no need of pull.
SQS - it is a message queue service used by distributed applications to exchange messages through a polling model, and can be used to decouple sending and receiving components.
A common pattern is to use SNS to publish messages to Amazon SQS queues to reliably send messages to one or many system components asynchronously.
Reference from Amazon SNS FAQs.
No, it is better practice to leave them out.
Without strip(), you can have empty keys and values:
apples<tab>round, fruity things
oranges<tab>round, fruity things
bananas<tab>
Without strip(), bananas is present in the dictionary but with an empty string as value. With strip(), this code will throw an exception because it strips the tab of the banana line.
String Replace
String s = "manchester united (with nice players)";
s = s.replace(" (with nice players)", "");
Edit:
By Index
s = s.substring(0, s.indexOf("(") - 1);
--- create a ws server vs2012 upd 3
new project
choose .net framework 3.5
asp.net web service application
right click on the project root
choose add service reference
choose wsdl
--- how can I create a ws client from a wsdl file?
I´ve a ws server Axis2 under tomcat 7 and I want to test the compatibility
There are a few ways to get all unique combinations of a set of factors.
with(df, interaction(yad, per, drop=TRUE)) # gives labels
with(df, yad:per) # ditto
aggregate(numeric(nrow(df)), df[c("yad", "per")], length) # gives a data frame
You can also use
android:layout_gravity="bottom"
for your textview
You can JOIN with the same table more than once by giving the joined tables an alias, as in the following example:
SELECT
airline, flt_no, fairport, tairport, depart, arrive, fare
FROM
flights
INNER JOIN
airports from_port ON (from_port.code = flights.fairport)
INNER JOIN
airports to_port ON (to_port.code = flights.tairport)
WHERE
from_port.code = '?' OR to_port.code = '?' OR airports.city='?'
Note that the to_port
and from_port
are aliases for the first and second copies of the airports
table.
document.getElementById("fname").style.borderTopColor = 'red';
document.getElementById("fname").style.borderBottomColor = 'red';
Try this
public class NetworkUtil {
public static final int TYPE_WIFI = 1;
public static final int TYPE_MOBILE = 2;
public static final int TYPE_NOT_CONNECTED = 0;
public static final int NETWORK_STATUS_NOT_CONNECTED = 0;
public static final int NETWORK_STATUS_WIFI = 1;
public static final int NETWORK_STATUS_MOBILE = 2;
public static int getConnectivityStatus(Context context) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
if (null != activeNetwork) {
if(activeNetwork.getType() == ConnectivityManager.TYPE_WIFI)
return TYPE_WIFI;
if(activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
return TYPE_MOBILE;
}
return TYPE_NOT_CONNECTED;
}
public static int getConnectivityStatusString(Context context) {
int conn = NetworkUtil.getConnectivityStatus(context);
int status = 0;
if (conn == NetworkUtil.TYPE_WIFI) {
status = NETWORK_STATUS_WIFI;
} else if (conn == NetworkUtil.TYPE_MOBILE) {
status = NETWORK_STATUS_MOBILE;
} else if (conn == NetworkUtil.TYPE_NOT_CONNECTED) {
status = NETWORK_STATUS_NOT_CONNECTED;
}
return status;
}
}
And for the BroadcastReceiver
public class NetworkChangeReceiver extends BroadcastReceiver {
@Override
public void onReceive(final Context context, final Intent intent) {
int status = NetworkUtil.getConnectivityStatusString(context);
Log.e("Sulod sa network reciever", "Sulod sa network reciever");
if ("android.net.conn.CONNECTIVITY_CHANGE".equals(intent.getAction())) {
if (status == NetworkUtil.NETWORK_STATUS_NOT_CONNECTED) {
new ForceExitPause(context).execute();
} else {
new ResumeForceExitPause(context).execute();
}
}
}
}
Don't forget to put this into your AndroidManifest.xml
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<receiver
android:name="NetworkChangeReceiver"
android:label="NetworkChangeReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
</intent-filter>
</receiver>
Hope this will help you Cheers!
When you say refresh the page, its new instance of the page that you are creating so you need to either have a static variable/session variable
or a method
to store and retrieve the count of hits on your page.
As far as refreshing the page is concerned, Response.Redirect(Request.RawUrl);
or window.location=window.location
would do the job for you.
mapStateToProps
receives the state
and props
and allows you to extract props from the state to pass to the component.
mapDispatchToProps
receives dispatch
and props
and is meant for you to bind action creators to dispatch so when you execute the resulting function the action gets dispatched.
I find this only saves you from having to do dispatch(actionCreator())
within your component thus making it a bit easier to read.
https://github.com/reactjs/react-redux/blob/master/docs/api.md#arguments
Here's what worked for me: right click the project-> source -> format After that just drag and drop the source folder into eclipse under the project and select link.
good luck!
Just additional note:
when you creating a new project from start.spring.io make sure you select your JDK version theirs by default is set to JDK 11, later it will cause the above issue.
I have an optimised implementation you could use in UnconstrainedMelody. Effectively it's just caching the list of names, but it's doing so in a nice, strongly typed, generically constrained way :)
This happens because you use the savedValue
in the onCreate()
method. The savedValue
is updated in onRestoreInstanceState()
method, but onRestoreInstanceState()
is called after the onCreate()
method. You can either:
savedValue
in onCreate()
method, orsavedValue
in onRestoreInstanceState()
method.But I suggest you to use the first approach, making the code like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
int display_mode = getResources().getConfiguration().orientation;
if (display_mode == 1) {
setContentView(R.layout.main_grid);
mGrid = (GridView) findViewById(R.id.gridview);
mGrid.setColumnWidth(95);
mGrid.setVisibility(0x00000000);
// mGrid.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
} else {
setContentView(R.layout.main_grid_land);
mGrid = (GridView) findViewById(R.id.gridview);
mGrid.setColumnWidth(95);
Log.d("Mode", "land");
// mGrid.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION);
}
if (savedInstanceState != null) {
savedUser = savedInstanceState.getString("TEXT");
} else {
savedUser = ""
}
Log.d("savedUser", savedUser);
if (savedUser.equals("admin")) { //value 0
adapter.setApps(appManager.getApplications());
} else if (savedUser.equals("prof")) { //value 1
adapter.setApps(appManager.getTeacherApplications());
} else {// default value
appManager = new ApplicationManager(this, getPackageManager());
appManager.loadApplications(true);
bindApplications();
}
}
You'll need to use DrawEllipse if you want to draw a circle using GDI+.
An example is here: http://www.websupergoo.com/helpig6net/source/3-examples/9-drawgdi.htm
Install C++ SDK:
Help > Install New Software > Work with: path for your eclipse version
> search for C++ and install C++ sdk development tools.
Example for a path: Mars - http://download.eclipse.org/releases/mars
See this thread for an explanation: VIM for Windows - What do I type to save and exit from a file?
As I wrote there: to learn Vimming, you could use one of the quick reference cards:
Also note How can I set up an editor to work with Git on Windows? if you're not comfortable in using Vim but want to use another editor for your commit messages.
If your commit message is not too long, you could also type
git commit -a -m "your message here"
If you want to use it with groups, you can use:
library(plyr)
mydata<-mtcars
ddply(mydata,.(carb),colwise(sd))
carb mpg cyl disp hp drat wt qsec vs am gear
1 1 6.001349 0.9759001 75.90037 19.78215 0.5548702 0.6214499 0.590867 0.0000000 0.5345225 0.5345225
2 2 5.472152 2.0655911 122.50499 43.96413 0.6782568 0.8269761 1.967069 0.5270463 0.5163978 0.7888106
3 3 1.053565 0.0000000 0.00000 0.00000 0.0000000 0.1835756 0.305505 0.0000000 0.0000000 0.0000000
4 4 3.911081 1.0327956 132.06337 62.94972 0.4575102 1.0536001 1.394937 0.4216370 0.4830459 0.6992059
5 6 NA NA NA NA NA NA NA NA NA NA
6 8 NA NA NA NA NA NA NA NA NA NA
You can use String unescapeJava(String)
method of StringEscapeUtils
from Apache Commons Lang.
Here's an example snippet:
String in = "a\\tb\\n\\\"c\\\"";
System.out.println(in);
// a\tb\n\"c\"
String out = StringEscapeUtils.unescapeJava(in);
System.out.println(out);
// a b
// "c"
The utility class has methods to escapes and unescape strings for Java, Java Script, HTML, XML, and SQL. It also has overloads that writes directly to a java.io.Writer
.
It looks like StringEscapeUtils
handles Unicode escapes with one u
, but not octal escapes, or Unicode escapes with extraneous u
s.
/* Unicode escape test #1: PASS */
System.out.println(
"\u0030"
); // 0
System.out.println(
StringEscapeUtils.unescapeJava("\\u0030")
); // 0
System.out.println(
"\u0030".equals(StringEscapeUtils.unescapeJava("\\u0030"))
); // true
/* Octal escape test: FAIL */
System.out.println(
"\45"
); // %
System.out.println(
StringEscapeUtils.unescapeJava("\\45")
); // 45
System.out.println(
"\45".equals(StringEscapeUtils.unescapeJava("\\45"))
); // false
/* Unicode escape test #2: FAIL */
System.out.println(
"\uu0030"
); // 0
System.out.println(
StringEscapeUtils.unescapeJava("\\uu0030")
); // throws NestableRuntimeException:
// Unable to parse unicode value: u003
A quote from the JLS:
Octal escapes are provided for compatibility with C, but can express only Unicode values
\u0000
through\u00FF
, so Unicode escapes are usually preferred.
If your string can contain octal escapes, you may want to convert them to Unicode escapes first, or use another approach.
The extraneous u
is also documented as follows:
The Java programming language specifies a standard way of transforming a program written in Unicode into ASCII that changes a program into a form that can be processed by ASCII-based tools. The transformation involves converting any Unicode escapes in the source text of the program to ASCII by adding an extra
u
-for example,\uxxxx
becomes\uuxxxx
-while simultaneously converting non-ASCII characters in the source text to Unicode escapes containing a single u each.This transformed version is equally acceptable to a compiler for the Java programming language and represents the exact same program. The exact Unicode source can later be restored from this ASCII form by converting each escape sequence where multiple
u
's are present to a sequence of Unicode characters with one feweru
, while simultaneously converting each escape sequence with a singleu
to the corresponding single Unicode character.
If your string can contain Unicode escapes with extraneous u
, then you may also need to preprocess this before using StringEscapeUtils
.
Alternatively you can try to write your own Java string literal unescaper from scratch, making sure to follow the exact JLS specifications.
Use Hosts Commander. It's simple and powerful. Translated description (from russian) here.
hosts add another.dev 192.168.1.1 # Remote host
hosts add test.local # 127.0.0.1 used by default
hosts set myhost.dev # new comment
hosts rem *.local
hosts enable local*
hosts disable localhost
...and many others...
Usage:
hosts - run hosts command interpreter
hosts <command> <params> - execute hosts command
Commands:
add <host> <aliases> <addr> # <comment> - add new host
set <host|mask> <addr> # <comment> - set ip and comment for host
rem <host|mask> - remove host
on <host|mask> - enable host
off <host|mask> - disable host
view [all] <mask> - display enabled and visible, or all hosts
hide <host|mask> - hide host from 'hosts view'
show <host|mask> - show host in 'hosts view'
print - display raw hosts file
format - format host rows
clean - format and remove all comments
rollback - rollback last operation
backup - backup hosts file
restore - restore hosts file from backup
recreate - empty hosts file
open - open hosts file in notepad
I've been in trouble within a scenario where Header was never reused even doing all the proper steps.
So as a tip note to everyone who want to achieve the situation of show empty sections (0 rows) be warn that:
dequeueReusableHeaderFooterViewWithIdentifier will not reuse the header until you return at least one row
Hope it helps
From ScottGu's blog:
Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:
The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:
Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).
Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.
This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.
Also see this.
In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".
Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.
Wikipedia
There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.
Do the following, download SQLLite Database Browser from here:
Locate your db. file in your phone.
Then, as soon you install the program go to: "Browse Data", you will see all the SMS there!!
You can actually export the data to an excel file or SQL.
Already answered but if you want to retrieve values in an easy way from a submitted form you can use the spread operator combined with creating a new Map iterable to get a nice structure.
new Map([...new FormData(form)])
Is there a js listener for when a user scrolls in a certain textbox that can be used?
DOM L3 UI Events spec gave the initial definition but is considered obsolete.
To add a single handler you can do:
let isTicking;
const debounce = (callback, evt) => {
if (isTicking) return;
requestAnimationFrame(() => {
callback(evt);
isTicking = false;
});
isTicking = true;
};
const handleScroll = evt => console.log(evt, window.scrollX, window.scrollY);
document.defaultView.onscroll = evt => debounce(handleScroll, evt);
For multiple handlers or, if preferable for style reasons, you may use addEventListener
as opposed to assigning your handler to onscroll
as shown above.
If using something like _.debounce
from lodash you could probably get away with:
const handleScroll = evt => console.log(evt, window.scrollX, window.scrollY);
document.defaultView.onscroll = evt => _.debounce(() => handleScroll(evt));
Review browser compatibility and be sure to test on some actual devices before calling it done.
Oh I found it in the PHP manual.
foreach ($array as $key => $value){
statement
}
The current element's key will be assigned to the variable $key on each loop.
SELECT TO_DATE(TO_CHAR(date_column,'MM/DD/YYYY'), 'YYYY-MM-DD')
FROM table;
What do you think this is supposed to be: ((t[1])/length) * t[1] += string
Python can't parse this, it's a syntax error.
As of 2014, here is a statement from a Microsoft representative (the Scripting Guy):
As much as we might hate to admit it, there are still no Windows PowerShell cmdlets from Microsoft that permit creating local user accounts or local user groups. We finally have a Desired State Configuration (DSC ) provider that can do this—but to date, no cmdlets.
I'm Tried this and it's working with me :
SELECT CONVERT(date, yourDate ,104)
This should do it (bold as well);
label1.Font = new Font("Serif", 24,FontStyle.Bold);
You can't import classes from the default package. You should avoid using the default package except for very small example programs.
From the Java language specification:
It is a compile time error to import a type from the unnamed package.
@last-child's answer is a great answer!
However, adding a border to my H2 produced an underline longer than the text.
If you're dynamically writing your CSS, or if like me you're lucky and know what the text will be, you can do the following:
change the content
to something the right length (ie the same
text) set the font color to transparent
(or rgba(0,0,0,0)
)
to underline <h2>Processing</h2>
(for example),
change last-child's code to be:
a {
text-decoration: none;
position: relative;
}
a:after {
content: 'Processing';
color: transparent;
width: 100%;
position: absolute;
left: 0;
bottom: 1px;
border-width: 0 0 1px;
border-style: solid;
}
There are a several things you need to address to get it working
@ouput
its @code
AddWithValue
since its not supposed to have a value just you Add
.ExecuteNonQuery
if you're not returning rows Try
SqlParameter output = new SqlParameter("@code", SqlDbType.Int);
output.Direction = ParameterDirection.Output;
cmd.Parameters.Add(output);
cmd.ExecuteNonQuery();
MessageBox.Show(output.Value.ToString());
I had to do both changes below to hide the status bar:
Add this code to the view controller where you want to hide the status bar:
- (BOOL)prefersStatusBarHidden
{
return YES;
}
Add this to your .plist file (go to 'info' in your application settings)
View controller-based status bar appearance --- NO
Then you can call this line to hide the status bar:
[[UIApplication sharedApplication] setStatusBarHidden:YES];
Unless I'm mistaken, the above code does not take unallocated space into account, so if you really want to know when you'll hit a hard limit, you should use maxbytes.
I think the code below does that. It calculates free space as "freespace" + unallocated space.
select
free.tablespace_name,
free.bytes,
reserv.maxbytes,
reserv.bytes,
reserv.maxbytes - reserv.bytes + free.bytes "max free bytes",
reserv.datafiles
from
(select tablespace_name, count(1) datafiles, sum(maxbytes) maxbytes, sum(bytes) bytes from dba_data_files group by tablespace_name) reserv,
(select tablespace_name, sum(bytes) bytes from dba_free_space group by tablespace_name) free
where free.tablespace_name = reserv.tablespace_name;
Method I used to split first_name into first_name and last_name when the data arrived all in the first_name field. This will put only the last word in the last name field, so "john phillips sousa" will be "john phillips" first name and "sousa" last name. It also avoids overwriting any records that have been fixed already.
set last_name=trim(SUBSTRING_INDEX(first_name, ' ', -1)), first_name=trim(SUBSTRING(first_name,1,length(first_name) - length(SUBSTRING_INDEX(first_name, ' ', -1)))) where list_id='$List_ID' and length(first_name)>0 and length(trim(last_name))=0
I also faced the same issue and got a solution very similar:
Changing the classpath to classpath 'com.android.tools.build:gradle:2.3.2'
A new message indicating to Update Build Tool version, so just click that message to update. Update
undo git rm
git rm file # delete file & update index
git checkout HEAD file # restore file & index from HEAD
undo git rm -r
git rm -r dir # delete tracked files in dir & update index
git checkout HEAD dir # restore file & index from HEAD
undo git rm -rf
git rm -r dir # delete tracked files & delete uncommitted changes
not possible # `uncommitted changes` can not be restored.
Uncommitted changes
includes not staged changes
, staged changes but not committed
.
I've been able to solve this by executing a dummy call ( e.g. IsAlive returning true ) just before the request with large content on the same wcf channel/client. Apparently ssl negotation is done on the first call. So no need to increase Uploadreadaheadsize.
VB.NET Sample Code
Dim A as String = "5.3"
Dim B as Double
B = CDbl(Val(A)) '// Val do hard work
'// Get output
MsgBox (B) '// Output is 5,3 Without Val result is 53.0
You don't need to go level up and use ..
since all buttons are on the same level:
//button[contains(.,'Arcade Reader')]/preceding-sibling::button[@name='settings']
Steps to upload project to git:-
step1-open cmd and change current working directory to your project location.
step2-Initialize your project directory as a Git repository.
$ git init
step3-Add files in your local repository.
$ add .
step4-Commit the files that you've staged in your local repository.
$ git commit -m "First commit"
step5-Copy the remote repository url.
step6-add the remote repository url as origin in your local location.
$ git add origin copied_remote_repository_url
step7-confirm your origin is updated ot not.
$ git remote show origin
step8-push the changed to your github repository
$ git push origin master.
You can use this solution. (Use nuget package) The source code is available on : Github: https://github.com/michelcedric/UserImpersonation
More detail https://michelcedric.wordpress.com/2015/09/03/usurpation-didentite-dun-user-c-user-impersonation/
Well, since you can currently only have one ngView directive... I use nested directive controls. This allows you to set up templating and inherit (or isolate) scopes among them. Outside of that I use ng-switch or even just ng-show to choose which controls I'm displaying based on what's coming in from $routeParams.
EDIT Here's some example pseudo-code to give you an idea of what I'm talking about. With a nested sub navigation.
Here's the main app page
<!-- primary nav -->
<a href="#/page/1">Page 1</a>
<a href="#/page/2">Page 2</a>
<a href="#/page/3">Page 3</a>
<!-- display the view -->
<div ng-view>
</div>
Directive for the sub navigation
app.directive('mySubNav', function(){
return {
restrict: 'E',
scope: {
current: '=current'
},
templateUrl: 'mySubNav.html',
controller: function($scope) {
}
};
});
template for the sub navigation
<a href="#/page/1/sub/1">Sub Item 1</a>
<a href="#/page/1/sub/2">Sub Item 2</a>
<a href="#/page/1/sub/3">Sub Item 3</a>
template for a main page (from primary nav)
<my-sub-nav current="sub"></my-sub-nav>
<ng-switch on="sub">
<div ng-switch-when="1">
<my-sub-area1></my-sub-area>
</div>
<div ng-switch-when="2">
<my-sub-area2></my-sub-area>
</div>
<div ng-switch-when="3">
<my-sub-area3></my-sub-area>
</div>
</ng-switch>
Controller for a main page. (from the primary nav)
app.controller('page1Ctrl', function($scope, $routeParams) {
$scope.sub = $routeParams.sub;
});
Directive for a Sub Area
app.directive('mySubArea1', function(){
return {
restrict: 'E',
templateUrl: 'mySubArea1.html',
controller: function($scope) {
//controller for your sub area.
}
};
});
I fixed it in my bootstrap page by setting the min-width and max-width to the same value in the select and then setting the select:focus to auto.
select {_x000D_
min-width: 120px;_x000D_
max-width: 120px;_x000D_
}_x000D_
select:focus {_x000D_
width: auto;_x000D_
}
_x000D_
<select style="width: 120px">_x000D_
<option>REALLY LONG TEXT, REALLY LONG TEXT, REALLY LONG TEXT</option>_x000D_
<option>ABC</option>_x000D_
</select>
_x000D_
Just click red button to stop all services on eclipse than re- run application as Spring Boot Application - This worked for me.
function poll(){
$("ajax.php", function(data){
//do stuff
});
}
setInterval(function(){ poll(); }, 5000);
If you are targeting Windows XP (v140_xp
), try installing Windows XP Support for C++.
Starting with Visual Studio 2012, the default toolset (v110) dropped support for Windows XP. As a result, a Windows.h
error can occur if your project is targeting Windows XP with the default C++ packages.
Check which Windows SDK version is specified in your project's Platform Toolset. (Project ? Properties ? Configuration Properties ? General
). If your Toolset ends in _xp
, you'll need to install XP support.
Open the Visual Studio Installer and click Modify for your version of Visual Studio. Open the Individual Components tab and scroll down to Compilers, build tools, and runtimes. Near the bottom, check Windows XP support for C++ and click Modify to begin installing.
I also had this same issue. My console window was no longer open, but I was able to see my application running by going to processes within task manager. The process name was the name of my application. Once I ended the process I was able to build and compile my code with no issues.
@m59 Directives will work for ng-bind-html you just need to wait for $viewContentLoaded
to finish
app.directive('targetBlank', function($timeout) {
return function($scope, element) {
$scope.initializeTarget = function() {
return $scope.$on('$viewContentLoaded', $timeout(function() {
var elems;
elems = element.prop('tagName') === 'A' ? element : element.find('a');
elems.attr('target', '_blank');
}));
};
return $scope.initializeTarget();
};
});
In Visual Studio 2010 right click your project name. Hit "View Windows Settings", this generates and opens a file called "app.manifest". Within this file replace "asInvoker" with "requireAdministrator" as explained in the commented sections within the file.
Simply cleaning the project solved it for me.
My project is a C++ application (not a shared library). I randomly got this error after a lot of successful builds.
what about this simple inArray function:
Function isInArray(ByRef stringToBeFound As String, ByRef arr As Variant) As Boolean
For Each element In arr
If element = stringToBeFound Then
isInArray = True
Exit Function
End If
Next element
End Function
Put each line in cmd or all of theme in the batch file:
@echo off
if not "%1"=="am_admin" (powershell start -verb runas '%0' am_admin & exit /b)
"Put your command here"
it works fine for me.
I downloaded an mvc 5 project and the offending issue pointing at
<add namespace="System.Web.Mvc.Ajax" />
With this error message:
CS0234: The type or namespace name 'Ajax' does not exist in the namespace 'System.Web.Mvc' (are you missing an assembly reference?)
-- > in which I came to this webpage and tried a clean and a few things above etc...
What worked for me was just to
Manage Nuget and Update all the packages. Then it worked fine.
Your line:
img = cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
will draw a rectangle in the image, but the return value will be None, so img changes to None and cannot be drawn.
Try
cv2.rectangle(img,(x,y),(x+w,y+h),(255,0,0),2)
If you "require" 'exampleDirective' from another directive + your logic is in 'exampleDirective's' controller (let's say 'exampleCtrl'):
app.directive('exampleDirective', function () {
return {
restrict: 'A',
scope: false,
bindToController: {
myCallback: '&exampleFunction'
},
controller: 'exampleCtrl',
controllerAs: 'vm'
};
});
app.controller('exampleCtrl', function () {
var vm = this;
vm.myCallback();
});
Here's some background on the mechanism you should use, called Package Configurations: Understanding Integration Services Package Configurations. The article describes 5 types of configurations:
Here's a walkthrough of setting up a configuration on a Connection Manager: SQL Server Integration Services SSIS Package Configuration - I do realize this is using an environment variable for the connection string (not a great idea), but the basics are identical to using an XML file. The only step(s) you have to change in that walkthrough are the configuration type, and then a path.
An HttpOnly
cookie means that it's not available to scripting languages like JavaScript. So in JavaScript, there's absolutely no API available to get/set the HttpOnly
attribute of the cookie, as that would otherwise defeat the meaning of HttpOnly
.
Just set it as such on the server side using whatever server side language the server side is using. If JavaScript is absolutely necessary for this, you could consider to just let it send some (ajax) request with e.g. some specific request parameter which triggers the server side language to create an HttpOnly cookie. But, that would still make it easy for hackers to change the HttpOnly
by just XSS and still have access to the cookie via JS and thus make the HttpOnly
on your cookie completely useless.
You can easily change the maximum allowed number of arguments in pylint. Just open your pylintrc file (generate it if you don't already have one) and change:
max-args=5
to:
max-args = 6 # or any value that suits you
From pylint's manual
Specifying all the options suitable for your setup and coding standards can be tedious, so it is possible to use a rc file to specify the default values. Pylint looks for /etc/pylintrc and ~/.pylintrc. The --generate-rcfile option will generate a commented configuration file according to the current configuration on standard output and exit. You can put other options before this one to use them in the configuration, or start with the default values and hand tune the configuration.
In my case, it was unable to find the .eslintrc
file so I copied from node_modules/.bin to root.
Like this:
>>> structTime = time.localtime()
>>> datetime.datetime(*structTime[:6])
datetime.datetime(2009, 11, 8, 20, 32, 35)
You forgot to print
the result. What you get is the P
in RE(P)L
and not the actual printed result.
In Py2.x you should so something like
>>> print "\n".join(['I', 'would', 'expect', 'multiple', 'lines'])
I
would
expect
multiple
lines
and in Py3.X, print is a function, so you should do
print("\n".join(['I', 'would', 'expect', 'multiple', 'lines']))
Now that was the short answer. Your Python Interpreter, which is actually a REPL, always displays the representation of the string rather than the actual displayed output. Representation is what you would get with the repr
statement
>>> print repr("\n".join(['I', 'would', 'expect', 'multiple', 'lines']))
'I\nwould\nexpect\nmultiple\nlines'
I used this to get to grips with Comet, I have also set up Comet using the Java Glassfish server and found lots of other examples by subscribing to cometdaily.com
there are many things which can cause this error. For example, I imported google api from the android SDK Manager and that is when I got this same error. Eclipse broke down on me. I could not even create a new android project.
To fix this, I went to help - Install New Software... - from the "work with" drop-down box I selected http://dl-ssl.google.com/android/eclipse/ - I then check marked "Developer Tools" and hit the Next button. I then followed the prompts and it basically did a re-install. It took less than 5 minutes. That resolved the error.
Now Im back up and running, and I got the lastest version of Eclipse.
The datasource is by default .\SQLEXPRESS (its the instance where databases are placed by default) or if u changed the name of the instance during installation of sql server so i advise you to do this :
connectionString="Data Source=.\\yourInstance(defaulT Data source is SQLEXPRESS);
Initial Catalog=databaseName;
User ID=theuser if u use it;
Password=thepassword if u use it;
integrated security=true(if u don t use user and pass; else change it false)"
Without to knowing your instance, I could help with this one. Hope it helped