Hudson can be configured to ignore changes to certain paths and files so that it does not prompt a new build.
On the job configuration page, under Source Code Management, click the Advanced button. In the Excluded Regions box you enter one or more regular expression to match exclusions.
For example to ignore changes to the version.properties file you can use:
/MyProject/trunk/version.properties
This will work for languages other than C# and allows you to store your version info within subversion.
So by adding the #!/bin/sh
will allow you to execute with no option.
It also helped me in fixing an issue where I was executing bash script from Jenkins master on my Linux slave. By just adding #!/bin/bash
above my actual script in "Execute Shell" block it fixed my issue as otherwise it was executing windows git provided version of bash shell that was giving an error.
One thing that got this working for me is to make sure that github.com
is in ~jenkins/.ssh/known_hosts
.
Use the script console (Manage Jenkins > Script Console) and something like this script to bulk delete a job's build history https://github.com/jenkinsci/jenkins-scripts/blob/master/scriptler/bulkDeleteBuilds.groovy
That script assumes you want to only delete a range of builds. To delete all builds for a given job, use this (tested):
// change this variable to match the name of the job whose builds you want to delete
def jobName = "Your Job Name"
def job = Jenkins.instance.getItem(jobName)
job.getBuilds().each { it.delete() }
// uncomment these lines to reset the build number to 1:
//job.nextBuildNumber = 1
//job.save()
On Ubuntu:
sudo apt install ca-certificates-java
or
sudo apt-get install ca-certificates-java
sorted it for me.
Add
/usr/bin/bash
at
Jenkins -> Manage Jenkins -> configure System -> Shell->Shell executable
Jenkins use the sh so that even /etc/profile doesn't work for me When I add this, I have all the env.
You could use Role Strategy plugin for that purpose. It works like a charm, just setup some roles and assign them. Even on project-specific level.
In Jenkins 2.60.3 there is a way to delete build artifacts (not the archived artifacts) in order to save hard drive space on the build machine. In the General section, check "Discard old builds" with strategy "Log Rotation" and then go into its Advanced options. Two more options will appear related to keeping build artifacts for the job based on number of days or builds.
The settings that work for me are to enter 1 for "Max # of builds to keep with artifacts" and then to have a post-build action to archive the artifacts. This way, all artifacts from all builds will be archived, all information from builds will be saved, but only the last build will keep its own artifacts.
I should this On Windows, environment variable expansion is %BUILD_NUMBER%
Just add my answer in addition to Nigel Kirby's as I can't comment yet:
In order to pass a dynamically created parameter, you can also export the variable in 'Execute Shell' tile and then pass it through 'Trigger parameterized build on other projects' => 'Predefined parameters" => give 'YOUR_VAR=$YOUR_VAR'. My team use this feature to pass npm package version from build job to deployment jobs
UPDATE: above only works for Jenkins injected parameters, parameter created from shell still need to use same method. eg. echo YOUR_VAR=${YOUR_VAR} > variable.properties and pass that file downstream
If you are using a declarative syntax of Jenkinsfile to describe your building pipeline, you can use changeset condition to limit stage execution only to the case when specific files are changed. This is now a standard feature of Jenkins and does not require any additional configruation/software.
stages {
stage('Nginx') {
when { changeset "nginx/*"}
steps {
sh "make build-nginx"
sh "make start-nginx"
}
}
}
You can combine multiple conditions using anyOf
or allOf
keywords for OR or AND behaviour accordingly:
when {
anyOf {
changeset "nginx/**"
changeset "fluent-bit/**"
}
}
steps {
sh "make build-nginx"
sh "make start-nginx"
}
In the new Jenkins 2.0 pipeline (previously named the Workflow Plugin), this is done differently for:
Here I am specifically referring to the Multibranch Pipeline version 2.9.
Main repository
This is the repository that contains your Jenkinsfile
.
In the Configure screen for your pipeline project, enter your repository name, etc.
Do not use Additional Behaviors > Check out to a sub-directory. This will put your Jenkinsfile
in the sub-directory where Jenkins cannot find it.
In Jenkinsfile
, check out the main repository in the subdirectory using dir()
:
dir('subDir') {
checkout scm
}
Additional repositories
If you want to check out more repositories, use the Pipeline Syntax generator to automatically generate a Groovy code snippet.
In the Configure screen for your pipeline project:
env.BRANCH_NAME
contains the branch name of the main repository.Jenkinsfile
.Just my take on the matter, three months later:
Jenkins has continued the path well-trodden by the original Hudson with frequent releases including many minor updates.
Oracle seems to have largely delegated work on the future path for Hudson to the Sonatype team, who has performed some significant changes, especially with respect to Maven. They have jointly moved it to the Eclipse foundation.
I would suggest that if you like the sound of:
, then I would suggest Hudson.
Conversely, if you prefer:
then I would suggest Jenkins. (and as a commenter noted, Jenkins now also has "LTS" releases which are maintained on a more "stable" branch)
The conservative course would be to choose Hudson now and migrate to Jenkins if must-have features are unavailable. The dynamic course would be to choose Jenkins now and migrate to Hudson if chasing updates becomes too time-consuming to justify.
Jenkins Pipeline also provides the current build number as the property number
of the currentBuild
. It can be read as currentBuild.number
.
For example:
// Scripted pipeline
def buildNumber = currentBuild.number
// Declarative pipeline
echo "Build number is ${currentBuild.number}"
Other properties of currentBuild
are described in the Pipeline Syntax: Global Variables page that is included on each Pipeline job page. That page describes the global variables available in the Jenkins instance based on the current plugins.
I did a similar thing a few months ago, and it turned out this simple format was enough for Hudson to accept it as a test protocol:
<testsuite tests="3">
<testcase classname="foo1" name="ASuccessfulTest"/>
<testcase classname="foo2" name="AnotherSuccessfulTest"/>
<testcase classname="foo3" name="AFailingTest">
<failure type="NotEnoughFoo"> details about failure </failure>
</testcase>
</testsuite>
This question has answers with more details: Spec. for JUnit XML Output
No, the String.isEmpty()
method looks as following:
public boolean isEmpty() {
return this.value.length == 0;
}
as you can see it checks the length of the string so you definitely have to check if the string is null before.
zIndex
is part of javaScript notation.(camelCase)
but jQuery.css uses same as CSS syntax.
so it is z-index
.
you forgot .css("attr","value"). use ' or " in both, attr and val. so,
.css("z-index","3000");
Example:
<input type="button" value="Click me" id="myButton">
<script>
var myButton = document.getElementById("myButton");
var test = "zipzambam";
myButton.onclick = function(eventObject) {
if (!eventObject) {
eventObject = window.event;
}
if (!eventObject.target) {
eventObject.target = eventObject.srcElement;
}
alert(eventObject.target);
alert(test);
};
(function(myMessage) {
alert(myMessage);
})("Hello");
</script>
NOTE:
pd.convert_objects
has now been deprecated. You should usepd.Series.astype(float)
orpd.to_numeric
as described in other answers.
This is available in 0.11. Forces conversion (or set's to nan)
This will work even when astype
will fail; its also series by series
so it won't convert say a complete string column
In [10]: df = DataFrame(dict(A = Series(['1.0','1']), B = Series(['1.0','foo'])))
In [11]: df
Out[11]:
A B
0 1.0 1.0
1 1 foo
In [12]: df.dtypes
Out[12]:
A object
B object
dtype: object
In [13]: df.convert_objects(convert_numeric=True)
Out[13]:
A B
0 1 1
1 1 NaN
In [14]: df.convert_objects(convert_numeric=True).dtypes
Out[14]:
A float64
B float64
dtype: object
.gitkeep
is just a placeholder. A dummy file, so Git will not forget about the directory, since Git tracks only files.
If you want an empty directory and make sure it stays 'clean' for Git, create a .gitignore
containing the following lines within:
# .gitignore sample
###################
# Ignore all files in this dir...
*
# ... except for this one.
!.gitignore
If you desire to have only one type of files being visible to Git, here is an example how to filter everything out, except .gitignore and all .txt
files:
# .gitignore to keep just .txt files
###################################
# Filter everything...
*
# ... except the .gitignore...
!.gitignore
# ... and all text files.
!*.txt
('#' indicates comments.)
My solution: I set almost every View as static
. Now my app interacts perfect. Being able to call the static methods from everywhere is maybe not a good style, but why to play around with code that doesn't work? I read a lot of questions and their answers here on SO and no solution brought success (for me).
I know it can leak the memory, and waste heap, and my code will not be fit on other projects, but I don't feel scared about this - I tested the app on different devices and conditions, no problems at all, the Android Platform seems to be able handle this. The UI gets refreshed every second and even on a S2 ICS (4.0.3) device the app is able to handle thousands of geo-markers.
Perhaps not in the context that you have it, but you could use
SELECT DISTINCT col1,
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1),
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1, col3),
FROM TableA
You would use this to return different levels of aggregation returned in a single row. The use case would be for when a single grouping would not suffice all of the aggregates needed.
I had same issue. I used PIL Image to load the images and converted to a numpy array then patched a rectangle using matplotlib. It was a jpg image, so there was no way for me to get the dpi from PIL img.info['dpi'], so the accepted solution did not work for me. But after some tinkering I figured out way to save the figure with the same size as the original.
I am adding the following solution here thinking that it will help somebody who had the same issue as mine.
import matplotlib.pyplot as plt
from PIL import Image
import numpy as np
img = Image.open('my_image.jpg') #loading the image
image = np.array(img) #converting it to ndarray
dpi = plt.rcParams['figure.dpi'] #get the default dpi value
fig_size = (img.size[0]/dpi, img.size[1]/dpi) #saving the figure size
fig, ax = plt.subplots(1, figsize=fig_size) #applying figure size
#do whatver you want to do with the figure
fig.tight_layout() #just to be sure
fig.savefig('my_updated_image.jpg') #saving the image
This saved the image with the same resolution as the original image.
In case you are not working with a jupyter notebook. you can get the dpi in the following manner.
figure = plt.figure()
dpi = figure.dpi
If you've tried some of the suggestions in the other answers, most notably:
Windows Management Instrumentation (WMI)
inbound firewall rule is enabled Then consider other common reasons for getting this error:
You can even use
window.open('https://support.wwf.org.uk', "_blank") || window.location.replace('https://support.wwf.org.uk');
This will open it on the same tab if the pop-up is blocked.
image_tag is the best way to do the job friend
Following steps has fixed my issue.
(1) Moved the website to a Dedicated application pool.
(2) Changed the Managed Pipeline Mode from integrated to Classic.
(3) Set Enable 32-Bit Applications from false to true.
ASP pages are working fine now!
Declare your progress dialog:
ProgressDialog progressDialog;
To start the progress dialog:
progressDialog = ProgressDialog.show(this, "","Please Wait...", true);
To dismiss the Progress Dialog :
progressDialog.dismiss();
String car [];
is a reference to an array of String-s. You can't see a length because there is no array there!
For anyone looking for a scalable solution: I wrote a small helper utility in SASS to generate responsive proportional rectangles for different breakpoints. Take a look at SASS Proportions
Hope it helps anybody!
You can make use of the reversed
function for this as:
>>> array=[0,10,20,40]
>>> for i in reversed(array):
... print(i)
Note that reversed(...)
does not return a list. You can get a reversed list using list(reversed(array))
.
You can use the CSS3 Linear Gradient property along with your background-image like this:
#landing-wrapper {
display:table;
width:100%;
background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
background-position:center top;
height:350px;
}
Here's a demo:
#landing-wrapper {_x000D_
display: table;_x000D_
width: 100%;_x000D_
background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
background-position: center top;_x000D_
height: 350px;_x000D_
color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
If you don't mind that the order will be changed, I recommend you to use @job solution, otherwise, you can use this:
def chunkIt(seq, num):
steps = int(len(seq) / float(num))
out = []
last = 0.0
while last < len(seq):
if len(seq) - (last + steps) < steps:
until = len(seq)
steps = len(seq) - last
else:
until = int(last + steps)
out.append(seq[int(last): until])
last += steps
return out
If you're using the iframe embed api, you can put html5:1
as one of the playerVars
arguments, like so:
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: '<VIDEO ID>',
playerVars: {
html5: 1
},
});
Totally works.
It appeared quite convenient for me to have a remote tmux session using the tmux new -d <shell cmd>
syntax like this:
ssh someone@elsewhere 'tmux new -d sleep 600'
This will launch new session on elsewhere
host and ssh command on local machine will return to shell almost instantly. You can then ssh to the remote host and tmux attach
to that session. Note that there's nothing about local tmux running, only remote!
Also, if you want your session to persist after the job is done, simply add a shell launcher after your command, but don't forget to enclose in quotes:
ssh someone@elsewhere 'tmux new -d "~/myscript.sh; bash"'
I understand you want to create stuff dynamically. That does not mean you have to actually construct DOM elements to do it. You can just make use of html
to achieve what you want .
Look at the code below :
HTML:
<table border="0" cellpadding="0" width="100%" id='providersFormElementsTable'></table>
JS :
createFormElement("Nickname","nickname")
function createFormElement(labelText, id) {
$("#providersFormElementsTable").html("<tr><td>Nickname</td><td><input type='text' id='"+id+"' name='nickname'></td><lable id='"+labelText+"'></lable></td></tr>");
$('#providersFormElementsTable').append('<br />');
}
This one does what you want dynamically, it just needs the id and labelText to make it work, which actually must be the only dynamic variables as only they will be changing. Your DOM structure will always remain the same .
Moreover, when you use the process you mentioned in your post you get only [object Object]
. That is because when you call createProviderFormFields
, it is a function call and hence it's returning an object for you. You will not be seeing the text box as it needs to be added . For that you need to strip individual content form the object
, then construct the html from it.
It's much easier to construct just the html and change the id
s of the label and input according to your needs.
Funny the answer is hidden in among the answers.
str.replace("•", "something")
would work if you use the right semantics.
str.replace(u"\u2022","something")
works wonders ;) , thnx to RParadox for the hint.
UPDATE: This answer was originally written in 2008 when nth-of-type
support was unreliable at best. Today I'd say you could safely use something like .bar:nth-of-type(2)
, unless you have to support IE8 and older.
Original answer from 2008 follows (Note that I would not recommend this anymore!):
If you can use Prototype JS you can use this code to set some style values, or add another classname:
// set style:
$$('div.theclassname')[1].setStyle({ backgroundColor: '#900', fontSize: '1.2em' });
// OR add class name:
$$('div.theclassname')[1].addClassName('secondclass'); // pun intentded...
(I didn't test this code, and it doesn't check if there actually is a second div present, but something like this should work.)
But if you're generating the html serverside you might just as well add an extra class on the second item...
C# 3.5 or below does not support the multiple inheritance, but C# 4.0 could do this by using, as I remembered, Dynamics.
HTML
<div id='a'>
<div>
<a class='click'>abc</a>
</div>
</div>
You could use the XPATH as :
//div[@id='a']//a[@class='click']
output
<a class="click">abc</a>
That said your Python code should be as :
driver.find_element_by_xpath("//div[@id='a']//a[@class='click']")
I had the same problem, here is my description of the problem
"I created a store procedure which would generate 2200 Rows and would get executed in almost 2 seconds however after calling the store procedure from SSRS 2008 and run the report it actually never ran and ultimately I have to kill the BIDS (Business Intelligence development Studio) from task manager".
What I Tried: I tried running the SP from reportuser Login but SP was running normal for that user as well, I checked Profiler but nothing worked out.
Solution:
Actually the problem is that even though SP is generating the result but SSRS engine is taking time to read these many rows and render it back. So I added WITH RECOMPILE option in SP and ran the report .. this is when miracle happened and my problem got resolve.
I don't have Python 2.7 installed, but in Python 3.3 calling Popen
with stdout
set to sys.stdout
worked just fine. Not before I had escaped the backslashes in the path, though.
>>> import subprocess
>>> import sys
>>> p = subprocess.Popen(['powershell.exe', 'C:\\Temp\\test.ps1'], stdout=sys.stdout)
>>> Hello World
_
you have to name your checkboxes accordingly:
<input type="checkbox" name="check_list[]" value="…" />
you can then access all checked checkboxes with
// loop over checked checkboxes
foreach($_POST['check_list'] as $checkbox) {
// do something
}
ps. make sure to properly escape your output (htmlspecialchars()
)
The title attribute also works well with other html elements, for example a link...
<a title="hover text" ng-href="{{getUrl()}}"> download link
</a>
After creating virtual environment copy the activate.bat file from Script folder of python and paste to it your environment and open cmd from your virtual environment and run activate.bat file.enter image description here
I used ganymede for this a few yeas ago... http://www.cleondris.ch/opensource/ssh2/
You did not register your nib as below:
tableView.registerNib(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "CustomCell")
Some tips:
Have fun :-)
So, your goal is to search and replace?
According to the Official Visual Studio's keyboard shotcuts pdf, you can press Ctrl + H on Windows and Linux, or ??F on Mac to enable search and replace tool:
If you mean to disable the code, you just have to put <h1>
in search, and replace to ####
.
But if you want to use this regex instead, you may enable it in the icon: and use the regex: <h1>(.+?)<\/h1>
and replace to: #### $1
.
And as @tpartee suggested, here is some more information about Visual Studio's engine if you would like to learn more:
Check out php-ip-2-country from code.google. The database they provide is updated daily, so it is not necessary to connect to an outside server for the check if you host your own SQL server. So using the code you would only have to type:
<?php
$ip = $_SERVER['REMOTE_ADDR'];
if(!empty($ip)){
require('./phpip2country.class.php');
/**
* Newest data (SQL) avaliable on project website
* @link http://code.google.com/p/php-ip-2-country/
*/
$dbConfigArray = array(
'host' => 'localhost', //example host name
'port' => 3306, //3306 -default mysql port number
'dbName' => 'ip_to_country', //example db name
'dbUserName' => 'ip_to_country', //example user name
'dbUserPassword' => 'QrDB9Y8CKMdLDH8Q', //example user password
'tableName' => 'ip_to_country', //example table name
);
$phpIp2Country = new phpIp2Country($ip,$dbConfigArray);
$country = $phpIp2Country->getInfo(IP_COUNTRY_NAME);
echo $country;
?>
Example Code (from the resource)
<?
require('phpip2country.class.php');
$dbConfigArray = array(
'host' => 'localhost', //example host name
'port' => 3306, //3306 -default mysql port number
'dbName' => 'ip_to_country', //example db name
'dbUserName' => 'ip_to_country', //example user name
'dbUserPassword' => 'QrDB9Y8CKMdLDH8Q', //example user password
'tableName' => 'ip_to_country', //example table name
);
$phpIp2Country = new phpIp2Country('213.180.138.148',$dbConfigArray);
print_r($phpIp2Country->getInfo(IP_INFO));
?>
Output
Array
(
[IP_FROM] => 3585376256
[IP_TO] => 3585384447
[REGISTRY] => RIPE
[ASSIGNED] => 948758400
[CTRY] => PL
[CNTRY] => POL
[COUNTRY] => POLAND
[IP_STR] => 213.180.138.148
[IP_VALUE] => 3585378964
[IP_FROM_STR] => 127.255.255.255
[IP_TO_STR] => 127.255.255.255
)
For completeness along with the other answers:
yourstring = "L%sLL" % yourstring
Or, more forward compatible with Python 3.x:
yourstring = "L{0}LL".format(yourstring)
Just to add to other comments - it would be worth while to disable scrolling up whilst at the top of the page. If the user accidentally scrolls up whilst already at the top they would have to scroll down twice to start
if(scrolled != 0){
$("#upClick").on("click" ,function(){
scrolled=scrolled-300;
$(".cover").animate({
scrollTop: scrolled
});
});
}
If you already know the filename
, you can use the boto3
builtin download_fileobj
import boto3
from io import BytesIO
session = boto3.Session()
s3_client = session.client("s3")
f = BytesIO()
s3_client.download_fileobj(bucket_name, filename, f)
f.seek(0)
print(f.getvalue())
And why not making a HTTP Request on the script and ignoring the response ?
http://php.net/manual/en/function.httprequest-send.php
If you make your request on the script you need to call your webserver will run it in background and you can (in your main script) show a message telling the user that the script is running.
I know it's a bit late to put my contribution on this subject but I lost so many hours that maybe this answer will help somebody.
I was trying to call a third party cookie on my site and of course it was not working on Internet Explorer 10, even at a low security level... don't ask me why. In the iframe I was calling a read_cookie.php (echo $_COOKIE) with ajax.
And I don't know why I was incapable of setting the P3P policy to solve the problem...
During my search I saw something about getting the cookie in JSON working. I don't even try because I thought that if the cookie won't pass through an iframe, it will not pass any more through an array...
Guess what, it does! So if you json_encode your cookie then decode after your ajax request, you'll get it!
Maybe there is something I missed and if I did, all my apologies, but i never saw something so stupid. Block third party cookies for security, why not, but let it pass if encoded? Where is the security now?
I hope this post will help somebody and again, if I missed something and I'm dumb, please educate me!
In your example, you prepended your source string with AccountKey=
but not your target string.
$c = $c -replace 'AccountKey=eKkij32jGEIYIEqAR5RjkKgf4OTiMO6SAyF68HsR/Zd/KXoKvSdjlUiiWyVV2+OUFOrVsd7jrzhldJPmfBBpQA==','AccountKey=DdOegAhDmLdsou6Ms6nPtP37bdw6EcXucuT47lf9kfClA6PjGTe3CfN+WVBJNWzqcQpWtZf10tgFhKrnN48lXA=='
By not including that in the target string, the resulting string will remove AccountKey=
instead of replacing it. You correctly do this with the AccountName=
example, which seems to support this conclusion since it is not giving you any problems. If you really mean to have that prepended, then this may resolve your issue.
I forgot to mention. This should also accept whitespace.
You could use:
/^[-@.\/#&+\w\s]*$/
Note how this makes use of the character classes \w
and \s
.
EDIT:- Added \ to escape /
What about this solution? Modules and Controllers in Files (at the end of the page) It works with multiple controllers, directives and so on:
app.js
var app = angular.module("myApp", ['deps']);
myCtrl.js
app.controller("myCtrl", function($scope) { ..});
html
<script src="app.js"></script>
<script src="myCtrl.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">
Google has also a Best Practice Recommendations for Angular App Structure I really like to group by context. Not all the html in one folder, but for example all files for login (html, css, app.js,controller.js and so on). So if I work on a module, all the directives are easier to find.
As to the short script, the following runs on my Linux host
#!/bin/bash
HOST_DIR=<pull-to>
DEVICE_DIR=/sdcard/<pull-from>
EXTENSION="\.jpg"
while read MYFILE ; do
adb pull "$DEVICE_DIR/$MYFILE" "$HOST_DIR/$MYFILE"
done < $(adb shell ls -1 "$DEVICE_DIR" | grep "$EXTENSION")
"ls minus one" lets "ls" show one file per line, and the quotation marks allow spaces in the filename.
You need to escape the slashes as %2F
.
If your source folder is structured /go/src/blog (assuming the name of your source folder is blog).
That should run all of your files at the same time, instead of you having to list the files manually or "bashing" a method on the command line.
All of the other answers are great, I just want to give a cool example of one thing you can do with constexpr that is amazing. See-Phit (https://github.com/rep-movsd/see-phit/blob/master/seephit.h) is a compile time HTML parser and template engine. This means you can put HTML in and get out a tree that is able to be manipulated. Having the parsing done at compile time can give you a bit of extra performance.
From the github page example:
#include <iostream>
#include "seephit.h"
using namespace std;
int main()
{
constexpr auto parser =
R"*(
<span >
<p color="red" height='10' >{{name}} is a {{profession}} in {{city}}</p >
</span>
)*"_html;
spt::tree spt_tree(parser);
spt::template_dict dct;
dct["name"] = "Mary";
dct["profession"] = "doctor";
dct["city"] = "London";
spt_tree.root.render(cerr, dct);
cerr << endl;
dct["city"] = "New York";
dct["name"] = "John";
dct["profession"] = "janitor";
spt_tree.root.render(cerr, dct);
cerr << endl;
}
You can implicitly convert between numerical types, even when that loses precision:
char c = i;
However, you might like to enable compiler warnings to avoid potentially lossy conversions like this. If you do, then use static_cast
for the conversion.
Of the other casts:
dynamic_cast
only works for pointers or references to polymorphic class types;const_cast
can't change types, only const
or volatile
qualifiers;reinterpret_cast
is for special circumstances, converting between pointers or references and completely unrelated types. Specifically, it won't do numeric conversions.static_cast
, const_cast
and reinterpret_cast
is needed to get the job done.You can add an alias
or a function
in your startup script file. Usually this is .bashrc
, .bash_login
or .profile
file in your home directory.
Since these files are hidden you will have to do an ls -a
to list them. If you don't have one you can create one.
If I remember correctly, when I had bought my Mac, the .bash_login
file wasn't there. I had to create it for myself so that I could put prompt info
, alias
, functions
, etc. in it.
Here are the steps if you would like to create one:
cd ~/
to go to your home foldertouch .bash_profile
to create your new file..bash_profile
with your favorite editor (or you can just type open -e .bash_profile
to open it in TextEdit.. .bash_profile
to reload .bash_profile
and update any alias you add.Refer to example at this link. It may be help to you.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.dropdownlist.aspx
void Page_Load(Object sender, EventArgs e)
{
// Load data for the DropDownList control only once, when the
// page is first loaded.
if(!IsPostBack)
{
// Specify the data source and field names for the Text
// and Value properties of the items (ListItem objects)
// in the DropDownList control.
ColorList.DataSource = CreateDataSource();
ColorList.DataTextField = "ColorTextField";
ColorList.DataValueField = "ColorValueField";
// Bind the data to the control.
ColorList.DataBind();
// Set the default selected item, if desired.
ColorList.SelectedIndex = 0;
}
}
void Selection_Change(Object sender, EventArgs e)
{
// Set the background color for days in the Calendar control
// based on the value selected by the user from the
// DropDownList control.
Calendar1.DayStyle.BackColor =
System.Drawing.Color.FromName(ColorList.SelectedItem.Value);
}
UPDATE ed
SET ed.kWh = ted.kWh
FROM energydata ed
INNER JOIN temp_energydata ted ON ted.webmeterID = ed.webmeterID
How do I select multiple columns by labels in pandas?
Multiple label-based range slicing is not easily supported with pandas, but position-based slicing is, so let's try that instead:
loc = df.columns.get_loc
df.iloc[:, np.r_[loc('A'):loc('C')+1, loc('E'), loc('G'):loc('I')+1]]
A B C E G H I
0 -1.666330 0.321260 -1.768185 -0.034774 0.023294 0.533451 -0.241990
1 0.911498 3.408758 0.419618 -0.462590 0.739092 1.103940 0.116119
2 1.243001 -0.867370 1.058194 0.314196 0.887469 0.471137 -1.361059
3 -0.525165 0.676371 0.325831 -1.152202 0.606079 1.002880 2.032663
4 0.706609 -0.424726 0.308808 1.994626 0.626522 -0.033057 1.725315
5 0.879802 -1.961398 0.131694 -0.931951 -0.242822 -1.056038 0.550346
6 0.199072 0.969283 0.347008 -2.611489 0.282920 -0.334618 0.243583
7 1.234059 1.000687 0.863572 0.412544 0.569687 -0.684413 -0.357968
8 -0.299185 0.566009 -0.859453 -0.564557 -0.562524 0.233489 -0.039145
9 0.937637 -2.171174 -1.940916 -1.553634 0.619965 -0.664284 -0.151388
Note that the +1
is added because when using iloc
the rightmost index is exclusive.
filter
is a nice and simple method for OP's headers, but this might not generalise well to arbitrary column names.
The "location-based" solution with loc
is a little closer to the ideal, but you cannot avoid creating intermediate DataFrames (that are eventually thrown out and garbage collected) to compute the final result range -- something that we would ideally like to avoid.
Lastly, "pick your columns directly" is good advice as long as you have a manageably small number of columns to pick. It will, however not be applicable in some cases where ranges span dozens (or possibly hundreds) of columns.
The desperate may also make sure they don't have extra newlines in the authorized_keys file due to copying file id_rsa.pub's text out of a confused terminal.
Interval class I have written can be used. It can be used in opposite way too.
composer require lubos/cakephp-interval
$Interval = new \Interval\Interval\Interval();
// output 2w 6h
echo $Interval->toHuman((2 * 5 * 8 + 6) * 3600);
// output 36000
echo $Interval->toSeconds('1d 2h');
More info here https://github.com/LubosRemplik/CakePHP-Interval
You can Use below code to call the web service and get response .Make sure that your Web Service return the response in Data Table Format..This code help you if you using data from SQL Server database .If you you using MYSQL you need to change one thing just replace word NewDataSet from sentence obj2=(SoapObject) obj1.getProperty("NewDataSet");
by DocumentElement
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://localhost/Web_Service.asmx?"; // you can use IP address instead of localhost
private static final String METHOD_NAME = "Function_Name";
private static final String SOAP_ACTION = NAMESPACE + METHOD_NAME;
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("parm_name", prm_value); // Parameter for Method
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope); //call the eb service Method
} catch (Exception e) {
e.printStackTrace();
} //Next task is to get Response and format that response
SoapObject obj, obj1, obj2, obj3;
obj = (SoapObject) envelope.getResponse();
obj1 = (SoapObject) obj.getProperty("diffgram");
obj2 = (SoapObject) obj1.getProperty("NewDataSet");
for (int i = 0; i < obj2.getPropertyCount(); i++) //the method getPropertyCount() return the number of rows
{
obj3 = (SoapObject) obj2.getProperty(i);
obj3.getProperty(0).toString(); //value of column 1
obj3.getProperty(1).toString(); //value of column 2
//like that you will get value from each column
}
If you have any problem regarding this you can write me..
The .NET Library EPPlus implements a conversation from the string definition to the built in number. See class ExcelNumberFormat:
internal static int GetFromBuildIdFromFormat(string format)
{
switch (format)
{
case "General":
return 0;
case "0":
return 1;
case "0.00":
return 2;
case "#,##0":
return 3;
case "#,##0.00":
return 4;
case "0%":
return 9;
case "0.00%":
return 10;
case "0.00E+00":
return 11;
case "# ?/?":
return 12;
case "# ??/??":
return 13;
case "mm-dd-yy":
return 14;
case "d-mmm-yy":
return 15;
case "d-mmm":
return 16;
case "mmm-yy":
return 17;
case "h:mm AM/PM":
return 18;
case "h:mm:ss AM/PM":
return 19;
case "h:mm":
return 20;
case "h:mm:ss":
return 21;
case "m/d/yy h:mm":
return 22;
case "#,##0 ;(#,##0)":
return 37;
case "#,##0 ;[Red](#,##0)":
return 38;
case "#,##0.00;(#,##0.00)":
return 39;
case "#,##0.00;[Red](#,#)":
return 40;
case "mm:ss":
return 45;
case "[h]:mm:ss":
return 46;
case "mmss.0":
return 47;
case "##0.0":
return 48;
case "@":
return 49;
default:
return int.MinValue;
}
}
When you use one of these formats, Excel will automatically identify them as a standard format.
I know this is a very old question but it still doesn't have an accepted answer. I see that you want the following removed: html tags that are "empty" and white spaces based on an html string.
I have come up with a solution based on your comment for the output you are looking for:
Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces
var str = "<p> </p><div> </div>Trimming using JavaScript<br /><br /><br /><br />all leading and trailing white spaces<p> </p><div> </div>";_x000D_
console.log(str.trim().replace(/ /g, '').replace(/<[^\/>][^>]*><\/[^>]+>/g, ""));
_x000D_
.trim()
removes leading and trailing whitespace
.replace(/ /g, '')
removes
.replace(/<[^\/>][^>]*><\/[^>]+>/g, ""));
removes empty tags
How about a function that jumps to the week before that week number and then steps through the next few days until the week number changes (max 7 steps), returning the new date?
CREATE FUNCTION dbo.fnGetDateFromWeekNo
(@weekNo int , @yearNo int)
RETURNS smalldatetime
AS
BEGIN
DECLARE @tmpDate smalldatetime
set @tmpdate= cast(cast (@yearNo as varchar) + '-01-01' as smalldatetime)
-- jump forward x-1 weeks to save counting through the whole year
set @tmpdate=dateadd(wk,@weekno-1,@tmpdate)
-- make sure weekno is not out of range
if @WeekNo <= datepart(wk,cast(cast (@yearNo as varchar) + '-12-31' as smalldatetime))
BEGIN
WHILE (datepart(wk,@tmpdate)<@WeekNo)
BEGIN
set @tmpdate=dateadd(dd,1,@tmpdate)
END
END
ELSE
BEGIN
-- invalid weeknumber given
set @tmpdate=null
END
RETURN @tmpDate
END
I have written a simple component using jQuery and bootstrap. Give it a try: https://github.com/mahpour/bootstrap-input-clear-button
This is not really 'slick' but it's faster to do integer operations than to do string concatenations for each padding 0
.
function ZeroPadNumber ( nValue )
{
if ( nValue < 10 )
{
return ( '000' + nValue.toString () );
}
else if ( nValue < 100 )
{
return ( '00' + nValue.toString () );
}
else if ( nValue < 1000 )
{
return ( '0' + nValue.toString () );
}
else
{
return ( nValue );
}
}
This function is also hardcoded to your particular need (4 digit padding), so it's not generic.
This jQuery-based answer posted by @user110902 was useful for me. However, I improved it a little to prevent a flaw mentioned in @B_N 's comment: it failed detecting CapsLock while you press Shift:
$('#example').keypress(function(e) {
var s = String.fromCharCode( e.which );
if (( s.toUpperCase() === s && s.toLowerCase() !== s && !e.shiftKey )
|| ( s.toLowerCase() === s && s.toUpperCase() !== s && e.shiftKey )) {
alert('caps is on');
}
});
Like this, it will work even while pressing Shift.
The better option would be to just use the resource returned array as an array, meaning :
getResources().getStringArray(R.array.your_array)[position]
This is a shortcut approach of above mentioned approaches but does the work in the fashion you want. Otherwise android doesnt provides direct XML indexing for xml based arrays.
There is a library called PhoneNumberUtils that can help you to cope with phone number conversions and comparisons. For instance, use ...
EditText text = (EditText) findViewById(R.id.editTextId);
PhoneNumberUtils.formatNumber(text.getText().toString())
... to format your number in a standard format.
PhoneNumberUtils.compare(String a, String b);
... helps with fuzzy comparisons. There are lots more. Check out http://developer.android.com/reference/android/telephony/PhoneNumberUtils.html for more.
p.s. setting the the EditText to phone
is already a good choice; eventually it might be helpful to add digits
e.g. in your layout it looks as ...
<EditText
android:id="@+id/editTextId"
android:inputType="phone"
android:digits="0123456789+"
/>
I tried many formats, but only that worked:
select /*+INDEX(e,dept_idx)*/ * from emp e;
Say you have activity stack like A>B>C>D>E. You are at activity D, and you want to close your app. This is what you wil do -
In Activity from where you want to close (Activity D)-
Intent intent = new Intent(D.this,A.class);
intent.putExtra("exit", "exit");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
In your RootActivity (ie your base activity, here Activity A) -
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent.hasExtra("exit")) {
setIntent(intent);
}
}
@Override
protected void onResume() {
super.onResume();
if (getIntent() != null) {
if (("exit").equalsIgnoreCase(getIntent().getStringExtra(("exit")))) {
onBackPressed();
}
}
}
onNewIntent is used because if activity is alive, it will get the first intent that started it. Not the new one. For more detail - Documentation
@DSchmdit answer worked for me. I would like to add on that. So my requirement was to filter a file based on some configurations stored in the table. The file is first retrieved and collected as list of dtos. I receive the configurations from the db and store it as another list. This is how I made the filtering work with streams
List<FPRSDeferralModel> modelList = Files
.lines(Paths.get("src/main/resources/rootFiles/XXXXX.txt")).parallel().parallel()
.map(line -> {
FileModel fileModel= new FileModel();
line = line.trim();
if (line != null && !line.isEmpty()) {
System.out.println("line" + line);
fileModel.setPlanId(Long.parseLong(line.substring(0, 5)));
fileModel.setDivisionList(line.substring(15, 30));
fileModel.setRegionList(line.substring(31, 50));
Map<String, String> newMap = new HashedMap<>();
newMap.put("other", line.substring(51, 80));
fileModel.setOtherDetailsMap(newMap);
}
return fileModel;
}).collect(Collectors.toList());
for (FileModel model : modelList) {
System.out.println("model:" + model);
}
DbConfigModelList respList = populate();
System.out.println("after populate");
List<DbConfig> respModelList = respList.getFeedbackResponseList();
Predicate<FileModel> somePre = s -> respModelList.stream().anyMatch(respitem -> {
System.out.println("sinde respitem:"+respitem.getPrimaryConfig().getPlanId());
System.out.println("s.getPlanid()"+s.getPlanId());
System.out.println("s.getPlanId() == respitem.getPrimaryConfig().getPlanId():"+
(s.getPlanId().compareTo(respitem.getPrimaryConfig().getPlanId())));
return s.getPlanId().compareTo(respitem.getPrimaryConfig().getPlanId()) == 0
&& (s.getSsnId() != null);
});
final List<FileModel> finalList = modelList.stream().parallel().filter(somePre).collect(Collectors.toList());
finalList.stream().forEach(item -> {
System.out.println("filtered item is:"+item);
});
The details are in the implementation of filter predicates. This proves much more perfomant over iterating over loops and filtering out
Once I found what format it was looking for in the connection string, it worked just fine like this with Oracle.ManagedDataAccess. Without having to mess around with anything separately.
DATA SOURCE=DSDSDS:1521/ORCL;
for followers, this error message can also mean "you have it referencing a foreign object that hasn't been saved to the DB yet" (even though it's there, and is non null).
Super remote reset button.
A rack of super special simulation hardware (backin the days when a room full of VME crates did less than your GPU) that a user on the other side of the world would crash in the early hours of the morning. It took an hour to get into the lab and through security.
But we weren't allowed to connect to the super special controller or modify the hardware. The solution was an old DEC workstation with an epson dot matrix printer, tape a plastic ruler to the paper feed knob, position the printer near the reset button.
Log in to the WS as a regular user (no root allowed, all external ports locked down), print a document with 24blank lines - which rotated the paper feed knob and the ruler pressed over the reset on the super special hardware.
Try pd.ExcelFile
:
xls = pd.ExcelFile('path_to_file.xls')
df1 = pd.read_excel(xls, 'Sheet1')
df2 = pd.read_excel(xls, 'Sheet2')
As noted by @HaPsantran, the entire Excel file is read in during the ExcelFile()
call (there doesn't appear to be a way around this). This merely saves you from having to read the same file in each time you want to access a new sheet.
Note that the sheet_name
argument to pd.read_excel()
can be the name of the sheet (as above), an integer specifying the sheet number (eg 0, 1, etc), a list of sheet names or indices, or None
. If a list is provided, it returns a dictionary where the keys are the sheet names/indices and the values are the data frames. The default is to simply return the first sheet (ie, sheet_name=0
).
If None
is specified, all sheets are returned, as a {sheet_name:dataframe}
dictionary.
Using context object you can get LayoutInflater from following code
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Generally you can achieve the same effect by using normal blocking IO and multiplexing several IO operations using select(2)
, poll(2)
or some other system calls available on your system.
See The C10K problem for the comparison of approaches to scalable IO multiplexing.
you can try to install another package:
pip install mysql-connector-python
This package worked fine for me and I got no issues to install.
The issue is it is missing Dynamic Web Module facet definition. Run the following at command line
mvn eclipse:eclipse -Dwtpversion=2.0
After build is success, refresh the project and you will be add the web project to server.
How about this?
fscanf(file,"%d %d %d %d %d %d %d",&line1_1,&line1_2, &line1_3, &line2_1, &line2_2, &line3_1, &line3_2);
In this case spaces in fscanf
match multiple occurrences of any whitespace until the next token in found.
There is no DROP CONSTRAINT
In MySql. This work like magic in mysql 5.7
ALTER TABLE answer DROP KEY const_name;
There is a simple solution for you called unique_together which does exactly what you want.
For example:
class MyModel(models.Model):
field1 = models.CharField(max_length=50)
field2 = models.CharField(max_length=50)
class Meta:
unique_together = ('field1', 'field2',)
And in your case:
class Volume(models.Model):
id = models.AutoField(primary_key=True)
journal_id = models.ForeignKey(Journals, db_column='jid', null=True, verbose_name = "Journal")
volume_number = models.CharField('Volume Number', max_length=100)
comments = models.TextField('Comments', max_length=4000, blank=True)
class Meta:
unique_together = ('journal_id', 'volume_number',)
Debug Diagnostics Tool (DebugDiag) can be a lifesaver. It creates and analyze IIS crash dumps. I figured out my crash in minutes once I saw the call stack. https://support.microsoft.com/en-us/kb/919789
Create Table as select (CTAS) is possible in Hive.
You can try out below command:
CREATE TABLE new_test
row format delimited
fields terminated by '|'
STORED AS RCFile
AS select * from source where col=1
Create table like is also possible in Hive.
Inline functions are faster because you don't need to push and pop things on/off the stack like parameters and the return address; however, it does make your binary slightly larger.
Does it make a significant difference? Not noticeably enough on modern hardware for most. But it can make a difference, which is enough for some people.
Marking something inline does not give you a guarantee that it will be inline. It's just a suggestion to the compiler. Sometimes it's not possible such as when you have a virtual function, or when there is recursion involved. And sometimes the compiler just chooses not to use it.
I could see a situation like this making a detectable difference:
inline int aplusb_pow2(int a, int b) {
return (a + b)*(a + b) ;
}
for(int a = 0; a < 900000; ++a)
for(int b = 0; b < 900000; ++b)
aplusb_pow2(a, b);
My answer would be "be careful". A lot of jQuery table-sorting add-ons only sort what you pass to the browser. In many cases, you have to keep in mind that tables are dynamic sets of data, and could potentially contain zillions of lines of data.
You do mention that you only have 4 columns, but much more importantly, you don't mention how many rows we're talking about here.
If you pass 5000 lines to the browser from the database, knowing that the actual database-table contains 100,000 rows, my question is: what's the point in making the table sortable? In order to do a proper sort, you'd have to send the query back to the database, and let the database (a tool actually designed to sort data) do the sorting for you.
In direct answer to your question though, the best sorting add-on I've come across is Ingrid. There are many reasons that I don't like this add-on ("unnecessary bells and whistles..." as you call it), but one of it's best features in terms of sort, is that it uses ajax, and doesn't assume that you've already passed it all the data before it does its sort.
I recognise that this answer is probably overkill (and over 2 years late) for your requirements, but I do get annoyed when developers in my field overlook this point. So I hope someone else picks up on it.
I feel better now.
In addition to the above I personally recommend
onKeyUp():
Programatically Speaking keydown will fire when the user depresses a key initially but It will repeat while the user keeps the key depressed.*
This remains true for all development platforms.
Google development suggested that if you are intercepting the BACK button in a view you should track the KeyEvent with starttracking on keydown then invoke with keyup.
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK
&& event.getRepeatCount() == 0) {
event.startTracking();
return true;
}
return super.onKeyDown(keyCode, event);
}
public boolean onKeyUp(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.isTracking()
&& !event.isCanceled()) {
// *** Your Code ***
return true;
}
return super.onKeyUp(keyCode, event);
}
It's work for me
private void showForgotDialog(Context c) {
final EditText taskEditText = new EditText(c);
AlertDialog dialog = new AlertDialog.Builder(c)
.setTitle("Forgot Password")
.setMessage("Enter your mobile number?")
.setView(taskEditText)
.setPositiveButton("Reset", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
String task = String.valueOf(taskEditText.getText());
}
})
.setNegativeButton("Cancel", null)
.create();
dialog.show();
}
How to call? (Current activity name)
showForgotDialog(current_activity_name.this);
Well, when writing it out to file, you do know what class T is, so you can store that in dump
. Then, when reading it back in, you can dynamically call it using reflection.
public JSONObject dump() throws JSONException {
JSONObject result = new JSONObject();
JSONArray a = new JSONArray();
for(T i : items){
a.put(i.dump());
// inside this i.dump(), store "class-name"
}
result.put("items", a);
return result;
}
public void load(JSONObject obj) throws JSONException {
JSONArray arrayItems = obj.getJSONArray("items");
for (int i = 0; i < arrayItems.length(); i++) {
JSONObject item = arrayItems.getJSONObject(i);
String className = item.getString("class-name");
try {
Class<?> clazzy = Class.forName(className);
T newItem = (T) clazzy.newInstance();
newItem.load(obj);
items.add(newItem);
} catch (InstantiationException e) {
// whatever
} catch (IllegalAccessException e) {
// whatever
} catch (ClassNotFoundException e) {
// whatever
}
}
this code is work for me
$(document).ready(function () {
setInterval(function(){
$(".blink").fadeOut(function () {
$(this).fadeIn();
});
} ,100)
});
Here is what I learned: PYTHONPATH is a directory to add to the Python import search path "sys.path", which is made up of current dir. CWD, PYTHONPATH, standard and shared library, and customer library. For example:
% python3 -c "import sys;print(sys.path)"
['',
'/home/username/Documents/DjangoTutorial/mySite',
'/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
where the first path '' denotes the current dir., the 2nd path is via
%export PYTHONPATH=/home/username/Documents/DjangoTutorial/mySite
which can be added to ~/.bashrc to make it permanent, and the rest are Python standard and dynamic shared library plus third-party library such as django.
As said not to mess with PYTHONHOME, even setting it to '' or 'None' will cause python3 shell to stop working:
% export PYTHONHOME=''
% python3
Fatal Python error: Py_Initialize: Unable to get the locale encoding
ModuleNotFoundError: No module named 'encodings'
Current thread 0x00007f18a44ff740 (most recent call first):
Aborted (core dumped)
Note that if you start a Python script, the CWD will be the script's directory. For example:
username@bud:~/Documents/DjangoTutorial% python3 mySite/manage.py runserver
==== Printing sys.path ====
/home/username/Documents/DjangoTutorial/mySite # CWD is where manage.py resides
/usr/lib/python3.6
/usr/lib/python3.6/lib-dynload
/usr/local/lib/python3.6/dist-packages
/usr/lib/python3/dist-packages
You can also append a path to sys.path at run-time: Suppose you have a file Fibonacci.py in ~/Documents/Python directory:
username@bud:~/Documents/DjangoTutorial% python3
>>> sys.path.append("/home/username/Documents")
>>> print(sys.path)
['', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages',
'/home/username/Documents']
>>> from Python import Fibonacci as fibo
or via
% PYTHONPATH=/home/username/Documents:$PYTHONPATH
% python3
>>> print(sys.path)
['',
'/home/username/Documents', '/home/username/Documents/DjangoTutorial/mySite',
'/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload',
'/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages']
>>> from Python import Fibonacci as fibo
my openion is valueof() always called tostring() for representaion and so for rpresentaion of primtive type valueof is generalized.and java by default does not support Data type but it define its work with objaect and class its made all thing in cllas and made object .here Integer.toString(int i) create a limit that conversion for only integer.
I usually use a defaultdict for situations like this. You supply a factory method that takes no arguments and creates a value when it sees a new key. It's more useful when you want to return something like an empty list on new keys (see the examples).
from collections import defaultdict
d = defaultdict(lambda: None)
print d['new_key'] # prints 'None'
In Google's closure library project , there is a module which has do the job , below is the API and source code.
Here is a VB.NET solution based on ShravankumarKumar's solution.
This will ONLY give you the text. The images are a different story.
Public Shared Function GetTextFromPDF(PdfFileName As String) As String
Dim oReader As New iTextSharp.text.pdf.PdfReader(PdfFileName)
Dim sOut = ""
For i = 1 To oReader.NumberOfPages
Dim its As New iTextSharp.text.pdf.parser.SimpleTextExtractionStrategy
sOut &= iTextSharp.text.pdf.parser.PdfTextExtractor.GetTextFromPage(oReader, i, its)
Next
Return sOut
End Function
Make sure that, server output is on otherwise output will not be display;
sql> set serveroutput on;
declare
n number(10):=1;
begin
while n<=10
loop
dbms_output.put_line(n);
n:=n+1;
end loop;
end;
/
Outout: 1 2 3 4 5 6 7 8 9 10
Here is a simple solution inside python using a decorator:
import os, time
def daemon(func):
def wrapper(*args, **kwargs):
if os.fork(): return
func(*args, **kwargs)
os._exit(os.EX_OK)
return wrapper
@daemon
def my_func(count=10):
for i in range(0,count):
print('parent pid: %d' % os.getppid())
time.sleep(1)
my_func(count=10)
#still in parent thread
time.sleep(2)
#after 2 seconds the function my_func lives on is own
You can of course replace the content of your bgservice.py
file in place of my_func
.
To add to Brian Diggs answer.
another way using grepl will return a data frame containing all your values.
toMatch <- myfile$Letter
matches <- myfile[grepl(paste(toMatch, collapse="|"), myfile$Letter), ]
matches
Letter Firstname
1 A1 Alex
2 A6 Alex
4 A1 Bob
5 A9 Chris
6 A6 Chris
Maybe a bit cleaner... maybe?
Date d2 = new Date();
Date d1 = new Date(1384831803875l);
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000);
int diffInDays = (int) diff / (1000 * 60 * 60 * 24);
System.out.println(diffInDays+" days");
System.out.println(diffHours+" Hour");
System.out.println(diffMinutes+" min");
System.out.println(diffSeconds+" sec");
class Second:
def __init__(self, data):
self.data = data
class First:
def SecondClass(self, data):
return Second(data)
FirstClass = First()
SecondClass = FirstClass.SecondClass('now you see me')
print SecondClass.data
I think that the main difference is that Marshalling supposedly also involves the codebase. In other words, you would not be able to marshal and unmarshal an object into a state-equivalent instance of a different class. .
Serialization just means that you can store the object and reobtain an equivalent state, even if it is an instance of another class.
That being said, they are typically synonyms.
Simply declare length to be a cons, if it is not then you should be allocating memory dynamically
Just iterate over DataFrame.columns
, now this is an example in which you will end up with a list of column names that match:
import pandas as pd
data = {'spike-2': [1,2,3], 'hey spke': [4,5,6], 'spiked-in': [7,8,9], 'no': [10,11,12]}
df = pd.DataFrame(data)
spike_cols = [col for col in df.columns if 'spike' in col]
print(list(df.columns))
print(spike_cols)
Output:
['hey spke', 'no', 'spike-2', 'spiked-in']
['spike-2', 'spiked-in']
Explanation:
df.columns
returns a list of column names[col for col in df.columns if 'spike' in col]
iterates over the list df.columns
with the variable col
and adds it to the resulting list if col
contains 'spike'
. This syntax is list comprehension. If you only want the resulting data set with the columns that match you can do this:
df2 = df.filter(regex='spike')
print(df2)
Output:
spike-2 spiked-in
0 1 7
1 2 8
2 3 9
Install Tidy2 plugin. I have Notepad++ v6.2.2, and Tidy2 works fine so far.
func resizeImage(image: UIImage, newWidth: CGFloat) -> UIImage? {
let scale = newWidth / image.size.width
let newHeight = CGFloat(200.0)
UIGraphicsBeginImageContext(CGSize(width: newWidth, height: newHeight))
image.draw(in: CGRect(x: 0, y: 0, width: newWidth, height: newHeight))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
Got to this question also looking to revert to match origin (ie, NO commits ahead of origin). Researching further, found there's a reset
command for exactly that:
git reset --hard @{u}
Note: @{u}
is shorthand for origin/master
. (And, of course, you need that remote repository for this to work.)
It's worth understanding what those error messages mean - needs merge
and error: you need to resolve your current index first
indicate that a merge failed, and that there are conflicts in those files. If you've decided that whatever merge you were trying to do was a bad idea after all, you can put things back to normal with:
git reset --merge
However, otherwise you should resolve those merge conflicts, as described in the git manual.
Once you've dealt with that by either technique you should be able to checkout the 9-sign-in-out
branch. The problem with just renaming your 9-sign-in-out
to master
, as suggested in wRAR's answer is that if you've shared your previous master branch with anyone, this will create problems for them, since if the history of the two branches diverged, you'll be publishing rewritten history.
Essentially what you want to do is to merge your topic branch 9-sign-in-out
into master
but exactly keep the versions of the files in the topic branch. You could do this with the following steps:
# Switch to the topic branch:
git checkout 9-sign-in-out
# Create a merge commit, which looks as if it's merging in from master, but is
# actually discarding everything from the master branch and keeping everything
# from 9-sign-in-out:
git merge -s ours master
# Switch back to the master branch:
git checkout master
# Merge the topic branch into master - this should now be a fast-forward
# that leaves you with master exactly as 9-sign-in-out was:
git merge 9-sign-in-out
The general rule-of-thumb is, if you can do it using a single SQL statement instead of using PL/SQL, you should. It will usually be more efficient.
However, if you need to add more procedural logic (for some reason), you might need to use PL/SQL, but you should use bulk operations instead of row-by-row processing. (Note: in Oracle 10g and later, your FOR loop will automatically use BULK COLLECT to fetch 100 rows at a time; however your insert statement will still be done row-by-row).
e.g.
DECLARE
TYPE tA IS TABLE OF FOO.A%TYPE INDEX BY PLS_INTEGER;
TYPE tB IS TABLE OF FOO.B%TYPE INDEX BY PLS_INTEGER;
TYPE tC IS TABLE OF FOO.C%TYPE INDEX BY PLS_INTEGER;
rA tA;
rB tB;
rC tC;
BEGIN
SELECT * BULK COLLECT INTO rA, rB, rC FROM FOO;
-- (do some procedural logic on the data?)
FORALL i IN rA.FIRST..rA.LAST
INSERT INTO BAR(A,
B,
C)
VALUES(rA(i),
rB(i),
rC(i));
END;
The above has the benefit of minimising context switches between SQL and PL/SQL. Oracle 11g also has better support for tables of records so that you don't have to have a separate PL/SQL table for each column.
Also, if the volume of data is very great, it is possible to change the code to process the data in batches.
the plus works just fine, i personally prefer using the concat function.
var s = string.Concat(string 1, string 2, string, 3, etc)
If post data is malformed, $_POST will not contain anything. Yet, php://input will have the malformed string.
For example there is some ajax applications, that do not form correct post key-value sequence for uploading a file, and just dump all the file as post data, without variable names or anything. $_POST will be empty, $_FILES empty also, and php://input will contain exact file, written as a string.
I've used this successfully inside R script:
library("reshape2",lib.loc="/path/to/R-packages/")
useful if for whatever reason libraries are in more than one place.
File pathToBinary = new File("C:\\user\\Programme\\FirefoxPortable\\App\\Firefox\\firefox.exe");
FirefoxBinary ffBinary = new FirefoxBinary(pathToBinary);
FirefoxProfile firefoxProfile = new FirefoxProfile();
WebDriver driver = new FirefoxDriver(ffBinary,firefoxProfile);
The thing I'd found confusing about -prune
is that it's an action (like -print
), not a test (like -name
). It alters the "to-do" list, but always returns true.
The general pattern for using -prune
is this:
find [path] [conditions to prune] -prune -o \
[your usual conditions] [actions to perform]
You pretty much always want the -o
(logical OR) immediately after -prune
, because that first part of the test (up to and including -prune
) will return false for the stuff you actually want (ie: the stuff you don't want to prune out).
Here's an example:
find . -name .snapshot -prune -o -name '*.foo' -print
This will find the "*.foo" files that aren't under ".snapshot" directories. In this example, -name .snapshot
makes up the [conditions to prune]
, and -name '*.foo' -print
is [your usual conditions]
and [actions to perform]
.
Important notes:
If all you want to do is print the results you might be used to leaving out the -print
action. You generally don't want to do that when using -prune
.
The default behavior of find is to "and" the entire expression with the -print
action if there are no actions other than -prune
(ironically) at the end. That means that writing this:
find . -name .snapshot -prune -o -name '*.foo' # DON'T DO THIS
is equivalent to writing this:
find . \( -name .snapshot -prune -o -name '*.foo' \) -print # DON'T DO THIS
which means that it'll also print out the name of the directory you're pruning, which usually isn't what you want. Instead it's better to explicitly specify the -print
action if that's what you want:
find . -name .snapshot -prune -o -name '*.foo' -print # DO THIS
If your "usual condition" happens to match files that also match your prune condition, those files will not be included in the output. The way to fix this is to add a -type d
predicate to your prune condition.
For example, suppose we wanted to prune out any directory that started with .git
(this is admittedly somewhat contrived -- normally you only need to remove the thing named exactly .git
), but other than that wanted to see all files, including files like .gitignore
. You might try this:
find . -name '.git*' -prune -o -type f -print # DON'T DO THIS
This would not include .gitignore
in the output. Here's the fixed version:
find . -name '.git*' -type d -prune -o -type f -print # DO THIS
Extra tip: if you're using the GNU version of find
, the texinfo page for find
has a more detailed explanation than its manpage (as is true for most GNU utilities).
if you need to eliminate duplicates on specific keys, such as a mysqli id, here's a simple funciton
function search_array_compact($data,$key){
$compact = [];
foreach($data as $row){
if(!in_array($row[$key],$compact)){
$compact[] = $row;
}
}
return $compact;
}
Bonus Points You can pass an array of keys and add an outer foreach, but it will be 2x slower per additional key.
If you just need to try something out quickly, here's a quick and dirty solution. Use single quotes for the attribute value:
<parameter name='Quote = " '>
Make sure that the path actually leads to the executables. I'm using version 11 and it did not work until this was set as the path:
C:\Program Files\PostgreSQL\11\bin\bin
Maybe this is how version 11 is structured or I somehow botched the installation but I haven't had a problem since.
MySQL 5.7.5 and up implements detection of functional dependence. If the ONLY_FULL_GROUP_BY SQL mode is enabled (which it is by default), MySQL rejects queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are neither named in the GROUP BY clause nor are functionally dependent on them.
This means that @Jader Dias's solution wouldn't work everywhere.
Here is a solution that would work when ONLY_FULL_GROUP_BY
is enabled:
SET @row := NULL;
SELECT
SomeColumn,
AnotherColumn
FROM (
SELECT
CASE @id <=> SomeColumn AND @row IS NOT NULL
WHEN TRUE THEN @row := @row+1
ELSE @row := 0
END AS rownum,
@id := SomeColumn AS SomeColumn,
AnotherColumn
FROM
SomeTable
ORDER BY
SomeColumn, -AnotherColumn DESC
) _values
WHERE rownum = 0
ORDER BY SomeColumn;
In my case I had a panda Series where the values are tuples of characters:
Out[67]
0 (H, H, H, H)
1 (H, H, H, T)
2 (H, H, T, H)
3 (H, H, T, T)
4 (H, T, H, H)
Therefore I could use indexing to filter the series, but to create the index I needed apply
. My condition is "find all tuples which have exactly one 'H'".
series_of_tuples[series_of_tuples.apply(lambda x: x.count('H')==1)]
I admit it is not "chainable", (i.e. notice I repeat series_of_tuples
twice; you must store any temporary series into a variable so you can call apply(...) on it).
There may also be other methods (besides .apply(...)
) which can operate elementwise to produce a Boolean index.
Many other answers (including accepted answer) using the chainable functions like:
.compress()
.where()
.loc[]
[]
These accept callables (lambdas) which are applied to the Series, not to the individual values in those series!
Therefore my Series of tuples behaved strangely when I tried to use my above condition / callable / lambda, with any of the chainable functions, like .loc[]
:
series_of_tuples.loc[lambda x: x.count('H')==1]
Produces the error:
KeyError: 'Level H must be same as name (None)'
I was very confused, but it seems to be using the Series.count series_of_tuples.count(...)
function , which is not what I wanted.
I admit that an alternative data structure may be better:
This creates a series of strings (i.e. by concatenating the tuple; joining the characters in the tuple on a single string)
series_of_tuples.apply(''.join)
So I can then use the chainable Series.str.count
series_of_tuples.apply(''.join).str.count('H')==1
Example based on ASP.NET CheckBoxList
<asp:CheckBoxList ID="checkBoxList1" runat="server">
<asp:ListItem>abc</asp:ListItem>
<asp:ListItem>def</asp:ListItem>
</asp:CheckBoxList>
private void SelectCheckBoxList(string valueToSelect)
{
ListItem listItem = this.checkBoxList1.Items.FindByText(valueToSelect);
if(listItem != null) listItem.Selected = true;
}
protected void Page_Load(object sender, EventArgs e)
{
SelectCheckBoxList("abc");
}
As others said, you can't actually strictly do what you are asking for. That said, all of the tools available to the angular framework are actually available to you as well! What that means is you can actually write your own elements and provide this feature yourself. I wrote one of these up as an example which you can see at the following plunkr (http://plnkr.co/edit/Qrz9zFjc7Ud6KQoNMEI1).
The key parts of this are that I define a "clickable" element (don't do this if you need older IE support). In code that looks like:
<clickable>
<h1>Hello World!</h1>
</clickable>
Then I defined a directive to take this clickable element and turn it into what I want (something that automatically sets up my click event):
app.directive('clickable', function() {
return {
transclude: true,
restrict: 'E',
template: '<div ng-transclude ng-click="handleClick($event)"></div>'
};
});
Finally in my controller I have the click event ready to go:
$scope.handleClick = function($event) {
var i = 0;
};
Now, its worth stating that this hard codes the name of the method that handles the click event. If you wanted to eliminate this, you should be able to provide the directive with the name of your click handler and "tada" - you have an element (or attribute) that you can use and never have to inject "$event" again.
Hope that helps!
My general pattern is that if it fits on one line, I'll do:
if(true) do_something();
If there's an else clause, or if the code I want to execute on true
is of significant length, braces all the way:
if(true) {
do_something_and_pass_arguments_to_it(argument1, argument2, argument3);
}
if(false) {
do_something();
} else {
do_something_else();
}
Ultimately, it comes down to a subjective issue of style and readability. The general programming world, however, pretty much splits into two parties (for languages that use braces): either use them all the time without exception, or use them all the time with exception. I'm part of the latter group.
mysql_connect("localhost", "root", "") or die(mysql_error()) ;
mysql_select_db("altabotanikk") or die(mysql_error()) ;
These are deprecated use the following..
// Connects to your Database
$link = mysqli_connect("localhost", "root", "", "");
and to insert data use the following
$sql = "INSERT INTO Table-Name (Column-Name)
VALUES ('$filename')" ;
Old-fashioned solution with appropriately named variables. This gives the code some spirit.
#include <cstdio>
int _(char*__){int ___=0;while(*__)___='_'==*__++?___+1:___;return ___;}int main(){char*__="_la_blba_bla__bla___";printf("The string \"%s\" contains %d _ characters\n",__,_(__));}
Edit: about 8 years later, looking at this answer I'm ashamed I did this (even though I justified it to myself as a snarky poke at a low-effort question). This is toxic and not OK. I'm not removing the post; I'm adding this apology to help shifting the atmosphere on StackOverflow. So OP: I apologize and I hope you got your homework right despite my trolling and that answers like mine did not discourage you from participating on the site.
I am currently researching this exact topic in the many (MANY) threads at GameDev.net and found the following two solutions to be good candidates on what I will develop for my game:
ser.read(64)
should be ser.read(size=64)
; ser.read uses keyword arguments, not positional.
Also, you're reading from the port twice; what you probably want to do is this:
i=0
for modem in PortList:
for port in modem:
try:
ser = serial.Serial(port, 9600, timeout=1)
ser.close()
ser.open()
ser.write("ati")
time.sleep(3)
read_val = ser.read(size=64)
print read_val
if read_val is not '':
print port
except serial.SerialException:
continue
i+=1
if you are using class component, you are most likely to use GSerjo suggestion. Pass in the params via <Route>
props to your target component:
exact path="/problem/:problemId" render={props => <ProblemPage {...props.match.params} />}
Assuming you're talking about a static library, DUMPBIN /SYMBOLS
shows the functions and data objects in the library. If you're talking about an import library (a .lib
used to refer to symbols exported from a DLL), then you want DUMPBIN /EXPORTS
.
Note that for functions linked with the "C" binary interface, this still won't get you return values, parameters, or calling convention. That information isn't encoded in the .lib
at all; you have to know that ahead of time (via prototypes in header files, for example) in order to call them correctly.
For functions linked with the C++ binary interface, the calling convention and arguments are encoded in the exported name of the function (also called "name mangling"). DUMPBIN /SYMBOLS
will show you both the "mangled" function name as well as the decoded set of parameters.
This DeltaX and DeltaY as suggested by a comment in the accepted answer to avoid the frustrating experience when trying to click and get a drag operation instead due to a one tick mousemove.
deltaX = deltaY = 2;//px
var element = document.getElementById('divID');
element.addEventListener("mousedown", function(e){
if (typeof InitPageX == 'undefined' && typeof InitPageY == 'undefined') {
InitPageX = e.pageX;
InitPageY = e.pageY;
}
}, false);
element.addEventListener("mousemove", function(e){
if (typeof InitPageX !== 'undefined' && typeof InitPageY !== 'undefined') {
diffX = e.pageX - InitPageX;
diffY = e.pageY - InitPageY;
if ( (diffX > deltaX) || (diffX < -deltaX)
||
(diffY > deltaY) || (diffY < -deltaY)
) {
console.log("dragging");//dragging event or function goes here.
}
else {
console.log("click");//click event or moving back in delta goes here.
}
}
}, false);
element.addEventListener("mouseup", function(){
delete InitPageX;
delete InitPageY;
}, false);
element.addEventListener("click", function(){
console.log("click");
}, false);
You may find this query useful:
SELECT *
FROM sys.dm_exec_requests
WHERE DB_NAME(database_id) = 'YourDBName'
AND blocking_session_id <> 0
I got the same error message as in the title, but in my case import google
was working and import google.protobuf
wasn't (on python3.5, ubuntu 16.04).
It turned out that I've installed python3-google-apputils
package (using apt) and it was installed to '/usr/lib/python3/dist-packages/google/apputils/', while protobuf (which was installed using pip) was in "/usr/lib/python3.5/dist-packages/google/protobuf/" - and it was a "google" namespace collapse.
Uninstalling google-apputils (from apt, and reinstalling it using pip) solved the problem.
sudo apt remove python3-google-apputils
sudo pip3 install google-apputils
Take a look at BackgroundWorker Class, with the OnRunWorkerCompleted you can do it.
Try the line-height property.
For example, 12px font-size and 4px distant from the bottom and upper lines:
line-height: 20px; /* 4px +12px + 4px */
Or with em
units
line-height: 1.7em; /* 1em = 12px in this case. 20/12 == 1.666666 */
Since there is some routine from the the pthread family on the bottom (but I don't know that particular one), my guess would be that you have launched some thread as joinable that has terminated execution.
The exit state information of that thread is kept available until you call pthread_join
. Thus, the memory is kept in a loss record at program termination, but it is still reachable since you could use pthread_join
to access it.
If this analysis is correct, either launch these threads detached, or join them before terminating your program.
Edit: I ran your sample program (after some obvious corrections) and I don't have errors but the following
==18933== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 4 from 4)
--18933--
--18933-- used_suppression: 2 dl-hack3-cond-1
--18933-- used_suppression: 2 glibc-2.5.x-on-SUSE-10.2-(PPC)-2a
Since the dl-
thing resembles much of what you see I guess that you see a known problem that has a solution in terms of a suppression file for valgrind
. Perhaps your system is not up to date, or your distribution doesn't maintain these things. (Mine is ubuntu 10.4, 64bit)
Writing this answer for people who wants to get a file to download with specific content from javascript. I was struggling with the same thing.
const data = {name: 'Ronn', age: 27}; //sample json
const a = document.createElement('a');
const blob = new Blob([JSON.stringify(data)]);
a.href = URL.createObjectURL(blob);
a.download = 'sample-profile'; //filename to download
a.click();
Check Blob documentation here - Blob MDN
ubuntu users:
sudo apt-get install libc6-dev
specially ruby developers that have problem installing gem install json -v '1.8.2'
on their VMs
Edit: Thanks Marc, read up on the struct vs class issue and you're right, thank you!
I tend to use the following method for doing what you describe, using a static method of JSon.Net:
MyObject deserializedObject = JsonConvert.DeserializeObject<MyObject>(json);
Link: Serializing and Deserializing JSON with Json.NET
For the Objects list, may I suggest using generic lists out made out of your own small class containing attributes
and position
class. You can use the Point
struct in System.Drawing
(System.Drawing.Point
or System.Drawing.PointF
for floating point numbers) for you X and Y.
After object creation it's much easier to get the data you're after vs. the text parsing you're otherwise looking at.
You have a few options:
Examples:
PS C:\> explorer
PS C:\> explorer .
PS C:\> explorer /n
PS C:\> Invoke-Item c:\path\
PS C:\> ii c:\path\
PS C:\> Invoke-Item c:\windows\explorer.exe
PS C:\> ii c:\windows\explorer.exe
PS C:\> [diagnostics.process]::start("explorer.exe")
There is another way without using $watch, using angular.copy:
var myApp = angular.module('myApp', []);
myApp.factory('Data', function(){
var service = {
FirstName: '',
setFirstName: function(name) {
// this is the trick to sync the data
// so no need for a $watch function
// call this from anywhere when you need to update FirstName
angular.copy(name, service.FirstName);
}
};
return service;
});
// Step 1 Controller
myApp.controller('FirstCtrl', function( $scope, Data ){
});
// Step 2 Controller
myApp.controller('SecondCtrl', function( $scope, Data ){
$scope.FirstName = Data.FirstName;
});
You do not embed the images in the bundle. They are called through the browser. So its;
var imgSrc = './image/image1.jpg';
return <img src={imgSrc} />
Here is another example that return's a boolean value using try/catch.
private boolean doSomeThing(int index){
try {
if(index%2==0)
return true;
} catch (Exception e) {
System.out.println(e.getMessage());
}finally {
System.out.println("Finally!!! ;) ");
}
return false;
}
Jin Yong - IE has an issue with polluting the global scope with object references to any DOM elements with a "name" or "id" attribute set on the "initial" page load.
Thus you may have issues due to your variable name.
Try this and see if it works.
var someOtherName="abc";
// ^^^^^^^^^^^^^
document.getElementById('msg').value = someOtherName;
document.getElementById('sp_100').checked = true;
There is a chance (in your original code) that IE attempts to set the value of the input to a reference to that actual element (ignores the error) but leaves you with no new value.
Keep in mind that in IE6/IE7 case doesn't matter for naming objects. IE believes that "foo" "Foo" and "FOO" are all the same object.
First you must stop the mousewheel event by either:
mousewheel.disableScroll
e.preventDefault();
el.blur();
The first two approaches both stop the window from scrolling and the last removes focus from the element; both of which are undesirable outcomes.
One workaround is to use el.blur()
and refocus the element after a delay:
$('input[type=number]').on('mousewheel', function(){
var el = $(this);
el.blur();
setTimeout(function(){
el.focus();
}, 10);
});
On thing to remember here is that the default param must be the last param in the function definition.
Following code will not compile:
void fun(int first, int second = 10, int third);
Following code will compile:
void fun(int first, int second, int third = 10);
For applications/projects: Definitely yes.
The composer documentation states on this (with emphasis):
Commit your application's composer.lock (along with composer.json) into version control.
Like @meza said: You should commit the lock file so you and your collaborators are working on the same set of versions and prevent you from sayings like "But it worked on my computer". ;-)
For libraries: Probably not.
The composer documentation notes on this matter:
Note: For libraries it is not necessarily recommended to commit the lock file (...)
And states here:
For your library you may commit the composer.lock file if you want to. This can help your team to always test against the same dependency versions. However, this lock file will not have any effect on other projects that depend on it. It only has an effect on the main project.
For libraries I agree with @Josh Johnson's answer.
One case which is prevalent in duplicates is the requirement to use quotes for external processes. A workaround for that is to not use a shell, which removes the requirement for one level of quoting.
os.system("""awk '/foo/ { print "bar" }' %""" % filename)
can usefully be replaced with
subprocess.call(['awk', '/foo/ { print "bar" }', filename])
(which also fixes the bug that shell metacharacters in filename
would need to be escaped from the shell, which the original code failed to do; but without a shell, no need for that).
Of course, in the vast majority of cases, you don't want or need an external process at all.
with open(filename) as fh:
for line in fh:
if 'foo' in line:
print("bar")
You can use np.where
to match the boolean conditions corresponding to Nan
values of the array and map
each outcome to generate a list of tuples
.
>>>list(map(tuple, np.where(np.isnan(x))))
[(1, 2), (2, 0)]
No need to use static in this case as thoroughly explained. You might as well initialise your property without GetItem()
method, example of both below:
namespace MyNamespace
{
using System;
public class MyType
{
public string MyProperty { get; set; } = new string();
public static string MyStatic { get; set; } = "I'm static";
}
}
Consuming:
using MyType;
public class Somewhere
{
public void Consuming(){
// through instance of your type
var myObject = new MyType();
var alpha = myObject.MyProperty;
// through your type
var beta = MyType.MyStatic;
}
}
<?xml version="1.0" encoding="utf-8"?>_x000D_
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"_x000D_
xmlns:app="http://schemas.android.com/apk/res-auto"_x000D_
xmlns:tools="http://schemas.android.com/tools"_x000D_
android:id="@+id/main_content"_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="match_parent"_x000D_
android:fitsSystemWindows="true"_x000D_
tools:context=".ui.MainActivity"_x000D_
>_x000D_
<android.support.design.widget.AppBarLayout_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="wrap_content"_x000D_
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">_x000D_
_x000D_
<android.support.v7.widget.Toolbar_x000D_
android:id="@+id/toolbar"_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="wrap_content"_x000D_
android:layout_alignParentTop="true"_x000D_
android:background="?attr/colorPrimary"_x000D_
android:elevation="6dp"_x000D_
android:minHeight="?attr/actionBarSize"_x000D_
android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"_x000D_
app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />_x000D_
_x000D_
<android.support.design.widget.TabLayout_x000D_
android:id="@+id/tabs"_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="wrap_content"_x000D_
app:tabMode="fixed"_x000D_
app:tabGravity="fill"_x000D_
>_x000D_
<android.support.design.widget.TabItem_x000D_
android:id="@+id/tabItem"_x000D_
android:layout_width="wrap_content"_x000D_
android:layout_height="wrap_content"_x000D_
android:text="@string/tab_text_1" />_x000D_
_x000D_
<android.support.design.widget.TabItem_x000D_
android:id="@+id/tabItem2"_x000D_
android:layout_width="wrap_content"_x000D_
android:layout_height="wrap_content"_x000D_
android:text="@string/tab_text_2" />_x000D_
<android.support.design.widget.TabItem_x000D_
android:id="@+id/tabItem3"_x000D_
android:layout_width="wrap_content"_x000D_
android:layout_height="wrap_content"_x000D_
android:text="@string/tab_text_3" />_x000D_
<android.support.design.widget.TabItem_x000D_
android:id="@+id/tItemab4"_x000D_
android:layout_width="wrap_content"_x000D_
android:layout_height="wrap_content"_x000D_
android:text="@string/tab_text_4" />_x000D_
</android.support.design.widget.TabLayout>_x000D_
</android.support.design.widget.AppBarLayout>_x000D_
<android.support.v4.view.ViewPager_x000D_
android:id="@+id/container"_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="match_parent"_x000D_
android:layout_below="@id/tabs"_x000D_
app:layout_behavior="@string/appbar_scrolling_view_behavior"_x000D_
tools:ignore="NotSibling"/>_x000D_
</android.support.constraint.ConstraintLayout>
_x000D_
<?xml version="1.0" encoding="utf-8"?>_x000D_
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"_x000D_
xmlns:tools="http://schemas.android.com/tools"_x000D_
android:id="@+id/activity_main"_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="match_parent"_x000D_
tools:context=".ui.MainActivity">_x000D_
<include layout="@layout/tabs"></include>_x000D_
<LinearLayout_x000D_
android:orientation="vertical"_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="match_parent"_x000D_
android:layout_marginBottom="@dimen/activity_vertical_margin"_x000D_
android:layout_marginLeft="@dimen/activity_horizontal_margin"_x000D_
android:layout_marginRight="@dimen/activity_horizontal_margin"_x000D_
android:layout_marginTop="80dp">_x000D_
<FrameLayout android:id="@+id/tabContent"_x000D_
android:layout_weight="1" android:layout_width="match_parent" android:layout_height="0dp">_x000D_
</FrameLayout>_x000D_
</LinearLayout>_x000D_
</RelativeLayout>
_x000D_
public class MainActivity extends AppCompatActivity{_x000D_
_x000D_
private Toolbar toolbar;_x000D_
private TabLayout tabLayout;_x000D_
private ViewPagerAdapter adapter;_x000D_
_x000D_
private final static int[] tabIcons = {_x000D_
R.drawable.ic_action_car,_x000D_
android.R.drawable.ic_menu_mapmode,_x000D_
android.R.drawable.ic_dialog_email,_x000D_
R.drawable.ic_action_settings_x000D_
};_x000D_
_x000D_
protected void onCreate(Bundle savedInstanceState) {_x000D_
super.onCreate(savedInstanceState);_x000D_
setContentView(R.layout.activity_main);_x000D_
_x000D_
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);_x000D_
setSupportActionBar(toolbar);_x000D_
_x000D_
ViewPager viewPager = (ViewPager) findViewById(R.id.container);_x000D_
setupViewPager(viewPager);_x000D_
_x000D_
_x000D_
tabLayout = (TabLayout) findViewById(R.id.tabs);_x000D_
tabLayout.setupWithViewPager(viewPager);_x000D_
setupTabIcons();_x000D_
_x000D_
_x000D_
}_x000D_
private void setupTabIcons() {_x000D_
tabLayout.getTabAt(0).setIcon(tabIcons[0]);_x000D_
tabLayout.getTabAt(1).setIcon(tabIcons[1]);_x000D_
tabLayout.getTabAt(2).setIcon(tabIcons[2]);_x000D_
tabLayout.getTabAt(3).setIcon(tabIcons[3]);_x000D_
}_x000D_
_x000D_
private void setupViewPager(ViewPager viewPager) {_x000D_
adapter = new ViewPagerAdapter(getSupportFragmentManager());_x000D_
adapter.addFrag(new CarFragment());_x000D_
adapter.addFrag(new LocationFragment());_x000D_
adapter.addFrag(new MessageFragment());_x000D_
adapter.addFrag(new SettingsFragment());_x000D_
viewPager.setAdapter(adapter);_x000D_
}_x000D_
_x000D_
class ViewPagerAdapter extends FragmentPagerAdapter {_x000D_
private final List<Fragment> mFragmentList = new ArrayList<>();_x000D_
ViewPagerAdapter(FragmentManager manager) {_x000D_
super(manager);_x000D_
}_x000D_
_x000D_
@Override_x000D_
public Fragment getItem(int position) {_x000D_
return mFragmentList.get(position);_x000D_
}_x000D_
_x000D_
@Override_x000D_
public int getCount() {_x000D_
return mFragmentList.size();_x000D_
}_x000D_
_x000D_
void addFrag(Fragment fragment) {_x000D_
mFragmentList.add(fragment);_x000D_
_x000D_
}_x000D_
_x000D_
}_x000D_
}
_x000D_
A POCO follows the rules of OOP. It should (but doesn't have to) have state and behavior. POCO comes from POJO, coined by Martin Fowler [anecdote here]. He used the term POJO as a way to make it more sexy to reject the framework heavy EJB implementations. POCO should be used in the same context in .Net. Don't let frameworks dictate your object's design.
A DTO's only purpose is to transfer state, and should have no behavior. See Martin Fowler's explanation of a DTO for an example of the use of this pattern.
Here's the difference: POCO describes an approach to programming (good old fashioned object oriented programming), where DTO is a pattern that is used to "transfer data" using objects.
While you can treat POCOs like DTOs, you run the risk of creating an anemic domain model if you do so. Additionally, there's a mismatch in structure, since DTOs should be designed to transfer data, not to represent the true structure of the business domain. The result of this is that DTOs tend to be more flat than your actual domain.
In a domain of any reasonable complexity, you're almost always better off creating separate domain POCOs and translating them to DTOs. DDD (domain driven design) defines the anti-corruption layer (another link here, but best thing to do is buy the book), which is a good structure that makes the segregation clear.
A pure javascript solution
<select id="choice" multiple="multiple">
<option value="1">One</option>
<option value="2">two</option>
<option value="3">three</option>
</select>
<script type="text/javascript">
var optionsToSelect = ['One', 'three'];
var select = document.getElementById( 'choice' );
for ( var i = 0, l = select.options.length, o; i < l; i++ )
{
o = select.options[i];
if ( optionsToSelect.indexOf( o.text ) != -1 )
{
o.selected = true;
}
}
</script>
Although I agree this should be done server-side.
DELIMITER $$
USE `temp` $$
DROP PROCEDURE IF EXISTS `GenerateUniqueValue`$$
CREATE PROCEDURE `GenerateUniqueValue`(IN tableName VARCHAR(255),IN columnName VARCHAR(255))
BEGIN
DECLARE uniqueValue VARCHAR(8) DEFAULT "";
DECLARE newUniqueValue VARCHAR(8) DEFAULT "";
WHILE LENGTH(uniqueValue) = 0 DO
SELECT CONCAT(SUBSTRING('ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789', RAND()*34+1, 1),
SUBSTRING('ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789', RAND()*34+1, 1),
SUBSTRING('ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789', RAND()*34+1, 1),
SUBSTRING('ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789', RAND()*34+1, 1),
SUBSTRING('ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789', RAND()*34+1, 1),
SUBSTRING('ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789', RAND()*34+1, 1),
SUBSTRING('ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789', RAND()*34+1, 1),
SUBSTRING('ABCDEFGHIJKLMNOPQRSTUVWXYZ123456789', RAND()*34+1, 1)
) INTO @newUniqueValue;
SET @rcount = -1;
SET @query=CONCAT('SELECT COUNT(*) INTO @rcount FROM ',tableName,' WHERE ',columnName,' like ''',newUniqueValue,'''');
PREPARE stmt FROM @query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
IF @rcount = 0 THEN
SET uniqueValue = @newUniqueValue ;
END IF ;
END WHILE ;
SELECT uniqueValue;
END$$
DELIMITER ;
And call the stored procedure as GenerateUniqueValue('tableName','columnName'). This will give you a 8 digit unique character everytime.
This example subtracts two lists:
# List of pairs of points
list = []
list.append([(602, 336), (624, 365)])
list.append([(635, 336), (654, 365)])
list.append([(642, 342), (648, 358)])
list.append([(644, 344), (646, 356)])
list.append([(653, 337), (671, 365)])
list.append([(728, 13), (739, 32)])
list.append([(756, 59), (767, 79)])
itens_to_remove = []
itens_to_remove.append([(642, 342), (648, 358)])
itens_to_remove.append([(644, 344), (646, 356)])
print("Initial List Size: ", len(list))
for a in itens_to_remove:
for b in list:
if a == b :
list.remove(b)
print("Final List Size: ", len(list))
If you are struggling with authenticating to a site, and Maven is caching the results, simply removing the meta-data about the site from the meta-data stash will force Maven to revisit the site.
gvim <local-git-repository>/commons-codec/resolver-status.properties
In console start the next command:
emulator -avd emulator_name -http-proxy you_proxy_ip_address:8080
You can't solve it. Simply answer1.sum()==0
, and you can't perform a division by zero.
This happens because answer1
is the exponential of 2 very large, negative numbers, so that the result is rounded to zero.
nan
is returned in this case because of the division by zero.
Now to solve your problem you could:
scipy/numpy
function that does exactly what you want! Check out @Warren Weckesser answer.Here I explain how to do some math manipulation that helps on this problem. We have that for the numerator:
exp(-x)+exp(-y) = exp(log(exp(-x)+exp(-y)))
= exp(log(exp(-x)*[1+exp(-y+x)]))
= exp(log(exp(-x) + log(1+exp(-y+x)))
= exp(-x + log(1+exp(-y+x)))
where above x=3* 1089
and y=3* 1093
. Now, the argument of this exponential is
-x + log(1+exp(-y+x)) = -x + 6.1441934777474324e-06
For the denominator you could proceed similarly but obtain that log(1+exp(-z+k))
is already rounded to 0
, so that the argument of the exponential function at the denominator is simply rounded to -z=-3000
. You then have that your result is
exp(-x + log(1+exp(-y+x)))/exp(-z) = exp(-x+z+log(1+exp(-y+x))
= exp(-266.99999385580668)
which is already extremely close to the result that you would get if you were to keep only the 2 leading terms (i.e. the first number 1089
in the numerator and the first number 1000
at the denominator):
exp(3*(1089-1000))=exp(-267)
For the sake of it, let's see how close we are from the solution of Wolfram alpha (link):
Log[(exp[-3*1089]+exp[-3*1093])/([exp[-3*1000]+exp[-3*4443])] -> -266.999993855806522267194565420933791813296828742310997510523
The difference between this number and the exponent above is +1.7053025658242404e-13
, so the approximation we made at the denominator was fine.
The final result is
'exp(-266.99999385580668) = 1.1050349147204485e-116
From wolfram alpha is (link)
1.105034914720621496.. × 10^-116 # Wolfram alpha.
and again, it is safe to use numpy here too.
You may want to consider placing the customer's name in the From
header and your address in the Sender
header:
From: Company A <[email protected]>
Sender: [email protected]
Most mailers will render this as "From [email protected] on behalf of Company A", which is accurate. And then a Reply-To
of Company A's address won't seem out of sorts.
From RFC 5322:
The "From:" field specifies the author(s) of the message, that is, the mailbox(es) of the person(s) or system(s) responsible for the writing of the message. The "Sender:" field specifies the mailbox of the agent responsible for the actual transmission of the message. For example, if a secretary were to send a message for another person, the mailbox of the secretary would appear in the "Sender:" field and the mailbox of the actual author would appear in the "From:" field.
What I usually do is have a separate filter by PID which would be the equivalent of the current session. But of course it changes every time you run the application. Not good, but it's the only way the have all the info about the app regardless of the log tag.
Here's one way. You have to get the individual components from the date object (day, month & year) and then build and format the string however you wish.
n = new Date();_x000D_
y = n.getFullYear();_x000D_
m = n.getMonth() + 1;_x000D_
d = n.getDate();_x000D_
document.getElementById("date").innerHTML = m + "/" + d + "/" + y;
_x000D_
<p id="date"></p>
_x000D_
Find the default constraint with this query here:
SELECT
df.name 'Constraint Name' ,
t.name 'Table Name',
c.NAME 'Column Name'
FROM sys.default_constraints df
INNER JOIN sys.tables t ON df.parent_object_id = t.object_id
INNER JOIN sys.columns c ON df.parent_object_id = c.object_id AND df.parent_column_id = c.column_id
This gives you the name of the default constraint, as well as the table and column name.
When you have that information you need to first drop the default constraint:
ALTER TABLE dbo.YourTable
DROP CONSTRAINT name-of-the-default-constraint-here
and then you can drop the column
ALTER TABLE dbo.YourTable DROP COLUMN YourColumn
The Android SDK doesn't come with any easy way to draw text on OpenGL views. Leaving you with the following options.
This is not exactly what you're asking for, but you can use docker export
on a stopped container if all you want is to inspect the files.
mkdir $TARGET_DIR
docker export $CONTAINER_ID | tar -x -C $TARGET_DIR
Your original problem was that you were checking if the list was null, which it would never be because you instantiated it with List<Integer> numbers = new ArrayList<Integer>();
. However, you have updated your code to use the List.isEmpty()
method to properly check if the list is empty.
The problem now is that you are never actually sending an empty list to giveList()
. In your do-while loop, you add any input number to the list, even if it is -1. To prevent -1 being added, change the do-while loop to only add numbers if they are not -1. Then, the list will be empty if the user's first input number is -1.
do {
number = Integer.parseInt(JOptionPane.showInputDialog("Enter a number (-1 to stop)"));
/* Change this line */
if (number != -1) numbers.add(number);
} while (number != -1);
replace:
transport_select.onChange = function(){toggleSelect(transport_select_id);};
with:
transport_select.onchange = function(){toggleSelect(transport_select_id);};
on'C'hange >> on'c'hange
You can use addEventListener too.
The problem here is that you have two different languages that solve two different problems... its like comparing C++ with assembler.
Python is for rapid application development and for when performance is a minimal concern.
C++ is not for rapid application development and inherits a legacy of speed from C - for low level programming.
I'll post what worked for me, thanks to @xavi-montero.
Put your CSS in your bundle's Resource/public/css
directory, and your images in say Resource/public/img
.
Change assetic paths to the form 'bundles/mybundle/css/*.css'
, in your layout.
In config.yml
, add rule css_rewrite
to assetic:
assetic:
filters:
cssrewrite:
apply_to: "\.css$"
Now install assets and compile with assetic:
$ rm -r app/cache/* # just in case
$ php app/console assets:install --symlink
$ php app/console assetic:dump --env=prod
This is good enough for the development box, and --symlink
is useful, so you don't have to reinstall your assets (for example, you add a new image) when you enter through app_dev.php
.
For the production server, I just removed the '--symlink' option (in my deployment script), and added this command at the end:
$ rm -r web/bundles/*/css web/bundles/*/js # all this is already compiled, we don't need the originals
All is done. With this, you can use paths like this in your .css files: ../img/picture.jpeg
awk '{print substr($0,6)}' file
You're calculating the y-part of your new coordinate based on the 'new' x-part of the new coordinate. Basically this means your calculating the new output in terms of the new output...
Try to rewrite in terms of input and output:
vector2<double> multiply( vector2<double> input, double cs, double sn ) {
vector2<double> result;
result.x = input.x * cs - input.y * sn;
result.y = input.x * sn + input.y * cs;
return result;
}
Then you can do this:
vector2<double> input(0,1);
vector2<double> transformed = multiply( input, cs, sn );
Note how choosing proper names for your variables can avoid this problem alltogether!
Just using an ALTER TABLE should work. Add the column with the proper type and an IDENTITY flag and it should do the trick
Check out this MSDN article http://msdn.microsoft.com/en-us/library/aa275462(SQL.80).aspx on the ALTER TABLE syntax
I've figured out a way that works. You can subclass SimpleFormatter and override the format method
public String format(LogRecord record) {
return new java.util.Date() + " " + record.getLevel() + " " + record.getMessage() + "\r\n";
}
A bit surprised at this API I would have thought that more functionality/flexibility would have been provided out of the box
If you are using javac
to compile, and you get this error, then
remove all the .class
files
rm *.class # On Unix-based systems
and recompile.
javac fileName.java
They each return the same singleton None
-- There is no functional difference.
I think that it is reasonably idiomatic to leave off the return
statement unless you need it to break out of the function early (in which case a bare return
is more common), or return something other than None
. It also makes sense and seems to be idiomatic to write return None
when it is in a function that has another path that returns something other than None
. Writing return None
out explicitly is a visual cue to the reader that there's another branch which returns something more interesting (and that calling code will probably need to handle both types of return values).
Often in Python, functions which return None
are used like void
functions in C -- Their purpose is generally to operate on the input arguments in place (unless you're using global data (shudders)). Returning None
usually makes it more explicit that the arguments were mutated. This makes it a little more clear why it makes sense to leave off the return
statement from a "language conventions" standpoint.
That said, if you're working in a code base that already has pre-set conventions around these things, I'd definitely follow suit to help the code base stay uniform...
Yes. Please see the man page of bash ( the first thing you go to ) under Special Parameters
Special Parameters
The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed.
*
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is,"$*"
is equivalent to"$1c$2c..."
, wherec
is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.
@
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is,"$@"
is equivalent to"$1"
"$2"
... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters,"$@"
and$@
expand to nothing (i.e., they are removed).
There is flexibility in using lambda as parameter. It enables functional programming in java. The basic syntax is
param -> method_body
Following is a way, you can define a method taking functional interface (lambda is used) as parameter.
a. if you wish to define a method declared inside a functional interface,
say, the functional interface is given as an argument/parameter to a method called from main()
@FunctionalInterface
interface FInterface{
int callMeLambda(String temp);
}
class ConcreteClass{
void funcUsesAnonymousOrLambda(FInterface fi){
System.out.println("===Executing method arg instantiated with Lambda==="));
}
public static void main(){
// calls a method having FInterface as an argument.
funcUsesAnonymousOrLambda(new FInterface() {
int callMeLambda(String temp){ //define callMeLambda(){} here..
return 0;
}
}
}
/***********Can be replaced by Lambda below*********/
funcUsesAnonymousOrLambda( (x) -> {
return 0; //(1)
}
}
FInterface fi = (x) -> { return 0; };
funcUsesAnonymousOrLambda(fi);
Here above it can be seen, how a lambda expression can be replaced with an interface.
Above explains a particular usage of lambda expression, there are more. ref Java 8 lambda within a lambda can't modify variable from outer lambda
Several things here.
First off, you're defining your CSS in 3 places!
In line, in the head and externally. I suggest you only choose one. I'm going to suggest externally.
I suggest you update your code in your ASP form from
<td style="background-color: #A3A3A3; color: #FFFFFF; font-family: 'Arial Black'; font-size: large; font-weight: bold;"
class="style6">
to this:
<td class="style6">
And then update your css too
.style6
{
height: 79px; background-color: #A3A3A3; color: #FFFFFF; font-family: 'Arial Black'; font-size: large; font-weight: bold;
}
This removes the inline.
Now, to move it from the head of the webForm.
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>AR Toolbox</title>
<link rel="Stylesheet" href="css/master.css" type="text/css" />
</head>
<body>
<form id="form1" runat="server">
<table class="style1">
<tr>
<td class="style6">
<asp:Menu ID="Menu1" runat="server">
<Items>
<asp:MenuItem Text="Home" Value="Home"></asp:MenuItem>
<asp:MenuItem Text="About" Value="About"></asp:MenuItem>
<asp:MenuItem Text="Compliance" Value="Compliance">
<asp:MenuItem Text="Item 1" Value="Item 1"></asp:MenuItem>
<asp:MenuItem Text="Item 2" Value="Item 2"></asp:MenuItem>
</asp:MenuItem>
<asp:MenuItem Text="Tools" Value="Tools"></asp:MenuItem>
<asp:MenuItem Text="Contact" Value="Contact"></asp:MenuItem>
</Items>
</asp:Menu>
</td>
</tr>
<tr>
<td class="style6">
<img alt="South University'" class="style7"
src="file:///C:/Users/jnewnam/Documents/Visual%20Studio%202010/WebSites/WebSite1/img/suo_n_seal_hor_pantone.png" /></td>
</tr>
<tr>
<td class="style2">
<table class="style3">
<tr>
<td>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td style="color: #FFFFFF; background-color: #A3A3A3">
This is the footer.</td>
</tr>
</table>
</form>
</body>
</html>
Now, in a new file called master.css (in your css folder) add
ul {
list-style-type:none;
margin:0;
padding:0;
}
li {
display:inline;
padding:20px;
}
.style1
{
width: 100%;
}
.style2
{
height: 459px;
}
.style3
{
width: 100%;
height: 100%;
}
.style6
{
height: 79px; background-color: #A3A3A3; color: #FFFFFF; font-family: 'Arial Black'; font-size: large; font-weight: bold;
}
.style7
{
width: 345px;
height: 73px;
}
Actually Windows does have a utility that encodes and decodes base64 - CERTUTIL
I'm not sure what version of Windows introduced this command.
To encode a file:
certutil -encode inputFileName encodedOutputFileName
To decode a file:
certutil -decode encodedInputFileName decodedOutputFileName
There are a number of available verbs and options available to CERTUTIL.
To get a list of nearly all available verbs:
certutil -?
To get help on a particular verb (-encode for example):
certutil -encode -?
To get complete help for nearly all verbs:
certutil -v -?
Mysteriously, the -encodehex
verb is not listed with certutil -?
or certutil -v -?
. But it is described using certutil -encodehex -?
. It is another handy function :-)
Regarding David Morales' comment, there is a poorly documented type option to the -encodehex
verb that allows creation of base64 strings without header or footer lines.
certutil [Options] -encodehex inFile outFile [type]
A type of 1 will yield base64 without the header or footer lines.
See https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p56536 for a brief listing of the available type formats. And for a more in depth look at the available formats, see https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p57918.
Not investigated, but the -decodehex
verb also has an optional trailing type argument.
public static byte[] my_int_to_bb_le(int myInteger){
return ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(myInteger).array();
}
public static int my_bb_to_int_le(byte [] byteBarray){
return ByteBuffer.wrap(byteBarray).order(ByteOrder.LITTLE_ENDIAN).getInt();
}
public static byte[] my_int_to_bb_be(int myInteger){
return ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(myInteger).array();
}
public static int my_bb_to_int_be(byte [] byteBarray){
return ByteBuffer.wrap(byteBarray).order(ByteOrder.BIG_ENDIAN).getInt();
}
Just Change the Connection mysql string to 127.0.0.1 and it will work
I downloaded this "IE Tab Multi" from Chrome. It works good! http://iblogbox.com/chrome/ietab/alert.php
In Vue2, use v-bind.
Say I have an object for a poll
<div class="options" v-for="option in poll.body.options">
<div class="poll-item">
<label v-bind:for="option._id" v-bind:style="{color: option.color}">{{option.text}}</label>
<input type="radio" v-model="picked" v-bind:value="option._id" v-bind:id="option._id">
</div>
</div>
The key is the sql query, which you will set up as a string:
$sqlquery = "SELECT field1, field2 FROM table WHERE NOT columnA = 'x' AND NOT columbB = 'y'";
Note that there are a lot of ways to specify NOT. Another one that works just as well is:
$sqlquery = "SELECT field1, field2 FROM table WHERE columnA != 'x' AND columbB != 'y'";
Here is a full example of how to use it:
$link = mysql_connect($dbHost,$dbUser,$dbPass) or die("Unable to connect to database");
mysql_select_db("$dbName") or die("Unable to select database $dbName");
$sqlquery = "SELECT field1, field2 FROM table WHERE NOT columnA = 'x' AND NOT columbB = 'y'";
$result=mysql_query($sqlquery);
while ($row = mysql_fetch_assoc($result) {
//do stuff
}
You can do whatever you would like within the above while loop. Access each field of the table as an element of the $row array
which means that $row['field1']
will give you the value for field1
on the current row, and $row['field2']
will give you the value for field2
.
Note that if the column(s) could have NULL
values, those will not be found using either of the above syntaxes. You will need to add clauses to include NULL
values:
$sqlquery = "SELECT field1, field2 FROM table WHERE (NOT columnA = 'x' OR columnA IS NULL) AND (NOT columbB = 'y' OR columnB IS NULL)";
You can give your input textboxes class names, like so:
<input type="text" value="2" name="pages_title[1]" class="pages_title">
<input type="text" value="1" name="pages_title[2]" class="pages_title">
and iterate like so:
$('input.pages_title').each(function() {
alert($(this).val());
});
After wasting a lot of time in finding its solution, I've found one. For your convenience I've used the complete code that you can replace your whole file with.
This is a general answer. Let's say you want to import a file named testjs.js into your angular 2 component. Create testjs.js in your assets folder:
assets > testjs.js
function test(){
alert('TestingFunction')
}
include testjs.js in your index.html
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Project1</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<script src="./assets/testjs.js"></script>
</head>
<body>
<app-root>Loading...</app-root>
</body>
</html>
In your app.component.ts or in any component.ts file where you want to call this js declare a variable and call the function like below:
app.component.ts
import { Component } from '@angular/core';
declare var test: any;
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'app works!';
f(){
new test();
}
}
Finally in your app.component.html test the function
app.component.html
<h1>
<button (click)='f()'>Test</button>
</h1>
right-click virtual directory (e.g. MyVirtualDirectory)
click convert to application.
You are reinventing the wheel.
If you need persistence and other enterprise features use JMS (I'd suggest ActiveMq).
If you need fast in-memory queues use one of the impementations of java's Queue.
If you need to support java 1.4 or earlier, use Doug Lea's excellent concurrent package.
To match regexes you need to use the =~
operator.
Try this:
[[ sed-4.2.2.tar.bz2 =~ tar.bz2$ ]] && echo matched
Alternatively, you can use wildcards (instead of regexes) with the ==
operator:
[[ sed-4.2.2.tar.bz2 == *tar.bz2 ]] && echo matched
If portability is not a concern, I recommend using [[
instead of [
or test
as it is safer and more powerful. See What is the difference between test, [ and [[ ? for details.
Adding this in the config.inc.php
file worked for me (under the last $cfg line):
$cfg['RowActionLinksWithoutUnique'] = 'true';
The file should be located in the phpMyAdmin
folder on your local computer
See ?merge
:
the name "row.names" or the number 0 specifies the row names.
Example:
R> de <- merge(d, e, by=0, all=TRUE) # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0 # replace NA values
R> de
Row.names a b c d e f g h i j k l m n o p q r s
1 1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2 2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9 1 0 0 0 0 0 0 0 0 0
3 3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0 21 22 23 24 25 26 27 28 29
t
1 20
2 0
3 30
use html5
's new attribute srcdoc
(srcdoc-polyfill) Docs
<iframe srcdoc="<html><body>Hello, <b>world</b>.</body></html>"></iframe>
Browser support - Tested in the following browsers:
Microsoft Internet Explorer
6, 7, 8, 9, 10, 11
Microsoft Edge
13, 14
Safari
4, 5.0, 5.1 ,6, 6.2, 7.1, 8, 9.1, 10
Google Chrome
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24.0.1312.5 (beta), 25.0.1364.5 (dev), 55
Opera
11.1, 11.5, 11.6, 12.10, 12.11 (beta) , 42
Mozilla FireFox
3.0, 3.6, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 (beta), 50
You can make it easier in your code (if you're doing this a lot anyway) by using an extension on the DataRow object, like:
static class Extensions
{
public static string GetColumn(this DataRow Row, int Ordinal)
{
return Row.Table.Columns[Ordinal].ColumnName;
}
}
Then call it using:
string MyColumnName = MyRow.GetColumn(5);
Had the same issue. I used a dirty trick like so:
var s = '<div id="myDiv"></div>';
var temp = document.createElement('div');
temp.innerHTML = s;
var htmlObject = temp.firstChild;
Now, you can add styles the way you like:
htmlObject.style.marginTop = something;
According to the json.org specification, your return is invalid. The names are always quoted, so you should be returning
{ "title": "One", "key": "1" }
and
[ { "title": "One", "key": "1" }, { "title": "Two", "key": "2" } ]
This may not be the problem with your setup, since you say one of them works now, but it should be fixed for correctness in case you need to switch to another JSON parser in the future.
To get the value of a pointer, just de-reference the pointer.
int *ptr;
int value;
*ptr = 9;
value = *ptr;
value is now 9.
I suggest you read more about pointers, this is their base functionality.
Based on (dangerouslySetInnerHTML).
It's a prop that does exactly what you want. However they name it to convey that it should be use with caution
Python slicing is an incredibly fast operation, and it's a handy way to quickly access parts of your data.
Slice notation to get the last nine elements from a list (or any other sequence that supports it, like a string) would look like this:
num_list[-9:]
When I see this, I read the part in the brackets as "9th from the end, to the end." (Actually, I abbreviate it mentally as "-9, on")
The full notation is
sequence[start:stop:step]
But the colon is what tells Python you're giving it a slice and not a regular index. That's why the idiomatic way of copying lists in Python 2 is
list_copy = sequence[:]
And clearing them is with:
del my_list[:]
(Lists get list.copy
and list.clear
in Python 3.)
You may find it useful to separate forming the slice from passing it to the list.__getitem__
method (that's what the square brackets do). Even if you're not new to it, it keeps your code more readable so that others that may have to read your code can more readily understand what you're doing.
However, you can't just assign some integers separated by colons to a variable. You need to use the slice object:
last_nine_slice = slice(-9, None)
The second argument, None
, is required, so that the first argument is interpreted as the start
argument otherwise it would be the stop
argument.
You can then pass the slice object to your sequence:
>>> list(range(100))[last_nine_slice]
[91, 92, 93, 94, 95, 96, 97, 98, 99]
islice
islice
from the itertools module is another possibly performant way to get this. islice
doesn't take negative arguments, so ideally your iterable has a __reversed__
special method - which list does have - so you must first pass your list (or iterable with __reversed__
) to reversed
.
>>> from itertools import islice
>>> islice(reversed(range(100)), 0, 9)
<itertools.islice object at 0xffeb87fc>
islice allows for lazy evaluation of the data pipeline, so to materialize the data, pass it to a constructor (like list
):
>>> list(islice(reversed(range(100)), 0, 9))
[99, 98, 97, 96, 95, 94, 93, 92, 91]
Take a look at TestComplete.
- (float)__getMemoryUsedPer1
{
struct mach_task_basic_info info;
mach_msg_type_number_t size = MACH_TASK_BASIC_INFO;
kern_return_t kerr = task_info(mach_task_self(), MACH_TASK_BASIC_INFO, (task_info_t)&info, &size);
if (kerr == KERN_SUCCESS)
{
float used_bytes = info.resident_size;
float total_bytes = [NSProcessInfo processInfo].physicalMemory;
//NSLog(@"Used: %f MB out of %f MB (%f%%)", used_bytes / 1024.0f / 1024.0f, total_bytes / 1024.0f / 1024.0f, used_bytes * 100.0f / total_bytes);
return used_bytes / total_bytes;
}
return 1;
}
If one will use TASK_BASIC_INFO_COUNT instead of MACH_TASK_BASIC_INFO, you will get
kerr == KERN_INVALID_ARGUMENT (4)
"...by a class and a div."
I assume when you say "div" you mean "id"? Try this:
$('#test2.test1').prop('checked', true);
No need to muck about with your [attributename=value]
style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".
Or more generally to select an input where you want to specify a multiple attribute selector:
$('input:radio[class=test1][id=test2]').prop('checked', true);
That is, list each attribute with its own square brackets.
Note that unless you have a pretty old version of jQuery you should use .prop()
rather than .attr()
for this purpose.
The git submodule update
command actually tells Git that you want your submodules to each check out the commit already specified in the index of the superproject. If you want to update your submodules to the latest commit available from their remote, you will need to do this directly in the submodules.
So in summary:
# Get the submodule initially
git submodule add ssh://bla submodule_dir
git submodule init
# Time passes, submodule upstream is updated
# and you now want to update
# Change to the submodule directory
cd submodule_dir
# Checkout desired branch
git checkout master
# Update
git pull
# Get back to your project root
cd ..
# Now the submodules are in the state you want, so
git commit -am "Pulled down update to submodule_dir"
Or, if you're a busy person:
git submodule foreach git pull origin master
Let's say that your list name is A
Then you can code the following and you will have it as a csv file (columns only!)
R="\n".join(A)
f = open('Columns.csv','w')
f.write(R)
f.close()
The correct way from hibernate doc:
Session s = HibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
try {
tx = s.beginTransaction();
// here get object
List<Employee> list = s.createCriteria(Employee.class).list();
tx.commit();
} catch (HibernateException ex) {
if (tx != null) {
tx.rollback();
}
Logger.getLogger("con").info("Exception: " + ex.getMessage());
ex.printStackTrace(System.err);
} finally {
s.close();
}
HibernateUtil code (can find at Google):
public class HibernateUtil {
private static final SessionFactory tmrSessionFactory;
private static final Ejb3Configuration tmrEjb3Config;
private static final EntityManagerFactory tmrEntityManagerFactory;
static {
try {
tmrSessionFactory = new Configuration().configure("tmr.cfg.xml").buildSessionFactory();
tmrEjb3Config = new Ejb3Configuration().configure("tmr.cfg.xml");
tmrEntityManagerFactory = tmrEjb3Config.buildEntityManagerFactory();
} catch (HibernateException ex) {
Logger.getLogger("app").log(Level.WARN, ex.getMessage());
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return tmrSessionFactory;
}
/* getters and setters here */
}
As you surmise, it is to do with the connection string being in app.config of the class library.
Copy the entry from the class app.config to the container's app.config
or web.config
file