It provides human readable version of output rather "Object": Example:
class Pet(object):
def __init__(self, name, species):
self.name = name
self.species = species
def getName(self):
return self.name
def getSpecies(self):
return self.species
def Norm(self):
return "%s is a %s" % (self.name, self.species)
if __name__=='__main__':
a = Pet("jax", "human")
print a
returns
<__main__.Pet object at 0x029E2F90>
while code with "str" return something different
class Pet(object):
def __init__(self, name, species):
self.name = name
self.species = species
def getName(self):
return self.name
def getSpecies(self):
return self.species
def __str__(self):
return "%s is a %s" % (self.name, self.species)
if __name__=='__main__':
a = Pet("jax", "human")
print a
returns:
jax is a human
While this question is really old. I believe there is a much simpler approach in numpy (a one liner).
import numpy as np
list = [1,3,9,5,2,5,6,9,7]
np.diff(np.sign(np.diff(list))) #the one liner
#output
array([ 0, -2, 0, 2, 0, 0, -2])
To find a local max or min we essentially want to find when the difference between the values in the list (3-1, 9-3...) changes from positive to negative (max) or negative to positive (min). Therefore, first we find the difference. Then we find the sign, and then we find the changes in sign by taking the difference again. (Sort of like a first and second derivative in calculus, only we have discrete data and don't have a continuous function.)
The output in my example does not contain the extrema (the first and last values in the list). Also, just like calculus, if the second derivative is negative, you have max, and if it is positive you have a min.
Thus we have the following matchup:
[1, 3, 9, 5, 2, 5, 6, 9, 7]
[0, -2, 0, 2, 0, 0, -2]
Max Min Max
Parameter Options FollowSymLinks
enables you to have a symlink in your webroot pointing to some other file/dir. With this disabled, Apache will refuse to follow such symlink. More secure Options SymLinksIfOwnerMatch
can be used instead - this will allow you to link only to other files which you do own.
If you use Options
directive in .htaccess
with parameter which has been forbidden in main Apache config, server will return HTTP 500 error code.
Allowed .htaccess
options are defined by directive AllowOverride
in the main Apache config file. To allow symlinks, this directive need to be set to All
or Options
.
Besides allowing use of symlinks, this directive is also needed to enable mod_rewrite in .htaccess
context. But for this, also the more secure SymLinksIfOwnerMatch
option can be used.
select MyDate
from MyTable
order by case when MyDate is null then 1 else 0 end, MyDate
the instructions for Vs2012
To Install FreeGLUT
Extract the compressed file freeglut-MSVC.zip to a folder freeglut
Inside freeglut folder:
On 32bit versions of windows
copy all files in include/GL folder to C:\Program Files\Windows Kits\8.0\Include\um\gl
copy all files in lib folder to C:\Program Files\Windows Kits\8.0\Lib\win8\um\ (note: Lib\freeglut.lib in a folder goes into x86)
copy freeglut.dll to C:\windows\system32
On 64bit versions of windows:(not 100% sure but try)
copy all files in include/GL folder to C:\Program Files(x86)\Windows Kits\8.0\Include\um\gl
copy all files in lib folder to C:\Program Files(x86)\Windows Kits\8.0\Lib\win8\um\ (note: Lib\freeglut.lib in a folder goes into x86)
copy freeglut.dll to C:\windows\SysWOW64
Displaying left middle and right of there parents. If you have more then 3 elements then use nth-child() for them.
HTML sample:
<body>
<ul class="nav-tabs">
<li><a id="btn-tab-business" class="btn-tab nav-tab-selected" onclick="openTab('business','btn-tab-business')"><i class="fas fa-th"></i>Business</a></li>
<li><a id="btn-tab-expertise" class="btn-tab" onclick="openTab('expertise', 'btn-tab-expertise')"><i class="fas fa-th"></i>Expertise</a></li>
<li><a id="btn-tab-quality" class="btn-tab" onclick="openTab('quality', 'btn-tab-quality')"><i class="fas fa-th"></i>Quality</a></li>
</ul>
</body>
CSS sample:
.nav-tabs{
position: relative;
padding-bottom: 50px;
}
.nav-tabs li {
display: inline-block;
position: absolute;
list-style: none;
}
.nav-tabs li:first-child{
top: 0px;
left: 0px;
}
.nav-tabs li:last-child{
top: 0px;
right: 0px;
}
.nav-tabs li:nth-child(2){
top: 0px;
left: 50%;
transform: translate(-50%, 0%);
}
My latest issue was how to integrate CKFinder for image upload in CKEditor. Here the solution.
Download CKEditor and extract in your web folder root.
Download CKFinder and extract withing ckeditor folder.
Then add references to the CKEditor, CKFinder and put
<CKEditor:CKEditorControl ID="CKEditorControl1" runat="server"></CKEditor:CKEditorControl>
to your aspx page.
In code behind page OnLoad event add this code snippet
protected override void OnLoad(EventArgs e)
{
CKFinder.FileBrowser _FileBrowser = new CKFinder.FileBrowser();
_FileBrowser.BasePath = "ckeditor/ckfinder/";
_FileBrowser.SetupCKEditor(CKEditorControl1);
}
Edit Confic.ascx file.
public override bool CheckAuthentication()
{
return true;
}
// Perform additional checks for image files.
SecureImageUploads = true;
(source)
git remote show origin
Result:
HEAD branch: master
Remote branch:
master tracked
Local branch configured for 'git pull':
master merges with remote master
Local ref configured for 'git push':
master pushes to master (local out of date) <-------
I was using eclipse and after trying all the other answers it didn't work for me.
In the end, what worked for me was moving the ojdb7.jar
to top in the Build Path. This occurs when multiple jars have conflicting same classes.
- Select project in
Project Explorer
- Right click on
Project -> Build Path -> Configure Build Path
- Go to
Order and Export
tab and selectojdbc.jar
- Click button
TOP
to move it to top
use this code:
private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
const char Delete = (char)8;
e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
}
Many of you must be landing here to find a solution for opaque border instead of a transparent one. In that case you can use rgba
, where a
stands for alpha
.
.your_class {
height: 100px;
width: 100px;
margin: 100px;
border: 10px solid rgba(255,255,255,.5);
}
Here, you can change the opacity
of the border
from 0-1
If you simply want a complete transparent border, the best thing to use is transparent
, like border: 1px solid transparent;
Joining fails if the DataFrames have some column names in common. The simplest way around it is to include an lsuffix
or rsuffix
keyword like so:
restaurant_review_frame.join(restaurant_ids_dataframe, on='business_id', how='left', lsuffix="_review")
This way, the columns have distinct names. The documentation addresses this very problem.
Or, you could get around this by simply deleting the offending columns before you join. If, for example, the stars in restaurant_ids_dataframe
are redundant to the stars in restaurant_review_frame
, you could del restaurant_ids_dataframe['stars']
.
this is my solution:
public Bitmap Blend(Bitmap topImage1, Bitmap bottomImage1, PorterDuff.Mode Type) {
Bitmap workingBitmap = Bitmap.createBitmap(topImage1);
Bitmap topImage = workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
Bitmap workingBitmap2 = Bitmap.createBitmap(bottomImage1);
Bitmap bottomImage = workingBitmap2.copy(Bitmap.Config.ARGB_8888, true);
Rect dest = new Rect(0, 0, bottomImage.getWidth(), bottomImage.getHeight());
new BitmapFactory.Options().inPreferredConfig = Bitmap.Config.ARGB_8888;
bottomImage.setHasAlpha(true);
Canvas canvas = new Canvas(bottomImage);
Paint paint = new Paint();
paint.setXfermode(new PorterDuffXfermode(Type));
paint.setFilterBitmap(true);
canvas.drawBitmap(topImage, null, dest, paint);
return bottomImage;
}
usage :
imageView.setImageBitmap(Blend(topBitmap, bottomBitmap, PorterDuff.Mode.SCREEN));
or
imageView.setImageBitmap(Blend(topBitmap, bottomBitmap, PorterDuff.Mode.OVERLAY));
and the results :
Make an exception handler like this,
private int ConvertIntoNumeric(String xVal)
{
try
{
return Integer.parseInt(xVal);
}
catch(Exception ex)
{
return 0;
}
}
.
.
.
.
int xTest = ConvertIntoNumeric("N/A"); //Will return 0
Running your code shows an image for me, after adjusting the path. Can you verify that your image path is correct, try absolute path for instance?
Just happened to us.
We were sure the cause is Apple's Christmas holoday (23-27 Dec 2016). But no - we've tried again 5 minutes later and the version passed.
However - the submission button is greyed out due to the holiday.
Uninstall whatever node version you have
sudo apt-get --purge remove node
sudo apt-get --purge remove nodejs-legacy
sudo apt-get --purge remove nodejs
install nvm (Node Version Manager) https://github.com/creationix/nvm
wget -qO- https://raw.githubusercontent.com/creationix/nvm/v0.31.0/install.sh | bash
Now you can install whatever version of node you want and switch between the versions.
Add the following code in .htaccess file.
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.example.com/$1 [R,L]
change example.com with your website domain
URLs redirect tutorial can be found from here - Redirect non-www to www & HTTP to HTTPS using .htaccess file
Can do a foreachloop too..
$collection = Model::get();
foreach($collection as $c) {
$c->delete();
}
A trivial approach would be to replace
<[^>]*>
with nothing. But depending on how ill-structured your input is that may well fail.
For Jersey 2 you'd need to modify the code:
return ClientBuilder.newBuilder()
.withConfig(config)
.hostnameVerifier(new TrustAllHostNameVerifier())
.sslContext(ctx)
.build();
https://gist.github.com/JAlexoid/b15dba31e5919586ae51 http://www.panz.in/2015/06/jersey2https.html
In the current version of Web API, the usage of multiple complex objects (like your Content
and Config
complex objects) within the Web API method signature is not allowed. I'm betting good money that config
(your second parameter) is always coming back as NULL. This is because only one complex object can be parsed from the body for one request. For performance reasons, the Web API request body is only allowed to be accessed and parsed once. So after the scan and parsing occurs of the request body for the "content" parameter, all subsequent body parses will end in "NULL". So basically:
[FromBody]
.[FromUri]
.Below is a useful extract from Mike Stall's excellent blog article (oldie but goldie!). You'll want to pay attention to item 4:
Here are the basic rules to determine whether a parameter is read with model binding or a formatter:
- If the parameter has no attribute on it, then the decision is made purely on the parameter's .NET type. "Simple types" use model binding. Complex types use the formatters. A "simple type" includes: primitives,
TimeSpan
,DateTime
,Guid
,Decimal
,String
, or something with aTypeConverter
that converts from strings.- You can use a
[FromBody]
attribute to specify that a parameter should be from the body.- You can use a
[ModelBinder]
attribute on the parameter or the parameter's type to specify that a parameter should be model bound. This attribute also lets you configure the model binder.[FromUri]
is a derived instance of[ModelBinder]
that specifically configures a model binder to only look in the URI.- The body can only be read once. So if you have 2 complex types in the signature, at least one of them must have a
[ModelBinder]
attribute on it.It was a key design goal for these rules to be static and predictable.
A key difference between MVC and Web API is that MVC buffers the content (e.g. request body). This means that MVC's parameter binding can repeatedly search through the body to look for pieces of the parameters. Whereas in Web API, the request body (an
HttpContent
) may be a read-only, infinite, non-buffered, non-rewindable stream.
You can read the rest of this incredibly useful article on your own so, to cut a long story short, what you're trying to do is not currently possible in that way (meaning, you have to get creative). What follows is not a solution, but a workaround and only one possibility; there are other ways.
(Disclaimer: I've not used it myself, I'm just aware of the theory!)
One possible "solution" is to use the JObject
object. This objects provides a concrete type specifically designed for working with JSON.
You simply need to adjust the signature to accept just one complex object from the body, the JObject
, let's call it stuff
. Then, you manually need to parse properties of the JSON object and use generics to hydrate the concrete types.
For example, below is a quick'n'dirty example to give you an idea:
public void StartProcessiong([FromBody]JObject stuff)
{
// Extract your concrete objects from the json object.
var content = stuff["content"].ToObject<Content>();
var config = stuff["config"].ToObject<Config>();
. . . // Now do your thing!
}
I did say there are other ways, for example you can simply wrap your two objects in a super-object of your own creation and pass that to your action method. Or you can simply eliminate the need for two complex parameters in the request body by supplying one of them in the URI. Or ... well, you get the point.
Let me just reiterate I've not tried any of this myself, although it should all work in theory.
You could simply convert the datetime. Something like:
@Convert.ToString(string.Format("{0:dd/MM/yyyy}", Model.Returndate))
You can get HTML5 tags working in IE8 by including this JavaScript in the head.
<script type="text/javascript">
document.createElement('header');
document.createElement('nav');
document.createElement('menu');
document.createElement('section');
document.createElement('article');
document.createElement('aside');
document.createElement('footer');
</script>
Check to see if the key-value pair is actually showing up in the request:
In Chrome, found somewhere like: F12: Developer Tools > Network Tab > Whatever request you have sent > "view source" under Response Headers
Depending on your testing workflow, if whatever pair you added isn't there, you may just need to clear your browser cache. To verify that your browser is using your most up-to-date code, you can check the page's sources, in Chrome this is found somewhere like:
F12: Developer Tools > Sources Tab > YourJavascriptSrc.js
and check your code.
But as other answers have said:
xhttp.setRequestHeader(key, value);
should add a key-value pair to your request header, just make sure to place it after your open()
and before your send()
For anyone who is still having this issue, this worked for me:
cordova platform update android@latest
then build and it will automatically download the newest gradle version and should work
first, you need to load URL helper like this type or you can upload within autoload.php file:
$this->load->helper('url');
if (!$user_logged_in)
{
redirect('/account/login', 'refresh');
}
Here is a more recent discombobulation. Documentation everywhere in angular JS and Pluralsight courses and books on angular, all refer to kebab-case as snake-case, not differentiating between the two.
Its too bad caterpillar-case did not stick because snake_case and caterpillar-case are easily remembered and actually look like what they represent (if you have a good imagination).
In MomentJs We can declare it like :
const start = moment().format('YYYY-MM-DD 00:00:01');
const end = moment().format('YYYY-MM-DD 23:59:59');
Threads share the same memory space to guarantee that two threads don't share the same memory location so special precautions must be taken the CPython interpreter handles this using a mechanism called GIL
, or the Global Interpreter Lock
what is GIL(Just I want to Clarify GIL it's repeated above)?
In CPython, the global interpreter lock, or GIL, is a mutex that protects access to Python objects, preventing multiple threads from executing Python bytecodes at once. This lock is necessary mainly because CPython's memory management is not thread-safe.
For the main question, we can compare using Use Cases, How?
1-Use Cases for Threading: in case of GUI programs threading can be used to make the application responsive For example, in a text editing program, one thread can take care of recording the user inputs, another can be responsible for displaying the text, a third can do spell-checking, and so on. Here, the program has to wait for user interaction. which is the biggest bottleneck. Another use case for threading is programs that are IO bound or network bound, such as web-scrapers.
2-Use Cases for Multiprocessing: Multiprocessing outshines threading in cases where the program is CPU intensive and doesn’t have to do any IO or user interaction.
For More Details visit this link and link or you need in-depth knowledge for threading visit here for Multiprocessing visit here
I'm using Object.keys(chars).map(...)
to loop in render
// chars = {a:true, b:false, ..., z:false}
render() {
return (
<div>
{chars && Object.keys(chars).map(function(char, idx) {
return <span key={idx}>{char}</span>;
}.bind(this))}
"Some text value"
</div>
);
}
I had the same problem on my mac, but in my case, the problem was that I did not run the database (sudo mongod) before; the problem was solved when I first ran the mondo sudod on the console and, once it was done, on another console, the connection to the server ...
As basZero mentioned, X-Forwarded-For should be checked for comma. (Look at : http://en.wikipedia.org/wiki/X-Forwarded-For). The general format of the field is: X-Forwarded-For: clientIP, proxy1, proxy2... and so on. So we will be seeing something like this : X-FORWARDED-FOR: 129.77.168.62, 129.77.63.62.
Take some base date which is the 31st of some month e.g. '20011231'. Then use the
following procedure (I have given 3 identical examples below, only the @dt value differs).
declare @dt datetime;
set @dt = '20140312'
SELECT DATEADD(month, DATEDIFF(month, '20011231', @dt), '20011231');
set @dt = '20140208'
SELECT DATEADD(month, DATEDIFF(month, '20011231', @dt), '20011231');
set @dt = '20140405'
SELECT DATEADD(month, DATEDIFF(month, '20011231', @dt), '20011231');
Perhaps you're asking about the DOM methods appendChild
and insertBefore
.
parentNode.insertBefore(newChild, refChild)
Inserts the node
newChild
as a child ofparentNode
before the existing child noderefChild
. (ReturnsnewChild
.)If
refChild
is null,newChild
is added at the end of the list of children. Equivalently, and more readably, useparentNode.appendChild(newChild)
.
/(?![[:alnum:]]|@|-|_|\.)./
Nowadays, if you use a HTML5 form with type=email
then you're already by 80% safe since browser engines have their own validator. To complement it, add this regex to your preg_match_all()
and negate it:
if (!preg_match_all("/(?![[:alnum:]]|@|-|_|\.)./",$email)) { .. }
Find the regex used by HTML5 forms for validation
https://regex101.com/r/mPEKmy/1
Qt Creator, apart from other goodies, also has a good debugger integration, for CDB, GDB and the Symnbian debugger, on all supported platforms. You don't need to use Qt to use the Qt Creator IDE, nor do you need to use QMake - it also has CMake integration, although QMake is very easy to use.
You may want to use Qt Creator as the IDE to teach programming with, consider it has some good features:
Try to enable the Bypass proxy server for local addresses. This works for all browsers installed (Firefox, Chrome, etc).
Open Internet Explorer by clicking the Start button Picture of the Start button. In the search box, type Internet Explorer, and then, in the list of results, click Internet Explorer.
Click the Tools button, and then click Internet Options.
Click the Connections tab, and then click LAN settings.
Select the Use a proxy server for your LAN check box.
Select the Bypass proxy server for local addresses
There is a great implementation of NavigationDrawer
that follows the Google Material Design Guidelines (and compatible down to API 10) - The MaterialDrawer library (link to GitHub). As of time of writing, May 2017, it's actively supported.
It's available in Maven Central repo. Gradle dependency setup:
compile 'com.mikepenz:materialdrawer:5.9.1'
Maven dependency setup:
<dependency>
<groupId>com.mikepenz</groupId>
<artifactId>materialdrawer</artifactId>
<version>5.9.1</version>
</dependency>
Is there a way in which I can update the plot just by adding more point[s] to it...
There are a number of ways of animating data in matplotlib, depending on the version you have. Have you seen the matplotlib cookbook examples? Also, check out the more modern animation examples in the matplotlib documentation. Finally, the animation API defines a function FuncAnimation which animates a function in time. This function could just be the function you use to acquire your data.
Each method basically sets the data
property of the object being drawn, so doesn't require clearing the screen or figure. The data
property can simply be extended, so you can keep the previous points and just keep adding to your line (or image or whatever you are drawing).
Given that you say that your data arrival time is uncertain your best bet is probably just to do something like:
import matplotlib.pyplot as plt
import numpy
hl, = plt.plot([], [])
def update_line(hl, new_data):
hl.set_xdata(numpy.append(hl.get_xdata(), new_data))
hl.set_ydata(numpy.append(hl.get_ydata(), new_data))
plt.draw()
Then when you receive data from the serial port just call update_line
.
As noted by konyak you can get the list of places mysql will look for your my.cnf
file by running mysqladmin --help
. Since this is pretty verbose you can get to the part you care about quickly with:
$ mysqladmin --help | grep -A1 'Default options'
This will give you output similar to:
Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/local/etc/my.cnf ~/.my.cnf
Depending on how you installed mysql it is possible that none of these files are present yet. You can cat
them in order to see how your config is being built and create your own my.cnf
if needed at your preferred location.
Because performance was really important for me, I benchmarked all the functions above.
NOTE: Data from @Simon O'Hanlon's post. Only with size 15000 instead of 10.
library(tidyverse)
library(microbenchmark)
set.seed(123)
df <- data.frame(id = 1:15000,
nas = rep(NA, 15000),
vals = sample(c(1:3, NA), 15000,
repl = TRUE))
df
MadSconeF1 <- function(x) x[, colSums(is.na(x)) != nrow(x)]
MadSconeF2 <- function(x) x[colSums(!is.na(x)) > 0]
BradCannell <- function(x) x %>% select_if(~sum(!is.na(.)) > 0)
SimonOHanlon <- function(x) x[ , !apply(x, 2 ,function(y) all(is.na(y)))]
jsta <- function(x) janitor::remove_empty(x)
SiboJiang <- function(x) x %>% dplyr::select_if(~!all(is.na(.)))
akrun <- function(x) Filter(function(y) !all(is.na(y)), x)
mbm <- microbenchmark(
"MadSconeF1" = {MadSconeF1(df)},
"MadSconeF2" = {MadSconeF2(df)},
"BradCannell" = {BradCannell(df)},
"SimonOHanlon" = {SimonOHanlon(df)},
"SiboJiang" = {SiboJiang(df)},
"jsta" = {jsta(df)},
"akrun" = {akrun(df)},
times = 1000)
mbm
Results:
Unit: microseconds
expr min lq mean median uq max neval cld
MadSconeF1 154.5 178.35 257.9396 196.05 219.25 5001.0 1000 a
MadSconeF2 180.4 209.75 281.2541 226.40 251.05 6322.1 1000 a
BradCannell 2579.4 2884.90 3330.3700 3059.45 3379.30 33667.3 1000 d
SimonOHanlon 511.0 565.00 943.3089 586.45 623.65 210338.4 1000 b
SiboJiang 2558.1 2853.05 3377.6702 3010.30 3310.00 89718.0 1000 d
jsta 1544.8 1652.45 2031.5065 1706.05 1872.65 11594.9 1000 c
akrun 93.8 111.60 139.9482 121.90 135.45 3851.2 1000 a
autoplot(mbm)
mbm %>%
tbl_df() %>%
ggplot(aes(sample = time)) +
stat_qq() +
stat_qq_line() +
facet_wrap(~expr, scales = "free")
Use a custom comparator:
Collections.sort(nodeList, new Comparator<DataNode>(){
public int compare(DataNode o1, DataNode o2){
if(o1.degree == o2.degree)
return 0;
return o1.degree < o2.degree ? -1 : 1;
}
});
Here's a quick overview that explains the different build targets.
From my own experience, if you're looking to build a project that will run on both x86 and x64 platforms, and you don't have any specific x64 optimizations, I'd change the build to specifically say "x86."
The reason for this is sometimes you can get some DLL files that collide or some code that winds up crashing WoW in the x64 environment. By specifically specifying x86, the x64 OS will treat the application as a pure x86 application and make sure everything runs smoothly.
You can use a For Each to iterate through all the cells in a defined range.
Public Sub IterateThroughRange()
Dim wb As Workbook
Dim ws As Worksheet
Dim rng As Range
Dim cell As Range
Set wb = Application.Workbooks(1)
Set ws = wb.Sheets(1)
Set rng = ws.Range("A1", "C3")
For Each cell In rng.Cells
cell.Value = cell.Address
Next cell
End Sub
I've got this error when I ran composer install
inside my PHP DOCKER container,
It's a memory issue.
Solved by increasing SWAP memory in DOCKER PREFERENCES from 512MB to 1.5GB
To do that:
Docker -> Preferences -> Rousources
This is a very important question and the answer is very simple, but fundamental:
docker run IMAGE_ID
and not docker run CONTAINER_ID
docker stop CONTAINER_ID
, you can relaunch the same container with the command docker start CONTAINER_ID
, and the data and settings will be the same.If you are going to be getting a random element multiple times, you want to make sure your random number generator is initialized only once.
import java.util.Random;
public class RandArray {
private int[] items = new int[]{1,2,3};
private Random rand = new Random();
public int getRandArrayElement(){
return items[rand.nextInt(items.length)];
}
}
If you are picking random array elements that need to be unpredictable, you should use java.security.SecureRandom rather than Random. That ensures that if somebody knows the last few picks, they won't have an advantage in guessing the next one.
If you are looking to pick a random number from an Object array using generics, you could define a method for doing so (Source Avinash R in Random element from string array):
import java.util.Random;
public class RandArray {
private static Random rand = new Random();
private static <T> T randomFrom(T... items) {
return items[rand.nextInt(items.length)];
}
}
using just the shell,
while read -r col1 col2
do
echo $col2 $col1
done <"file"
I solved the same problem by add android:elevation="1dp"
to which view you want it over another. But it can't display below 5.0, and it will have a little shadow, if you can accept it, it's OK.
So, the most correct solution which is @kcoppock said.
Since you're using PHP, you will probably need to use the CURLOPT_PORT
option, like so:
curl_setopt($ch, CURLOPT_PORT, 11740);
Bear in mind, you may face problems with SELinux:
I have a plunker that adds it to the string prototype: string.format It is not just as short as some of the other examples, but a lot more flexible.
Usage is similar to c# version:
var str2 = "Meet you on {0}, ask for {1}";
var result2 = str2.format("Friday", "Suzy");
//result: Meet you on Friday, ask for Suzy
//NB: also accepts an array
Also, added support for using names & object properties
var str1 = "Meet you on {day}, ask for {Person}";
var result1 = str1.format({day: "Thursday", person: "Frank"});
//result: Meet you on Thursday, ask for Frank
I had the same issue on a brand new Windows 10 machine. My setup:
But I couldn't build .NET 4.0 projects:
Die Aufgabe konnte "AL.exe" mit dem SdkToolsPath-Wert "" oder dem Registrierungsschlüssel "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v8.0A\WinSDK-NetFx40Tools-x86
Solution: After trying (and failing) to install the Windows 7 SDK (because thats also includes the .NET 4.0 SDK) I needed to install the Windows 8 SDK and make sure the ".NET Framework 4.5 SDK" is installed.
It's crazy... but worked.
Try the -fno-stack-protector
flag.
Here's a rehashing of some other so-called "cop out" answers. There are situations in which simply throwing away the troublesome characters/strings is a good solution, despite the protests voiced here.
def safeStr(obj):
try: return str(obj)
except UnicodeEncodeError:
return obj.encode('ascii', 'ignore').decode('ascii')
except: return ""
Testing it:
if __name__ == '__main__':
print safeStr( 1 )
print safeStr( "test" )
print u'98\xb0'
print safeStr( u'98\xb0' )
Results:
1
test
98°
98
UPDATE: My original answer was written for Python 2. For Python 3:
def safeStr(obj):
try: return str(obj).encode('ascii', 'ignore').decode('ascii')
except: return ""
Note: if you'd prefer to leave a ?
indicator where the "unsafe" unicode characters are, specify replace
instead of ignore
in the call to encode for the error handler.
Suggestion: you might want to name this function toAscii
instead? That's a matter of preference...
Finally, here's a more robust PY2/3 version using six
, where I opted to use replace
, and peppered in some character swaps to replace fancy unicode quotes and apostrophes which curl left or right with the simple vertical ones that are part of the ascii set. You might expand on such swaps yourself:
from six import PY2, iteritems
CHAR_SWAP = { u'\u201c': u'"'
, u'\u201D': u'"'
, u'\u2018': u"'"
, u'\u2019': u"'"
}
def toAscii( text ) :
try:
for k,v in iteritems( CHAR_SWAP ):
text = text.replace(k,v)
except: pass
try: return str( text ) if PY2 else bytes( text, 'replace' ).decode('ascii')
except UnicodeEncodeError:
return text.encode('ascii', 'replace').decode('ascii')
except: return ""
if __name__ == '__main__':
print( toAscii( u'testin\u2019' ) )
Now, there's also another option for any general csv file: https://github.com/seahboonsiew/pyspark-csv as follows:
Assume we have the following context
sc = SparkContext
sqlCtx = SQLContext or HiveContext
First, distribute pyspark-csv.py to executors using SparkContext
import pyspark_csv as pycsv
sc.addPyFile('pyspark_csv.py')
Read csv data via SparkContext and convert it to DataFrame
plaintext_rdd = sc.textFile('hdfs://x.x.x.x/blah.csv')
dataframe = pycsv.csvToDataFrame(sqlCtx, plaintext_rdd)
Just remove the slash after Data
and prepend the root:
<xsl:variable name="myVarA" select="/root/DataSet/Data[@Value1='2']/@Value2"/>
What you’re looking for is the CSS Sticky Footer.
* {_x000D_
margin: 0;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
html,_x000D_
body {_x000D_
height: 100%;_x000D_
}_x000D_
_x000D_
#wrap {_x000D_
min-height: 100%;_x000D_
}_x000D_
_x000D_
#main {_x000D_
overflow: auto;_x000D_
padding-bottom: 180px;_x000D_
/* must be same height as the footer */_x000D_
}_x000D_
_x000D_
#footer {_x000D_
position: relative;_x000D_
margin-top: -180px;_x000D_
/* negative value of footer height */_x000D_
height: 180px;_x000D_
clear: both;_x000D_
background-color: red;_x000D_
}_x000D_
_x000D_
_x000D_
/* Opera Fix thanks to Maleika (Kohoutec) */_x000D_
_x000D_
body:before {_x000D_
content: "";_x000D_
height: 100%;_x000D_
float: left;_x000D_
width: 0;_x000D_
margin-top: -32767px;_x000D_
/* thank you Erik J - negate effect of float*/_x000D_
}
_x000D_
<div id="wrap">_x000D_
<div id="main"></div>_x000D_
</div>_x000D_
_x000D_
<div id="footer"></div>
_x000D_
Solution for me was (thx to David Ljung Madison post)
adb kill-server
I believe you could do it like this :
var fd = new FormData();
fd.append( 'file', input.files[0] );
$.ajax({
url: 'http://example.com/script.php',
data: fd,
processData: false,
contentType: false,
type: 'POST',
success: function(data){
alert(data);
}
});
Notes:
Setting processData
to false
lets you prevent jQuery from automatically transforming the data into a query string. See the docs for more info.
Setting the contentType
to false
is imperative, since otherwise jQuery will set it incorrectly.
How about this?
for item in mylist:
if item in checklist:
pass
else:
# do something
print item
X <- data.frame(Variable1=c(11,14,12,15),Variable2=c(2,3,1,4))
> X
Variable1 Variable2
1 11 2
2 14 3
3 12 1
4 15 4
> X[X$Variable1!=11 & X$Variable1!=12, ]
Variable1 Variable2
2 14 3
4 15 4
> X[ ! X$Variable1 %in% c(11,12), ]
Variable1 Variable2
2 14 3
4 15 4
You can functionalize this however you like.
Instead of client-side geocoding
geocoder.geocode({
'address': your_address
}, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var geo_data = results[0];
// your code ...
}
})
I would go to server-side geocoding API
var apikey = YOUR_API_KEY;
var query = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + address + '&key=' + apikey;
$.getJSON(query, function (data) {
if (data.status === 'OK') {
var geo_data = data.results[0];
}
})
var upload = multer({dest: "./uploads"});
var mongo = require('mongodb');
var Grid = require("gridfs-stream");
Grid.mongo = mongo;
router.post('/:id', upload.array('photos', 200), function(req, res, next){
gfs = Grid(db);
var ss = req.files;
for(var j=0; j<ss.length; j++){
var originalName = ss[j].originalname;
var filename = ss[j].filename;
var writestream = gfs.createWriteStream({
filename: originalName
});
fs.createReadStream("./uploads/" + filename).pipe(writestream);
}
});
In your view:
<form action="/" method="post" enctype="multipart/form-data">
<input type="file" name="photos">
With this code you can add single as well as multiple images in MongoDB.
This will never work, because the JS VM has moved on from that async_call and returned the value, which you haven't set yet.
Don't try to fight what is natural and built-in the language behaviour. You should use a callback technique or a promise.
function f(input, callback) {
var value;
// Assume the async call always succeed
async_call(input, function(result) { callback(result) };
}
The other option is to use a promise, have a look at Q. This way you return a promise, and then you attach a then listener to it, which is basically the same as a callback. When the promise resolves, the then will trigger.
You may need to do AndroidStudio - Build - Clean
If you updated manifest through the filesystem or Git it won't pick up the changes.
Right-click on an aspx file and choose 'browse with'. I think there's an option there to set as default.
There is a library for this purpose: https://github.com/bestiejs/platform.js#readme
Then you can use it this way
// example 1
platform.os; // 'Windows Server 2008 R2 / 7 x64'
// example 2 on an iPad
platform.os; // 'iOS 5.0'
// you can also access on the browser and some other properties
platform.name; // 'Safari'
platform.version; // '5.1'
platform.product; // 'iPad'
platform.manufacturer; // 'Apple'
platform.layout; // 'WebKit'
// or use the description to put all together
platform.description; // 'Safari 5.1 on Apple iPad (iOS 5.0)'
You can create Class Person
with fields firstName
and lastName
and define method toString()
. Here I created a util method which returns String presentation of a Person
object.
This is a sample
Main
public class Main {
public static void main(String[] args) {
Person person = generatePerson();
String personStr = personToString(person);
System.out.println(personStr);
}
private static Person generatePerson() {
String firstName = "firstName";//generateFirstName();
String lastName = "lastName";//generateLastName;
return new Person(firstName, lastName);
}
/*
You can even put this method into a separate util class.
*/
private static String personToString(Person person) {
return person.getFirstName() + "\n" + person.getLastName();
}
}
Person
public class Person {
private String firstName;
private String lastName;
//getters, setters, constructors.
}
I prefer a separate util method to toString()
, because toString()
is used for debug.
https://stackoverflow.com/a/3615741/4587961
I had experience writing programs with many outputs: HTML UI, excel or txt file, console. They may need different object presentation, so I created a util class which builds a String depending on the output.
If you need to print an approximate representation of the string to the screen, rather than ignoring those nonprintable characters, please try unidecode
package here:
https://pypi.python.org/pypi/Unidecode
The explanation is found here:
https://www.tablix.org/~avian/blog/archives/2009/01/unicode_transliteration_in_python/
This is better than using the u.encode('ascii', 'ignore')
for a given string u
, and can save you from unnecessary headache if character precision is not what you are after, but still want to have human readability.
Wirawan
You can create a closure and pass it that way here is my example working
$.get('https://data.seattle.gov/resource/3k2p-39jp.json?$limit=10&$where=within_circle(incident_location, 47.594972, -122.331518, 1609.34)',
function(responce) {
var filter = 'event_clearance_group', //sort by key group name
data = responce;
var compare = function (filter) {
return function (a,b) {
var a = a[filter],
b = b[filter];
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
};
};
filter = compare(filter); //set filter
console.log(data.sort(filter));
});
Actually, jQuery has a built in trim function:
var emailAdd = jQuery.trim($(this).text());
See here for details.
Lot's of different ways to do this, but my favorite is simply typing 'exit' on the bash prompt.
Put the control you want to bring to front at the end of your xaml code. I.e.
<Grid>
<TabControl ...>
</TabControl>
<Button Content="ALways on top of TabControl Button"/>
</Grid>
This seems to be an issue with local Maven repository. (i.e. .m2 folder) may be due to some corrupt .jar file
For me, the following actions helped to overcome this issue.
On my local file system, I've deleted the directory .m2 (Maven local repository)
In Eclipse, updated the project (select Maven > Update Project)
Ran the app again on Tomcat server.
Using styling from CSS, you can define how something is positioned. If you define the element as fixed, it will always remain in the same position on the screen at all times.
div
{
position:fixed;
top:20px;
}
From man curl
:
-x, --proxy <[protocol://][user:password@]proxyhost[:port]>
Use the specified HTTP proxy.
If the port number is not specified, it is assumed at port 1080.
General way:
export http_proxy=http://your.proxy.server:port/
Then you can connect through proxy from (many) application.
And, as per comment below, for https:
export https_proxy=https://your.proxy.server:port/
Use lambda expression:
df[df.apply(lambda x: x['col1'] != x['col2'], axis = 1)]
Stegmenn nalied it for me but I had one change for when you have an IEnumerbale instead of a string = message like in his example.
private static string GetRoles(IEnumerable<External.Role> roles)
{
string[] switchStrings = { "Staff", "Board Member" };
switch (switchStrings.FirstOrDefault<string>(s => roles.Select(t => t.RoleName).Contains(s)))
{
case
"Staff":
roleNameValues += "Staff,";
break;
case
"Board Member":
roleNameValues += "Director,";
break;
default:
break;
}
If you know the app id of the package (like org.mozilla.firefox), it is easy. First to get the path of actual package file of the appId,
$ adb shell pm list packages -f com.google.android.apps.inbox
package:/data/app/com.google.android.apps.inbox-1/base.apk=com.google.android.apps.inbox
Now you can do some grep|sed magic to extract the path : /data/app/com.google.android.apps.inbox-1/base.apk
After that aapt tool comes in handy :
$ adb shell aapt dump badging /data/app/com.google.android.apps.inbox-1/base.apk
...
application-label:'Inbox'
application-label-hi:'Inbox'
application-label-ru:'Inbox'
...
Again some grep magic to get the Label.
Please use this at class level for the bean:
@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler","fieldHandler"})
The schema definition for an attribute determines whether an attribute must have a value. If the manager
attribute in the example given is the attribute defined in RFC4524 with OID 0.9.2342.19200300.100.1.10
, then that attribute has DN syntax. DN syntax is a sequence of relative distinguished names and must not be empty. The filter given in the example is used to cause the LDAP directory server to return only entries that do not have a manager
attribute to the LDAP client in the search result.
"Segmentation fault" means that you tried to access memory that you do not have access to.
The first problem is with your arguments of main
. The main
function should be int main(int argc, char *argv[])
, and you should check that argc
is at least 2 before accessing argv[1]
.
Also, since you're passing in a float
to printf
(which, by the way, gets converted to a double
when passing to printf
), you should use the %f
format specifier. The %s
format specifier is for strings ('\0'
-terminated character arrays).
If you're going to raise an exception, you might raise a StopIteration exception. That will at least make the intent obvious.
You need to add a reference to System.Drawing.dll
.
As mentioned in the comments below this can be done as follows: In your Solution Explorer (Where all the files are shown with your project), right click the "References" folder and find System.Drawing on the .NET Tab.
Following are the differences/advantages:
Constraint Layout has dual power of both Relative Layout as well as Linear layout: Set relative positions of views ( like Relative layout ) and also set weights for dynamic UI (which was only possible in Linear Layout).
A very powerful use is grouping of elements by forming a chain. This way we can form a group of views which as a whole can be placed in a desired way without adding another layer of hierarchy just to form another group of views.
In addition to weights, we can apply horizontal and vertical bias which is nothing but the percentage of displacement from the centre. ( bias of 0.5 means centrally aligned. Any value less or more means corresponding movement in the respective direction ) .
Another very important feature is that it respects and provides the functionality to handle the GONE views so that layouts do not break if some view is set to GONE through java code. More can be found here: https://developer.android.com/reference/android/support/constraint/ConstraintLayout.html#VisibilityBehavior
Provides power of automatic constraint applying by the use of Blue print and Visual Editor tool which makes it easy to design a page.
All these features lead to flattening of the view hierarchy which improves performance and also helps in making responsive and dynamic UI which can more easily adapt to different screen size and density.
Here is the best place to learn quickly: https://codelabs.developers.google.com/codelabs/constraint-layout/#0
For when you want a 1-liner
while( -not ( ($choice= (Read-Host "May I continue?")) -match "y|n")){ "Y or N ?"}
Assuming the question is about cleaning the workspace of the current job, you can run:
test -n "$WORKSPACE" && rm -rf "$WORKSPACE"/*
Are you running a 64 bit system with the database running 32 bit but the console running 64 bit? There are no MS Access drivers that run 64 bit and would report an error identical to the one your reported.
Your code works for me. When does addSalespersonOption
get called? There may be a problem with that call.
Also some of your html is a bit off (maybe copy/paste problem?), but that didn't seem to cause any problems. Your select should look like this:
<select id="salesperson">
<option value="">(select)</option>
</select>
instead of this:
<select id="salesperson" />
<option value"">(select)</option>
</select>
Edit: When does your options list get dynamically populated? Are you sure you are passing 'on'
for the defSales
value in your call to addSalespersonOption
? Try changing that code to this:
if (selected == "on") {
alert('setting default selected option to ' + text);
html = '<option value="'+value+'" selected="selected">'+text+'</option>';
}
and see if the alert happens and what is says if it does happen.
Edit: Working example of my testing (the error:undefined is from jsbin, not my code).
To replace commas with newline characters use this formula (assuming that the text to be altered is in cell A1):
=SUBSTITUTE(A1,",",CHAR(10))
You may have to then alter the row height to see all of the values in the cell
I've left a comment about the other part of your question
Edit: here's a screenshot of this working - I had to turn on "Wrap Text" in the "Format Cells" dialog.
dear friend, Jon Skeet said you can find character Decimal codebut it is not character Hex code as it should mention in unicode, so you should represent character codes via HexCode not in Deciaml.
there is an open source tool at http://unicode.codeplex.com that provides complete information about a characer or a sentece.
so it is better to create a parser that give a char as a parameter and return ahexCode as string
public static String GetHexCode(char character)
{
return String.format("{0:X4}", GetDecimal(character));
}//end
hope it help
You have to use the date part fetching method:
SELECT * FROM testbed WHERE start_date ::date >= to_date('2012-09-08' ,'YYYY-MM-DD') and date::date <= to_date('2012-10-09' ,'YYYY-MM-DD')
Adding an answer because I was directed here after asking how to run a bash script from python. You receive an error OSError: [Errno 2] file not found
if your script takes in parameters. Lets say for instance your script took in a sleep time parameter: subprocess.call("sleep.sh 10")
will not work, you must pass it as an array: subprocess.call(["sleep.sh", 10])
Change your gradle version in project setting: If you are using mac,click File->Project structure,then change gradle version,here:
And check your build.gradle of project,change dependency of gradle,like this:
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.0.1'
}
}
In my case, I found out by using "mb_convert_encoding" that the previous encoding was iso-8859-1 (which is latin1) then I fixed my problem by using an sql query :
UPDATE myDB.myTable SET myColumn = CAST(CAST(CONVERT(myColumn USING latin1) AS binary) AS CHAR)
However, it is stated in the mysql documentations that conversion may be lossy if the column contains characters that are not in both character sets.
Guys in my case none of the solutions above worked.
I had to delete the files within the Project workspace:
And the folder:
Then I copied the ones from a similar project that was working before. This managed to fix my broken project.
Of course do not use this method before trying the previous alternatives!.
I found that doing it in two relatively simple steps seemed to work quite well. The first css definition for ul sets the base indent that you want for the list as a whole. The second definition sets the indent value for each nested list item within it. In my case they are the same, but you can obviously pick whatever you want.
ul {
margin-left: 1.5em;
}
ul > ul {
margin-left: 1.5em;
}
No, you're creating an array, but there's a big difference:
char *string = "Some CONSTANT string";
printf("%c\n", string[1]);//prints o
string[1] = 'v';//INVALID!!
The array is created in a read only part of memory, so you can't edit the value through the pointer, whereas:
char string[] = "Some string";
creates the same, read only, constant string, and copies it to the stack array. That's why:
string[1] = 'v';
Is valid in the latter case.
If you write:
char string[] = {"some", " string"};
the compiler should complain, because you're constructing an array of char arrays (or char pointers), and assigning it to an array of chars. Those types don't match up. Either write:
char string[] = {'s','o','m', 'e', ' ', 's', 't','r','i','n','g', '\o'};
//this is a bit silly, because it's the same as char string[] = "some string";
//or
char *string[] = {"some", " string"};//array of pointers to CONSTANT strings
//or
char string[][10] = {"some", " string"};
Where the last version gives you an array of strings (arrays of chars) that you actually can edit...
The javascript array has a constructor that accepts the length of the array:
let arr = new Array<number>(3);
console.log(arr); // [undefined × 3]
However, this is just the initial size, there's no restriction on changing that:
arr.push(5);
console.log(arr); // [undefined × 3, 5]
Typescript has tuple types which let you define an array with a specific length and types:
let arr: [number, number, number];
arr = [1, 2, 3]; // ok
arr = [1, 2]; // Type '[number, number]' is not assignable to type '[number, number, number]'
arr = [1, 2, "3"]; // Type '[number, number, string]' is not assignable to type '[number, number, number]'
the same problem occurs to me...
I check the file wrx permissions with:
$ls -l ./gradlew
-> -rw-rw-r-- (no execute permission)
so I use command $chmod +x ./gradlew
and this problem solved.
First of all I'd like to say that I 100% agree with John Saunders that you must avoid loops in SQL in most cases especially in production.
But occasionally as a one time thing to populate a table with a hundred records for testing purposes IMHO it's just OK to indulge yourself to use a loop.
For example in your case to populate your table with records with hospital ids between 16 and 100 and make emails and descriptions distinct you could've used
CREATE PROCEDURE populateHospitals
AS
DECLARE @hid INT;
SET @hid=16;
WHILE @hid < 100
BEGIN
INSERT hospitals ([Hospital ID], Email, Description)
VALUES(@hid, 'user' + LTRIM(STR(@hid)) + '@mail.com', 'Sample Description' + LTRIM(STR(@hid)));
SET @hid = @hid + 1;
END
And result would be
ID Hospital ID Email Description
---- ----------- ---------------- ---------------------
1 16 [email protected] Sample Description16
2 17 [email protected] Sample Description17
...
84 99 [email protected] Sample Description99
Two files: 1) An app.config or web.config file. The settings her can be customized after build with a text editer. 2) The settings.designer.cs file. This file has autogenerated code to load the setting from the config file, but a default value is also present in case the config file does not have the particular setting.
Just in case it helps someone, since these questions (and answers) helped me really much; I decided to create an alias that runs these 4 commands in a row:
Just add the following line to your ~/.bashrc
file (modify the main
keyword accordingly to the name of your .tex
and .bib
files)
alias texbib = 'pdflatex main.tex && bibtex main && pdflatex main.tex && pdflatex main.tex'
And now, by just executing the texbib
command (alias), all these commands will be executed sequentially.
Difference between 'true XHTML', 'faux XHTML' and HTML as well as importance of the server-sent MIME type had been already described here well. If you want to try it out right now, here is simple editable snippet with live preview including self-closed script tag for capable browsers:
div { display: flex; }_x000D_
div + div {flex-direction: column; }
_x000D_
<div>Mime type: <label><input type="radio" onchange="t.onkeyup()" id="x" checked name="mime"> application/xhtml+xml</label>_x000D_
<label><input type="radio" onchange="t.onkeyup()" name="mime"> text/html</label></div>_x000D_
<div><textarea id="t" rows="4" _x000D_
onkeyup="i.src='data:'+(x.checked?'application/xhtml+xml':'text/html')+','+encodeURIComponent(t.value)"_x000D_
><?xml version="1.0"?>_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"_x000D_
[<!ENTITY x "true XHTML">]>_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<body>_x000D_
<p>_x000D_
<span id="greet" swapto="Hello">Hell, NO :(</span> &x;._x000D_
<script src="data:text/javascript,(g=document.getElementById('greet')).innerText=g.getAttribute('swapto')" />_x000D_
Nice to meet you!_x000D_
<!-- _x000D_
Previous text node and all further content falls into SCRIPT element content in text/html mode, so is not rendered. Because no end script tag is found, no script runs in text/html_x000D_
-->_x000D_
</p>_x000D_
</body>_x000D_
</html></textarea>_x000D_
_x000D_
<iframe id="i" height="80"></iframe>_x000D_
_x000D_
<script>t.onkeyup()</script>_x000D_
</div>
_x000D_
You should see Hello, true XHTML. Nice to meet you!
below textarea.
For incapable browsers you can copy content of the textarea and save it as a file with .xhtml
(or .xht
) extension (thanks Alek for this hint).
None of the above worked for me. My database didn't show any active connections using Activity Monitor or sp_who. I ultimately had to:
Not the most elegant solution but it works and it doesn't require restarting SQL Server (not an option for me, since the DB server hosted a bunch of other databases)
DataRow has a method that is called IsNull()
that you can use to test the column if it has a null value - regarding to the null as it's seen by the database.
DataRow["col"]==null
will allways be false
.
use
DataRow r;
if (r.IsNull("col")) ...
instead.
After following @Neelam Verma's answer or @dawid's answer, which has the same end result as @Neelam Verma's answer, difference being that @dawid's answer starts with the drag and drop of the file into the Xcode project and @Neelam Verma's answer starts with a file already a part of the Xcode project, I still could not get NSBundle.mainBundle().pathForResource("file-title", ofType:"type")
to find my video file.
I thought maybe because I had my file was in a Group nested in the Xcode project that this was the cause, so I moved the video file to the root of my Xcode project, still no luck, this was my code:
guard let path = NSBundle.mainBundle().pathForResource("testVid1", ofType:"mp4") else {
print("Invalid video path")
return
}
Originally, this was the name of my file: testVid1.MP4
, renaming the video file to testVid1.mp4
fixed my issue, so, at least the ofType
string argument is case sensitive.
Add this annotation in main java file
@EnableAutoConfiguration(exclude=DataSourceAutoConfiguration.class)
You forget to enable your service in Developer console.
In Xcode Version 6.1.1 (6A2008a), after "Processing Symbol Files", a folder containing symbols associated with the device (including iOS version and CPU type) was created in ~/Library/Developer/Xcode/iOS DeviceSupport/ like this:
To avoid this sort of trouble, you can use replace
(which takes a plain string) instead of replaceAll
(which takes a regular expression). You will still need to escape backslashes, but not in the wild ways required with regular expressions.
All the above solutions require two database calls. The below sql code combine two sql statements into one.
select * from foo
where (
id = IFNULL((select min(id) from foo where id > 4),0)
or id = IFNULL((select max(id) from foo where id < 4),0)
)
Create Bean for Rest Template to auto wiring the Rest Template object.
@SpringBootApplication
public class ChatAppApplication {
@Bean
public RestTemplate getRestTemplate(){
return new RestTemplate();
}
public static void main(String[] args) {
SpringApplication.run(ChatAppApplication.class, args);
}
}
Consume the GET/POST API by using RestTemplate - exchange() method. Below is for the post api which is defined in the controller.
@RequestMapping(value = "/postdata",method = RequestMethod.POST)
public String PostData(){
return "{\n" +
" \"value\":\"4\",\n" +
" \"name\":\"David\"\n" +
"}";
}
@RequestMapping(value = "/post")
public String getPostResponse(){
HttpHeaders headers=new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity=new HttpEntity<String>(headers);
return restTemplate.exchange("http://localhost:8080/postdata",HttpMethod.POST,entity,String.class).getBody();
}
Refer this tutorial[1]
[1] https://www.tutorialspoint.com/spring_boot/spring_boot_rest_template.htm
I need the collection length to decide whether I should render table <thead></thead>
but don't know why @Django 2.1.7 the chosen answer will fail(empty) my forloop
afterward.
I got to use {% if forloop.first %} {% endif %}
to overcome:
<table>
{% for record in service_list %}
{% if forloop.first %}
<thead>
<tr>
<th>??</th>
</tr>
</thead>
{% endif %}
<tbody>
<tr>
<td>{{ record.date }}</td>
</tr>
{% endfor %}
</tbody>
</table>
There is also xclip-copyfile.
pandas read_csv method is great for parsing dates. Complete documentation at http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html
you can even have the different date parts in different columns and pass the parameter:
parse_dates : boolean, list of ints or names, list of lists, or dict
If True -> try parsing the index. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a
separate date column. If [[1, 3]] -> combine columns 1 and 3 and parse as a single date
column. {‘foo’ : [1, 3]} -> parse columns 1, 3 as date and call result ‘foo’
The default sensing of dates works great, but it seems to be biased towards north american Date formats. If you live elsewhere you might occasionally be caught by the results. As far as I can remember 1/6/2000 means 6 January in the USA as opposed to 1 Jun where I live. It is smart enough to swing them around if dates like 23/6/2000 are used. Probably safer to stay with YYYYMMDD variations of date though. Apologies to pandas developers,here but i have not tested it with local dates recently.
you can use the date_parser parameter to pass a function to convert your format.
date_parser : function
Function to use for converting a sequence of string columns to an array of datetime
instances. The default uses dateutil.parser.parser to do the conversion.
In case a virus scanner (like McAfee) is running, try:
In MVP the view draws data from the presenter which draws and prepares/normalizes data from the model while in MVC the controller draws data from the model and set, by push in the view.
In MVP you can have a single view working with multiple types of presenters and a single presenter working with different multiple views.
MVP usually uses some sort of a binding framework, such as Microsoft WPF binding framework or various binding frameworks for HTML5 and Java.
In those frameworks, the UI/HTML5/XAML, is aware of what property of the presenter each UI element displays, so when you bind a view to a presenter, the view looks for the properties and knows how to draw data from them and how to set them when a value is changed in the UI by the user.
So, if for example, the model is a car, then the presenter is some sort of a car presenter, exposes the car properties (year, maker, seats, etc.) to the view. The view knows that the text field called 'car maker' needs to display the presenter Maker property.
You can then bind to the view many different types of presenter, all must have Maker property - it can be of a plane, train or what ever , the view doesn't care. The view draws data from the presenter - no matter which - as long as it implements an agreed interface.
This binding framework, if you strip it down, it's actually the controller :-)
And so, you can look on MVP as an evolution of MVC.
MVC is great, but the problem is that usually its controller per view. Controller A knows how to set fields of View A. If now, you want View A to display data of model B, you need Controller A to know model B, or you need Controller A to receive an object with an interface - which is like MVP only without the bindings, or you need to rewrite the UI set code in Controller B.
Conclusion - MVP and MVC are both decouple of UI patterns, but MVP usually uses a bindings framework which is MVC underneath. THUS MVP is at a higher architectural level than MVC and a wrapper pattern above of MVC.
As an extra thought, if is needed to pass the column name unquoted to the custom function, perhaps match.call()
could be useful as well in this case, as an alternative to deparse(substitute())
:
df <- data.frame(A = 1:10, B = 2:11)
fun <- function(x, column){
arg <- match.call()
max(x[[arg$column]])
}
fun(df, A)
#> [1] 10
fun(df, B)
#> [1] 11
If there is a typo in the column name, then would be safer to stop with an error:
fun <- function(x, column) max(x[[match.call()$column]])
fun(df, typo)
#> Warning in max(x[[match.call()$column]]): no non-missing arguments to max;
#> returning -Inf
#> [1] -Inf
# Stop with error in case of typo
fun <- function(x, column){
arg <- match.call()
if (is.null(x[[arg$column]])) stop("Wrong column name")
max(x[[arg$column]])
}
fun(df, typo)
#> Error in fun(df, typo): Wrong column name
fun(df, A)
#> [1] 10
Created on 2019-01-11 by the reprex package (v0.2.1)
I do not think I would use this approach since there is extra typing and complexity than just passing the quoted column name as pointed in the above answers, but well, is an approach.
In order to reset the value in angular 2 use:
this.rootNode.findNode("objectname").resetValue();
You can use this code:
def is_valid(string):
words = string.split('_')
for word in words:
if not word.istitle():
return False, word
return True, words
x="Alpha_beta_Gamma"
assert is_valid(x)==(False,'beta')
x="Alpha_Beta_Gamma"
assert is_valid(x)==(True,['Alpha', 'Beta', 'Gamma'])
This way you know if is valid and what word is wrong
Its simply means that you have an array of values and you want record except that values/records.
you can simply pass a array into whereNotIn() laravel function.
With query builder
$users = DB::table('applications')
->whereNotIn('id', [1,3,5])
->get(); //will return without applications which contain this id's
With eloquent.
$result = ModelClassName::select('your_column_name')->whereNotIn('your_column_name', ['satatus1', 'satatus2']); //return without application which contain this status.
For info, if you are binding to a class, you can do this in your type via DisplayNameAttribute
:
[DisplayName("Access key")]
public string AccessKey { get {...} set {...} }
Now the header-text on auto-generated columns will be "Access key".
If you check the length seperately, you can do the following:
var regularExpression = /^[a-zA-Z]$/;
if (regularExpression.test(newPassword)) {
alert("password should contain atleast one number and one special character");
return false;
}
<context:component-scan base-package="" />
tells Spring to scan those packages for Annotations.
<mvc:annotation-driven>
registers a RequestMappingHanderMapping, a RequestMappingHandlerAdapter, and an ExceptionHandlerExceptionResolver to support the annotated controller methods like @RequestMapping, @ExceptionHandler, etc. that come with MVC.
This also enables a ConversionService that supports Annotation driven formatting of outputs as well as Annotation driven validation for inputs. It also enables support for @ResponseBody which you can use to return JSON data.
You can accomplish the same things using Java-based Configuration using @ComponentScan(basePackages={"...", "..."} and @EnableWebMvc in a @Configuration class.
Check out the 3.1 documentation to learn more.
http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/mvc.html#mvc-config
Open .eclipseproduct
in the product installation folder. Or open Configuration\config.ini
and check property eclipse.buildId
if exist.
Yes, you can install IPA in iPad, first you have to import that IPA to your itunes. Connect your iPad to iTunes then install application just by click on install and then sync.
You can also do the following:
CREATE TABLE #TEMPTABLE
(
Column1 type1,
Column2 type2,
Column3 type3
)
INSERT INTO #TEMPTABLE
SELECT ...
SELECT *
FROM #TEMPTABLE ...
DROP TABLE #TEMPTABLE
Working syntax for multiple optional params:
<Route path="/section/(page)?/:page?/(sort)?/:sort?" component={Section} />
Now, url can be:
I'm on rails 5.2, and trying to rename a column on a devise User.
the rename_column
bit worked for me, but the singular :table_name
threw a "User table not found" error. Plural worked for me.
rails g RenameAgentinUser
Then change migration file to this:
rename_column :users, :agent?, :agent
Where :agent? is the old column name.
The two errors you have in your code are very different.
The first problem is that you're initializing and populating your Map
in the body of the class without a statement.
You can either have a static Map
and a static {//TODO manipulate Map}
statement in the body of the class, or initialize and populate the Map in a method or in the class' constructor.
The second problem is that you cannot treat a Map
syntactically like an array
, so the statement data["John"] = "Taxi Driver";
should be replaced by data.put("John", "Taxi Driver")
.
If you already have a "John" key in your HashMap
, its value will be replaced with "Taxi Driver".
too many ) parenthesis remove one of them.
I prefer:
def g(x):
y0 = x + 1
y1 = x * 3
y2 = y0 ** y3
return {'y0':y0, 'y1':y1 ,'y2':y2 }
It seems everything else is just extra code to do the same thing.
I'm using Version 4.0.2.15 with Build 15.21
For me I needed this:
UPDATE table_name SET column_name = REPLACE(column_name,"search str","replace str");
Putting t.column_name
in the first argument of replace
did not work.
I had the same question and solved the problem. In my case, the Windows Firewall (not the router) was blocking the V8 machine I/O on the hosting machine.
My guess is that "Evented I/O for V8 Javascript" is the I/O process that node.js communicates to outside world and we need to free it before it can send packets outside of the local computer. After enabling this program to communicate over Windows firewall, I could use any port numbers to listen.
If you use the overflow:hidden
hack on the <body>
element, to get back normal scrolling behavior, you can position a <div>
absolutely inside of the element to get scrolling back with overflow:auto
. I think this is the best option, and it's quite easy to implement using only css!
Or, you can try with jQuery:
$(document).bind(
'touchmove',
function(e) {
e.preventDefault();
}
);
Same in javasrcipt:
document.addEventListener(
'touchmove',
function(e) {
e.preventDefault();
},
false
);
Last option, check ipad safari: disable scrolling, and bounce effect?
I've managed to get this working by the following fix:
//www.youtube.com/embed/_YOUR_VIDEO_CODE_/?vq=hd720
You video should have the hd720 resolution to do so.
I was using the embedding via iframe, BTW. Hope someone will find this helpful.
If you're having troubles accessing your Flask server, deployed using PyCharm, take the following into account:
PyCharm doesn't run your main .py file directly, so any code in if __name__ == '__main__':
won't be executed, and any changes (like app.run(host='0.0.0.0', port=5000)
) won't take effect.
Instead, you should configure the Flask server using Run Configurations, in particular, placing --host 0.0.0.0 --port 5000
into Additional options field.
More about configuring Flask server in PyCharm
You can use LINQ-to-DataSet
with Enumerable.Any
:
String author = "John Grisham";
bool contains = tbl.AsEnumerable().Any(row => author == row.Field<String>("Author"));
Another approach is to use DataTable.Select
:
DataRow[] foundAuthors = tbl.Select("Author = '" + searchAuthor + "'");
if(foundAuthors.Length != 0)
{
// do something...
}
Q: what if we do not know the columns Headers and we want to find if any cell value
PEPSI
exist in any rows'c columns? I can loop it all to find out but is there a better way? –
Yes, you can use this query:
DataColumn[] columns = tbl.Columns.Cast<DataColumn>().ToArray();
bool anyFieldContainsPepsi = tbl.AsEnumerable()
.Any(row => columns.Any(col => row[col].ToString() == "PEPSI"));
For the non-selected radio buttons, flag them as disabled. This prevents them from responding to user input and clearing out the checked radio button. For example:
<input type="radio" name="var" checked="yes" value="Yes"></input>
<input type="radio" name="var" disabled="yes" value="No"></input>
Creating Tags
Git uses two main types of tags: lightweight and annotated.
Annotated Tags:
To create an annotated tag in Git you can just run the following simple commands on your terminal.
$ git tag -a v2.1.0 -m "xyz feature is released in this tag."
$ git tag
v1.0.0
v2.0.0
v2.1.0
The -m denotes message for that particular tag. We can write summary of features which is going to tag here.
Lightweight Tags:
The other way to tag commits is lightweight tag. We can do it in the following way:
$ git tag v2.1.0
$ git tag
v1.0.0
v2.0.0
v2.1.0
Push Tag
To push particular tag you can use below command:
git push origin v1.0.3
Or if you want to push all tags then use the below command:
git push --tags
List all tags:
To list all tags, use the following command.
git tag
Both rebase
(and cherry-pick
) and merge
have their advantages and disadvantages. I argue for merge
here, but it's worth understanding both. (Look here for an alternate, well-argued answer enumerating cases where rebase
is preferred.)
merge
is preferred over cherry-pick
and rebase
for a couple of reasons.
merge
workflow fairly easily. rebase
tends to be considered more advanced. It's best to understand both, but people who do not want to be experts in version control (which in my experience has included many colleagues who are damn good at what they do, but don't want to spend the extra time) have an easier time just merging.Even with a merge-heavy workflow rebase
and cherry-pick
are still useful for particular cases:
merge
is cluttered history. rebase
prevents a long series of commits from being scattered about in your history, as they would be if you periodically merged in others' changes. That is in fact its main purpose as I use it. What you want to be very careful of, is never to rebase
code that you have shared with other repositories. Once a commit is push
ed someone else might have committed on top of it, and rebasing will at best cause the kind of duplication discussed above. At worst you can end up with a very confused repository and subtle errors it will take you a long time to ferret out.cherry-pick
is useful for sampling out a small subset of changes from a topic branch you've basically decided to discard, but realized there are a couple of useful pieces on.As for preferring merging many changes over one: it's just a lot simpler. It can get very tedious to do merges of individual changesets once you start having a lot of them. The merge resolution in git (and in Mercurial, and in Bazaar) is very very good. You won't run into major problems merging even long branches most of the time. I generally merge everything all at once and only if I get a large number of conflicts do I back up and re-run the merge piecemeal. Even then I do it in large chunks. As a very real example I had a colleague who had 3 months worth of changes to merge, and got some 9000 conflicts in 250000 line code-base. What we did to fix is do the merge one month's worth at a time: conflicts do not build up linearly, and doing it in pieces results in far fewer than 9000 conflicts. It was still a lot of work, but not as much as trying to do it one commit at a time.
Even though this answer does elaborate on returning a recordset from a stored procedure, I am posting here, because it took me ages to figure it out and this thread helped me.
My application was using Eclipselink-2.3.1, but I will force an upgrade to Eclipselink-2.5.0, as JPA 2.1 has much better support for stored procedures.
This method requires imports of EclipseLink classes from "org.eclipse.persistence", so it is specific to Eclipselink implementation.
I found it at "http://www.yenlo.nl/en/calling-oracle-stored-procedures-from-eclipselink-with-multiple-out-parameters".
StoredProcedureCall storedProcedureCall = new StoredProcedureCall();
storedProcedureCall.setProcedureName("mypackage.myprocedure");
storedProcedureCall.addNamedArgument("i_input_1"); // Add input argument name.
storedProcedureCall.addNamedOutputArgument("o_output_1"); // Add output parameter name.
DataReadQuery query = new DataReadQuery();
query.setCall(storedProcedureCall);
query.addArgument("i_input_1"); // Add input argument names (again);
List<Object> argumentValues = new ArrayList<Object>();
argumentValues.add("valueOf_i_input_1"); // Add input argument values.
JpaEntityManager jpaEntityManager = (JpaEntityManager) getEntityManager();
Session session = jpaEntityManager.getActiveSession();
List<?> results = (List<?>) session.executeQuery(query, argumentValues);
DatabaseRecord record = (DatabaseRecord) results.get(0);
String result = String.valueOf(record.get("o_output_1")); // Get output parameter
This method is implementation independent (don't need Eclipslink imports).
StoredProcedureQuery query = getEntityManager().createStoredProcedureQuery("mypackage.myprocedure");
query.registerStoredProcedureParameter("i_input_1", String.class, ParameterMode.IN);
query.registerStoredProcedureParameter("o_output_1", String.class, ParameterMode.OUT);
query.setParameter("i_input_1", "valueOf_i_input_1");
boolean queryResult = query.execute();
String result = String.valueOf(query.getOutputParameterValue("o_output_1"));
I don't know the logging module very well, but I'm using it in the way that I usually want to disable only debug (or info) messages. You can use Handler.setLevel()
to set the logging level to CRITICAL or higher.
Also, you could replace sys.stderr and sys.stdout by a file open for writing. See http://docs.python.org/library/sys.html#sys.stdout. But I wouldn't recommend that.
Docker Compose has been updated. They now have a version 2 file format.
Version 2 files are supported by Compose 1.6.0+ and require a Docker Engine of version 1.10.0+.
They now support the networking feature of Docker which when run sets up a default network called myapp_default
From their documentation your file would look something like the below:
version: '2'
services:
web:
build: .
ports:
- "8000:8000"
fpm:
image: phpfpm
nginx
image: nginx
As these containers are automatically added to the default myapp_default network they would be able to talk to each other. You would then have in the Nginx config:
fastcgi_pass fpm:9000;
Also as mentioned by @treeface in the comments remember to ensure PHP-FPM is listening on port 9000, this can be done by editing /etc/php5/fpm/pool.d/www.conf
where you will need listen = 9000
.
I have kept the below here for those using older version of Docker/Docker compose and would like the information.
I kept stumbling upon this question on google when trying to find an answer to this question but it was not quite what I was looking for due to the Q/A emphasis on docker-compose (which at the time of writing only has experimental support for docker networking features). So here is my take on what I have learnt.
Docker has recently deprecated its link feature in favour of its networks feature
Therefore using the Docker Networks feature you can link containers by following these steps. For full explanations on options read up on the docs linked previously.
First create your network
docker network create --driver bridge mynetwork
Next run your PHP-FPM container ensuring you open up port 9000 and assign to your new network (mynetwork
).
docker run -d -p 9000 --net mynetwork --name php-fpm php:fpm
The important bit here is the --name php-fpm
at the end of the command which is the name, we will need this later.
Next run your Nginx container again assign to the network you created.
docker run --net mynetwork --name nginx -d -p 80:80 nginx:latest
For the PHP and Nginx containers you can also add in --volumes-from
commands etc as required.
Now comes the Nginx configuration. Which should look something similar to this:
server {
listen 80;
server_name localhost;
root /path/to/my/webroot;
index index.html index.htm index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_split_path_info ^(.+\.php)(/.+)$;
fastcgi_pass php-fpm:9000;
fastcgi_index index.php;
include fastcgi_params;
}
}
Notice the fastcgi_pass php-fpm:9000;
in the location block. Thats saying contact container php-fpm
on port 9000
. When you add containers to a Docker bridge network they all automatically get a hosts file update which puts in their container name against their IP address. So when Nginx sees that it will know to contact the PHP-FPM container you named php-fpm
earlier and assigned to your mynetwork
Docker network.
You can add that Nginx config either during the build process of your Docker container or afterwards its up to you.
Try this
Sub Demo()
Dim lngCount As Long
Dim cl As Range
Set cl = ActiveCell
' Open the file dialog
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = True
.Show
' Display paths of each file selected
For lngCount = 1 To .SelectedItems.Count
' Add Hyperlinks
cl.Worksheet.Hyperlinks.Add _
Anchor:=cl, Address:=.SelectedItems(lngCount), _
TextToDisplay:=.SelectedItems(lngCount)
' Add file name
'cl.Offset(0, 1) = _
' Mid(.SelectedItems(lngCount), InStrRev(.SelectedItems(lngCount), "\") + 1)
' Add file as formula
cl.Offset(0, 1).FormulaR1C1 = _
"=TRIM(RIGHT(SUBSTITUTE(RC[-1],""\"",REPT("" "",99)),99))"
Set cl = cl.Offset(1, 0)
Next lngCount
End With
End Sub
In my case, I added below code in dependencies of app level build.gradle
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
After that, I clean the project and rebuild.My problem solved.
You can try this solution.... It works great
function explodeX( $delimiters, $string )
{
return explode( chr( 1 ), str_replace( $delimiters, chr( 1 ), $string ) );
}
$list = 'Thing 1&Thing 2,Thing 3|Thing 4';
$exploded = explodeX( array('&', ',', '|' ), $list );
echo '<pre>';
print_r($exploded);
echo '</pre>';
Source : http://www.phpdevtips.com/2011/07/exploding-a-string-using-multiple-delimiters-using-php/
String fileName = url.substring(url.lastIndexOf('/') + 1);
If I had to guess, you did this:
import datetime
at the top of your code. This means that you have to do this:
datetime.datetime.strptime(date, "%Y-%m-%d")
to access the strptime
method. Or, you could change the import statement to this:
from datetime import datetime
and access it as you are.
The people who made the datetime
module also named their class datetime
:
#module class method
datetime.datetime.strptime(date, "%Y-%m-%d")
There are third-party implementations of interfaces for Python (most popular is Zope's, also used in Twisted), but more commonly Python coders prefer to use the richer concept known as an "Abstract Base Class" (ABC), which combines an interface with the possibility of having some implementation aspects there too. ABCs are particularly well supported in Python 2.6 and later, see the PEP, but even in earlier versions of Python they're normally seen as "the way to go" -- just define a class some of whose methods raise NotImplementedError
so that subclasses will be on notice that they'd better override those methods!-)
Try getPrameterValues()
for getting values from multiple checkboxes.
I simplified your code to isolate the test for "%" being in the cell. Once you get that to work, you can add in the rest of your code.
Try this:
Option Explicit
Sub DoIHavePercentSymbol()
Dim rng As Range
Set rng = ActiveCell
Do While rng.Value <> Empty
If InStr(rng.Value, "%") = 0 Then
MsgBox "I know nothing about percentages!"
Set rng = rng.Offset(1)
rng.Select
Else
MsgBox "I contain a % symbol!"
Set rng = rng.Offset(1)
rng.Select
End If
Loop
End Sub
InStr
will return the number of times your search text appears in the string. I changed your if
test to check for no matches first.
The message boxes and the .Selects
are there simply for you to see what is happening while you are stepping through the code. Take them out once you get it working.
What solved it for me is to set listeners like so:
advertised.listeners = PLAINTEXT://my.public.ip:9092
listeners = PLAINTEXT://0.0.0.0:9092
This makes KAFKA broker listen to all interfaces.
Maybe this will help you learn:
//<![CDATA[_x000D_
/* external.js */_x000D_
var doc, bod, htm, C, E, addClassName, removeClassName; // for use onload elsewhere_x000D_
addEventListener('load', function(){_x000D_
doc = document; bod = doc.body; htm = doc.documentElement;_x000D_
C = function(tag){_x000D_
return doc.createElement(tag);_x000D_
}_x000D_
E = function(id){_x000D_
return doc.getElementById(id);_x000D_
}_x000D_
addClassName = function(element, className){_x000D_
var rx = new RegExp('^(.+\s)*'+className+'(\s.+)*$');_x000D_
if(!element.className.match(rx)){_x000D_
element.className += ' '+className;_x000D_
}_x000D_
return element.className;_x000D_
}_x000D_
removeClassName = function(element, className){_x000D_
element.className = element.className.replace(new RegExp('\s?'+className), '');_x000D_
return element.className;_x000D_
}_x000D_
var out = E('output'), mn = doc.getElementsByClassName('main')[0];_x000D_
out.innerHTML = addClassName(mn, 'wow');_x000D_
out.innerHTML = addClassName(mn, 'cool');_x000D_
out.innerHTML = addClassName(mn, 'it works');_x000D_
out.innerHTML = removeClassName(mn, 'wow');_x000D_
out.innerHTML = removeClassName(mn, 'main');_x000D_
_x000D_
}); // close load_x000D_
//]]>
_x000D_
/* external.css */_x000D_
html,body{_x000D_
padding:0; margin:0;_x000D_
}_x000D_
.main{_x000D_
width:980px; margin:0 auto;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en' lang='en'>_x000D_
<head>_x000D_
<meta http-equiv='content-type' content='text/html;charset=utf-8' />_x000D_
<link type='text/css' rel='stylesheet' href='external.css' />_x000D_
<script type='text/javascript' src='external.js'></script>_x000D_
</head>_x000D_
<body>_x000D_
<div class='main'>_x000D_
<div id='output'></div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
you can use this.
<span [attr.checked]="val? true : false"> </span>
LENGTH()
does return the string length (just verified). I suppose that your data is padded with blanks - try
SELECT typ, LENGTH(TRIM(t1.typ))
FROM AUTA_VIEW t1;
instead.
As OraNob
mentioned, another cause could be that CHAR
is used in which case LENGTH()
would also return the column width, not the string length. However, the TRIM()
approach also works in this case.
signed char
has range -128 to 127; unsigned char
has range 0 to 255.
char
will be equivalent to either signed char or unsigned char, depending on the compiler, but is a distinct type.
If you're using C-style strings, just use char
. If you need to use chars for arithmetic (pretty rare), specify signed or unsigned explicitly for portability.
It's included because your minimum SDK version is set to 10. The ActionBar
was introduced in API 11. Eclipse adds it automatically so your app can look more consistent throughout the spectrum of all android versions you are supporting.
ALTER TABLE TABLENAME ADD FOREIGN KEY (Column Name) REFERENCES TableName(column name)
Example:-
ALTER TABLE Department ADD FOREIGN KEY (EmployeeId) REFERENCES Employee(EmployeeId)
You could do it like this.
JS
var select = document.getElementById('mySelect');
select.onchange = function () {
select.className = this.options[this.selectedIndex].className;
}
CSS
.redText {
background-color:#F00;
}
.greenText {
background-color:#0F0;
}
.blueText {
background-color:#00F;
}
You could use option { background-color: #FFF; }
if you want the list to be white.
HTML
<select id="mySelect" class="greenText">
<option class="greenText" value="apple" >Apple</option>
<option class="redText" value="banana" >Banana</option>
<option class="blueText" value="grape" >Grape</option>
</select>
Since this is a select
it doesn't really make sense to use .yellowText
as none selected if that's what you were getting at as something must be selected.
Maybe useful for anyone else running into this issue: When setting the port on the properties:
props.put("mail.smtp.port", smtpPort);
..make sure to use a string object. Using a numeric (ie Long) object will cause this statement to seemingly have no effect.
var last_selected:IndexPath!
define last_selected:IndexPath inside the class
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let cell = tableView.cellForRow(at: indexPath) as! Cell
cell.contentView.backgroundColor = UIColor.lightGray
cell.txt.textColor = UIColor.red
if(last_selected != nil){
//deselect
let deselect_cell = tableView.cellForRow(at: last_selected) as! Cell
deselect_cell.contentView.backgroundColor = UIColor.white
deselect_cell.txt.textColor = UIColor.black
}
last_selected = indexPath
}
<a href="javaScript:{openPopUp();}"></a>
<form action="actionName">
<div id="divId" style="display:none;">
UsreName:<input type="text" name="userName"/>
</div>
</form>
function openPopUp()
{
$('#divId').css('display','block');
$('#divId').dialog();
}
I had the same issue. Sublime3 no longer shows all of the installed packages when you choose Show Packages from the Preferences Menu.
To customise a colour scheme do the following (UNIX):
--- EDIT ---
For Mac OS X the themes are stored in zipped files so although the preferences file shows them as being in Packages/Color Scheme - Default/ they don't appear in that directory unless you extract them.
for example
"color_scheme": "Packages/Color Scheme - Legacy/myTheme.tmTheme"
It might be that the code in your service somehow breaks out of Angular's zone. This breaks change detection. This should work:
import {Component, OnInit, NgZone} from 'angular2/core';
export class RecentDetectionComponent implements OnInit {
recentDetections: Array<RecentDetection>;
constructor(private zone:NgZone, // <== added
private recentDetectionService: RecentDetectionService) {
this.recentDetections = new Array<RecentDetection>();
}
getRecentDetections(): void {
this.recentDetectionService.getJsonFromApi()
.subscribe(recent => {
this.zone.run(() => { // <== added
this.recentDetections = recent;
console.log(this.recentDetections[0].macAddress)
});
});
}
ngOnInit() {
this.getRecentDetections();
let timer = Observable.timer(2000, 5000);
timer.subscribe(() => this.getRecentDetections());
}
}
For other ways to invoke change detection see Triggering change detection manually in Angular
Alternative ways to invoke change detection are
ChangeDetectorRef.detectChanges()
to immediately run change detection for the current component and its children
ChangeDetectorRef.markForCheck()
to include the current component the next time Angular runs change detection
ApplicationRef.tick()
to run change detection for the whole application
Check if your viewController
has following method:
- (BOOL) tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath {
return NO;
}
if you return "NO" didSelectRow won't be called
Here's a possible way to do it:
$string=exec('getmac');
$mac=substr($string, 0, 17);
echo $mac;
There is no show
event in js - you need to bind your button either to the click
event:
$('#id').on('click', function (e) {
//your awesome code here
})
Mind that if your button is inside a form
, you may prefer to bind the whole form to the submit
event.
FragmentActivity
is part of the support library, while Activity
is the framework's default class. They are functionally equivalent.
You should always use FragmentActivity
and android.support.v4.app.Fragment
instead of the platform default Activity
and android.app.Fragment
classes. Using the platform defaults mean that you are relying on whatever implementation of fragments is used in the device you are running on. These are often multiple years old, and contain bugs that have since been fixed in the support library.
parseInt((new Date('2012.08.10').getTime() / 1000).toFixed(0))
It's important to add the toFixed(0)
to remove any decimals when dividing by 1000 to convert from milliseconds to seconds.
The .getTime()
function returns the timestamp in milliseconds, but true unix timestamps are always in seconds.
Use .toString instead like below:
String myString = myIntegerObject.toString();
Got the error (in the function init) with the following code ;
"use strict" ;
var hdr ;
function init(){ // called on load
hdr = document.getElementById("hdr");
}
... while using the stock browser on a Samsung galaxy Fame ( crap phone which makes it a good tester ) - userAgent ; Mozilla/5.0 (Linux; U; Android 4.1.2; en-gb; GT-S6810P Build/JZO54K) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30
The same code works everywhere else I tried including the stock browser on an older HTC phone - userAgent ; Mozilla/5.0 (Linux; U; Android 2.3.5; en-gb; HTC_WildfireS_A510e Build/GRJ90) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1
The fix for this was to change
var hdr ;
to
var hdr = null ;
I think what you want to do is this:
$(this).children('img').eq(0);
this will give you a jquery object containing the first img element, whereas
$(this).children('img')[0];
will give you the img element itself.
Andre Silva's answer works great for me, with one caveat in the "barplot" line:
barplot(mtcars$qsec, col="grey50",
main="",
ylab="mtcars - qsec", ylim=c(0,5+max(mtcars$qsec)),
xlab = "",
xaxt = "n",
space=1)
Notice the "xaxt" argument. Without it, the labels are drawn twice, the first time without the 60 degree rotation.
to preserve the console output, that is, write to a file and also have it displayed on the console, you could use a class like:
public class TeePrintStream extends PrintStream {
private final PrintStream second;
public TeePrintStream(OutputStream main, PrintStream second) {
super(main);
this.second = second;
}
/**
* Closes the main stream.
* The second stream is just flushed but <b>not</b> closed.
* @see java.io.PrintStream#close()
*/
@Override
public void close() {
// just for documentation
super.close();
}
@Override
public void flush() {
super.flush();
second.flush();
}
@Override
public void write(byte[] buf, int off, int len) {
super.write(buf, off, len);
second.write(buf, off, len);
}
@Override
public void write(int b) {
super.write(b);
second.write(b);
}
@Override
public void write(byte[] b) throws IOException {
super.write(b);
second.write(b);
}
}
and used as in:
FileOutputStream file = new FileOutputStream("test.txt");
TeePrintStream tee = new TeePrintStream(file, System.out);
System.setOut(tee);
(just an idea, not complete)
I had to send my context through a constructor on a custom adapter displayed in a fragment and had this issue with getApplicationContext(). I solved it with:
this.getActivity().getWindow().getContext()
in the fragments' onCreate
callback.
Mongoose basically wraps mongodb's api to give you a pseudo relational db api so queries are not going to be exactly like mongodb queries. Mongoose findOne query returns a query object, not a document. You can either use a callback as the solution suggests or as of v4+ findOne returns a thenable so you can use .then or await/async to retrieve the document.
// thenables
Auth.findOne({nick: 'noname'}).then(err, result) {console.log(result)};
Auth.findOne({nick: 'noname'}).then(function (doc) {console.log(doc)});
// To use a full fledge promise you will need to use .exec()
var auth = Auth.findOne({nick: 'noname'}).exec();
auth.then(function (doc) {console.log(doc)});
// async/await
async function auth() {
const doc = await Auth.findOne({nick: 'noname'}).exec();
return doc;
}
auth();
See the docs if you would like to use a third party promise library.
You'll need to run this command from the MySQL prompt:
REPAIR TABLE tbl_name USE_FRM;
From MySQL's documentation on the Repair command:
The USE_FRM option is available for use if the .MYI index file is missing or if its header is corrupted. This option tells MySQL not to trust the information in the .MYI file header and to re-create it using information from the .frm file. This kind of repair cannot be done with myisamchk.
Unfortunately the examples above didn't work for me in Chrome.
I came up with the below solution where you can specify the max height in PXs of each page. This will then splits the table into separate tables when the rows equal that height.
$(document).ready(function(){
var MaxHeight = 200;
var RunningHeight = 0;
var PageNo = 1;
$('table.splitForPrint>tbody>tr').each(function () {
if (RunningHeight + $(this).height() > MaxHeight) {
RunningHeight = 0;
PageNo += 1;
}
RunningHeight += $(this).height();
$(this).attr("data-page-no", PageNo);
});
for(i = 1; i <= PageNo; i++){
$('table.splitForPrint').parent().append("<div class='tablePage'><hr /><table id='Table" + i + "'><tbody></tbody></table><hr /></div>");
var rows = $('table tr[data-page-no="' + i + '"]');
$('#Table' + i).find("tbody").append(rows);
}
$('table.splitForPrint').remove();
});
You will also need the below in your stylesheet
div.tablePage {
page-break-inside:avoid; page-break-after:always;
}
Create a new XML by example named "shadow.xml" at DRAWABLE with the following code (you can modify it or find another better):
<?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="@color/middle_grey"/>
</shape>
</item>
<item android:left="2dp"
android:right="2dp"
android:bottom="2dp">
<shape android:shape="rectangle">
<solid android:color="@color/white"/>
</shape>
</item>
</layer-list>
After creating the XML in the LinearLayout or another Widget you want to create shade, you use the BACKGROUND property to see the efect. It would be something like :
<LinearLayout
android:orientation="horizontal"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:paddingRight="@dimen/margin_med"
android:background="@drawable/shadow"
android:minHeight="?attr/actionBarSize"
android:gravity="center_vertical">
timeboard
package does this.
Suppose your date is 04 Sep 2017. In spite of being a Monday, it was a holiday in the US (the Labor Day). So, the most recent business day was Friday, Sep 1.
>>> import timeboard.calendars.US as US
>>> clnd = US.Weekly8x5()
>>> clnd('04 Sep 2017').rollback().to_timestamp().date()
datetime.date(2017, 9, 1)
In UK, 04 Sep 2017 was the regular business day, so the most recent business day was itself.
>>> import timeboard.calendars.UK as UK
>>> clnd = UK.Weekly8x5()
>>> clnd('04 Sep 2017').rollback().to_timestamp().date()
datetime.date(2017, 9, 4)
DISCLAIMER: I am the author of timeboard.
You need to set cors header on server side where you are requesting data from. For example if your backend server is in Ruby on rails, use following code before sending back response. Same headers should be set for any backend server.
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
Below Test Init will also do the job.
[TestInitialize]
public void TestInit()
{
HttpContext.Current = new HttpContext(new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null));
YourControllerToBeTestedController = GetYourToBeTestedController();
}
There are two possible result rearrangements (following example by @eumiro). Einops
package provides a powerful notation to describe such operations non-ambigously
>> a = np.arange(18).reshape(9,2)
# this version corresponds to eumiro's answer
>> einops.rearrange(a, '(x y) z -> z y x', x=3)
array([[[ 0, 6, 12],
[ 2, 8, 14],
[ 4, 10, 16]],
[[ 1, 7, 13],
[ 3, 9, 15],
[ 5, 11, 17]]])
# this has the same shape, but order of elements is different (note that each paer was trasnposed)
>> einops.rearrange(a, '(x y) z -> z x y', x=3)
array([[[ 0, 2, 4],
[ 6, 8, 10],
[12, 14, 16]],
[[ 1, 3, 5],
[ 7, 9, 11],
[13, 15, 17]]])
jdk is necessary to compile to code and convert java code to byte codes while jre is necessary for executing the byte codes.
My answer is here lacks technomalogical sophistication to the extent it even employs words like "technomalogical" which are one of those words which aren't actually in the dictionary but have infrequent usage such as the word "gullible" which also cannot be found in the dictionary either.
All that aside: here's me simple answer to a simple question in a simple way to answer a question like this one which is very complicated to ask and the simple wishy washy answer to the wishy washy question like this is thus:
The $('#ident') thing says "document.getElementById('ident').
The $('.classname') thing says "document.getElementByClass('classname').
Yes I know there is no getElementByClass but thats kind of what people are saying when they use the $ symbol like that which is a jQuery syntax. Now you know the answer, I bet you are still lost for how to ask the question. Well now you dont have to learn jQuery just to understand jQuery babel a bit right? Give me a +10 please!
We chose a combination of Mongo/Dynamo for a healthcare product. Basically mongo allows better searching, but the hosted Dynamo is great because its HIPAA compliant without any extra work. So we host the mongo portion with no personal data on a standard setup and allow amazon to deal with the HIPAA portion in terms of infrastructure. We can query certain items from mongo which bring up documents with pointers (ID's) of the relatable Dynamo document.
The main reason we chose to do this using mongo instead of hosting the entire application on dynamo was for 2 reasons. First, we needed to preform location based searches which mongo is great at and at the time, Dynamo was not, but they do have an option now.
Secondly was that some documents were unstructured and we did not know ahead of time what the data would be, so for example lets say user a inputs a document in the "form" collection like this: {"username": "user1", "email": "[email protected]"}. And another user puts this in the same collection {"phone": "813-555-3333", "location": [28.1234,-83.2342]}. With mongo we can search any of these dynamic and unknown fields at any time, with Dynamo, you could do this but would have to make a index every time a new field was added that you wanted searchable. So if you have never had a phone field in your Dynamo document before and then all of the sudden, some one adds it, its completely unsearchable.
Now this brings up another point in which you have mentioned. Sometimes choosing the right solution for the job does not always mean choosing the best product for the job. For example you may have a client who needs and will use the system you created for 10+ years. Going with a SaaS/IaaS solution that is good enough to get the job done may be a better option as you can rely on amazon to have up-kept and maintained their systems over the long haul.
UPDATE:
Modified the code based on this answer to get rid of obsolete methods.
You can use the Security namespace to check this:
public void ExportToFile(string filename)
{
var permissionSet = new PermissionSet(PermissionState.None);
var writePermission = new FileIOPermission(FileIOPermissionAccess.Write, filename);
permissionSet.AddPermission(writePermission);
if (permissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))
{
using (FileStream fstream = new FileStream(filename, FileMode.Create))
using (TextWriter writer = new StreamWriter(fstream))
{
// try catch block for write permissions
writer.WriteLine("sometext");
}
}
else
{
//perform some recovery action here
}
}
As far as getting those permission, you are going to have to ask the user to do that for you somehow. If you could programatically do this, then we would all be in trouble ;)
Don't have sql server around to test but I think it's just:
insert into newtable select * from oldtable;
First of all, you're testing fp
twice. so printf("Error Reading File\n");
never gets executed.
Then, the output of fscanf
should be equal to 2
since you're reading two values.
this
referes to the object the onclick
method belongs to. So inside func
this
would be the DOM node of the a
element and this.innerText
would be here
.
I would go with Larry K's solution, but you can also set the display to inline-block if you want the benefits of both block and inline elements.
You can do this in the div tag by inserting:
style="display:inline-block;"
Or in a CSS stylesheet with this method:
div { display:inline-block; }
Hope it helps, but as earlier mentioned, I would personally go for Larry K's solution ;-)
Java 8 Collection has a nice method called removeIf that makes things easier and safer. From the API docs:
default boolean removeIf(Predicate<? super E> filter)
Removes all of the elements of this collection that satisfy the given predicate.
Errors or runtime exceptions thrown during iteration or by the predicate
are relayed to the caller.
Interesting note:
The default implementation traverses all elements of the collection using its iterator().
Each matching element is removed using Iterator.remove().
I solved this on my WAMP setup by enabling the php_openssl
extension, since the URL I was loading from used https://
.
The best way is to store native JavaScript Date objects, which map onto BSON native Date objects.
> db.test.insert({date: ISODate()})
> db.test.insert({date: new Date()})
> db.test.find()
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:42.389Z") }
{ "_id" : ObjectId("..."), "date" : ISODate("2014-02-10T10:50:57.240Z") }
The native type supports a whole range of useful methods out of the box, which you can use in your map-reduce jobs, for example.
If you need to, you can easily convert Date
objects to and from Unix timestamps1), using the getTime()
method and Date(milliseconds)
constructor, respectively.
1) Strictly speaking, the Unix timestamp is measured in seconds. The JavaScript Date object measures in milliseconds since the Unix epoch.
ids
must be unique where as class
can be applied to many things. In CSS, id
s look like #elementID
and class
elements look like .someClass
In general, use id
whenever you want to refer to a specific element and class
when you have a number of things that are all alike. For instance, common id
elements are things like header
, footer
, sidebar
. Common class
elements are things like highlight
or external-link
.
It's a good idea to read up on the cascade and understand the precedence assigned to various selectors: http://www.w3.org/TR/CSS2/cascade.html
The most basic precedence you should understand, however, is that id
selectors take precedence over class
selectors. If you had this:
<p id="intro" class="foo">Hello!</p>
and:
#intro { color: red }
.foo { color: blue }
The text would be red because the id
selector takes precedence over the class
selector.
my css
TR.gray-t {background:#949494;}
h3{
padding-top:3px;
font:bold 12px/2px Arial;
}
my html
<TR class='gray-t'>
<TD colspan='3'><h3>KAJANG</h3>
I decrease the 2nd size in font.
padding-top
is used to fix the size in IE7.
simply assign a variable to ()
or " "
, then when needed type
print(x, x, x, Hello World, x)
or something like that.
Hope this is a little less complicated:)
In case anyone is interested (even if the question does not ask for this version), in C# 2 would be: (I have edited the answer, following some suggestions)
myList.Sort(CLASS_FOR_COMPARER);
List<string> fiveElements = myList.GetRange(0, 5);
If we need to move from one component to another service then we have to define that service into app.module providers array.