The TypeInitializationException
that is thrown as a wrapper around the exception thrown by the class initializer. This class cannot be inherited.
TypeInitializationException is also called static constructors.
You cannot update UI from any other thread other than the UI thread. Use this to update thread on the UI thread.
private void AggiornaContatore()
{
if(this.lblCounter.InvokeRequired)
{
this.lblCounter.BeginInvoke((MethodInvoker) delegate() {this.lblCounter.Text = this.index.ToString(); ;});
}
else
{
this.lblCounter.Text = this.index.ToString(); ;
}
}
Please go through this chapter and more from this book to get a clear picture about threading:
http://www.albahari.com/threading/part2.aspx#_Rich_Client_Applications
static void Main(string[] args)
{
//---listen at the specified IP and port no.---
IPAddress localAdd = IPAddress.Parse(SERVER_IP);
TcpListener listener = new TcpListener(localAdd, PORT_NO);
Console.WriteLine("Listening...");
listener.Start();
while (true)
{
//---incoming client connected---
TcpClient client = listener.AcceptTcpClient();
//---get the incoming data through a network stream---
NetworkStream nwStream = client.GetStream();
byte[] buffer = new byte[client.ReceiveBufferSize];
//---read incoming stream---
int bytesRead = nwStream.Read(buffer, 0, client.ReceiveBufferSize);
//---convert the data received into a string---
string dataReceived = Encoding.ASCII.GetString(buffer, 0, bytesRead);
Console.WriteLine("Received : " + dataReceived);
//---write back the text to the client---
Console.WriteLine("Sending back : " + dataReceived);
nwStream.Write(buffer, 0, bytesRead);
client.Close();
}
listener.Stop();
Console.ReadLine();
}
In addition to @Nudier Mena answer, keep a while loop to keep the server in listening mode. So that we can have multiple instance of client connected.
The task gives you all the goodness of the task API:
Task.ContinueWith
)Note that in both cases you can make your code slightly simpler with method group conversions:
DataInThread = new Thread(ThreadProcedure);
// Or...
Task t = Task.Factory.StartNew(ThreadProcedure);
If you do find yourslef needing a Comparator
, and you already use Guava
, you can use Ordering.natural()
.
I had a similar issue with Datagrip and none of these solutions worked.
Once I restarted the Datagrip Client it was no longer an issue and I could drop tables again.
For a CSS only solution:
<div class="file-area">
<input type="file">
<div class="file-dummy">
<span class="default">Click to select a file, or drag it here</span>
<span class="success">Great, your file is selected</span>
</div>
</div>
.file-area {
width: 100%;
position: relative;
font-size: 18px;
}
.file-area input[type=file] {
position: absolute;
width: 100%;
height: 100%;
top: 0;
left: 0;
right: 0;
bottom: 0;
opacity: 0;
cursor: pointer;
}
.file-area .file-dummy {
width: 100%;
padding: 50px 30px;
border: 2px dashed #ccc;
background-color: #fff;
text-align: center;
transition: background 0.3s ease-in-out;
}
.file-area .file-dummy .success {
display: none;
}
.file-area:hover .file-dummy {
border: 2px dashed #1abc9c;
}
.file-area input[type=file]:valid + .file-dummy {
border-color: #1abc9c;
}
.file-area input[type=file]:valid + .file-dummy .success {
display: inline-block;
}
.file-area input[type=file]:valid + .file-dummy .default {
display: none;
}
Adapted from https://codepen.io/Scribblerockerz/pen/qdWzJw
Adding a unique item to a another list
searchResults: [
{
name: 'Hello',
artist: 'Selana',
album: 'Riga',
id: 1,
},
{
name: 'Hello;s',
artist: 'Selana G',
album: 'Riga1',
id: 2,
},
{
name: 'Hello2',
artist: 'Selana',
album: 'Riga11',
id: 3,
}
],
playlistTracks: [
{
name: 'Hello',
artist: 'Mamunuus',
album: 'Riga',
id: 4,
},
{
name: 'Hello;s',
artist: 'Mamunuus G',
album: 'Riga1',
id: 2,
},
{
name: 'Hello2',
artist: 'Mamunuus New',
album: 'Riga11',
id: 3,
}
],
playlistName: "New PlayListTrack",
};
}
// Adding an unique track in the playList
addTrack = track => {
if(playlistTracks.find(savedTrack => savedTrack.id === track.id)) {
return;
}
playlistTracks.push(track);
this.setState({
playlistTracks
})
};
In IntelliJ you can specify default settings for each run configuration. In Run/Debug configuration dialog (the one you use to configure heap per test) click on Defaults and JUnit. These settings will be automatically applied to each new JUnit test configuration. I guess similar setting exists for Eclipse.
However there is no simple option to transfer such settings (at least in IntelliJ) across environments. You can commit IntelliJ project files to your repository: it might work, but I do not recommend it.
You know how to set these for maven-surefire-plugin
. Good. This is the most portable way (see Ptomli's answer for an example).
For the rest - you must remember that JUnit test cases are just a bunch of Java classes, not a standalone program. It is up to the runner (let it be a standalone JUnit runner, your IDE, maven-surefire-plugin
to set those options. That being said there is no "portable" way to set them, so that memory settings are applied irrespective to the runner.
To give you an example: you cannot define Xmx
parameter when developing a servlet - it is up to the container to define that. You can't say: "this servlet should always be run with Xmx=1G
.
You can use except , for example something like this :
-- DB1..Tb1 have values than DB2..Tb1 not have
Select Col1,Col2,Col3 From DB1..Tb1
except
Select Col1,Col2,Col3 From DB2..Tb1
-- Now we change order
-- DB2..Tb1 have values than DB1..Tb1 not have
Select Col1,Col2,Col3 From DB2..Tb1
except
Select Col1,Col2,Col3 From DB1..Tb1
I've made an attempt to implement a pull to refresh component, it's far from complete but demonstrates a possible implementation, https://github.com/johannilsson/android-pulltorefresh.
Main logic is implemented in PullToRefreshListView
that extends ListView
. Internally it controls the scrolling of a header view using The widget is now updated with support for 1.5 and later, please read the README for 1.5 support though.smoothScrollBy
(API Level 8).
In your layouts you simply add it like this.
<com.markupartist.android.widget.PullToRefreshListView
android:id="@+id/android:list"
android:layout_height="fill_parent"
android:layout_width="fill_parent"
/>
Sadly, no, you can't run 4.5 programs on XP.
And the relevant post from that Connect page:
Posted by Microsoft on 23/03/2012 at 10:39
Thanks for the report. This behavior is by design in .NET Framework 4.5 Beta. The minimum supported operating systems are Windows 7, Windows Server 2008 SP2 and Windows Server 2008 R2 SP1. Windows XP is not a supported operating system for the Beta release.
from tkinter import *
import time
tk=Tk()
def clock():
t=time.strftime('%I:%M:%S',time.localtime())
if t!='':
label1.config(text=t,font='times 25')
tk.after(100,clock)
label1=Label(tk,justify='center')
label1.pack()
clock()
tk.mainloop()
We can write something like this. I have used with python-3.7.x
import sys
def print_fn():
print("Hi")
def sum_fn(a, b):
print(a + b)
if __name__ == "__main__":
args = sys.argv
# args[0] = current file
# args[1] = function name
# args[2:] = function args : (*unpacked)
globals()[args[1]](*args[2:])
python demo.py print_fn
python demo.py sum_fn 5 8
The accepted answer will work if you can easily reproduce the issue. However, as a matter of best practice, you should be catching any exceptions (and logging) that are executed within a task. Otherwise, your application will crash if anything unexpected occurs within the task.
Task.Factory.StartNew(x=>
throw new Exception("I didn't account for this");
)
However, if we do this, at least the application does not crash.
Task.Factory.StartNew(x=>
try {
throw new Exception("I didn't account for this");
}
catch(Exception ex) {
//Log ex
}
)
I found something very useful on this site when I was searching for an answer on this question. You can check it out at http://www.codingforums.com/javascript-programming/230503-how-get-margin-left-value.html. The part that helped me was the following:
/***
* get live runtime value of an element's css style
* http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element
* note: "styleName" is in CSS form (i.e. 'font-size', not 'fontSize').
***/
var getStyle = function(e, styleName) {
var styleValue = "";
if (document.defaultView && document.defaultView.getComputedStyle) {
styleValue = document.defaultView.getComputedStyle(e, "").getPropertyValue(styleName);
} else if (e.currentStyle) {
styleName = styleName.replace(/\-(\w)/g, function(strMatch, p1) {
return p1.toUpperCase();
});
styleValue = e.currentStyle[styleName];
}
return styleValue;
}
////////////////////////////////////
var e = document.getElementById('yourElement');
var marLeft = getStyle(e, 'margin-left');
console.log(marLeft); // 10px
_x000D_
#yourElement {
margin-left: 10px;
}
_x000D_
<div id="yourElement"></div>
_x000D_
I am combining the solutions from answers of @FredFoo and @Renaud. My solution is able to apply @Renaud's preprocessing on the text corpus of @FredFoo and then display pairwise similarities where the similarity is greater than 0. I ran this code on Windows by installing python and pip first. pip is installed as part of python but you may have to explicitly do it by re-running the installation package, choosing modify and then choosing pip. I use the command line to execute my python code saved in a file "similarity.py". I had to execute the following commands:
>set PYTHONPATH=%PYTHONPATH%;C:\_location_of_python_lib_
>python -m pip install sklearn
>python -m pip install nltk
>py similarity.py
The code for similarity.py is as follows:
from sklearn.feature_extraction.text import TfidfVectorizer
import nltk, string
import numpy as np
nltk.download('punkt') # if necessary...
stemmer = nltk.stem.porter.PorterStemmer()
remove_punctuation_map = dict((ord(char), None) for char in string.punctuation)
def stem_tokens(tokens):
return [stemmer.stem(item) for item in tokens]
def normalize(text):
return stem_tokens(nltk.word_tokenize(text.lower().translate(remove_punctuation_map)))
corpus = ["I'd like an apple",
"An apple a day keeps the doctor away",
"Never compare an apple to an orange",
"I prefer scikit-learn to Orange",
"The scikit-learn docs are Orange and Blue"]
vect = TfidfVectorizer(tokenizer=normalize, stop_words='english')
tfidf = vect.fit_transform(corpus)
pairwise_similarity = tfidf * tfidf.T
#view the pairwise similarities
print(pairwise_similarity)
#check how a string is normalized
print(normalize("The scikit-learn docs are Orange and Blue"))
Two problems:
You write that you ran
git init
git commit -m "first commit"
and that, at that stage, you got
nothing added to commit but untracked files present (use "git add" to track).
Git is telling you that you never told it to start tracking any files in the first place, and it has nothing to take a snapshot of. Therefore, Git creates no commit. Before attempting to commit, you should tell Git (for instance):
Hey Git, you see that
README.md
file idly sitting in my working directory, there? Could you put it under version control for me? I'd like it to go in my first commit/snapshot/revision...
For that you need to stage the files of interest, using
git add README.md
before running
git commit -m "some descriptive message"
You then ran
git remote add origin https://github.com/VijayNew/NewExample.git
After that, your local repository should be able to communicate with the remote repository that resides at the specified URL (https://github.com/VijayNew/NewExample.git)... provided that remote repo actually exists! However, it seems that you never created that remote repo on GitHub in the first place: at the time of writing this answer, if I try to visit the correponding URL, I get
Before attempting to push to that remote repository, you need to make sure that the latter actually exists. So go to GitHub and create the remote repo in question. Then and only then will you be able to successfully push with
git push -u origin master
For a laugh, thought I'd try and get a single LINQ statement by using the new C# 6 null-conditional operator. Looks pretty crazy and probably horribly inefficient, but it works.
private string GetLocalIPv4(NetworkInterfaceType type = NetworkInterfaceType.Ethernet)
{
// Bastardized from: http://stackoverflow.com/a/28621250/2685650.
return NetworkInterface
.GetAllNetworkInterfaces()
.FirstOrDefault(ni =>
ni.NetworkInterfaceType == type
&& ni.OperationalStatus == OperationalStatus.Up
&& ni.GetIPProperties().GatewayAddresses.FirstOrDefault() != null
&& ni.GetIPProperties().UnicastAddresses.FirstOrDefault(ip => ip.Address.AddressFamily == AddressFamily.InterNetwork) != null
)
?.GetIPProperties()
.UnicastAddresses
.FirstOrDefault(ip => ip.Address.AddressFamily == AddressFamily.InterNetwork)
?.Address
?.ToString()
?? string.Empty;
}
Logic courtesy of Gerardo H
(and by reference compman2408
).
IP + "User Agent" could be a better for unique visitor.
Just pass mute=1
.
For example:
<iframe id="myVideo" src="https://www.youtube.com/embed/k0DN-BZrM4o?rel=0&autoplay=1;mute=1" width="100%" height="600" frameborder="0" allowfullscreen></iframe>
I had this problem today, too.
It was caused by ActiveSync on Windows Mobile - the folder I was working in was synced so the AS process grabbed the DB file from time to time causing this error.
Yes. Using the JsonConvert class which contains helper methods for this precise purpose:
// To convert an XML node contained in string xml into a JSON string
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
// To convert JSON text contained in string json into an XML node
XmlDocument doc = JsonConvert.DeserializeXmlNode(json);
Documentation here: Converting between JSON and XML with Json.NET
First is a reference to a pointer, second is a reference to a pointer to a pointer. See also FAQ on how pointers and references differ.
void foo(int*& x, int**& y) {
// modifying x or y here will modify a or b in main
}
int main() {
int val = 42;
int *a = &val;
int **b = &a;
foo(a, b);
return 0;
}
Use display:none/block
, instead of visibility
, and add a margin-top/bottom
for the space you want to see ONLY when the inputs are shown
function yesnoCheck() {
if (document.getElementById('yesCheck').checked) {
document.getElementById('ifYes').style.display = 'block';
} else {
document.getElementById('ifYes').style.display = 'none';
}
}
and your HTML line for the ifYes
tag
<div id="ifYes" style="display:none;margin-top:3%;">If yes, explain:
If you are using SQL Server 2005 (or greater) you might want to consider switching to NVARCHAR(MAX) in your table definition; TEXT, NTEXT, and IMAGE data types of SQL Server 2000 will be deprecated in future versions of SQL Server. SQL Server 2005 provides backward compatibility to data types, but you should probably be using VARCHAR(MAX), NVARCHAR(MAX), and VARBINARY(MAX) instead.
A directive
allows you to extend the HTML vocabulary in a declarative fashion for building web components. The ng-app
attribute is a directive, so is ng-controller
and all of the ng- prefixed attributes
. Directives can be attributes
, tags
or even class
names
, comments
.
How directives are born (compilation
and instantiation
)
Compile: We’ll use the compile
function to both manipulate
the DOM before it’s rendered and return a link
function (that will handle the linking for us). This also is the place to put any methods that need to be shared around with all of the instances
of this directive.
link: We’ll use the link
function to register all listeners on a specific DOM element (that’s cloned from the template) and set up our bindings to the page.
If set in the compile()
function they would only have been set once (which is often what you want). If set in the link()
function they would be set every time the HTML element is bound to data in the
object.
<div ng-repeat="i in [0,1,2]">
<simple>
<div>Inner content</div>
</simple>
</div>
app.directive("simple", function(){
return {
restrict: "EA",
transclude:true,
template:"<div>{{label}}<div ng-transclude></div></div>",
compile: function(element, attributes){
return {
pre: function(scope, element, attributes, controller, transcludeFn){
},
post: function(scope, element, attributes, controller, transcludeFn){
}
}
},
controller: function($scope){
}
};
});
Compile
function returns the pre
and post
link function. In the pre link function we have the instance template and also the scope from the controller
, but yet the template is not bound to scope and still don't have transcluded content.
Post
link function is where post link is the last function to execute. Now the transclusion
is complete, the template is linked to a scope
, and the view will update with data bound values after the next digest cycle
. The link
option is just a shortcut to setting up a post-link
function.
controller: The directive controller can be passed to another directive linking/compiling phase. It can be injected into other directices as a mean to use in inter-directive communication.
You have to specify the name of the directive to be required – It should be bound to same element or its parent. The name can be prefixed with:
? – Will not raise any error if a mentioned directive does not exist.
^ – Will look for the directive on parent elements, if not available on the same element.
Use square bracket [‘directive1', ‘directive2', ‘directive3']
to require multiple directives controller.
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $element) {
});
app.directive('parentDirective', function() {
return {
restrict: 'E',
template: '<child-directive></child-directive>',
controller: function($scope, $element){
this.variable = "Hi Vinothbabu"
}
}
});
app.directive('childDirective', function() {
return {
restrict: 'E',
template: '<h1>I am child</h1>',
replace: true,
require: '^parentDirective',
link: function($scope, $element, attr, parentDirectCtrl){
//you now have access to parentDirectCtrl.variable
}
}
});
Was following the documentations - Apache Log4j2 Configuratoin and Apache Log4j2 Maven in configuring log4j2 with yaml. As per the documentation, the following maven dependencies are required:
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.8.1</version>
</dependency>
and
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-yaml</artifactId>
<version>2.8.6</version>
</dependency>
Just adding these didn't pick the configuration and always gave error. The way of debugging configuration by adding -Dorg.apache.logging.log4j.simplelog.StatusLogger.level=TRACE
helped in seeing the logs. Later had to download the source using Maven and debugging helped in understanding the depended classes of log4j2. They are listed in org.apache.logging.log4j.core.config.yaml.YamlConfigurationFactory
:
com.fasterxml.jackson.databind.ObjectMapper
com.fasterxml.jackson.databind.JsonNode
com.fasterxml.jackson.core.JsonParser
com.fasterxml.jackson.dataformat.yaml.YAMLFactory
Adding dependency mapping for jackson-dataformat-yaml
will not have the first two classes. Hence, add the jackson-databind
dependency to get yaml configuration working:
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.6</version>
</dependency>
You may add the version by referring to the Test Dependencies
section of log4j-api
version item from MVN Repository. E.g. for 2.8.1 version of log4j-api, refer this link and locate the jackson-databind
version.
Moreover, you can use the below Java code to check if the classes are available in the classpath:
System.out.println(ClassLoader.getSystemResource("log4j2.yml")); //Check if file is available in CP
ClassLoader cl = Thread.currentThread().getContextClassLoader(); //Code as in log4j2 API. Version: 2.8.1
String [] classes = {"com.fasterxml.jackson.databind.ObjectMapper",
"com.fasterxml.jackson.databind.JsonNode",
"com.fasterxml.jackson.core.JsonParser",
"com.fasterxml.jackson.dataformat.yaml.YAMLFactory"};
for(String className : classes) {
cl.loadClass(className);
}
Lets say you have an global array declared at the top of the page
int global[] = { 1, 2, 3, 4 };
To find out how many elements are there (in c++) in the array type the following code:
sizeof(global) / 4;
The sizeof(NAME_OF_ARRAY) / 4 will give you back the number of elements for the given array name.
When git push [$there]
does not say what to push, we have used the
traditional "matching" semantics so far (all your branches were sent
to the remote as long as there already are branches of the same name
over there). In Git 2.0, the default is now the "simple" semantics,
which pushes:
only the current branch to the branch with the same name, and only when the current branch is set to integrate with that remote branch, if you are pushing to the same remote as you fetch from; or
only the current branch to the branch with the same name, if you are pushing to a remote that is not where you usually fetch from.
You can use the configuration variable "push.default" to change this. If you are an old-timer who wants to keep using the "matching" semantics, you can set the variable to "matching", for example. Read the documentation for other possibilities.
When git add -u
and git add -A
are run inside a subdirectory
without specifying which paths to add on the command line, they
operate on the entire tree for consistency with git commit -a
and
other commands (these commands used to operate only on the current
subdirectory). Say git add -u .
or git add -A .
if you want to
limit the operation to the current directory.
git add <path>
is the same as git add -A <path>
now, so that
git add dir/
will notice paths you removed from the directory and
record the removal. In older versions of Git, git add <path>
used
to ignore removals. You can say git add --ignore-removal <path>
to
add only added or modified paths in <path>
, if you really want to.
window.location.origin+"/"+window.location.pathname.split('/')[1]+"/"+page+"/"+page+"_list.jsp"
almost same as Jenish answer but a little shorter.
It's good practice to always use the []
notation. One reason is that attribute notation (df.column_name
) does not work for numbered indices:
In [1]: df = DataFrame([[1, 2, 3], [4, 5, 6]])
In [2]: df[1]
Out[2]:
0 2
1 5
Name: 1
In [3]: df.1
File "<ipython-input-3-e4803c0d1066>", line 1
df.1
^
SyntaxError: invalid syntax
We can find the the mean of a row using the range function, i.e in your case, from the Y1961 column to the Y1965
df['mean'] = df.iloc[:, 0:4].mean(axis=1)
And if you want to select individual columns
df['mean'] = df.iloc[:, [0,1,2,3,4].mean(axis=1)
You can use the Closure compiler to compile your javascript.
You can also use CoffeeScript to compile your coffeescript to javascript.
What do you want to achieve with compiling?
The task of compiling arbitrary non-blocking JavaScript down to say, C sounds very daunting.
There really isn't that much speed to be gained by compiling to C or ASM. If you want speed gain offload computation to a C program through a sub process.
function refreshPage()
{
jQuery.mobile.changePage(window.location.href, {
allowSamePageTransition: true,
transition: 'none',
reloadPage: true
});
}
Taken from here http://scottwb.com/blog/2012/06/29/reload-the-same-page-without-blinking-on-jquery-mobile/ also tested on jQuery Mobile 1.2.0
Answer Given by rushUp Is correct but this will be more convenient
for (let [index, val] of array.entries() || []) {
// your code goes here
}
If you're on the Model Overview page you get a tab with the schema. If you rightclick on that tab you get an option to "edit schema". From there you can rename the schema by adding a new name, then click outside the field. This goes for MySQL Workbench 5.2.30 CE
Edit: On the model overview it's under Physical Schemata
Screenshot:
Auto Refresh Workbook for example every 5 sec. Apply to module
Public Sub Refresh()
'refresh
ActiveWorkbook.RefreshAll
alertTime = Now + TimeValue("00:00:05") 'hh:mm:ss
Application.OnTime alertTime, "Refresh"
End Sub
Apply to Workbook on Open
Private Sub Workbook_Open()
alertTime = Now + TimeValue("00:00:05") 'hh:mm:ss
Application.OnTime alertTime, "Refresh"
End Sub
:)
If your div has a fixed-width it shouldn't expand, because you've fixed its width. However, modern browsers support a min-width
CSS property.
You can emulate the min-width property in old IE browsers by using CSS expressions or by using auto width and having a spacer object in the container. This solution isn't elegant but may do the trick:
<div id="container" style="float: left">
<div id="spacer" style="height: 1px; width: 300px"></div>
<button>Button 1 text</button>
<button>Button 2 text</button>
</div>
There's no need for Prototype here: JavaScript has for..in
loops. If you're not sure that no one messed with Object.prototype
, check hasOwnProperty()
as well, ie
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
doSomethingWith(obj[prop]);
}
elementFormDefault="qualified" is used to control the usage of namespaces in XML instance documents (.xml file), rather than namespaces in the schema document itself (.xsd file).
By specifying elementFormDefault="qualified" we enforce namespace declaration to be used in documents validated with this schema.
It is common practice to specify this value to declare that the elements should be qualified rather than unqualified. However, since attributeFormDefault="unqualified" is the default value, it doesn't need to be specified in the schema document, if one does not want to qualify the namespaces.
start chrome https://www.google.com/
or start firefox https://www.google.com/
If you're doing this in Drupal and use the Form API to change the #type from text to 'hidden' in hook_form_alter (for example), be advised that the output HTML will have different (or omitted) DIV wrappers, IDs and class names.
If you have a url and your php supports it, you could just call file_get_contents:
$response = file_get_contents('http://example.com/path/to/api/call?param1=5');
if $response is JSON, use json_decode to turn it into php array:
$response = json_decode($response);
if $response is XML, use simple_xml class:
$response = new SimpleXMLElement($response);
Use array_shift
function
$myarray = array_shift($myarray);
This will move array elements one level up and you can access any array element without using [0]
key
echo $myarray['email'];
will show [email protected]
Ok. I found a program buried deep in other files from the beginning of the year that does what I want. I can't really comment on the suggestions offered because I'm not an experienced spim or low level programmer.Here it is:
.text
.globl __start
__start:
la $a0,str1 #Load and print string asking for string
li $v0,4
syscall
li $v0,8 #take in input
la $a0, buffer #load byte space into address
li $a1, 20 # allot the byte space for string
move $t0,$a0 #save string to t0
syscall
la $a0,str2 #load and print "you wrote" string
li $v0,4
syscall
la $a0, buffer #reload byte space to primary address
move $a0,$t0 # primary address = t0 address (load pointer)
li $v0,4 # print string
syscall
li $v0,10 #end program
syscall
.data
buffer: .space 20
str1: .asciiz "Enter string(max 20 chars): "
str2: .asciiz "You wrote:\n"
###############################
#Output:
#Enter string(max 20 chars): qwerty 123
#You wrote:
#qwerty 123
#Enter string(max 20 chars): new world oreddeYou wrote:
# new world oredde //lol special character
###############################
One example would be for modeling trees. If you are using a HashMap to represent a tree structure, where the key is the parent and the value is list of children, then the values for the null
key would be the root nodes.
<StyledInput text="NAME" imgUri={require('../assets/userIcon.png')} ></StyledInput>
<Image
source={this.props.imgUri}
style={{
height: 30,
width: 30,
resizeMode: 'contain',
}}
/>
in my case i tried so much but finally it work StyledInput component name image inside the StyledInput if you still not understand let me know
The best way I found to make this to my purpose was to increment from the max value you have in the field and for that, I used the following syntax:
maxObj = db.CollectionName.aggregate([
{
$group : { _id: '$item', maxValue: { $max: '$fieldName' } }
}
];
fieldNextValue = maxObj.maxValue + 1;
$fieldName
is the name of your field, but without the $
sign.
CollectionName
is the name of your collection.
The reason I am not using count()
is that the produced value could meet an existing value.
The creation of an enforcing unique index could make it safer:
db.CollectionName.createIndex( { "fieldName": 1 }, { unique: true } )
Best solution:
.disabled{filter: alpha(opacity=50);opacity: 0.5;z-index: 1;pointer-events: none;}
Runs perfectly on all browsers
string time = "19851231";
DateTime theTime= DateTime.ParseExact(time,
"yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None);
The best way is to create a variable of type Worksheet
, assign the worksheet and use it every time the VBA would implicitly use the ActiveSheet
.
This will help you avoid bugs that will eventually show up when your program grows in size.
For example something like Range("A1:C10").Sort Key1:=Range("A2")
is good when the macro works only on one sheet. But you will eventually expand your macro to work with several sheets, find out that this doesn't work, adjust it to ShTest1.Range("A1:C10").Sort Key1:=Range("A2")
... and find out that it still doesn't work.
Here is the correct way:
Dim ShTest1 As Worksheet
Set ShTest1 = Sheets("Test1")
ShTest1.Range("A1:C10").Sort Key1:=ShTest1.Range("A2")
The SpeechRecognition
library requires Python 3.3 or up:
Requirements
[...]
The first software requirement is Python 3.3 or better. This is required to use the library.
and from the Trove classifiers:
Programming Language :: Python
Programming Language :: Python :: 3
Programming Language :: Python :: 3.3
Programming Language :: Python :: 3.4
The urllib.request
module is part of the Python 3 standard library; in Python 2 you'd use urllib2
here.
I guess the main thing here is:
Never user:
@anything = NULL
@anything <> NULL
@anything != null
Always use:
@anything IS NULL
@anything IS NOT NULL
As Andy said the document will be not valid, but nevertheless the script will still be interpreted. See the snippet from WebKit for example:
void HTMLParser::processCloseTag(Token* t)
{
// Support for really broken html.
// we never close the body tag, since some stupid web pages close it before
// the actual end of the doc.
// let's rely on the end() call to close things.
if (t->tagName == htmlTag || t->tagName == bodyTag
|| t->tagName == commentAtom)
return;
...
SQLAlchemy is the Python SQL toolkit and Object Relational Mapper that gives application developers the full power and flexibility of SQL. SQLAlchemy provides a full suite of well known enterprise-level persistence patterns, designed for efficient and high-performing database access, adapted into a simple and Pythonic domain language.
pip install sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
engine = create_engine("mysql://<user_name>:<password>@<host_name>/<db_name>")
session_obj = sessionmaker(bind=engine)
session = scoped_session(session_obj)
# insert into database
session.execute("insert into person values(2, 'random_name')")
session.flush()
session.commit()
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
Base = declarative_base()
engine = create_engine("mysql://<user_name>:<password>@<host_name>/<db_name>")
session_obj = sessionmaker(bind=engine)
session = scoped_session(session_obj)
# Bind the engine to the metadata of the Base class so that the
# declaratives can be accessed through a DBSession instance
Base.metadata.bind = engine
class Person(Base):
__tablename__ = 'person'
# Here we define columns for the table person
# Notice that each column is also a normal Python instance attribute.
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
# insert into database
person_obj = Person(id=12, name="name")
session.add(person_obj)
session.flush()
session.commit()
TLDR: use theString = theString.replace("\\", "\\\\");
instead.
replaceAll(target, replacement)
uses regular expression (regex) syntax for target
and partially for replacement
.
Problem is that \
is special character in regex (it can be used like \d
to represents digit) and in String literal (it can be used like "\n"
to represent line separator or \"
to escape double quote symbol which normally would represent end of string literal).
In both these cases to create \
symbol we can escape it (make it literal instead of special character) by placing additional \
before it (like we escape "
in string literals via \"
).
So to target
regex representing \
symbol will need to hold \\
, and string literal representing such text will need to look like "\\\\"
.
So we escaped \
twice:
\\
"\\\\"
(each \
is represented as "\\"
). In case of replacement
\
is also special there. It allows us to escape other special character $
which via $x
notation, allows us to use portion of data matched by regex and held by capturing group indexed as x
, like "012".replaceAll("(\\d)", "$1$1")
will match each digit, place it in capturing group 1 and $1$1
will replace it with its two copies (it will duplicate it) resulting in "001122"
.
So again, to let replacement
represent \
literal we need to escape it with additional \
which means that:
\\
\\
looks like "\\\\"
BUT since we want replacement
to hold two backslashes we will need "\\\\\\\\"
(each \
represented by one "\\\\"
).
So version with replaceAll
can look like
replaceAll("\\\\", "\\\\\\\\");
To make out life easier Java provides tools to automatically escape text into target
and replacement
parts. So now we can focus only on strings, and forget about regex syntax:
replaceAll(Pattern.quote(target), Matcher.quoteReplacement(replacement))
which in our case can look like
replaceAll(Pattern.quote("\\"), Matcher.quoteReplacement("\\\\"))
If we don't really need regex syntax support lets not involve replaceAll
at all. Instead lets use replace
. Both methods will replace all target
s, but replace
doesn't involve regex syntax. So you could simply write
theString = theString.replace("\\", "\\\\");
First we install the Microsoft.EntityFrameworkCore.SqlServer NuGet Package:
PM > Install-Package Microsoft.EntityFrameworkCore.SqlServer
Then, after importing the namespace with
using Microsoft.EntityFrameworkCore;
we add the database context:
services.AddDbContext<AspDbContext>(options =>
options.UseSqlServer(config.GetConnectionString("optimumDB")));
For docker-compose
using bridge networking to create a private network between containers, the accepted solution using docker0
doesn't work because the egress interface from the containers is not docker0
, but instead, it's a randomly generated interface id, such as:
$ ifconfig
br-02d7f5ba5a51: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500
inet 192.168.32.1 netmask 255.255.240.0 broadcast 192.168.47.255
Unfortunately that random id is not predictable and will change each time compose has to recreate the network (e.g. on a host reboot). My solution to this is to create the private network in a known subnet and configure iptables
to accept that range:
Compose file snippet:
version: "3.7"
services:
mongodb:
image: mongo:4.2.2
networks:
- mynet
# rest of service config and other services removed for clarity
networks:
mynet:
name: mynet
ipam:
driver: default
config:
- subnet: "192.168.32.0/20"
You can change the subnet if your environment requires it. I arbitrarily selected 192.168.32.0/20
by using docker network inspect
to see what was being created by default.
Configure iptables
on the host to permit the private subnet as a source:
$ iptables -I INPUT 1 -s 192.168.32.0/20 -j ACCEPT
This is the simplest possible iptables
rule. You may wish to add other restrictions, for example by destination port. Don't forget to persist your iptables rules when you're happy they're working.
This approach has the advantage of being repeatable and therefore automatable. I use ansible's template
module to deploy my compose file with variable substitution and then use the iptables
and shell
modules to configure and persist the firewall rules, respectively.
For listing everything with full path, only in current directory
find $PWD -maxdepth 1
Same as above but only matches a particular extension, case insensitive (.sh files in this case)
find $PWD -maxdepth 1 -iregex '.+\.sh'
$PWD is for current directory, it can be replaced with any directory
mydir="/etc/sudoers.d/" ; find $mydir -maxdepth 1
maxdepth
prevents find from going into subdirectories, for example you can set it to "2" for listing items in children as well. Simply remove it if you need it recursive.
To limit it to only files, can use -type f
option.
find $PWD -maxdepth 1 -type f
Storing money as BIGINT
multiplied by 100 or more with the reason to use less storage space makes no sense in all "normal" situations.
DECIMAL(13,4)
DECIMAL
.
DECIMAL(13,4)
represents 9 digits + 4 fraction digits (decimal places) => 4 + 2 bytes = 6 bytesBIGINT
.Another issue to watch out for with Entity Framework specifically is when using a combination of creating new entities, lazy loading, and then using those new entities (from the same context). If you don't use IDbSet.Create (vs just new), Lazy loading on that entity doesn't work when its retrieved out of the context it was created in. Example:
public class Foo {
public string Id {get; set; }
public string BarId {get; set; }
// lazy loaded relationship to bar
public virtual Bar Bar { get; set;}
}
var foo = new Foo {
Id = "foo id"
BarId = "some existing bar id"
};
dbContext.Set<Foo>().Add(foo);
dbContext.SaveChanges();
// some other code, using the same context
var foo = dbContext.Set<Foo>().Find("foo id");
var barProp = foo.Bar.SomeBarProp; // fails with null reference even though we have BarId set.
For some instrutions, like ALTER TABLE, this is not possible with MySQL, even with transactions (1 and 2).
Strings are immutable. string.replace
(python 2.x) or str.replace
(python 3.x) creates a new string. This is stated in the documentation:
Return a copy of string s with all occurrences of substring old replaced by new. ...
This means you have to re-allocate the set or re-populate it (re-allocating is easier with set comprehension):
new_set = {x.replace('.good', '').replace('.bad', '') for x in set1}
You cant run PHP when a user clicks on a link without leaving the page unless you use AJAX. PHP is a serverside scripting language, meaning the second that the browser sees the page, there is no PHP in it.
Unlike Javascript, PHP is ran completely on the server, and browser wouldn't know how to interpret it if it bit them on the rear. The only way to invoke PHP code is to make a Page request, by either refreshing the page, or using javascript to go fetch a page.
In an AJAX Solution, basically the page uses javascript to send a page request to another page on your domain. Javascript then gets whatever you decide to echo
in the response, and it can parse it and do what it wants from there. When you are creating the response, you can also do any backend stuff like updating databases.
>>> import subprocess
>>> cmd = [ 'echo', 'arg1', 'arg2' ]
>>> output = subprocess.Popen( cmd, stdout=subprocess.PIPE ).communicate()[0]
>>> print output
arg1 arg2
>>>
There is a bug in using of the subprocess.PIPE. For the huge output use this:
import subprocess
import tempfile
with tempfile.TemporaryFile() as tempf:
proc = subprocess.Popen(['echo', 'a', 'b'], stdout=tempf)
proc.wait()
tempf.seek(0)
print tempf.read()
Object.withDefault = (defaultValue,o={}) => {
return new Proxy(o, {
get: (o, k) => (k in o) ? o[k] : defaultValue
});
}
o = Object.withDefault(42);
o.x //=> 42
o.x = 10
o.x //=> 10
o.xx //=> 42
var dd = document.getElementById("dropdownID");
var selectedItem = dd.options[dd.selectedIndex].value;
SELECT id, COUNT(id) FROM table1 GROUP BY id HAVING COUNT(id)>1;
I think this will work properly to search repeated values in a particular column.
Here is a NuGet plugin called Cassette, which among other things provides you the ability to reference scripts and styles in partials.
Though there are a number of configurations available for this plugin, which makes it highly flexible. Here is the simplest way of referring script or stylesheet files:
Bundles.Reference("scripts/app");
According to the documentation:
Calls to
Reference
can appear anywhere in a page, layout or partial view.The path argument can be one of the following:
- A bundle path
- An asset path - the whole bundle containing this asset is referenced
- A URL
It is worth to note that it's possible to add Q expressions.
For example:
from django.db.models import Q
query = Q(first_name='mark')
query.add(Q(email='[email protected]'), Q.OR)
query.add(Q(last_name='doe'), Q.AND)
queryset = User.objects.filter(query)
This ends up with a query like :
(first_name = 'mark' or email = '[email protected]') and last_name = 'doe'
This way there is no need to deal with or operators, reduce's etc.
start xampp (as administrator), (1) right click C:\xampp\xampp-control.exe, and run as administrator. (2) unistall service module and then install service module. (3) now try start the apache and mysql.
You can use EL if you want to work as IF:
<h:outputLabel value="#{row==10? '10' : '15'}"/>
Changing styles or classes:
style="#{test eq testMB.test? 'font-weight:bold' : 'font-weight:normal'}"
class="#{test eq testMB.test? 'divRred' : 'divGreen'}"
It took me a little while to figure out how to disable draggable on drop—use ui.draggable
to reference the object being dragged from inside the drop function:
$("#drop-target").droppable({
drop: function(event, ui) {
ui.draggable.draggable("disable", 1); // *not* ui.draggable("disable", 1);
…
}
});
HTH someone
{{app.session}}
refers to the Session
object and not the $_SESSION
array. I don't think the $_SESSION
array is accessible unless you explicitly pass it to every Twig template or if you do an extension that makes it available.
Symfony2 is object-oriented, so you should use the Session
object to set session attributes and not rely on the array. The Session
object will abstract this stuff away from you so it is easier to, say, store the session in a database because storing the session variable is hidden from you.
So, set your attribute in the session and retrieve the value in your twig template by using the Session
object.
// In a controller
$session = $this->get('session');
$session->set('filter', array(
'accounts' => 'value',
));
// In Twig
{% set filter = app.session.get('filter') %}
{% set account-filter = filter['accounts'] %}
Hope this helps.
Regards,
Matt
What worked for me was:
git config --global fetch.prune true
Now it keeps on running prune automatically.
Try this:
var setCanvasSize = function() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
}
Follow the below steps to show the name of the branch of your GIT repo in ubuntu terminal:
step1: open terminal and edit .bashrc using the following command.
vi .bashrc
step2: add the following line at the end of the .bashrc file :
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/' }
export PS1="\u@\h \W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] $ "
step3: source .bashrc in the root (home) directory by doing:
/rootfolder:~$ source .bashrc
Step4: Restart and open the terminal and check the cmd. Navigate to your GIt repo directory path and you are done. :)
If you want to retain the last one of the duplicates you could use
tac a.csv | sort -u -t, -r -k1,1 |tac
Which was my requirement
here
tac
will reverse the file line by line
Or you may try this:
?php
/**
* Mobile Detect
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
*/
class Mobile_Detect
{
protected $accept;
protected $userAgent;
protected $isMobile = false;
protected $isAndroid = null;
protected $isAndroidtablet = null;
protected $isIphone = null;
protected $isIpad = null;
protected $isBlackberry = null;
protected $isBlackberrytablet = null;
protected $isOpera = null;
protected $isPalm = null;
protected $isWindows = null;
protected $isWindowsphone = null;
protected $isGeneric = null;
protected $devices = array(
"android" => "android.*mobile",
"androidtablet" => "android(?!.*mobile)",
"blackberry" => "blackberry",
"blackberrytablet" => "rim tablet os",
"iphone" => "(iphone|ipod)",
"ipad" => "(ipad)",
"palm" => "(avantgo|blazer|elaine|hiptop|palm|plucker|xiino)",
"windows" => "windows ce; (iemobile|ppc|smartphone)",
"windowsphone" => "windows phone os",
"generic" => "(kindle|mobile|mmp|midp|pocket|psp|symbian|smartphone|treo|up.browser|up.link|vodafone|wap|opera mini)");
public function __construct()
{
$this->userAgent = $_SERVER['HTTP_USER_AGENT'];
$this->accept = $_SERVER['HTTP_ACCEPT'];
if (isset($_SERVER['HTTP_X_WAP_PROFILE']) || isset($_SERVER['HTTP_PROFILE']))
{
$this->isMobile = true;
}
elseif (strpos($this->accept, 'text/vnd.wap.wml') > 0 || strpos($this->accept, 'application/vnd.wap.xhtml+xml') > 0)
{
$this->isMobile = true;
}
else
{
foreach ($this->devices as $device => $regexp)
{
if ($this->isDevice($device))
{
$this->isMobile = true;
}
}
}
}
/**
* Overloads isAndroid() | isAndroidtablet() | isIphone() | isIpad() | isBlackberry() | isBlackberrytablet() | isPalm() | isWindowsphone() | isWindows() | isGeneric() through isDevice()
*
* @param string $name
* @param array $arguments
* @return bool
*/
public function __call($name, $arguments)
{
$device = substr($name, 2);
if ($name == "is" . ucfirst($device) && array_key_exists(strtolower($device), $this->devices))
{
return $this->isDevice($device);
}
else
{
trigger_error("Method $name not defined", E_USER_WARNING);
}
}
/**
* Returns true if any type of mobile device detected, including special ones
* @return bool
*/
public function isMobile()
{
return $this->isMobile;
}
protected function isDevice($device)
{
$var = "is" . ucfirst($device);
$return = $this->$var === null ? (bool) preg_match("/" . $this->devices[strtolower($device)] . "/i", $this->userAgent) : $this->$var;
if ($device != 'generic' && $return == true) {
$this->isGeneric = false;
}
return $return;
}
The second way is a tad more efficient, but a much better way is to execute them in batches:
public void executeBatch(List<Entity> entities) throws SQLException {
try (
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL);
) {
for (Entity entity : entities) {
statement.setObject(1, entity.getSomeProperty());
// ...
statement.addBatch();
}
statement.executeBatch();
}
}
You're however dependent on the JDBC driver implementation how many batches you could execute at once. You may for example want to execute them every 1000 batches:
public void executeBatch(List<Entity> entities) throws SQLException {
try (
Connection connection = dataSource.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL);
) {
int i = 0;
for (Entity entity : entities) {
statement.setObject(1, entity.getSomeProperty());
// ...
statement.addBatch();
i++;
if (i % 1000 == 0 || i == entities.size()) {
statement.executeBatch(); // Execute every 1000 items.
}
}
}
}
As to the multithreaded environments, you don't need to worry about this if you acquire and close the connection and the statement in the shortest possible scope inside the same method block according the normal JDBC idiom using try-with-resources statement as shown in above snippets.
If those batches are transactional, then you'd like to turn off autocommit of the connection and only commit the transaction when all batches are finished. Otherwise it may result in a dirty database when the first bunch of batches succeeded and the later not.
public void executeBatch(List<Entity> entities) throws SQLException {
try (Connection connection = dataSource.getConnection()) {
connection.setAutoCommit(false);
try (PreparedStatement statement = connection.prepareStatement(SQL)) {
// ...
try {
connection.commit();
} catch (SQLException e) {
connection.rollback();
throw e;
}
}
}
}
You can change the index as explained already using set_index
.
You don't need to manually swap rows with columns, there is a transpose (data.T
) method in pandas that does it for you:
> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
['ABERFELDIE', 534000, 600000]],
columns=['Locality', 2005, 2006])
> newdf = df.set_index('Locality').T
> newdf
Locality ABBOTSFORD ABERFELDIE
2005 427000 534000
2006 448000 600000
then you can fetch the dataframe column values and transform them to a list:
> newdf['ABBOTSFORD'].values.tolist()
[427000, 448000]
Example:
create table longtable(id number,text long);
insert into longtable values(1,'hello world');
insert into longtable values(2,'say hello!');
commit;
create or replace function search_long(r rowid) return varchar2 is
temporary_varchar varchar2(4000);
begin
select text into temporary_varchar from longtable where rowid=r;
return temporary_varchar;
end;
/
SQL> select text from longtable where search_long(rowid) like '%hello%';
TEXT
--------------------------------------------------------------------------------
hello world
say hello!
But be careful. A PL/SQL function will only search the first 32K of LONG.
If your application uses async stuff and you're fiddling with Mouse's cursor, you probably want to do it only in main UI thread. You can use app's Dispatcher thread for that:
Application.Current.Dispatcher.Invoke(() =>
{
// The check is required to prevent cursor flickering
if (Mouse.OverrideCursor != cursor)
Mouse.OverrideCursor = cursor;
});
After some research I have found method that doesn't require maven or any 3rd party extension/program.
You can use "Class-Path" in your manifest file.
For example:
Create manifest file MANIFEST.MF
Manifest-Version: 1.0
Created-By: Bundle
Class-Path: ./custom_lib.jar
Main-Class: YourMainClass
Compile all your classes and run jar cfm Testing.jar MANIFEST.MF *.class custom_lib.jar
c
stands for create archive
f
indicates that you want to specify file
v
is for verbose input
m
means that we will pass custom manifest file
Be sure that you included lib in jar package. You should be able to run jar in the normal way.
based on: http://www.ibm.com/developerworks/library/j-5things6/
all other information you need about the class-path do you find here
Since Windows 10 15063 upwards
Since Windows 10 build 15063, there is a new feature called "Implicit Visibility conversion" that binds Visibility to bool value natively - There is no need anymore to use a converter.
My code (which supposes that MVVM is used, and Template 10 as well):
<!-- In XAML -->
<StackPanel x:Name="Msg_StackPanel" Visibility="{x:Bind ViewModel.ShowInlineHelp}" Orientation="Horizontal" Margin="0,24,0,0">
<TextBlock Text="Frosty the snowman was a jolly happy soul" Margin="0,0,8,0"/>
<SymbolIcon Symbol="OutlineStar "/>
<TextBlock Text="With a corncob pipe and a button nose" Margin="8,0,0,0"/>
</StackPanel>
<!-- in companion View-Model -->
public bool ShowInlineHelp // using T10 SettingsService
{
get { return (_settings.ShowInlineHelp); }
set { _settings.ShowInlineHelp = !value; base.RaisePropertyChanged(); }
}
I am aware that this question is about C++11. However, for those who googled and landed on this page, templated lambdas are now supported in C++14 and go by the name Generic Lambdas.
[info] Most of the popular compilers support this feature now. Microsoft Visual Studio 2015 supports. Clang supports. GCC supports.
You can simply add show.legend=FALSE
to geom to suppress the corresponding legend
Since HTTP Params class is immutable therefore you need to chain the set method:
const params = new HttpParams()
.set('aaa', '111')
.set('bbb', "222");
Here is the accepted answer in swift for anyone who is too lazy to convert it :)
var contentRect = CGRectZero
for view in self.scrollView.subviews {
contentRect = CGRectUnion(contentRect, view.frame)
}
self.scrollView.contentSize = contentRect.size
I originally intentionally never learned how to use eval, because most people will recommend to stay away from it like the plague. However I recently discovered a use case that made me facepalm for not recognizing it sooner.
If you have cron jobs that you want to run interactively to test, you might view the contents of the file with cat, and copy and paste the cron job to run it. Unfortunately, this involves touching the mouse, which is a sin in my book.
Lets say you have a cron job at /etc/cron.d/repeatme with the contents:
*/10 * * * * root program arg1 arg2
You cant execute this as a script with all the junk in front of it, but we can use cut to get rid of all the junk, wrap it in a subshell, and execute the string with eval
eval $( cut -d ' ' -f 6- /etc/cron.d/repeatme)
The cut command only prints out the 6th field of the file, delimited by spaces. Eval then executes that command.
I used a cron job here as an example, but the concept is to format text from stdout, and then evaluate that text.
The use of eval in this case is not insecure, because we know exactly what we will be evaluating before hand.
Your traceback is telling you that int()
takes integers, you are trying to give a decimal, so you need to use float()
:
a = float(a)
This should work as expected:
>>> int(input("Type a number: "))
Type a number: 0.3
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '0.3'
>>> float(input("Type a number: "))
Type a number: 0.3
0.3
Computers store numbers in a variety of different ways. Python has two main ones. Integers, which store whole numbers (Z), and floating point numbers, which store real numbers (R). You need to use the right one based on what you require.
(As a note, Python is pretty good at abstracting this away from you, most other language also have double precision floating point numbers, for instance, but you don't need to worry about that. Since 3.0, Python will also automatically convert integers to floats if you divide them, so it's actually very easy to work with.)
Your problem is that whatever you are typing is can't be converted into a number. This could be caused by a lot of things, for example:
>>> int(input("Type a number: "))
Type a number: -1
-1
>>> int(input("Type a number: "))
Type a number: - 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '- 1'
Adding a space between the -
and 1
will cause the string not to be parsed correctly into a number. This is, of course, just an example, and you will have to tell us what input you are giving for us to be able to say for sure what the issue is.
y = [int(a)**(-2),int(a)**(-1.75),int(a)**(-1.5),int(a)**(-1.25),
int(a)**(-1),int(a)**(-0.75),int(a)**(-0.5),int(a)**(-0.25),
int(a)**(0),int(a)**(0.25),int(a)**(0.5),int(a)**(0.75),
int(a)**1,int(a)**(1.25),int(a)**(1.5),int(a)**(1.75), int(a)**(2)]
This is an example of a really bad coding habit. Where you are copying something again and again something is wrong. Firstly, you use int(a)
a ton of times, wherever you do this, you should instead assign the value to a variable, and use that instead, avoiding typing (and forcing the computer to calculate) the value again and again:
a = int(a)
In this example I assign the value back to a
, overwriting the old value with the new one we want to use.
y = [a**i for i in x]
This code produces the same result as the monster above, without the masses of writing out the same thing again and again. It's a simple list comprehension. This also means that if you edit x
, you don't need to do anything to y
, it will naturally update to suit.
Also note that PEP-8, the Python style guide, suggests strongly that you don't leave spaces between an identifier and the brackets when making a function call.
I was integrating a slider and needed to get all the files in the folder and was having same situationof C# array to javascript array.This solution by @heymega worked perfectly except my javascript parser was annoyed on var
use in foreach
loop. So i did a little work around avoiding the loop.
var allowedExtensions = new string[] { ".jpg", ".jpeg", ".bmp", ".png", ".gif" };
var bannerImages = string.Join(",", Directory.GetFiles(Path.Combine(System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath, "Images", "banners"), "*.*", SearchOption.TopDirectoryOnly)
.Where(d => allowedExtensions.Contains(Path.GetExtension(d).ToLower()))
.Select(d => string.Format("'{0}'", Path.GetFileName(d)))
.ToArray());
And the javascript code is
var imagesArray = new Array(@Html.Raw(bannerImages));
Hope it helps
If you want to run some action against the filename only, using basename
can be tough.
For example this:
find ~/clang+llvm-3.3/bin/ -type f -exec echo basename {} \;
will just echo basename /my/found/path
. Not what we want if we want to execute on the filename.
But you can then xargs
the output. for example to kill the files in a dir based on names in another dir:
cd dirIwantToRMin;
find ~/clang+llvm-3.3/bin/ -type f -exec basename {} \; | xargs rm
SQLite out-of-the-box is not really feature-full regarding concurrency. You will get into trouble if you have hundreds of web requests hitting the same SQLite database.
You should definitely go with MySQL or PostgreSQL.
If it is for a single-person project, SQLite will be easier to setup though.
What's your innodb buffer-pool size? Make sure you've set it to 75% of your RAM. Usually inserts are better when in primary key order for InnoDB. But with a big pool-size, you should see good speeds.
"hello _there_".replace(/_(.*?)_/, function(a, b){
return '<div>' + b + '</div>';
})
Oh, or you could also:
"hello _there_".replace(/_(.*?)_/, "<div>$1</div>")
EDIT by Liran H:
For six other people including myself, $1
did not work, whereas \1
did.
You can use the following code snippet :
java -XX:+PrintFlagsFinal -Xms512m -Xmx1024m -Xss512k -XX:PermSize=64m -XX:MaxPermSize=128m
-version | grep -iE 'HeapSize|PermSize|ThreadStackSize'
In my pc I am getting following output :
uintx InitialHeapSize := 536870912 {product}
uintx MaxHeapSize := 1073741824 {product}
uintx PermSize := 67108864 {pd product}
uintx MaxPermSize := 134217728 {pd product}
intx ThreadStackSize := 512 {pd product}
Well here is something I used in several projects. It may look like a hack, but it works fine.
public class AttachedProperties : DependencyObject //adds a bindable DialogResult to window
{
public static readonly DependencyProperty DialogResultProperty =
DependencyProperty.RegisterAttached("DialogResult", typeof(bool?), typeof(AttachedProperties),
new PropertyMetaData(default(bool?), OnDialogResultChanged));
public bool? DialogResult
{
get { return (bool?)GetValue(DialogResultProperty); }
set { SetValue(DialogResultProperty, value); }
}
private static void OnDialogResultChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var window = d as Window;
if (window == null)
return;
window.DialogResult = (bool?)e.NewValue;
}
}
Now you can bind DialogResult
to a VM and set its value of a property. The Window
will close, when the value is set.
<!-- Assuming that the VM is bound to the DataContext and the bound VM has a property DialogResult -->
<Window someNs:AttachedProperties.DialogResult={Binding DialogResult} />
This is an abstract of what's running in our production environment
<Window x:Class="AC.Frontend.Controls.DialogControl.Dialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:DialogControl="clr-namespace:AC.Frontend.Controls.DialogControl"
xmlns:hlp="clr-namespace:AC.Frontend.Helper"
MinHeight="150" MinWidth="300" ResizeMode="NoResize" SizeToContent="WidthAndHeight"
WindowStartupLocation="CenterScreen" Title="{Binding Title}"
hlp:AttachedProperties.DialogResult="{Binding DialogResult}" WindowStyle="ToolWindow" ShowInTaskbar="True"
Language="{Binding UiCulture, Source={StaticResource Strings}}">
<!-- A lot more stuff here -->
</Window>
As you can see, I'm declaring the namespace xmlns:hlp="clr-namespace:AC.Frontend.Helper"
first and afterwards the binding hlp:AttachedProperties.DialogResult="{Binding DialogResult}"
.
The AttachedProperty
looks like this. It's not the same I posted yesterday, but IMHO it shouldn't have any effect.
public class AttachedProperties
{
#region DialogResult
public static readonly DependencyProperty DialogResultProperty =
DependencyProperty.RegisterAttached("DialogResult", typeof (bool?), typeof (AttachedProperties), new PropertyMetadata(default(bool?), OnDialogResultChanged));
private static void OnDialogResultChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var wnd = d as Window;
if (wnd == null)
return;
wnd.DialogResult = (bool?) e.NewValue;
}
public static bool? GetDialogResult(DependencyObject dp)
{
if (dp == null) throw new ArgumentNullException("dp");
return (bool?)dp.GetValue(DialogResultProperty);
}
public static void SetDialogResult(DependencyObject dp, object value)
{
if (dp == null) throw new ArgumentNullException("dp");
dp.SetValue(DialogResultProperty, value);
}
#endregion
}
Use the XML Tools plugin for Notepad++ and then you can Auto-Indent the code with Ctrl+Alt+Shift+B .For the more point-and-click inclined, you could also go to Plugins --> XML Tools --> Pretty Print.
bool is a primitive type, meaning that the value (true/false in this case) is stored directly in the variable. Boolean is an object. A variable of type Boolean stores a reference to a Boolean object. The only real difference is storage. An object will always take up more memory than a primitive type, but in reality, changing all your Boolean values to bool isn't going to have any noticeable impact on memory usage.
I was wrong; that's how it works in java with boolean and Boolean. In C#, bool and Boolean are both reference types. Both of them store their value directly in the variable, both of them cannot be null, and both of them require a "convertTO" method to store their values in another type (such as int). It only matters which one you use if you need to call a static function defined within the Boolean class.
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item>
<shape android:shape="oval">
<solid android:color="@color/orange"/>
</shape>
</item>
<item
android:top="2dp"
android:bottom="2dp"
android:left="2dp"
android:right="2dp">
<shape android:shape="oval">
<solid android:color="@color/white"/>
</shape>
</item>
<item
android:drawable="@drawable/messages" //here messages is my image name, please give here your image name.
android:bottom="15dp"
android:left="15dp"
android:right="15dp"
android:top="15dp"/>
<ImageView
android:id="@+id/imageView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/merchant_circle" /> // here merchant_circle will be your first .xml file name
To do any of the above (i.e. access protected folders from within your phone itself), you still need root. (That includes changing mount-permissions on the /data folder and accessing it)
Without root, accessing the /data
directly to read except from within your application via code isn't possible. So you could try copying that file to sdcard or somewhere accessible, and then, you should be able to access it normally.
Rooting won't void your warranty if you have a developer device. I'm sorry, there isn't any other way AFAIK.
I would not use .at for performance reasons.
Define a struct:
//#pragma pack(push, 2) //not useful (see comments below)
struct RGB {
uchar blue;
uchar green;
uchar red; };
And then use it like this on your cv::Mat image:
RGB& rgb = image.ptr<RGB>(y)[x];
image.ptr(y) gives you a pointer to the scanline y. And iterate through the pixels with loops of x and y
Because you can't easily union a function definition and another data type, I find having these types around useful to strongly type them. Based on Drew's answer.
type Func<TArgs extends any[], TResult> = (...args: TArgs) => TResult;
//Syntax sugar
type Action<TArgs extends any[]> = Func<TArgs, undefined>;
Now you can strongly type every parameter and the return type! Here's an example with more parameters than what is above.
save(callback: Func<[string, Object, boolean], number>): number
{
let str = "";
let obj = {};
let bool = true;
let result: number = callback(str, obj, bool);
return result;
}
Now you can write a union type, like an object or a function returning an object, without creating a brand new type that may need to be exported or consumed.
//THIS DOESN'T WORK
let myVar1: boolean | (parameters: object) => boolean;
//This works, but requires a type be defined each time
type myBoolFunc = (parameters: object) => boolean;
let myVar1: boolean | myBoolFunc;
//This works, with a generic type that can be used anywhere
let myVar2: boolean | Func<[object], boolean>;
Here is media queries for common device breakpoints.
/* Smartphones (portrait and landscape) ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) {
/* Styles */
}
/* Smartphones (landscape) ----------- */
@media only screen and (min-width : 321px) {
/* Styles */
}
/* Smartphones (portrait) ----------- */
@media only screen and (max-width : 320px) {
/* Styles */
}
/* iPads (portrait and landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) {
/* Styles */
}
/* iPads (landscape) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) {
/* Styles */
}
/* iPads (portrait) ----------- */
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) {
/* Styles */
}
/**********
iPad 3
**********/
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
@media only screen and (min-device-width : 768px) and (max-device-width : 1024px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
/* Desktops and laptops ----------- */
@media only screen and (min-width : 1224px) {
/* Styles */
}
/* Large screens ----------- */
@media only screen and (min-width : 1824px) {
/* Styles */
}
/* iPhone 4 ----------- */
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : landscape) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
@media only screen and (min-device-width : 320px) and (max-device-width : 480px) and (orientation : portrait) and (-webkit-min-device-pixel-ratio : 2) {
/* Styles */
}
Access 2010 has both stored procedures, and also has table triggers. And, both features are available even when you not using a server (so, in 100% file based mode).
If you using SQL Server with Access, then of course the stored procedures are built using SQL Server and not Access.
For Access 2010, you open up the table (non-design view), and then choose the table tab. You see options there to create store procedures and table triggers.
For example:
Note that the stored procedure language is its own flavor just like Oracle or SQL Server (T-SQL). Here is example code to update an inventory of fruits as a result of an update in the fruit order table
Keep in mind these are true engine-level table triggers. In fact if you open up that table with VB6, VB.NET, FoxPro or even modify the table on a computer WITHOUT Access having been installed, the procedural code and the trigger at the table level will execute. So, this is a new feature of the data engine jet (now called ACE) for Access 2010. As noted, this is procedural code that runs, not just a single statement.
All of the above answers are correct and recommended; this answer is intended only as a last-resort if none of the aforementioned approaches can be used.
If all else fails, you can always recompile your program with various temporary debug-print statements (e.g. fprintf(stderr, "CHECKPOINT REACHED @ %s:%i\n", __FILE__, __LINE__);
) sprinkled throughout what you believe to be the relevant parts of your code. Then run the program, and observe what the was last debug-print printed just before the crash occurred -- you know your program got that far, so the crash must have happened after that point. Add or remove debug-prints, recompile, and run the test again, until you have narrowed it down to a single line of code. At that point you can fix the bug and remove all of the temporary debug-prints.
It's quite tedious, but it has the advantage of working just about anywhere -- the only times it might not is if you don't have access to stdout or stderr for some reason, or if the bug you are trying to fix is a race-condition whose behavior changes when the timing of the program changes (since the debug-prints will slow down the program and change its timing)
Got it working with
Actions builder = new Actions(driver);
WebElement el = some element;
builder.keyDown(Keys.CONTROL)
.moveByOffset( 10, 25 )
.clickAndHold(el)
.build().perform();
As above, synonyms of "contract" and "protocol" are appropriate.
The interface comprises the methods and properties you can expect to be exposed by a class.
So if a class Cheetos Bag
implements the Chip Bag
interface, you should expect a Cheetos Bag
to behave exactly like any other Chip Bag
. (That is, expose the .attemptToOpenWithoutSpillingEverywhere()
method, etc.)
document.body.innerHTML = '';
does clear the body
, yeah. But it clears the innerHTML
as it is at the moment the code is ran. As you run the code before the images and the script are actually in the body
, it tries to clear the body
, but there's nothing to clear.
If you want to clear the body
, you have to run the code after the body
has been filled with content. You can do this by either placing the <script>
block as the last child of body
, so everything is loaded before the code is ran, or you have to use some way to listen to the dom:loaded
event.
For IE8 or console support limited to console.log (no debug, trace, ...) you can do the following:
If console OR console.log undefined: Create dummy functions for console functions (trace, debug, log, ...)
window.console = {
debug : function() {}, ...};
Else if console.log is defined (IE8) AND console.debug (any other) is not defined: redirect all logging functions to console.log, this allows to keep those logs !
window.console = {
debug : window.console.log, ...};
Not sure about the assert support in various IE versions, but any suggestions are welcome.
Making it open from rtl isn't good for user experience, to make it responsive to the user locale I just added the following line to my DrawerLayout parameters:
android:layoutDirection="locale"
Added it to my AppBarLayout to make the hamburger layout match the drawer opening direction too.
You can use nircmd.exe's elevate command
NirCmd Command Reference - elevate
elevate [Program] {Command-Line Parameters}
For Windows Vista/7/2008 only: Run a program with administrator rights. When the [Program] contains one or more space characters, you must put it in quotes.
Examples:
elevate notepad.exe
elevate notepad.exe C:\Windows\System32\Drivers\etc\HOSTS
elevate "c:\program files\my software\abc.exe"
PS: I use it on win 10 and it works
alternatively you can retrieve DOM properties
with .prop
here is sample code for select box
if( ctrl.prop('type') == 'select-one' ) { // for single select }
if( ctrl.prop('type') == 'select-multiple' ) { // for multi select }
for textbox
if( ctrl.prop('type') == 'text' ) { // for text box }
This comes down to browser image support; it looks like the only mainstream browser that supports tiff is Safari:
http://en.wikipedia.org/wiki/Comparison_of_web_browsers#Image_format_support
Where are you getting the tiff images from? Is it possible for them to be generated in a different format?
If you have a static set of images then I'd recommend using something like PaintShop Pro to batch convert them, changing the format.
If this isn't an option then there might be some mileage in looking for a pre-written Java applet (or another browser plugin) that can display the images in the browser.
I was getting this problem because I put context.xml
into the wrong path:
./src/main/resources/META-INF/context.xml
The correct path was:
./src/main/webapp/META-INF/context.xml
You can use Oracle.ManagedDataAccess NuGet package too (.NET >= 4.0, database >= 10g Release 2).
Yes, you can specify the notebooks location in your profile configuration. Since it's not saving them to the directory where you started the notebook, I assume that you have this option set in your profile. You can find out the the path to the profiles directory by using:
$ ipython locate
Either in your default profile or in the profile you use, edit the ipython_notebook_config.py
file and change the lines:
Note: In case you don't have a profile, or the profile folder does not contain the ipython_notebook_config.py
file, use ipython profile create
.
# The directory to use for notebooks.
c.NotebookManager.notebook_dir = u'/path/to/your/notebooks'
and
# The directory to use for notebooks.
c.FileNotebookManager.notebook_dir = u'/path/to/your/notebooks'
Or just comment them out if you want the notebooks saved in the current directory.
Update (April 11th 2014): in IPython 2.0 the property name in the config file changed, so it's now:
c.NotebookApp.notebook_dir = u'/path/to/your/notebooks'
You can just give the glyphicon a font-size to your liking:
span.glyphicon-link {
font-size: 1.2em;
}
Simply put you can't do the following:
class C(object):
def x(self, y, **kwargs):
# Which y to use, kwargs or declaration?
pass
c = C()
y = "Arbitrary value"
kwargs["y"] = "Arbitrary value"
c.x(y, **kwargs) # FAILS
Because you pass the variable 'y' into the function twice: once as kwargs and once as function declaration.
In Pass By Reference You only add "ref" in the function parameters and one
more thing you should be declaring function "static" because of main is static(#public void main(String[] args)
)!
namespace preparation
{
public class Program
{
public static void swap(ref int lhs,ref int rhs)
{
int temp = lhs;
lhs = rhs;
rhs = temp;
}
static void Main(string[] args)
{
int a = 10;
int b = 80;
Console.WriteLine("a is before sort " + a);
Console.WriteLine("b is before sort " + b);
swap(ref a, ref b);
Console.WriteLine("");
Console.WriteLine("a is after sort " + a);
Console.WriteLine("b is after sort " + b);
}
}
}
If you use a current version of m2eclipse (which you should if you use eclipse and maven):
Select the menu entry
Navigate -> Open Maven POM
and enter the artifact you are looking for.
The pom will open in the pom editor, from which you can select the tab Dependency Hierarchy
to view the dependency hierarchy (as the name suggests :-) )
You first have to 'dot' source the script, so for you :
. .\Get-NetworkStatistics.ps1
The first 'dot' asks PowerShell to load the script file into your PowerShell environment, not to start it. You should also use set-ExecutionPolicy Unrestricted
or set-ExecutionPolicy AllSigned
see(the Execution Policy instructions).
_ [$%-4009] * #,##0_ ;_ [$%-4009] * -#,##0_ ;_ [$%-4009] * "-"??_ ;_ @_
I usually use the Timer function to pause the application. Insert this code to yours
T0 = Timer
Do
Delay = Timer - T0
Loop Until Delay >= 1 'Change this value to pause time for a certain amount of seconds
The main difference is the scope difference, while let can be only available inside the scope it's declared, like in for loop, var can be accessed outside the loop for example. From the documentation in MDN (examples also from MDN):
let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
Variables declared by let have as their scope the block in which they are defined, as well as in any contained sub-blocks. In this way, let works very much like var. The main difference is that the scope of a var variable is the entire enclosing function:
function varTest() {
var x = 1;
if (true) {
var x = 2; // same variable!
console.log(x); // 2
}
console.log(x); // 2
}
function letTest() {
let x = 1;
if (true) {
let x = 2; // different variable
console.log(x); // 2
}
console.log(x); // 1
}`
At the top level of programs and functions, let, unlike var, does not create a property on the global object. For example:
var x = 'global';
let y = 'global';
console.log(this.x); // "global"
console.log(this.y); // undefined
When used inside a block, let limits the variable's scope to that block. Note the difference between var whose scope is inside the function where it is declared.
var a = 1;
var b = 2;
if (a === 1) {
var a = 11; // the scope is global
let b = 22; // the scope is inside the if-block
console.log(a); // 11
console.log(b); // 22
}
console.log(a); // 11
console.log(b); // 2
Also don't forget it's ECMA6 feature, so it's not fully supported yet, so it's better always transpiles it to ECMA5 using Babel etc... for more info about visit babel website
As an extension to what have been proposed by Nico Coallier (apply to multiple columns) and U10-Forward(using apply style of methods), and summarising it into a one-liner I propose:
df.loc[:,['col1','col2']].transform(lambda x: x.map(lambda x: {1: "A", 2: "B"}.get(x,x))
The .transform()
processes each column as a series. Contrary to .apply()
which passes the columns aggregated in a DataFrame.
Consequently you can apply the Series method map()
.
Finally, and I discovered this behaviour thanks to U10, you can use the whole Series in the .get() expression. Unless I have misunderstood its behaviour and it processes sequentially the series instead of bitwisely.
The .get(x,x)
accounts for the values you did not mention in your mapping dictionary which would be considered as Nan otherwise by the .map()
method
Right click your project > Run As > Run Configuration... > Java Application (in left side panel) - double click on it. That will create new configuration. click on search button under Main Class section and select your main class from it.
TelephonyManager
is not the right solution, because in some cases the number is not stored in the SIM. I suggest that you should use the shared preference to store the user's phone number for the first time the application is open and the number will used whenever you need.
Have you tried adding lines below to your web.xml
?
<context-param>
<param-name>com.sun.faces.enableRestoreView11Compatibility</param-name>
<param-value>true</param-value>
</context-param>
I found this to be very effective when I encountered this issue.
In short, always prefer initialization lists when possible. 2 reasons:
If you do not mention a variable in a class's initialization list, the constructor will default initialize it before entering the body of the constructor you've written. This means that option 2 will lead to each variable being written to twice, once for the default initialization and once for the assignment in the constructor body.
Also, as mentioned by mwigdahl and avada in other answers, const members and reference members can only be initialized in an initialization list.
Also note that variables are always initialized on the order they are declared in the class declaration, not in the order they are listed in an initialization list (with proper warnings enabled a compiler will warn you if a list is written out of order). Similarly, destructors will call member destructors in the opposite order, last to first in the class declaration, after the code in your class's destructor has executed.
With existing Hamcrest libraries (as of v.2.0.0.0) you are forced to use Collection.toArray() method on your Collection in order to use containsInAnyOrder Matcher. Far nicer would be to add this as a separate method to org.hamcrest.Matchers:
public static <T> org.hamcrest.Matcher<java.lang.Iterable<? extends T>> containsInAnyOrder(Collection<T> items) {
return org.hamcrest.collection.IsIterableContainingInAnyOrder.<T>containsInAnyOrder((T[]) items.toArray());
}
Actually I ended up adding this method to my custom test library and use it to increase readability of my test cases (due to less verbosity).
I'm not sure that there is any option for simply printing the full effective search path.
But: the search path consists of directories specified by -L
options on the command line, followed by directories added to the search path by SEARCH_DIR("...")
directives in the linker script(s). So you can work it out if you can see both of those, which you can do as follows:
If you're invoking ld
directly:
-L
options are whatever you've said they are.--verbose
option. Look for the SEARCH_DIR("...")
directives, usually near the top of the output. (Note that these are not necessarily the same for every invocation of ld
-- the linker has a number of different built-in default linker scripts, and chooses between them based on various other linker options.)If you're linking via gcc
:
-v
option to gcc
so that it shows you how it invokes the linker. In fact, it normally does not invoke ld
directly, but indirectly via a tool called collect2
(which lives in one of its internal directories), which in turn invokes ld
. That will show you what -L
options are being used.-Wl,--verbose
to the gcc
options to make it pass --verbose
through to the linker, to see the linker script as described above.Did you try RedirectView where you can provide the contextRelative parameter?
will work on all majors browsers (IE included)
On osX
, Your path should be:
path = "/Users/name/Downloads/filename"
with name
the current user logged in
Another solution would be to implement a download handler or download handler middleware. (see scrapy docs for more information on downloader middleware) The following is an example class using selenium with headless phantomjs webdriver:
1) Define class within the middlewares.py
script.
from selenium import webdriver
from scrapy.http import HtmlResponse
class JsDownload(object):
@check_spider_middleware
def process_request(self, request, spider):
driver = webdriver.PhantomJS(executable_path='D:\phantomjs.exe')
driver.get(request.url)
return HtmlResponse(request.url, encoding='utf-8', body=driver.page_source.encode('utf-8'))
2) Add JsDownload()
class to variable DOWNLOADER_MIDDLEWARE
within settings.py
:
DOWNLOADER_MIDDLEWARES = {'MyProj.middleware.MiddleWareModule.MiddleWareClass': 500}
3) Integrate the HTMLResponse
within your_spider.py
. Decoding the response body will get you the desired output.
class Spider(CrawlSpider):
# define unique name of spider
name = "spider"
start_urls = ["https://www.url.de"]
def parse(self, response):
# initialize items
item = CrawlerItem()
# store data as items
item["js_enabled"] = response.body.decode("utf-8")
Optional Addon:
I wanted the ability to tell different spiders which middleware to use so I implemented this wrapper:
def check_spider_middleware(method):
@functools.wraps(method)
def wrapper(self, request, spider):
msg = '%%s %s middleware step' % (self.__class__.__name__,)
if self.__class__ in spider.middleware:
spider.log(msg % 'executing', level=log.DEBUG)
return method(self, request, spider)
else:
spider.log(msg % 'skipping', level=log.DEBUG)
return None
return wrapper
for wrapper to work all spiders must have at minimum:
middleware = set([])
to include a middleware:
middleware = set([MyProj.middleware.ModuleName.ClassName])
Advantage:
The main advantage to implementing it this way rather than in the spider is that you only end up making one request. In A T's solution for example: The download handler processes the request and then hands off the response to the spider. The spider then makes a brand new request in it's parse_page function -- That's two requests for the same content.
I don't think any of the current answers really do what you said you want. (Correction: I now see that @Gareth Latty / @Lattyware has incorporated my answer into his own as an "Edit" near the end.)
Anyway, here's my take:
Say these are the tab-separated values in your input file:
1 2 3 4 5
6 7 8 9 10
11 12 13 14 15
16 17 18 19 20
then this:
with open("tab-separated-values.txt") as inp:
print( list(zip(*(line.strip().split('\t') for line in inp))) )
would produce the following:
[('1', '6', '11', '16'),
('2', '7', '12', '17'),
('3', '8', '13', '18'),
('4', '9', '14', '19'),
('5', '10', '15', '20')]
As you can see, it put the k-th element of each row into the k-th array.
A string to char array is as simple as
String str = "someString";
char[] charArray = str.toCharArray();
Can you explain a little more on what you are trying to do?
* Update *
if I am understanding your new comment, you can use a byte array and example is provided.
byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();
for (byte b : bytes) {
System.out.format("0x%x ", b);
}
With the following output
0x65 0x10 0xf3 0x29
path = path.substring(0, path.length() - 5);
perl -0pE 's{^KEY.*?\K\s+(\d+)$}{ $1}msg;' data.txt > data_merged-lines.txt
-0
gobbles the whole file instead of reading it line-by-line;
pE
wraps code with loop and prints the output, see details in http://perldoc.perl.org/perlrun.html;
^KEY
match "KEY" in the beginning of line, followed by non-greedy match of anything (.*?
) before sequence of
\s+
of any kind including line breaks;(\d+)
which we capture and later re-insert as $1
;followed by the end of line $
.
\K
conveniently excludes everything on its left hand side from substitution so { $1}
replaces only 1-2 sequence, see http://perldoc.perl.org/perlre.html.
you can use this methods
var numbers=Array<Int>(size,init)
var numbers=IntArray(size,init)
var numbers= intArrayOf(1,2,3)
example
var numbers = Array<Int>(5, { i -> 0 })
init represents the default value ( initialize )
If you are using an external style sheet, the code could look something like this:
@font-face { font-family: Junebug; src: url('Junebug.ttf'); }
.junebug { font-family: Junebug; font-size: 4.2em; }
And should be saved in a separate .css file (eg styles.css). If your .css file is in a location separate from the page code, the actual font file should have the same path as the .css file, NOT the .html or .php web page file. Then the web page needs something like:
<link rel="stylesheet" href="css/styles.css">
in the <head> section of your html page. In this example, the font file should be located in the css folder along with the stylesheet. After this, simply add the class="junebug" inside any tag in your html to use Junebug font in that element.
If you're putting the css in the actual web page, add the style tag in the head of the html like:
<style>
@font-face { font-family: Junebug; src: url('Junebug.ttf'); }
</style>
And the actual element style can either be included in the above <style>
and called per element by class or id, or you can just declare the style inline with the element. By element I mean <div>, <p>, <h1> or any other element within the html that needs to use the Junebug font. With both of these options, the font file (Junebug.ttf) should be located in the same path as the html page. Of these two options, the best practice would look like:
<style>
@font-face { font-family: Junebug; src: url('Junebug.ttf'); }
.junebug { font-family: Junebug; font-size: 4.2em; }
</style>
and
<h1 class="junebug">This is Junebug</h1>
And the least acceptable way would be:
<style>
@font-face { font-family: Junebug; src: url('Junebug.ttf'); }
</style>
and
<h1 style="font-family: Junebug;">This is Junebug</h1>
The reason it's not good to use inline styles is best practice dictates that styles should be kept all in one place so editing is practical. This is also the main reason that I recommend using the very first option of using external style sheets. I hope this helps.
It didn't work, because QuerySets are not JSON serializable.
1) In case of json.dumps
you have to explicitely convert your QuerySet to JSON serializable objects:
class Model(model.Model):
def as_dict(self):
return {
"id": self.id,
# other stuff
}
And the serialization:
dictionaries = [ obj.as_dict() for obj in self.get_queryset() ]
return HttpResponse(json.dumps({"data": dictionaries}), content_type='application/json')
2) In case of serializers. Serializers accept either JSON serializable object or QuerySet, but a dictionary containing a QuerySet is neither. Try this:
serializers.serialize("json", self.get_queryset())
Read more about it here:
If lakes
is your DataFrame
, you can do something like
area_dict = dict(zip(lakes.area, lakes.count))
Unique key is actually an index. http://codeghar.wordpress.com/2008/03/28/drop-unique-constraint-in-mysql/
I had the same problem. I don't know how AFNetworking implements https request, but the reason for me is the NSURLSession's cache problem.
After my application tracking back from safari and then post a http request, "http load failed 1005" error will appear.
If I stop using "[NSURLSession sharedSession]"
, but to use a configurable NSURLSession instance to call "dataTaskWithRequest:" method as follow, the problem is solved.
NSURLSessionConfiguration *config = [NSURLSessionConfiguration defaultSessionConfiguration];
config.requestCachePolicy = NSURLRequestReloadIgnoringLocalCacheData;
config.URLCache = nil;
self.session = [NSURLSession sessionWithConfiguration:config];
Just remember to set config.URLCache = nil;
.
I suppose because you didn't specify plugin version so it triggers the download of associated metadata in order to get the last one.
Otherwise did you try to force local repo usage using -o ?
PEAR::Mail_Mime? Sure, PEAR dependency of (min) 2 files (just mail_mime itself if you edit it to remove the pear dependencies), but it works well. Additionally, most servers have PEAR installed to some extent, and in the best cases they have Pear/Mail and Pear/Mail_Mime. Something that cannot be said for most other libraries offering the same functionality.
You may also consider looking in to PHP's IMAP extension. It's a little more complicated, and requires more setup (not enabled or installed by default), but is must more efficient at compilng and sending messages to an IMAP capable server.
The @ symbol serves 2 purposes in C#:
Firstly, it allows you to use a reserved keyword as a variable like this:
int @int = 15;
The second option lets you specify a string without having to escape any characters. For instance the '\' character is an escape character so typically you would need to do this:
var myString = "c:\\myfolder\\myfile.txt"
alternatively you can do this:
var myString = @"c:\myFolder\myfile.txt"
Do you want the JDK or the JRE? Anyways, I had this problem too, a few weeks ago. I followed the instructions here and it worked:
http://www.backtrack-linux.org/wiki/index.php/Java_Install
root@bt:~# killall -9 /opt/firefox/firefox-bin
root@bt:~# mkdir /opt/java
root@bt:~# mv -f jre1.7.0_05/ /opt/java/
root@bt:~# update-alternatives --install /usr/bin/java java /opt/java/jre1.7.0_05/bin/java 1
root@bt:~# update-alternatives --set java /opt/java/jre1.7.0_05/bin/java
root@bt:~# export JAVA_HOME="/opt/java/jre1.7.0_05"
For Java 7 (32 bit)
root@bt:~# ln -sf $JAVA_HOME/lib/i386/libnpjp2.so /usr/lib/mozilla/plugins/
For Java 8 (64 bit)
root@bt:~# ln -sf $JAVA_HOME/jre/lib/amd64/libnpjp2.so /usr/lib/mozilla/plugins/
root@bt:~# firefox http://java.com/en/download/testjava.jsp
This is just an improvement to the previous answers because it didn't work for me with some zipcodes even when in https://www.google.com/maps it does, I fixed just adding the word "zipcode " before to put the zipcode, like this:
function getLatLngByZipcode(zipcode) _x000D_
{_x000D_
var geocoder = new google.maps.Geocoder();_x000D_
var address = zipcode;_x000D_
geocoder.geocode({ 'address': 'zipcode '+address }, function (results, status) {_x000D_
if (status == google.maps.GeocoderStatus.OK) {_x000D_
var latitude = results[0].geometry.location.lat();_x000D_
var longitude = results[0].geometry.location.lng();_x000D_
alert("Latitude: " + latitude + "\nLongitude: " + longitude);_x000D_
} else {_x000D_
alert("Request failed.")_x000D_
}_x000D_
});_x000D_
return [latitude, longitude];_x000D_
}
_x000D_
Reader they show at http://www.webqr.com/index.html works like a charm, but literaly, you need the one on the webpage, the github version it's really hard to make it work, however, it is possible. The best way to go is reverse-engineer the example shown at the webpage.
However, to edit and get the full potential out of it, it's not so easy. At some point I may post the stripped-down reverse-engineered QR reader, but in the meantime have some fun hacking the code.
Happy coding.
I am also using nunique
but it will be very helpful if you have to use an aggregate function like 'min', 'max', 'count' or 'mean'
etc.
df.groupby('YEARMONTH')['CLIENTCODE'].transform('nunique') #count(distinct)
df.groupby('YEARMONTH')['CLIENTCODE'].transform('min') #min
df.groupby('YEARMONTH')['CLIENTCODE'].transform('max') #max
df.groupby('YEARMONTH')['CLIENTCODE'].transform('mean') #average
df.groupby('YEARMONTH')['CLIENTCODE'].transform('count') #count
Maven pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>some.examples</groupId>
<artifactId>sslcliauth</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>sslcliauth</name>
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.4</version>
</dependency>
</dependencies>
</project>
Java code:
package some.examples;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.http.entity.InputStreamEntity;
public class SSLCliAuthExample {
private static final Logger LOG = Logger.getLogger(SSLCliAuthExample.class.getName());
private static final String CA_KEYSTORE_TYPE = KeyStore.getDefaultType(); //"JKS";
private static final String CA_KEYSTORE_PATH = "./cacert.jks";
private static final String CA_KEYSTORE_PASS = "changeit";
private static final String CLIENT_KEYSTORE_TYPE = "PKCS12";
private static final String CLIENT_KEYSTORE_PATH = "./client.p12";
private static final String CLIENT_KEYSTORE_PASS = "changeit";
public static void main(String[] args) throws Exception {
requestTimestamp();
}
public final static void requestTimestamp() throws Exception {
SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(
createSslCustomContext(),
new String[]{"TLSv1"}, // Allow TLSv1 protocol only
null,
SSLConnectionSocketFactory.getDefaultHostnameVerifier());
try (CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(csf).build()) {
HttpPost req = new HttpPost("https://changeit.com/changeit");
req.setConfig(configureRequest());
HttpEntity ent = new InputStreamEntity(new FileInputStream("./bytes.bin"));
req.setEntity(ent);
try (CloseableHttpResponse response = httpclient.execute(req)) {
HttpEntity entity = response.getEntity();
LOG.log(Level.INFO, "*** Reponse status: {0}", response.getStatusLine());
EntityUtils.consume(entity);
LOG.log(Level.INFO, "*** Response entity: {0}", entity.toString());
}
}
}
public static RequestConfig configureRequest() {
HttpHost proxy = new HttpHost("changeit.local", 8080, "http");
RequestConfig config = RequestConfig.custom()
.setProxy(proxy)
.build();
return config;
}
public static SSLContext createSslCustomContext() throws KeyStoreException, IOException, NoSuchAlgorithmException, CertificateException, KeyManagementException, UnrecoverableKeyException {
// Trusted CA keystore
KeyStore tks = KeyStore.getInstance(CA_KEYSTORE_TYPE);
tks.load(new FileInputStream(CA_KEYSTORE_PATH), CA_KEYSTORE_PASS.toCharArray());
// Client keystore
KeyStore cks = KeyStore.getInstance(CLIENT_KEYSTORE_TYPE);
cks.load(new FileInputStream(CLIENT_KEYSTORE_PATH), CLIENT_KEYSTORE_PASS.toCharArray());
SSLContext sslcontext = SSLContexts.custom()
//.loadTrustMaterial(tks, new TrustSelfSignedStrategy()) // use it to customize
.loadKeyMaterial(cks, CLIENT_KEYSTORE_PASS.toCharArray()) // load client certificate
.build();
return sslcontext;
}
}
There are no problems with the second version of the assignment operator. In fact, that is the standard way for an assignment operator.
Edit: Note that I am referring to the return type of the assignment operator, not to the implementation itself. As has been pointed out in comments, the implementation itself is another issue. See here.
It seems to work fine in Postgresql 9.5:
SELECT current_setting('TIMEZONE');
You have a few options:
Put different URLs in the action for the two forms. Then you'll have two different view functions to deal with the two different forms.
Read the submit button values from the POST data. You can tell which submit button was clicked: How can I build multiple submit buttons django form?
This method should do it. It serializes the form data and then converts them to an object. Takes care of groups of checkboxes as well.
function getFormObj(formId) {
var formParams = {};
$('#' + formId)
.serializeArray()
.forEach(function(item) {
if (formParams[item.name]) {
formParams[item.name] = [formParams[item.name]];
formParams[item.name].push(item.value)
} else {
formParams[item.name] = item.value
}
});
return formParams;
}
This is an example with subprocess
library:
import subprocess
python_version = '3'
path_to_run = './'
py_name = '__main__.py'
# args = [f"python{python_version}", f"{path_to_run}{py_name}"] # Avaible in python3
args = ["python{}".format(python_version), "{}{}".format(path_to_run, py_name)]
res = subprocess.Popen(args, stdout=subprocess.PIPE)
output, error_ = res.communicate()
if not error_:
print(output)
else:
print(error_)
tl;dr: use OSX's native process launcher and manager, launchd
.
To do so, make a launchctl
daemon. You'll have full control over all aspects of the script. You can run once or keep alive as a daemon. In most cases, this is the way to go.
.plist
file according to the instructions in the Apple Dev docs here or more detail below.~/Library/LaunchAgents
launchctl load [filename.plist]
)For more on launchd
, the wikipedia article is quite good and describes the system and its advantages over other older systems.
Here's the specific plist file to run a script at login.
Updated 2017/09/25 for OSX El Capitan and newer (credit to José Messias Jr):
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>com.user.loginscript</string>
<key>ProgramArguments</key>
<array><string>/path/to/executable/script.sh</string></array>
<key>RunAtLoad</key>
<true/>
</dict>
</plist>
Replace the <string>
after the Program key with your desired command (note that any script referenced by that command must be executable: chmod a+x /path/to/executable/script.sh
to ensure it is for all users).
Save as ~/Library/LaunchAgents/com.user.loginscript.plist
Run launchctl load ~/Library/LaunchAgents/com.user.loginscript.plist
and log out/in to test (or to test directly, run launchctl start com.user.loginscript
)
Tail /var/log/system.log
for error messages.
The key is that this is a User-specific launchd entry, so it will be run on login for the given user. System-specific launch daemons (placed in /Library/LaunchDaemons
) are run on boot.
If you want a script to run on login for all users, I believe LoginHook is your only option, and that's probably the reason it exists.
Added webkit specific values missing from above
white-space: -moz-pre-wrap; /* Firefox */
white-space: -o-pre-wrap; /* Opera */
white-space: pre-wrap; /* Chrome */
word-wrap: break-word; /* IE */
A PHP file must have permissions set to 644. Any folder containing PHP files and PHP access (to upload files, for example) must have permissions set to 755. PHP will run a 500 error when dealing with any file or folder that has permissions set to 777!
Read up on the configuration settings (e.g., display_errors
, display_startup_errors
, log_errors
) and update your php.ini
or .htaccess
or .user.ini
file, whichever is appropriate.
It works.
You can specify gradients for colours in certain circumstances in CSS3, and of course borders can be set to a colour, so you should be able to use a gradient as a border colour. This would include the option of specifying a transparent colour, which means you should be able to achieve the effect you're after.
However, I've never seen it used, and I don't know how well supported it is by current browsers. You'll certainly need to accept that at least some of your users won't be able to see it.
A quick google turned up these two pages which should help you on your way:
Hope that helps.
In order to call this you will have to store a reference to your form and pass the reference to the run method. Then you can call this in an actionhandler.
public partial class Form1 : Form
{
public void ChangeSize(int width, int height)
{
this.Size = new Size(width, height);
}
}
For me it was not running the minify task after concatenation as it expects concatenated input and it was not generated some times.
I tried adding to a default task in execution order and it didn't worked. It worked after adding just a return
for each tasks and getting the minification inside gulp.start()
like below.
/**
* Concatenate JavaScripts
*/
gulp.task('concat-js', function(){
return gulp.src([
'js/jquery.js',
'js/jquery-ui.js',
'js/bootstrap.js',
'js/jquery.onepage-scroll.js',
'js/script.js'])
.pipe(maps.init())
.pipe(concat('ux.js'))
.pipe(maps.write('./'))
.pipe(gulp.dest('dist/js'));
});
/**
* Minify JavaScript
*/
gulp.task('minify-js', function(){
return gulp.src('dist/js/ux.js')
.pipe(uglify())
.pipe(rename('ux.min.js'))
.pipe(gulp.dest('dist/js'));
});
gulp.task('concat', ['concat-js'], function(){
gulp.start('minify-js');
});
gulp.task('default',['concat']);
All I wanted were 1) English only and 2) just enough to build a legacy desktop project written in C. No Azure, no mobile development, no .NET, and no other components that I don't know what to do with.
[Note: Options are in multiple lines for readability, but they should be in 1 line]
vs_community__xxxxxxxxxx.xxxxxxxxxx.exe
--lang en-US
--layout ".\Visual Studio Cummunity 2017"
--add Microsoft.VisualStudio.Workload.NativeDesktop
--includeRecommended
I chose "NativeDesktop" from "workload and component ID" site (https://docs.microsoft.com/en-us/visualstudio/install/workload-component-id-vs-community).
The result was about 1.6GB downloaded files and 5GB when installed. I'm sure I could have removed a few unnecessary components to save space, but the list was rather long, so I stopped there.
"--includeRecommended" was the key ingredient for me, which included Windows SDK along with other essential things for building the legacy project.
As a general rule of thumb, if I have to set the value of the string more than once, or if there are any appends to the string, then it needs to be a string builder. I have seen applications that I have written in the past before learning about string builders that have had a huge memory foot print that just seems to keep growing and growing. Changing these programs to use the string builder cut down the memory usage significantly. Now I swear by the string builder.
print "bla: ", $_, "\n" if ($_ = $myvar) =~ s/a/b/g or 1;
It depends on your situation.
I would say, if your bool has a good name, then:
if (control.IsEnabled) // Read "If control is enabled."
{
}
would be preferred.
If, however, the variable has a not-so-obvious name, checking against true
would be helpful in understanding the logic.
if (first == true) // Read "If first is true."
{
}
Create file ~/.config/autostart/MyScript.desktop with
[Desktop Entry]
Encoding=UTF-8
Name=MyScript
Comment=MyScript
Icon=gnome-info
Exec=python /home/your_path/script.py
Terminal=false
Type=Application
Categories=
X-GNOME-Autostart-enabled=true
X-GNOME-Autostart-Delay=0
It helps me!
After you connect to SQLite:
con = sqlite3.connect(.....)
it is sufficient to just run:
con.row_factory = sqlite3.Row
Voila!
An important consideration is the web.config file, Some packages can mangle your binding redirects causing havoc (the rogue package was in house package that I did not remove the web.config from the package or making sure the web.config in in the package doesn't have any binding redirects. For example by removing the duplicate and incorrect node resolves this
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31BF3856AD364E35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0"/>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
<assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
<assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0"/>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930"/>
<assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2"/>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35"/>
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="SimpleInjector" publicKeyToken="984cb50dea722e99" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-3.3.2.0" newVersion="3.3.2.0"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2"/>
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="HtmlAgilityPack" publicKeyToken="bd319b19eaf3b43a" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-1.4.9.5" newVersion="1.4.9.5"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
by removing lines 8 to 24 fixes the build.
Follow as in picture for removing that lint error and adding automatic fix by addin g--fix in package.json
Many of the above methods have been deprecated. It is now recommended to use the constructor found here
function clickAnchorTag() {
var event = document.createEvent('MouseEvent');
event = new CustomEvent('click');
var a = document.getElementById('nameOfID');
a.dispatchEvent(event);
}
This will cause the anchor tag to be clicked, but it wont show if pop-up blockers are active so the user will need to allow pop-ups.
<script>
var listh = document.getElementById( 'list-home-list' );
var hb = document.getElementsByTagName('hb');
$("#list-home-list").click(function(){
$(this).style.color = '#2C2E33';
hb.style.color = 'white';
});
</script>
Here's another JavaScript solution. Works very good and very fast.
https://github.com/dobiatowski/jQuery.FastEllipsis
Tested on Chrome, FF, IE on Windows and Mac.
Just use cd /d %root%
to switch driver letters and change directories.
Alternatively, use pushd %root%
to switch drive letters when changing directories as well as storing the previous directory on a stack so you can use popd
to switch back.
Note that pushd
will also allow you to change directories to a network share. It will actually map a network drive for you, then unmap it when you execute the popd
for that directory.
If you created the DLL using .net 4.5 , then copy and paste this command on command prompt.
%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\regasm.exe MyAssembly.dll
If an algorithm is of T(g(n)), it means that the running time of the algorithm as n (input size) gets larger is proportional to g(n).
If an algorithm is of O(g(n)), it means that the running time of the algorithm as n gets larger is at most proportional to g(n).
Normally, even when people talk about O(g(n)) they actually mean T(g(n)) but technically, there is a difference.
O(n) represents upper bound. T(n) means tight bound. O(n) represents lower bound.
f(x) = T(g(x)) iff f(x) = O(g(x)) and f(x) = O(g(x))
Basically when we say an algorithm is of O(n), it's also O(n2), O(n1000000), O(2n), ... but a T(n) algorithm is not T(n2).
In fact, since f(n) = T(g(n)) means for sufficiently large values of n, f(n) can be bound within c1g(n) and c2g(n) for some values of c1 and c2, i.e. the growth rate of f is asymptotically equal to g: g can be a lower bound and and an upper bound of f. This directly implies f can be a lower bound and an upper bound of g as well. Consequently,
f(x) = T(g(x)) iff g(x) = T(f(x))
Similarly, to show f(n) = T(g(n)), it's enough to show g is an upper bound of f (i.e. f(n) = O(g(n))) and f is a lower bound of g (i.e. f(n) = O(g(n)) which is the exact same thing as g(n) = O(f(n))). Concisely,
f(x) = T(g(x)) iff f(x) = O(g(x)) and g(x) = O(f(x))
There are also little-oh and little-omega (?
) notations representing loose upper and loose lower bounds of a function.
To summarize:
f(x) = O(g(x))
(big-oh) means that the growth rate off(x)
is asymptotically less than or equal to to the growth rate ofg(x)
.
f(x) = O(g(x))
(big-omega) means that the growth rate off(x)
is asymptotically greater than or equal to the growth rate ofg(x)
f(x) = o(g(x))
(little-oh) means that the growth rate off(x)
is asymptotically less than the growth rate ofg(x)
.
f(x) = ?(g(x))
(little-omega) means that the growth rate off(x)
is asymptotically greater than the growth rate ofg(x)
f(x) = T(g(x))
(theta) means that the growth rate off(x)
is asymptotically equal to the growth rate ofg(x)
For a more detailed discussion, you can read the definition on Wikipedia or consult a classic textbook like Introduction to Algorithms by Cormen et al.
First of all jar
creates a jar, and does not run it. Try java -jar
instead.
Second, why do you pass the class twice, as FQCN (com.mycomp.myproj.dir2.MainClass2
) and as file (com/mycomp/myproj/dir2/MainClass2.class
)?
Edit:
It seems as if java -jar
requires a main class to be specified. You could try java -cp your.jar com.mycomp.myproj.dir2.MainClass2 ...
instead. -cp
sets the jar on the classpath and enables java to look up the main class there.
As per the question, i have listed the answers in javascript
By Selecting TagName
document.getElementsByTagName('textarea')[0].style.resize = "none";
By Selecting Id
document.getElementById('textArea').style.resize = "none";
The sizeof the structure should be 8 bytes on a 32 bit system, so that the size of the structure becomes multiple of 2. This makes individual structures available at the correct byte boundaries when an array of structures is declared. This is achieved by padding the structure with 3 bytes at the end.
If the structure had the pointer declared after the char, it would still be 8 bytes in size but the 3 byte padding would have been added to keep the pointer (which is a 4 byte element) aligned at a 4 byte address boundary.
The rule of thumb is that elements should be at an offset which is the multiple of their byte size and the structure itself should be of a size which is a multiple of 2.
@ts-expect-error
TS 3.9 introduces a new magic comment. @ts-expect-error
will:
@ts-ignore
if (false) {
// @ts-expect-error: Let's ignore a single compiler error like this unreachable code
console.log("hello"); // compiles
}
// If @ts-expect-error didn't suppress anything at all, we now get a nice warning
let flag = true;
// ...
if (flag) {
// @ts-expect-error
// ^~~~~~~~~~~~~~~^ error: "Unused '@ts-expect-error' directive.(2578)"
console.log("hello");
}
@ts-ignore
and @ts-expect-error
can be used for all sorts of compiler errors. For type issues (like in OP), I recommend one of the following alternatives due to narrower error suppression scope:
? Use any
type
// type assertion for single expression
delete ($ as any).summernote.options.keyMap.pc.TAB;
// new variable assignment for multiple usages
const $$: any = $
delete $$.summernote.options.keyMap.pc.TAB;
delete $$.summernote.options.keyMap.mac.TAB;
? Augment JQueryStatic
interface
// ./global.d.ts
interface JQueryStatic {
summernote: any;
}
// ./main.ts
delete $.summernote.options.keyMap.pc.TAB; // works
In other cases, shorthand module declarations or module augmentations for modules with no/extendable types are handy utilities. A viable strategy is also to keep not migrated code in .js
and use --allowJs
with checkJs: false
.
I wouldn't do it. Use virtual PCs instead. It might take a little setup, but you'll thank yourself in the long run. In my experience, you can't really get them cleanly installed side by side and unless they are standalone installs you can't really verify that it is 100% true-to-browser rendering.
Update: Looks like one of the better ways to accomplish this (if running Windows 7) is using Windows XP mode to set up multiple virtual machines: Testing Multiple Versions of IE on one PC at the IEBlog.
Update 2: (11/2014) There are new solutions since this was last updated. Microsoft now provides VMs for any environment to test multiple versions of IE: Modern.IE
This should do the trick...
'recalculate all open workbooks
Application.Calculate
'recalculate a specific worksheet
Worksheets(1).Calculate
' recalculate a specific range
Worksheets(1).Columns(1).Calculate
Note: This code is untested
Define a record for your refCursor return type, call it rec. For example:
TYPE MyRec IS RECORD (col1 VARCHAR2(10), col2 VARCHAR2(20), ...); --define the record
rec MyRec; -- instantiate the record
Once you have the refcursor returned from your procedure, you can add the following code where your comments are now:
LOOP
FETCH refCursor INTO rec;
EXIT WHEN refCursor%NOTFOUND;
dbms_output.put_line(rec.col1||','||rec.col2||','||...);
END LOOP;
function func(a, b)
{
if (typeof a == 'undefined')
a = 10;
if (typeof b == 'undefined')
b = 20;
// do what you want ... for example
alert(a + ',' + b);
}
in shorthand
function func(a, b)
{
a = (typeof a == 'undefined')?10:a;
b = (typeof b == 'undefined')?20:b;
// do what you want ... for example
alert(a + ',' + b);
}
In my case I wasn't sure what had caused this to happen, but I knew I just wanted the submodules to be reset to their latest remote commit and be done with it. This involved combining answers from a couple of different questions on here:
git submodule update --recursive --remote --init
Sources:
There was auto generated Copyright message in XML
and a blank line before <resources>
tag, once I removed it my build was successful.
You are using a function, which is marked as deleted
.
Eg:
int doSomething( int ) = delete;
The =delete is a new feature of C++0x. It means the compiler should immediately stop compiling and complain "this function is deleted" once the user use such function.
If you see this error, you should check the function declaration for =delete
.
To know more about this new feature introduced in C++0x, check this out.
When you want to throw away a specific number of characters from the input stream manually.
A very common use case is using this to safely ignore newline characters since cin will sometimes leave newline characters that you will have to go over to get to the next line of input.
Long story short it gives you flexibility when handling stream input.
You have forgotten to mark the getProducts return type as an array. In your getProducts it says that it will return a single product. So change it to this:
public getProducts(): Observable<Product[]> {
return this.http.get<Product[]>(`api/products/v1/`);
}
I always go for the second method (using the GString template), though when there are more than a couple of parameters like you have, I tend to wrap them in ${X}
as I find it makes it more readable.
Running some benchmarks (using Nagai Masato's excellent GBench module) on these methods also shows templating is faster than the other methods:
@Grab( 'com.googlecode.gbench:gbench:0.3.0-groovy-2.0' )
import gbench.*
def (foo,bar,baz) = [ 'foo', 'bar', 'baz' ]
new BenchmarkBuilder().run( measureCpuTime:false ) {
// Just add the strings
'String adder' {
foo + bar + baz
}
// Templating
'GString template' {
"$foo$bar$baz"
}
// I find this more readable
'Readable GString template' {
"${foo}${bar}${baz}"
}
// StringBuilder
'StringBuilder' {
new StringBuilder().append( foo )
.append( bar )
.append( baz )
.toString()
}
'StringBuffer' {
new StringBuffer().append( foo )
.append( bar )
.append( baz )
.toString()
}
}.prettyPrint()
That gives me the following output on my machine:
Environment
===========
* Groovy: 2.0.0
* JVM: Java HotSpot(TM) 64-Bit Server VM (20.6-b01-415, Apple Inc.)
* JRE: 1.6.0_31
* Total Memory: 81.0625 MB
* Maximum Memory: 123.9375 MB
* OS: Mac OS X (10.6.8, x86_64)
Options
=======
* Warm Up: Auto
* CPU Time Measurement: Off
String adder 539
GString template 245
Readable GString template 244
StringBuilder 318
StringBuffer 370
So with readability and speed in it's favour, I'd recommend templating ;-)
NB: If you add toString()
to the end of the GString methods to make the output type the same as the other metrics, and make it a fairer test, StringBuilder
and StringBuffer
beat the GString methods for speed. However as GString can be used in place of String for most things (you just need to exercise caution with Map keys and SQL statements), it can mostly be left without this final conversion
Adding these tests (as it has been asked in the comments)
'GString template toString' {
"$foo$bar$baz".toString()
}
'Readable GString template toString' {
"${foo}${bar}${baz}".toString()
}
Now we get the results:
String adder 514
GString template 267
Readable GString template 269
GString template toString 478
Readable GString template toString 480
StringBuilder 321
StringBuffer 369
So as you can see (as I said), it is slower than StringBuilder or StringBuffer, but still a bit faster than adding Strings...
But still lots more readable.
Updated to latest gbench, larger strings for concatenation and a test with a StringBuilder initialised to a good size:
@Grab( 'org.gperfutils:gbench:0.4.2-groovy-2.1' )
def (foo,bar,baz) = [ 'foo' * 50, 'bar' * 50, 'baz' * 50 ]
benchmark {
// Just add the strings
'String adder' {
foo + bar + baz
}
// Templating
'GString template' {
"$foo$bar$baz"
}
// I find this more readable
'Readable GString template' {
"${foo}${bar}${baz}"
}
'GString template toString' {
"$foo$bar$baz".toString()
}
'Readable GString template toString' {
"${foo}${bar}${baz}".toString()
}
// StringBuilder
'StringBuilder' {
new StringBuilder().append( foo )
.append( bar )
.append( baz )
.toString()
}
'StringBuffer' {
new StringBuffer().append( foo )
.append( bar )
.append( baz )
.toString()
}
'StringBuffer with Allocation' {
new StringBuffer( 512 ).append( foo )
.append( bar )
.append( baz )
.toString()
}
}.prettyPrint()
gives
Environment
===========
* Groovy: 2.1.6
* JVM: Java HotSpot(TM) 64-Bit Server VM (23.21-b01, Oracle Corporation)
* JRE: 1.7.0_21
* Total Memory: 467.375 MB
* Maximum Memory: 1077.375 MB
* OS: Mac OS X (10.8.4, x86_64)
Options
=======
* Warm Up: Auto (- 60 sec)
* CPU Time Measurement: On
user system cpu real
String adder 630 0 630 647
GString template 29 0 29 31
Readable GString template 32 0 32 33
GString template toString 429 0 429 443
Readable GString template toString 428 1 429 441
StringBuilder 383 1 384 396
StringBuffer 395 1 396 409
StringBuffer with Allocation 277 0 277 286
If you want to count the number of appearances subsequently, you can make use of the sapply
function:
index<-sapply(1:length(numbers),function(x)sum(numbers[1:x]==numbers[x]))
cbind(numbers, index)
Output:
numbers index
[1,] 4 1
[2,] 23 1
[3,] 4 2
[4,] 23 2
[5,] 5 1
[6,] 43 1
[7,] 54 1
[8,] 56 1
[9,] 657 1
[10,] 67 1
[11,] 67 2
[12,] 435 1
[13,] 453 1
[14,] 435 2
[15,] 324 1
[16,] 34 1
[17,] 456 1
[18,] 56 2
[19,] 567 1
[20,] 65 1
[21,] 34 2
[22,] 435 3
The query string that I used to to escape the new line character in JS :
LOAD DATA LOCAL INFILE 'Data.csv' INTO TABLE DEMO FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\r\n' IGNORE 1 ROWS;
This involves new ES6 syntax - Template Literals `` and I tried changing '\n' to '\r\n' and worked perfectly in my case.
PS: This example is my query to upload CSV data into mysql DB.
You can copy subscribers dictionary object to a same type of temporary dictionary object and then iterate the temporary dictionary object using foreach loop.
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
THIS IS THE EASY AND PERFECT CODE FOR DURATION AND DISTANCE FINDING
Step 1;(add this and sync in your gradle)
compile 'com.android.volley:volley:1.0.0'
Step 2:(write this in your trigger method)
public void clicked(View view) throws JSONException {
JSONObject locationJsonObject = new JSONObject();
locationJsonObject.put("origin", "54.406505,18.67708");
locationJsonObject.put("destination", "54.446251,18.570993");
LatlngCalc(locationJsonObject);
}
Step 3:(Copy & Paste in your class)
private void LatlngCalc(JSONObject locationJsonObject) throws JSONException {
RequestQueue queue = Volley.newRequestQueue(MainActivity.this);
String url = "http://maps.googleapis.com/maps/api/distancematrix/" +
"json?origins=" + locationJsonObject.getString("origin") + "&destinations=" + locationJsonObject.getString("destination") + "&mode=driving&" +
"language=en-EN&sensor=false";
StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
mTextView.setText("Response is: " + response.substring(0, 500));
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
mTextView.setText("That didn't work!");
}
});
queue.add(stringRequest);
}
For those who do not want to include the whole of jQuery UI, you can use jQuery.pulse.js instead.
To have looping animation of changing opacity, do this:
$('#target').pulse({opacity: 0.8}, {duration : 100, pulses : 5});
It is light (less than 1kb), and allows you to loop any kind of animations.