In my case, the error was triggered by duplicating an import of a component in the module.
I tried to generate a form dynamically because the amount of questions depend on an object and for me the error was fixed when I added ngDefaultControl
to my mat-form-field
.
<form [formGroup]="questionsForm">
<ng-container *ngFor="let question of questions">
<mat-form-field [formControlName]="question.id" ngDefaultControl>
<mat-label>{{question.questionContent}}</mat-label>
<textarea matInput rows="3" required></textarea>
</mat-form-field>
</ng-container>
<button mat-raised-button (click)="sendFeedback()">Submit all questions</button>
</form>
In sendFeedback() I get the value from my dynamic form by selecting the formgroup's value as such
sendFeedbackAsAgent():void {
if (this.questionsForm.valid) {
console.log(this.questionsForm.value)
}
}
I struggled with the same issue when trying to feed floats to the classifiers. I wanted to keep floats and not integers for accuracy. Try using regressor algorithms. For example:
import numpy as np
from sklearn import linear_model
from sklearn import svm
classifiers = [
svm.SVR(),
linear_model.SGDRegressor(),
linear_model.BayesianRidge(),
linear_model.LassoLars(),
linear_model.ARDRegression(),
linear_model.PassiveAggressiveRegressor(),
linear_model.TheilSenRegressor(),
linear_model.LinearRegression()]
trainingData = np.array([ [2.3, 4.3, 2.5], [1.3, 5.2, 5.2], [3.3, 2.9, 0.8], [3.1, 4.3, 4.0] ])
trainingScores = np.array( [3.4, 7.5, 4.5, 1.6] )
predictionData = np.array([ [2.5, 2.4, 2.7], [2.7, 3.2, 1.2] ])
for item in classifiers:
print(item)
clf = item
clf.fit(trainingData, trainingScores)
print(clf.predict(predictionData),'\n')
This answer is to give a better understanding of this warning
Deprecation warning is caused when you use moment to create time object, var today = moment();
.
If this warning is okay with you then I have a simpler method.
Don't use date
object from js
use moment
instead. For example use moment()
to get the current date.
Or convert the js
date object to moment
date. You can simply do that specifying the format of your js
date object.
ie, moment("js date", "js date format");
eg:
moment("2014 04 25", "YYYY MM DD");
(BUT YOU CAN ONLY USE THIS METHOD UNTIL IT'S DEPRECIATED, this may be depreciated from moment
in the future)
if you have a string of date, then you should try this.
const FORMAT = "YYYY ddd MMM DD HH:mm";
const theDate = moment("2019 Tue Apr 09 13:30", FORMAT);
// Tue Apr 09 2019 13:30:00 GMT+0300
const theDate1 = moment("2019 Tue Apr 09 13:30", FORMAT).format('LL')
// April 9, 2019
or try this :
const theDate1 = moment("2019 Tue Apr 09 13:30").format(FORMAT);
You could also get the error if your Billing is not set up correctly.
Google hands out credit worth $300 or 12 months of free usage whichever runs out faster. After that you would need to enable billing.
Cors can be a pain in the ass, but with this simple code you are Cors ONLY!!!! to to specified method
@CrossOrigin(origins="*")// in this line add your url and thats is all for spring boot side
@GetMapping("/some")
public String index() {
return "pawned cors!!!!";
}
Like a charm in spring boot 2.0.2
Other answers are outdated, or incomplete, or simply don't work.
You need to also specify an X-11 server on the host machine to handle the launch of GUId programs. If the client is a Windows machine install Xming. If the client is a Linux machine install XQuartz.
Now suppose this is Windows connecting to Linux. In order to be able to launch X11 programs as well over putty do the following:
- Launch XMing on Windows client
- Launch Putty
* Fill in basic options as you know in session category
* Connection -> SSH -> X11
-> Enable X11 forwarding
-> X display location = :0.0
-> MIT-Magic-Cookie-1
-> X authority file for local display = point to the Xming.exe executable
Of course the ssh server should have permitted Desktop Sharing "Allow other user to view your desktop".
MobaXterm and other complete remote desktop programs work too.
After mid-2018:
1:) Invite @getidsbot or @RawDataBot
to your group and get your group id from the chat id field.
Message
+ message_id: 338
+ from
? + id: *****
? + is_bot: false
? + first_name: ???
? + username: ******
? + language_code: en
+ chat
? + id: -1001118554477 // This is Your Group id
? + title: Test Group
? + type: supergroup
+ date: 1544948900
+ text: A
2:) use an unofficial Messenger like Plus Messenger and see your group id in group/channel info.
Before mid-2018: (don't Use)
1: Goto (https://web.telegram.org)
2: Goto your Gorup and Find your link of Gorup(https://web.telegram.org/#/im?p=g154513121)
3: Copy That number after g and put a (-) Before That -154513121
4: Send Your Message to Gorup
bot.sendMessage(-154513121, "Hi")
I Tested Now and Work like a Charm
Whenever user communicate with bot it send information like below:
$response = {
"update_id":640046715,
"message":{
"message_id":1665,
"from":{"id":108177xxxx,"is_bot":false,"first_name":"Suresh","last_name":"Kamrushi","language_code":"en"},
"chat":{"id":108xxxxxx,"first_name":"Suresh","last_name":"Kamrushi","type":"private"},
"date":1604381276,
"text":"1"
}
}
So you can access chat it like:
$update["message"]["chat"]["id"]
Assuming you are using PHP.
First, we need GOPATH
The $GOPATH
is a folder (or set of folders) specified by its environment variable. We must notice that this is not the $GOROOT
directory where Go is installed.
export GOPATH=$HOME/gocode
export PATH=$PATH:$GOPATH/bin
We used ~/gocode
path in our computer to store the source of our application and its dependencies. The GOPATH
directory will also store the binaries of their packages.
Then check Go env
You system must have $GOPATH
and $GOROOT
, below is my Env:
GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/elpsstu/gocode"
GORACE=""
GOROOT="/home/pravin/go"
GOTOOLDIR="/home/pravin/go/pkg/tool/linux_amd64"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"
Now, you run download go package:
go get [-d] [-f] [-fix] [-t] [-u] [build flags] [packages]
Get downloads and installs the packages named by the import paths, along with their dependencies. For more details you can look here.
I had the similar prolem with OP. As the terminal output suggested, I went to http://wiki.apache.org/hadoop/ConnectionRefused
I tried to change my /etc/hosts file as suggested here, i.e. remove 127.0.1.1 as OP suggested it will create another error.
So in the end, I leave it as is. The following is my /etc/hosts
127.0.0.1 localhost.localdomain localhost
127.0.1.1 linux
# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
In the end, I found that my namenode did not started correctly, i.e.
When you type sudo netstat -lpten | grep java
in the terminal, there will not be any JVM process running(listening) on port 9000.
So I made two directories for namenode and datanode respectively(if you have not done so). You don't have to put where I put it, please replace it based on your hadoop directory. i.e.
mkdir -p /home/hadoopuser/hadoop-2.6.2/hdfs/namenode
mkdir -p /home/hadoopuser/hadoop-2.6.2/hdfs/datanode
I reconfigured my hdfs-site.xml.
<configuration>
<property>
<name>dfs.replication</name>
<value>1</value>
</property>
<property>
<name>dfs.namenode.name.dir</name>
<value>file:/home/hadoopuser/hadoop-2.6.2/hdfs/namenode</value>
</property>
<property>
<name>dfs.datanode.data.dir</name>
<value>file:/home/hadoopuser/hadoop-2.6.2/hdfs/datanode</value>
</property>
</configuration>
In terminal, stop your hdfs and yarn with script stop-dfs.sh
and stop-yarn.sh
. They are located in your hadoop directory/sbin. In my case, it's /home/hadoopuser/hadoop-2.6.2/sbin/.
Then start your hdfs and yarn with script start-dfs.sh
and start-yarn.sh
After it is started, type jps
in your terminal to see if your JVM processes are running correctly. It should show the following.
15678 NodeManager
14982 NameNode
15347 SecondaryNameNode
23814 Jps
15119 DataNode
15548 ResourceManager
Then try to use netstat again to see if your namenode is listening to port 9000
sudo netstat -lpten | grep java
If you successfully set up the namenode, you should see the following in your terminal output.
tcp 0 0 127.0.0.1:9000 0.0.0.0:* LISTEN 1001 175157 14982/java
Then try to type the command hdfs dfs -mkdir /user/hadoopuser
If this command executes sucessfully, now you can list your directory in the HDFS user directory by hdfs dfs -ls /user
You can try this modal:https://github.com/xue2han/react-dynamic-modal It is stateless and can be rendered only when needed.So it is very easy to use.Just like this:
class MyModal extends Component{
render(){
const { text } = this.props;
return (
<Modal
onRequestClose={this.props.onRequestClose}
openTimeoutMS={150}
closeTimeoutMS={150}
style={customStyle}>
<h1>What you input : {text}</h1>
<button onClick={ModalManager.close}>Close Modal</button>
</Modal>
);
}
}
class App extends Component{
openModal(){
const text = this.refs.input.value;
ModalManager.open(<MyModal text={text} onRequestClose={() => true}/>);
}
render(){
return (
<div>
<div><input type="text" placeholder="input something" ref="input" /></div>
<div><button type="button" onClick={this.openModal.bind(this)}>Open Modal </button> </div>
</div>
);
}
}
ReactDOM.render(<App />,document.getElementById('main'));
It is very simple to do. Code are given below :
DB::table('user')->where('email', $userEmail)->update(array('member_type' => $plan));
$users = Get-ADGroupMember -Identity 'Client Services' -Recursive ; $users.count
The above one-liner gives a clean count of recursive members found. Simple, easy, and one line.
This method takes one Function as an argument, this function accepts one parameter T as an input argument and return one stream of parameter R as a return value. When this function is applied on each element of this stream, it produces a stream of new values. All the elements of these new streams generated by each element are then copied to a new stream, which will be a return value of this method.
As Herman pointed out, you can get the index and element from each iteration.
{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}
Working example:
package main
import (
"html/template"
"os"
)
type EntetiesClass struct {
Name string
Value int32
}
// In the template, we use rangeStruct to turn our struct values
// into a slice we can iterate over
var htmlTemplate = `{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}`
func main() {
data := map[string][]EntetiesClass{
"Yoga": {{"Yoga", 15}, {"Yoga", 51}},
"Pilates": {{"Pilates", 3}, {"Pilates", 6}, {"Pilates", 9}},
}
t := template.New("t")
t, err := t.Parse(htmlTemplate)
if err != nil {
panic(err)
}
err = t.Execute(os.Stdout, data)
if err != nil {
panic(err)
}
}
Output:
Pilates
3
6
9
Yoga
15
51
Playground: http://play.golang.org/p/4ISxcFKG7v
For the sake of defensive programming, objects should be checked against nullity before using.
if obj is None:
or
if obj is not None:
In file /etc/ssh/sshd_config
# Change to no to disable tunnelled clear text passwords
#PasswordAuthentication no
Uncomment the second line, and, if needed, change yes to no.
Then run
service ssh restart
What about WORDPRESS + MULTI-LANGUAGE SITE BASIS
(plugin) ?
the site will have structure:
The plugin provides Interface for Translation all phrases, with simple logic:
(ENG) my_title - "Hello user"
(SPA) my_title - "Holla usuario"
then it can be outputed:
echo translate('my_title', LNG); // LNG is auto-detected
p.s. however, check, if the plugin is still active.
To throw another potential solution into the mix, I had a settings
folder as well as a settings.py
in my project dir. (I was switching back from environment-based settings files to one file. I have since reconsidered.)
Python was getting confused about whether I wanted to import project/settings.py
or project/settings/__init__.py
. I removed the settings
dir and everything now works fine.
This is all you need, no wrapper needed:
.login-icon{
display:inline-block;
font-size: 40px;
line-height: 50px;
background-color:black;
color:white;
width: 50px;
height: 50px;
text-align: center;
vertical-align: bottom;
}
Arrays.asList()
this method returns its own implementation of List.It takes an array as an argument and builds methods and attributes on top of it, since it is not copying any data from an array but using the original array this causes alteration in original array when you modify list returned by the Arrays.asList()
method.
on the other hand.
ArrayList(Arrays.asList());
is a constructor of ArrayList
class which takes a list as argument and returns an ArrayList
that is independent of list ie. Arrays.asList()
in this case passed as an argument.
that is why you see these results;
Where did it come from scrollBottom
this is not a valid property it should be scrollTop
and this can be positive(+
) or negative(-
) values to scroll down(+
) and up(-
), so you can change:
scrollBottom
to this scrollTop
:
$("#upClick").on("click", function () {
scrolled = scrolled - 300;
$(".cover").animate({
scrollTop: scrolled
});//^^^^^^^^------------------------------this one
});
Firstly this is a very good question.
e.g. The authorization header or content type header. Which is absolutely required by the server to understand the request. This can differ from server to server.
This is less severe than 400. The request has reached the server. The server has acknowledged the request has got the basic structure right. But the information in the request body can't be parsed or understood.
e.g. Content-Type: application/xml
when request body is JSON.
Here's an article listing status codes and its use in REST APIs. https://metamug.com/article/status-codes-for-rest-api.php
We use the Url Rewrite extension for IIS for redirecting all HTTP requests to HTTPS. When trying to call a service not using transport security on an http://... address, this is the error that appeared.
So it might be worth checking if you can hit both the http and https addresses of the service via a browser and that it doesn't auto forward you with a 303 status code.
You should avoid using nested selects and I would go as far to say you should never use them in the actual select part of your statement. You will be running that select for each row that is returned. This is a really expensive operation. Rather use joins. It is much more readable and the performance is much better.
In your case the query below should help. Note the cases statement is still there, but now it is a simple compare operation.
select
p.product_id,
p.type_id,
p.product_name,
p.type,
case p.type_id when 10 then (CONCAT_WS(' ' , first_name, middle_name, last_name )) else (null) end artistC
from
Product p
inner join Product_Type pt on
pt.type_id = p.type_id
left join Product_ArtistAuthor paa on
paa.artist_id = p.artist_id
where
p.product_id = $pid
I used a left join since I don't know the business logic.
The second div is position: static
(the default) so the z-index does not apply to it.
You need to position (set the position property to anything other than static
, you probably want relative
in this case) anything you want to give a z-index
to.
To mark a lambda async, simply prepend async
before its argument list:
// Add a command to delete the current Group
contextMenu.Commands.Add(new UICommand("Delete this Group", async (contextMenuCmd) =>
{
SQLiteUtils slu = new SQLiteUtils();
await slu.DeleteGroupAsync(groupName);
}));
Adding a StreamHandler without arguments goes to stderr instead of stdout. If some other process has a dependency on the stdout dump (i.e. when writing an NRPE plugin), then make sure to specify stdout explicitly or you might run into some unexpected troubles.
Here's a quick example reusing the assumed values and LOGFILE from the question:
import logging
from logging.handlers import RotatingFileHandler
from logging import handlers
import sys
log = logging.getLogger('')
log.setLevel(logging.DEBUG)
format = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
ch = logging.StreamHandler(sys.stdout)
ch.setFormatter(format)
log.addHandler(ch)
fh = handlers.RotatingFileHandler(LOGFILE, maxBytes=(1048576*5), backupCount=7)
fh.setFormatter(format)
log.addHandler(fh)
If you are trying to capitalize the first letter of each word in an array you can simply put this:
array_name.map(&:capitalize)
I dont know about XamGrid
but that's what i'll do with a standard wpf DataGrid
:
<DataGrid>
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Since the TextBlock
and the TextBox
specified in the cell templates will be part of the visual tree, you can walk up and find whatever control you need.
Please check that you have registered all HTTP endpoints in the local mahcine's Access Control List (ACL)
http://just2thepoint.blogspot.fr/2013/10/windows-service-on-local-computer.html
Another form that works with Postgres 9.1+ is combining a Common Table Expression with the USING statement for the join.
WITH prod AS (select m_product_id, upc from m_product where upc='7094')
DELETE FROM m_productprice B
USING prod C
WHERE B.m_product_id = C.m_product_id
AND B.m_pricelist_version_id = '1000020';
Using get and set methods within a service you can passing messages between controllers very easily.
var myApp = angular.module("myApp",[]);
myApp.factory('myFactoryService',function(){
var data="";
return{
setData:function(str){
data = str;
},
getData:function(){
return data;
}
}
})
myApp.controller('FirstController',function($scope,myFactoryService){
myFactoryService.setData("Im am set in first controller");
});
myApp.controller('SecondController',function($scope,myFactoryService){
$scope.rslt = myFactoryService.getData();
});
in HTML HTML you can check like this
<div ng-controller='FirstController'>
</div>
<div ng-controller='SecondController'>
{{rslt}}
</div>
I had a similar problem getting scrollTop to work after reload of div content. The content scrolled to top each time the procedure below was run. I found that a little delay before setting the new scrolltop solved the issue.
This is cut from wdCalendar where I modified this procedure:
function BuildDaysAndWeekView(startday, l, events, config)
....
var scrollpos = $("#dvtec").scrollTop();
gridcontainer.html(html.join(""));
setTimeout(function() {
$("#dvtec").scrollTop(scrollpos);
}, 25);
....
Without the delay, it simply did not work.
And with Prototype:
$('yourDivId').setStyle({top: '100px', left:'80px'});
If you want to keep the GNU compiler extensions, use -std=gnu++0x rather than -std=c++0x. Here's a quote from the man page:
The compiler can accept several base standards, such as c89 or c++98, and GNU dialects of those standards, such as gnu89 or gnu++98. By specifying a base standard, the compiler will accept all programs following that standard and those using GNU extensions that do not contradict it. For example, -std=c89 turns off certain features of GCC that are incompatible with ISO C90, such as the "asm" and "typeof" keywords, but not other GNU extensions that do not have a meaning in ISO C90, such as omitting the middle term of a "?:" expression. On the other hand, by specifying a GNU dialect of a standard, all features the compiler support are enabled, even when those features change the meaning of the base standard and some strict-conforming programs may be rejected. The particular standard is used by -pedantic to identify which features are GNU extensions given that version of the standard. For example-std=gnu89 -pedantic would warn about C++ style // comments, while -std=gnu99 -pedantic would not.
I found this question while looking for a way to have fine grained flow control to break from a specific block of code. The solution I settled on wasn't mentioned...
From: about_break
A Break statement can include a label that lets you exit embedded loops. A label can specify any loop keyword, such as Foreach, For, or While, in a script.
Here's a simple example
:myLabel for($i = 1; $i -le 2; $i++) {
Write-Host "Iteration: $i"
break myLabel
}
Write-Host "After for loop"
# Results:
# Iteration: 1
# After for loop
And then a more complicated example that shows the results with nested labels and breaking each one.
:outerLabel for($outer = 1; $outer -le 2; $outer++) {
:innerLabel for($inner = 1; $inner -le 2; $inner++) {
Write-Host "Outer: $outer / Inner: $inner"
#break innerLabel
#break outerLabel
}
Write-Host "After Inner Loop"
}
Write-Host "After Outer Loop"
# Both breaks commented out
# Outer: 1 / Inner: 1
# Outer: 1 / Inner: 2
# After Inner Loop
# Outer: 2 / Inner: 1
# Outer: 2 / Inner: 2
# After Inner Loop
# After Outer Loop
# break innerLabel Results
# Outer: 1 / Inner: 1
# After Inner Loop
# Outer: 2 / Inner: 1
# After Inner Loop
# After Outer Loop
# break outerLabel Results
# Outer: 1 / Inner: 1
# After Outer Loop
You can also adapt it to work in other situations by wrapping blocks of code in loops that will only execute once.
:myLabel do {
1..2 | % {
Write-Host "Iteration: $_"
break myLabel
}
} while ($false)
Write-Host "After do while loop"
# Results:
# Iteration: 1
# After do while loop
Adding to C2H5OH's answer, in Python 3.6+ you can use format strings to make it a bit cleaner:
s = "something about cupcakes"
print(f"L{s}LL")
Thanks for enlightening us Cypawer.
I also tried this app https://play.google.com/store/apps/details?id=com.oneguyinabasement.leapwifi
and it worked flawlessly.
The previous answers are great, but nobody said how to exclude a single field from being validated for HTML/JavaScript injections. I don't know about previous versions, but in MVC3 Beta you can do this:
[HttpPost, ValidateInput(true, Exclude = "YourFieldName")]
public virtual ActionResult Edit(int id, FormCollection collection)
{
...
}
This still validates all the fields except for the excluded one. The nice thing about this is that your validation attributes still validate the field, but you just don't get the "A potentially dangerous Request.Form value was detected from the client" exceptions.
I've used this for validating a regular expression. I've made my own ValidationAttribute to see if the regular expression is valid or not. As regular expressions can contain something that looks like a script I applied the above code - the regular expression is still being checked if it's valid or not, but not if it contains scripts or HTML.
Based on other answers, there are basically two approaches: subclassing HashMap
or wrapping String
. The first one requires a little more work. In fact, if you want to do it correctly, you must override almost all methods (containsKey, entrySet, get, put, putAll and remove
).
Anyway, it has a problem. If you want to avoid future problems, you must specify a Locale
in String
case operations. So you would create new methods (get(String, Locale)
, ...). Everything is easier and clearer wrapping String:
public final class CaseInsensitiveString {
private final String s;
public CaseInsensitiveString(String s, Locale locale) {
this.s = s.toUpperCase(locale);
}
// equals, hashCode & toString, no need for memoizing hashCode
}
And well, about your worries on performance: premature optimization is the root of all evil :)
I tried what Samuel Slade has suggested. Didn't work for me. The PropertyInfo
list was coming as empty. So, I tried the following and it worked for me.
Type type = typeof(Record);
FieldInfo[] properties = type.GetFields();
foreach (FieldInfo property in properties) {
Debug.LogError(property.Name);
}
The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct
approach is executed like:
business_key
values to a temporary tableThe group by
could be executed like:
business key
in a hashtableThe first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.
Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.
Gwerder's solution wont work because hash = hmac.read();
happens before the stream is done being finalized. Thus AngraX's issues. Also the hmac.write
statement is un-necessary in this example.
Instead do this:
var crypto = require('crypto');
var hmac;
var algorithm = 'sha1';
var key = 'abcdeg';
var text = 'I love cupcakes';
var hash;
hmac = crypto.createHmac(algorithm, key);
// readout format:
hmac.setEncoding('hex');
//or also commonly: hmac.setEncoding('base64');
// callback is attached as listener to stream's finish event:
hmac.end(text, function () {
hash = hmac.read();
//...do something with the hash...
});
More formally, if you wish, the line
hmac.end(text, function () {
could be written
hmac.end(text, 'utf8', function () {
because in this example text is a utf string
matcher.find()
does not find all matches, only the next match.
long matches = matcher.results().count();
You'll have to do the following. (Starting from Java 9, there is a nicer solution)
int count = 0;
while (matcher.find())
count++;
Btw, matcher.groupCount()
is something completely different.
Complete example:
import java.util.regex.*;
class Test {
public static void main(String[] args) {
String hello = "HelloxxxHelloxxxHello";
Pattern pattern = Pattern.compile("Hello");
Matcher matcher = pattern.matcher(hello);
int count = 0;
while (matcher.find())
count++;
System.out.println(count); // prints 3
}
}
When counting matches of aa
in aaaa
the above snippet will give you 2.
aaaa
aa
aa
To get 3 matches, i.e. this behavior:
aaaa
aa
aa
aa
You have to search for a match at index <start of last match> + 1
as follows:
String hello = "aaaa";
Pattern pattern = Pattern.compile("aa");
Matcher matcher = pattern.matcher(hello);
int count = 0;
int i = 0;
while (matcher.find(i)) {
count++;
i = matcher.start() + 1;
}
System.out.println(count); // prints 3
Make sure that Spring version and xsd version both are same.In my case I am using Spring 4.1.1 so my all xsd should be version *-4.1.xsd
If I am reading your question right - the code that wants the synchronous call to an async method is executing on a suspended dispatcher thread. And you want to actually synchronously block that thread until the async method is completed.
Async methods in C# 5 are powered by effectively chopping the method into pieces under the hood, and returning a Task
that can track the overall completion of the whole shabang. However, how the chopped up methods execute can depend on the type of the expression passed to the await
operator.
Most of the time, you'll be using await
on an expression of type Task
. Task's implementation of the await
pattern is "smart" in that it defers to the SynchronizationContext
, which basically causes the following to happen:
await
is on a Dispatcher or WinForms message loop thread, it ensures that the chunks of the async method occurs as part of the processing of the message queue.await
is on a thread pool thread, then the remaining chunks of the async method occur anywhere on the thread pool.That's why you're probably running into problems - the async method implementation is trying to run the rest on the Dispatcher - even though it's suspended.
.... backing up! ....
I have to ask the question, why are you trying to synchronously block on an async method? Doing so would defeat the purpose on why the method wanted to be called asynchronously. In general, when you start using await
on a Dispatcher or UI method, you will want to turn your entire UI flow async. For example, if your callstack was something like the following:
WebRequest.GetResponse()
YourCode.HelperMethod()
YourCode.AnotherMethod()
YourCode.EventHandlerMethod()
[UI Code].Plumbing()
- WPF
or WinForms
CodeWPF
or WinForms
Message LoopThen once the code has been transformed to use async, you'll typically end up with
WebRequest.GetResponseAsync()
YourCode.HelperMethodAsync()
YourCode.AnotherMethodAsync()
YourCode.EventHandlerMethodAsync()
[UI Code].Plumbing()
- WPF
or WinForms
CodeWPF
or WinForms
Message LoopActually Answering
The AsyncHelpers class above actually works because it behaves like a nested message loop, but it installs its own parallel mechanic to the Dispatcher rather than trying to execute on the Dispatcher itself. That's one workaround for your problem.
Another workaround is to execute your async method on a threadpool thread, and then wait for it to complete. Doing so is easy - you can do it with the following snippet:
var customerList = TaskEx.RunEx(GetCustomers).Result;
The final API will be Task.Run(...), but with the CTP you'll need the Ex suffixes (explanation here).
sample code below
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet sheet = wb.createSheet("your sheet name");
HSSFRow row = sheet.createRow(0);
cell = row.createCell(0);
cell.setCellValue("A BIG NAME WITH AUTO SIZE FEATURE ENABLED");
//this is crucial
sheet.autoSizeColumn(0);
//argument must be cell number
cell = row.createCell(1);
cell.setCellValue("a big name without auto size feature enabled");
Check the output and go nuts :)
var elem = document.getElementById("myvideo");
function openFullscreen() {
if (elem.requestFullscreen) {
elem.requestFullscreen();
} else if (elem.mozRequestFullScreen) { /* Firefox */
elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) { /* Chrome, Safari & Opera */
elem.webkitRequestFullscreen();
} else if (elem.msRequestFullscreen) { /* IE/Edge */
elem.msRequestFullscreen();
}
}
//Internet Explorer 10 and earlier does not support the msRequestFullscreen() method.
In the Hibernate mapping file for the id
property, if you use any generator class, for that property you should not set the value explicitly by using a setter method.
If you set the value of the Id property explicitly, it will lead the error above. Check this to avoid this error.
It depends on which Ruby version you use:
Ruby 2.4 and higher:
It just works, as since Ruby v2.4.0 supports Unicode case mapping:
"?????".capitalize #=> ?????
Ruby 2.3 and lower:
"maria".capitalize #=> "Maria"
"?????".capitalize #=> ?????
The problem is, it just doesn't do what you want it to, it outputs ?????
instead of ?????
.
If you're using Rails there's an easy workaround:
"?????".mb_chars.capitalize.to_s # requires ActiveSupport::Multibyte
Otherwise, you'll have to install the unicode gem and use it like this:
require 'unicode'
Unicode::capitalize("?????") #=> ?????
Ruby 1.8:
Be sure to use the coding magic comment:
#!/usr/bin/env ruby
puts "?????".capitalize
gives invalid multibyte char (US-ASCII)
, while:
#!/usr/bin/env ruby
#coding: utf-8
puts "?????".capitalize
works without errors, but also see the "Ruby 2.3 and lower" section for real capitalization.
After decoding, it looks like the data is a repeating structure that's 8 bytes long, or some multiple thereof. It's just binary data though; what it might mean, I have no idea. There are 2064 entries, which means that it could be a list of 2064 8-byte items down to 129 128-byte items.
onchange
only fires when the user types into the input and then the input loses focus.
You can manually call the onchange
event using after setting the value:
$("#mytext").change(); // someObject.onchange(); in standard JS
Alternatively, you can trigger the event using:
$("#mytext").trigger("change");
You need to do something like this:
// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");
// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");
// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
// grab the "id" attribute
XmlAttribute idAttribute = aNode.Attributes["id"];
// check if that attribute even exists...
if (idAttribute != null)
{
// if yes - read its current value
string currentValue = idAttribute.Value;
// here, you can now decide what to do - for demo purposes,
// I just set the ID value to a fixed value if it was empty before
if (string.IsNullOrEmpty(currentValue))
{
idAttribute.Value = "515";
}
}
}
// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");
A common misunderstanding among starters is that they think that the call of a forward()
, sendRedirect()
, or sendError()
would magically exit and "jump" out of the method block, hereby ignoring the remnant of the code. For example:
protected void doXxx() {
if (someCondition) {
sendRedirect();
}
forward(); // This is STILL invoked when someCondition is true!
}
This is thus actually not true. They do certainly not behave differently than any other Java methods (expect of System#exit()
of course). When the someCondition
in above example is true
and you're thus calling forward()
after sendRedirect()
or sendError()
on the same request/response, then the chance is big that you will get the exception:
java.lang.IllegalStateException: Cannot forward after response has been committed
If the if
statement calls a forward()
and you're afterwards calling sendRedirect()
or sendError()
, then below exception will be thrown:
java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed
To fix this, you need either to add a return;
statement afterwards
protected void doXxx() {
if (someCondition) {
sendRedirect();
return;
}
forward();
}
... or to introduce an else block.
protected void doXxx() {
if (someCondition) {
sendRedirect();
} else {
forward();
}
}
To naildown the root cause in your code, just search for any line which calls a forward()
, sendRedirect()
or sendError()
without exiting the method block or skipping the remnant of the code. This can be inside the same servlet before the particular code line, but also in any servlet or filter which was been called before the particular servlet.
In case of sendError()
, if your sole purpose is to set the response status, use setStatus()
instead.
Another probable cause is that the servlet writes to the response while a forward()
will be called, or has been called in the very same method.
protected void doXxx() {
out.write("some string");
// ...
forward(); // Fail!
}
The response buffer size defaults in most server to 2KB, so if you write more than 2KB to it, then it will be committed and forward()
will fail the same way:
java.lang.IllegalStateException: Cannot forward after response has been committed
Solution is obvious, just don't write to the response in the servlet. That's the responsibility of the JSP. You just set a request attribute like so request.setAttribute("data", "some string")
and then print it in JSP like so ${data}
. See also our Servlets wiki page to learn how to use Servlets the right way.
Another probable cause is that the servlet writes a file download to the response after which e.g. a forward()
is called.
protected void doXxx() {
out.write(bytes);
// ...
forward(); // Fail!
}
This is technically not possible. You need to remove the forward()
call. The enduser will stay on the currently opened page. If you actually intend to change the page after a file download, then you need to move the file download logic to page load of the target page.
Yet another probable cause is that the forward()
, sendRedirect()
or sendError()
methods are invoked via Java code embedded in a JSP file in form of old fashioned way <% scriptlets %>
, a practice which was officially discouraged since 2001. For example:
<!DOCTYPE html>
<html lang="en">
<head>
...
</head>
<body>
...
<% sendRedirect(); %>
...
</body>
</html>
The problem here is that JSP internally immediately writes template text (i.e. HTML code) via out.write("<!DOCTYPE html> ... etc ...")
as soon as it's encountered. This is thus essentially the same problem as explained in previous section.
Solution is obvious, just don't write Java code in a JSP file. That's the responsibility of a normal Java class such as a Servlet or a Filter. See also our Servlets wiki page to learn how to use Servlets the right way.
Unrelated to your concrete problem, your JDBC code is leaking resources. Fix that as well. For hints, see also How often should Connection, Statement and ResultSet be closed in JDBC?
You should only need to unbind the service in onDestroy()
. Then, The warning will go.
See here.
As the Activity doc tries to explain, there are three main bind/unbind groupings you will use: onCreate() and onDestroy(), onStart() and onStop(), and onResume() and onPause().
Upcasting (using (Employee)someInstance
) is generally easy as the compiler can tell you at compile time if a type is derived from another.
Downcasting however has to be done at run time generally as the compiler may not always know whether the instance in question is of the type given. C# provides two operators for this - is which tells you if the downcast works, and return true/false. And as which attempts to do the cast and returns the correct type if possible, or null if not.
To test if an employee is a manager:
Employee m = new Manager();
Employee e = new Employee();
if(m is Manager) Console.WriteLine("m is a manager");
if(e is Manager) Console.WriteLine("e is a manager");
You can also use this
Employee someEmployee = e as Manager;
if(someEmployee != null) Console.WriteLine("someEmployee (e) is a manager");
Employee someEmployee = m as Manager;
if(someEmployee != null) Console.WriteLine("someEmployee (m) is a manager");
You can do this by using below code
<HorizontalScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="wrap_content"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
</LinearLayout>
</ScrollView>
</HorizontalScrollView>
@dfa answer is great, so I took it a step farther to make it possible to test blocks of ouput.
First I created TestHelper
with a method captureOutput
that accepts the annoymous class CaptureTest
. The captureOutput method does the work of setting and tearing down the output streams. When the implementation of CaptureOutput
's test
method is called, it has access to the output generate for the test block.
Source for TestHelper:
public class TestHelper {
public static void captureOutput( CaptureTest test ) throws Exception {
ByteArrayOutputStream outContent = new ByteArrayOutputStream();
ByteArrayOutputStream errContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
test.test( outContent, errContent );
System.setOut(new PrintStream(new FileOutputStream(FileDescriptor.out)));
System.setErr(new PrintStream(new FileOutputStream(FileDescriptor.out)));
}
}
abstract class CaptureTest {
public abstract void test( ByteArrayOutputStream outContent, ByteArrayOutputStream errContent ) throws Exception;
}
Note that TestHelper and CaptureTest are defined in the same file.
Then in your test, you can import the static captureOutput. Here is an example using JUnit:
// imports for junit
import static package.to.TestHelper.*;
public class SimpleTest {
@Test
public void testOutput() throws Exception {
captureOutput( new CaptureTest() {
@Override
public void test(ByteArrayOutputStream outContent, ByteArrayOutputStream errContent) throws Exception {
// code that writes to System.out
assertEquals( "the expected output\n", outContent.toString() );
}
});
}
If you aren't worried about squeaking every single last bit of performance the suggestion to use a HashSet or binary search is solid. Your datasets just aren't large enough that this is going to be a problem 99% of the time.
But if this just one of thousands of times you are going to do this and performance is critical (and proven to be unacceptable using HashSet/binary search), you could certainly write your own algorithm that walked the sorted lists doing comparisons as you went. Each list would be walked at most once and in the pathological cases wouldn't be bad (once you went this route you'd probably find that the comparison, assuming it's a string or other non-integral value, would be the real expense and that optimizing that would be the next step).
Yes you can check below is the code:
public boolean isGPSEnabled (Context mContext){
LocationManager locationManager = (LocationManager)
mContext.getSystemService(Context.LOCATION_SERVICE);
return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
}
If you know that the values are strings, you can call the replace method on them while in the cycle: this way you will change the value.
Altohugh this is limited to the case in which the values are strings and hence doesn't answer the question fully, I thought it can be useful to someone.
We can all see that the code you provided won't work at run time. That's because we know that the expression new A()
can never be an object of type B
.
But that's not how the compiler sees it. By the time the compiler is checking whether the cast is allowed, it just sees this:
variable_of_type_B = (B)expression_of_type_A;
And as others have demonstrated, that sort of cast is perfectly legal. The expression on the right could very well evaluate to an object of type B
. The compiler sees that A
and B
have a subtype relation, so with the "expression" view of the code, the cast might work.
The compiler does not consider the special case when it knows exactly what object type expression_of_type_A
will really have. It just sees the static type as A
and considers the dynamic type could be A
or any descendant of A
, including B
.
For the most part, ApplicationContext is preferred unless you need to save resources, like on a mobile application.
I'm not sure about depending on XML format, but I'm pretty sure the most common implementations of ApplicationContext are the XML ones such as ClassPathXmlApplicationContext, XmlWebApplicationContext, and FileSystemXmlApplicationContext. Those are the only three I've ever used.
If your developing a web app, it's safe to say you'll need to use XmlWebApplicationContext.
If you want your beans to be aware of Spring, you can have them implement BeanFactoryAware and/or ApplicationContextAware for that, so you can use either BeanFactory or ApplicationContext and choose which interface to implement.
Is this what you mean?
SELECT DISTINCT C.valueC
FROM
C
INNER JOIN B ON C.id = B.lookupC
INNER JOIN A ON B.id = A.lookupB
Aspx
<ajax:ModalPopupExtender runat="server" ID="modalPop"
PopupControlID="pnlpopup"
TargetControlID="btnGo"
BackgroundCssClass="modalBackground"
DropShadow="true"
CancelControlID="btnCancel" X="470" Y="300" />
//Codebehind
protected void OkButton_Clicked(object sender, EventArgs e)
{
modalPop.Hide();
//Do something in codebehind
}
And don't set the OK button as OkControlID.
An other very good documentation tool is sphinx. It will be used for the upcoming python 2.6 documentation and is used by django and a lot of other python projects.
From the sphinx website:
Use:
using System.Linq.Enumerable;
...
List<KeyValuePair<string, string>> myList = aDictionary.ToList();
myList.Sort(
delegate(KeyValuePair<string, string> pair1,
KeyValuePair<string, string> pair2)
{
return pair1.Value.CompareTo(pair2.Value);
}
);
Since you're targeting .NET 2.0 or above, you can simplify this into lambda syntax -- it's equivalent, but shorter. If you're targeting .NET 2.0 you can only use this syntax if you're using the compiler from Visual Studio 2008 (or above).
var myList = aDictionary.ToList();
myList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value));
I think these kinds of problems are solved if we think about real life.
Bad Practice:
Example 1:
Darling everything is FINE/OK (HTTP CODE 200) - (Success):
{
...but I don't want us to be together anymore!!!... (Error)
// Then everything isn't OK???
}
Example 2:
You are the best employee (HTTP CODE 200) - (Success):
{
...But we cannot continue your contract!!!... (Error)
// Then everything isn't OK???
}
Good Practices:
Darling I don't feel good (HTTP CODE 400) - (Error):
{
...I no longer feel anything for you, I think the best thing is to separate... (Error)
// In this case, you are alerting me from the beginning that something is wrong ...
}
This is only my personal opinion, each one can implement it as it is most comfortable or needs.
Note: The idea for this explanation was drawn from a great friend @diosney
$('img.conversation_img[alt="example"]')
.each(function(){
alert($(this).attr('src'))
});
This will display src attributes of all images of class 'conversation_img' with alt='example'
DPB
DPB
to DPx
Check http://blog.getspool.com/396/best-vba-password-recovery-cracker-tool-remove/
On the terminal, type:
$ sudo bash
Then write as many commands as you want. Type exit
when you done.
If you need to automate it, create a script.sh
file and run it:
$ sudo ./script.sh
No jQuery is necessary in this situation.
window.opener.location.reload(false);
You have multiple columns named the same thing in your inner query, so the error is raised in the outer query. If you get rid of the outer query, it should run, although still be confusing:
SELECT DISTINCT
coaches.id,
people.*,
users.*,
coaches.*
FROM "COACHES"
INNER JOIN people ON people.id = coaches.person_id
INNER JOIN users ON coaches.person_id = users.person_id
LEFT OUTER JOIN organizations_users ON organizations_users.user_id = users.id
WHERE
rownum <= 25
It would be much better (for readability and performance both) to specify exactly what fields you need from each of the tables instead of selecting them all anyways. Then if you really need two fields called the same thing from different tables, use column aliases to differentiate between them.
Instance variable on a class:
class Parent
@things = []
def self.things
@things
end
def things
self.class.things
end
end
class Child < Parent
@things = []
end
Parent.things << :car
Child.things << :doll
mom = Parent.new
dad = Parent.new
p Parent.things #=> [:car]
p Child.things #=> [:doll]
p mom.things #=> [:car]
p dad.things #=> [:car]
Class variable:
class Parent
@@things = []
def self.things
@@things
end
def things
@@things
end
end
class Child < Parent
end
Parent.things << :car
Child.things << :doll
p Parent.things #=> [:car,:doll]
p Child.things #=> [:car,:doll]
mom = Parent.new
dad = Parent.new
son1 = Child.new
son2 = Child.new
daughter = Child.new
[ mom, dad, son1, son2, daughter ].each{ |person| p person.things }
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]
#=> [:car, :doll]
With an instance variable on a class (not on an instance of that class) you can store something common to that class without having sub-classes automatically also get them (and vice-versa). With class variables, you have the convenience of not having to write self.class
from an instance object, and (when desirable) you also get automatic sharing throughout the class hierarchy.
Merging these together into a single example that also covers instance variables on instances:
class Parent
@@family_things = [] # Shared between class and subclasses
@shared_things = [] # Specific to this class
def self.family_things
@@family_things
end
def self.shared_things
@shared_things
end
attr_accessor :my_things
def initialize
@my_things = [] # Just for me
end
def family_things
self.class.family_things
end
def shared_things
self.class.shared_things
end
end
class Child < Parent
@shared_things = []
end
And then in action:
mama = Parent.new
papa = Parent.new
joey = Child.new
suzy = Child.new
Parent.family_things << :house
papa.family_things << :vacuum
mama.shared_things << :car
papa.shared_things << :blender
papa.my_things << :quadcopter
joey.my_things << :bike
suzy.my_things << :doll
joey.shared_things << :puzzle
suzy.shared_things << :blocks
p Parent.family_things #=> [:house, :vacuum]
p Child.family_things #=> [:house, :vacuum]
p papa.family_things #=> [:house, :vacuum]
p mama.family_things #=> [:house, :vacuum]
p joey.family_things #=> [:house, :vacuum]
p suzy.family_things #=> [:house, :vacuum]
p Parent.shared_things #=> [:car, :blender]
p papa.shared_things #=> [:car, :blender]
p mama.shared_things #=> [:car, :blender]
p Child.shared_things #=> [:puzzle, :blocks]
p joey.shared_things #=> [:puzzle, :blocks]
p suzy.shared_things #=> [:puzzle, :blocks]
p papa.my_things #=> [:quadcopter]
p mama.my_things #=> []
p joey.my_things #=> [:bike]
p suzy.my_things #=> [:doll]
Both approaches behave differently if you use a spied object (annotated with @Spy
) instead of a mock (annotated with @Mock
):
when(...) thenReturn(...)
makes a real method call just before the specified value will be returned. So if the called method throws an Exception you have to deal with it / mock it etc. Of course you still get your result (what you define in thenReturn(...)
)
doReturn(...) when(...)
does not call the method at all.
Example:
public class MyClass {
protected String methodToBeTested() {
return anotherMethodInClass();
}
protected String anotherMethodInClass() {
throw new NullPointerException();
}
}
Test:
@Spy
private MyClass myClass;
// ...
// would work fine
doReturn("test").when(myClass).anotherMethodInClass();
// would throw a NullPointerException
when(myClass.anotherMethodInClass()).thenReturn("test");
When Card I always use RoundedRectangleBorder.
Card(
color: Colors.grey[900],
shape: RoundedRectangleBorder(
side: BorderSide(color: Colors.white70, width: 1),
borderRadius: BorderRadius.circular(10),
),
margin: EdgeInsets.all(20.0),
child: Container(
child: Column(
children: <Widget>[
ListTile(
title: Text(
'example',
style: TextStyle(fontSize: 18, color: Colors.white),
),
),
],
),
),
),
What I believe you're looking for is a way to work with arrays as object values:
var o = {} // empty Object
var key = 'Orientation Sensor';
o[key] = []; // empty Array, which you can push() values into
var data = {
sampleTime: '1450632410296',
data: '76.36731:3.4651554:0.5665419'
};
var data2 = {
sampleTime: '1450632410296',
data: '78.15431:0.5247617:-0.20050584'
};
o[key].push(data);
o[key].push(data2);
This is standard JavaScript and not something NodeJS specific. In order to serialize it to a JSON string you can use the native JSON.stringify
:
JSON.stringify(o);
//> '{"Orientation Sensor":[{"sampleTime":"1450632410296","data":"76.36731:3.4651554:0.5665419"},{"sampleTime":"1450632410296","data":"78.15431:0.5247617:-0.20050584"}]}'
for me , in sql server 2016, I do it like this
*To rename column Column1 to column2
EXEC sp_rename 'dbo.T_Table1.Column1', 'Column2', 'COLUMN'
*To modify column Type from string to int:( Please be sure that data are in the correct format)
ALTER TABLE dbo.T_Table1 ALTER COLUMN Column2 int;
I think this is a simple code in java which will show the string value in CSV after compile this code.
public class CsvWriter {
public static void main(String args[]) {
// File input path
System.out.println("Starting....");
File file = new File("/home/Desktop/test/output.csv");
try {
FileWriter output = new FileWriter(file);
CSVWriter write = new CSVWriter(output);
// Header column value
String[] header = { "ID", "Name", "Address", "Phone Number" };
write.writeNext(header);
// Value
String[] data1 = { "1", "First Name", "Address1", "12345" };
write.writeNext(data1);
String[] data2 = { "2", "Second Name", "Address2", "123456" };
write.writeNext(data2);
String[] data3 = { "3", "Third Name", "Address3", "1234567" };
write.writeNext(data3);
write.close();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
System.out.println("End.");
}
}
The two functions you need are documented here:
In short:
// Load images in the C++ format
cv::Mat img = cv::imread("something.jpg");
cv::Mat src = cv::imread("src.jpg");
// Resize src so that is has the same size as img
cv::resize(src, src, img.size());
And please, please, stop using the old and completely deprecated IplImage* classes
PostgreSQL allows partial indexes, where only rows that match a predicate are indexed. For instance, you might want to index the customer table for only those records which are active. This might look something like:
create index i on customers (id, name, whatever) where is_active is true;
If your index many columns, and you have many inactive customers, this can be a big win in terms of space (the index will be stored in fewer disk pages) and thus performance. To hit the index you need to, at a minimum, specify the predicate:
select name from customers where is_active is true;
In a language implementing classical inheritance like Java, C# or C++ you start by creating a class--a blueprint for your objects--and then you can create new objects from that class or you can extend the class, defining a new class that augments the original class.
In JavaScript you first create an object (there is no concept of class), then you can augment your own object or create new objects from it. It's not difficult, but a little foreign and hard to metabolize for somebody used to the classical way.
Example:
//Define a functional object to hold persons in JavaScript_x000D_
var Person = function(name) {_x000D_
this.name = name;_x000D_
};_x000D_
_x000D_
//Add dynamically to the already defined object a new getter_x000D_
Person.prototype.getName = function() {_x000D_
return this.name;_x000D_
};_x000D_
_x000D_
//Create a new object of type Person_x000D_
var john = new Person("John");_x000D_
_x000D_
//Try the getter_x000D_
alert(john.getName());_x000D_
_x000D_
//If now I modify person, also John gets the updates_x000D_
Person.prototype.sayMyName = function() {_x000D_
alert('Hello, my name is ' + this.getName());_x000D_
};_x000D_
_x000D_
//Call the new method on john_x000D_
john.sayMyName();
_x000D_
Until now I've been extending the base object, now I create another object and then inheriting from Person.
//Create a new object of type Customer by defining its constructor. It's not
//related to Person for now.
var Customer = function(name) {
this.name = name;
};
//Now I link the objects and to do so, we link the prototype of Customer to
//a new instance of Person. The prototype is the base that will be used to
//construct all new instances and also, will modify dynamically all already
//constructed objects because in JavaScript objects retain a pointer to the
//prototype
Customer.prototype = new Person();
//Now I can call the methods of Person on the Customer, let's try, first
//I need to create a Customer.
var myCustomer = new Customer('Dream Inc.');
myCustomer.sayMyName();
//If I add new methods to Person, they will be added to Customer, but if I
//add new methods to Customer they won't be added to Person. Example:
Customer.prototype.setAmountDue = function(amountDue) {
this.amountDue = amountDue;
};
Customer.prototype.getAmountDue = function() {
return this.amountDue;
};
//Let's try:
myCustomer.setAmountDue(2000);
alert(myCustomer.getAmountDue());
var Person = function (name) {_x000D_
this.name = name;_x000D_
};_x000D_
Person.prototype.getName = function () {_x000D_
return this.name;_x000D_
};_x000D_
var john = new Person("John");_x000D_
alert(john.getName());_x000D_
Person.prototype.sayMyName = function () {_x000D_
alert('Hello, my name is ' + this.getName());_x000D_
};_x000D_
john.sayMyName();_x000D_
var Customer = function (name) {_x000D_
this.name = name;_x000D_
};_x000D_
Customer.prototype = new Person();_x000D_
_x000D_
var myCustomer = new Customer('Dream Inc.');_x000D_
myCustomer.sayMyName();_x000D_
Customer.prototype.setAmountDue = function (amountDue) {_x000D_
this.amountDue = amountDue;_x000D_
};_x000D_
Customer.prototype.getAmountDue = function () {_x000D_
return this.amountDue;_x000D_
};_x000D_
myCustomer.setAmountDue(2000);_x000D_
alert(myCustomer.getAmountDue());
_x000D_
While as said I can't call setAmountDue(), getAmountDue() on a Person.
//The following statement generates an error.
john.setAmountDue(1000);
For such a simple application even MFC would be overkill. If don't want to introduce another dependency just do it in plain vanilla Win32. It will be easier for you if you have never used MFC.
Check out the classic "Programming Windows" by Charles Petzold or some online tutorial (e.g. http://www.winprog.org/tutorial/) and you are ready to go.
I was trying to set the log_statement
in some postgres config file but in fact the file was not read by our postgres.
I confirmed that using the request :
select *
from pg_settings
[...]
log_statement none # That was not the value i was expected for !!!
I use this way https://stackoverflow.com/a/41912295/2294168
command: postgres -c config_file=/etc/postgresql.conf
I depends on what is the regexp language you use, but informally, it would be:
[:alpha:][:alpha:][:digit:][:digit:][:digit:][:digit:][:digit:][:digit:]
where [:alpha:] = [a-zA-Z]
and [:digit:] = [0-9]
If you use a regexp language that allows finite repetitions, that would look like:
[:alpha:]{2}[:digit:]{6}
The correct syntax depends on the particular language you're using, but that is the idea.
Play around with this jsFiddle example:
HTML:
<p id="foo" name="bar">Hello, world!</p>
jQuery:
$(function() {
var name = $('#foo').attr('name');
alert(name);
console.log(name);
});
This uses jQuery's .attr() method to get value for the first element in the matched set.
While not specifically jQuery, the result is shown as an alert prompt and written to the browser's console.
ClassLoader.class.getResourceAsStream("/path/file.ext");
Well... I've found some issues in every proposed solution here.
Here is my solution that include jQuery
.fn
instance function and expression
. I've created more variables inside my function than I could, but for complex logical problem I like to divide it into smaller, clearly named pieces.
I'm using getBoundingClientRect
method that returns element position relatively to the viewport so I don't need to care about scroll position
Useage:
$(".some-element").filter(":onscreen").doSomething();
$(".some-element").filter(":entireonscreen").doSomething();
$(".some-element").isOnScreen(); // true / false
$(".some-element").isOnScreen(true); // true / false (partially on screen)
$(".some-element").is(":onscreen"); // true / false (partially on screen)
$(".some-element").is(":entireonscreen"); // true / false
Source:
$.fn.isOnScreen = function(partial){
//let's be sure we're checking only one element (in case function is called on set)
var t = $(this).first();
//we're using getBoundingClientRect to get position of element relative to viewport
//so we dont need to care about scroll position
var box = t[0].getBoundingClientRect();
//let's save window size
var win = {
h : $(window).height(),
w : $(window).width()
};
//now we check against edges of element
//firstly we check one axis
//for example we check if left edge of element is between left and right edge of scree (still might be above/below)
var topEdgeInRange = box.top >= 0 && box.top <= win.h;
var bottomEdgeInRange = box.bottom >= 0 && box.bottom <= win.h;
var leftEdgeInRange = box.left >= 0 && box.left <= win.w;
var rightEdgeInRange = box.right >= 0 && box.right <= win.w;
//here we check if element is bigger then window and 'covers' the screen in given axis
var coverScreenHorizontally = box.left <= 0 && box.right >= win.w;
var coverScreenVertically = box.top <= 0 && box.bottom >= win.h;
//now we check 2nd axis
var topEdgeInScreen = topEdgeInRange && ( leftEdgeInRange || rightEdgeInRange || coverScreenHorizontally );
var bottomEdgeInScreen = bottomEdgeInRange && ( leftEdgeInRange || rightEdgeInRange || coverScreenHorizontally );
var leftEdgeInScreen = leftEdgeInRange && ( topEdgeInRange || bottomEdgeInRange || coverScreenVertically );
var rightEdgeInScreen = rightEdgeInRange && ( topEdgeInRange || bottomEdgeInRange || coverScreenVertically );
//now knowing presence of each edge on screen, we check if element is partially or entirely present on screen
var isPartiallyOnScreen = topEdgeInScreen || bottomEdgeInScreen || leftEdgeInScreen || rightEdgeInScreen;
var isEntirelyOnScreen = topEdgeInScreen && bottomEdgeInScreen && leftEdgeInScreen && rightEdgeInScreen;
return partial ? isPartiallyOnScreen : isEntirelyOnScreen;
};
$.expr.filters.onscreen = function(elem) {
return $(elem).isOnScreen(true);
};
$.expr.filters.entireonscreen = function(elem) {
return $(elem).isOnScreen(true);
};
In bootstrap 4 is easiest.
You can use the classes:
bg-transparent
and border-0
By default any integral primitive data type (byte, short, int, long) will be treated as int type by java compiler. For byte and short, as long as value assigned to them is in their range, there is no problem and no suffix required. If value assigned to byte and short exceeds their range, explicit type casting is required.
Ex:
byte b = 130; // CE: range is exceeding.
to overcome this perform type casting.
byte b = (byte)130; //valid, but chances of losing data is there.
In case of long data type, it can accept the integer value without any hassle. Suppose we assign like
Long l = 2147483647; //which is max value of int
in this case no suffix like L/l is required. By default value 2147483647 is considered by java compiler is int type. Internal type casting is done by compiler and int is auto promoted to Long type.
Long l = 2147483648; //CE: value is treated as int but out of range
Here we need to put suffix as L to treat the literal 2147483648 as long type by java compiler.
so finally
Long l = 2147483648L;// works fine.
yourPictureBox.ImageLocation = "http://www.gravatar.com/avatar/6810d91caff032b202c50701dd3af745?d=identicon&r=PG"
In Android Studio 1.0, this worked for me :-
Open the build.gradle (Module : app)
file and paste this (at the end) :-
dependencies {
compile "com.android.support:appcompat-v7:21.0.+"
}
Note that this dependencies
is different from the dependencies
inside buildscript
in build.gradle (Project)
When you edit the gradle file, a message shows that you must sync the file. Press "Sync now"
Source : https://developer.android.com/tools/support-library/setup.html#add-library
I just meet a same problem. I solve it by updating the newest version of OpenCV. It works well with me. Hope it is also ok with you.
For any method in a Spring CrudRepository you should be able to specify the @Query yourself. Something like this should work:
@Query( "select o from MyObject o where inventoryId in :ids" )
List<MyObject> findByInventoryIds(@Param("ids") List<Long> inventoryIdList);
I have had excellent success with a technique which resembles the X macros pointed to by @RolandXu. We made heavy use of the stringize operator, too. The technique mitigates the maintenance nightmare when you have an application domain where items appear both as strings and as numerical tokens.
It comes in particularily handy when machine readable documentation is available so that the macro X(...) lines can be auto-generated. A new documentation would immediately result in a consistent program update covering the strings, enums and the dictionaries translating between them in both directions. (We were dealing with PCL6 tokens).
And while the preprocessor code looks pretty ugly, all those technicalities can be hidden in the header files which never have to be touched again, and neither do the source files. Everything is type safe. The only thing that changes is a text file containing all the X(...) lines, and that is possibly auto generated.
The trick is that you have to set it as position:fixed, but only after the user has scrolled past it.
This is done with something like this, attaching a handler to the window.scroll event
// Cache selectors outside callback for performance.
var $window = $(window),
$stickyEl = $('#the-sticky-div'),
elTop = $stickyEl.offset().top;
$window.scroll(function() {
$stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);
});
This simply adds a sticky
CSS class when the page has scrolled past it, and removes the class when it's back up.
And the CSS class looks like this
#the-sticky-div.sticky {
position: fixed;
top: 0;
}
EDIT- Modified code to cache jQuery objects, faster now.
You can try this website http://www.decompileandroid.com Just upload the .apk file and rest of it will be done by this site.
You should be able to use jQuery.ajax
:
Load a remote page using an HTTP request.
And you can specify which method should be used, with the type
option :
The type of request to make ("
POST
" or "GET
"), default is "GET
".
Note: Other HTTP request methods, such asPUT
andDELETE
, can also be used here, but they are not supported by all browsers.
Just find a code-free solution for UITextView:
Enable Detection->Links options, the URL and also email will be detected and clickable!
def fact(n):
f = 1
for i in range(1, n + 1):
f *= i
return f
class UTF8{
static encode(str:string){return new UTF8().encode(str)}
static decode(data:Uint8Array){return new UTF8().decode(data)}
private EOF_byte:number = -1;
private EOF_code_point:number = -1;
private encoderError(code_point) {
console.error("UTF8 encoderError",code_point)
}
private decoderError(fatal, opt_code_point?):number {
if (fatal) console.error("UTF8 decoderError",opt_code_point)
return opt_code_point || 0xFFFD;
}
private inRange(a:number, min:number, max:number) {
return min <= a && a <= max;
}
private div(n:number, d:number) {
return Math.floor(n / d);
}
private stringToCodePoints(string:string) {
/** @type {Array.<number>} */
let cps = [];
// Based on http://www.w3.org/TR/WebIDL/#idl-DOMString
let i = 0, n = string.length;
while (i < string.length) {
let c = string.charCodeAt(i);
if (!this.inRange(c, 0xD800, 0xDFFF)) {
cps.push(c);
} else if (this.inRange(c, 0xDC00, 0xDFFF)) {
cps.push(0xFFFD);
} else { // (inRange(c, 0xD800, 0xDBFF))
if (i == n - 1) {
cps.push(0xFFFD);
} else {
let d = string.charCodeAt(i + 1);
if (this.inRange(d, 0xDC00, 0xDFFF)) {
let a = c & 0x3FF;
let b = d & 0x3FF;
i += 1;
cps.push(0x10000 + (a << 10) + b);
} else {
cps.push(0xFFFD);
}
}
}
i += 1;
}
return cps;
}
private encode(str:string):Uint8Array {
let pos:number = 0;
let codePoints = this.stringToCodePoints(str);
let outputBytes = [];
while (codePoints.length > pos) {
let code_point:number = codePoints[pos++];
if (this.inRange(code_point, 0xD800, 0xDFFF)) {
this.encoderError(code_point);
}
else if (this.inRange(code_point, 0x0000, 0x007f)) {
outputBytes.push(code_point);
} else {
let count = 0, offset = 0;
if (this.inRange(code_point, 0x0080, 0x07FF)) {
count = 1;
offset = 0xC0;
} else if (this.inRange(code_point, 0x0800, 0xFFFF)) {
count = 2;
offset = 0xE0;
} else if (this.inRange(code_point, 0x10000, 0x10FFFF)) {
count = 3;
offset = 0xF0;
}
outputBytes.push(this.div(code_point, Math.pow(64, count)) + offset);
while (count > 0) {
let temp = this.div(code_point, Math.pow(64, count - 1));
outputBytes.push(0x80 + (temp % 64));
count -= 1;
}
}
}
return new Uint8Array(outputBytes);
}
private decode(data:Uint8Array):string {
let fatal:boolean = false;
let pos:number = 0;
let result:string = "";
let code_point:number;
let utf8_code_point = 0;
let utf8_bytes_needed = 0;
let utf8_bytes_seen = 0;
let utf8_lower_boundary = 0;
while (data.length > pos) {
let _byte = data[pos++];
if (_byte == this.EOF_byte) {
if (utf8_bytes_needed != 0) {
code_point = this.decoderError(fatal);
} else {
code_point = this.EOF_code_point;
}
} else {
if (utf8_bytes_needed == 0) {
if (this.inRange(_byte, 0x00, 0x7F)) {
code_point = _byte;
} else {
if (this.inRange(_byte, 0xC2, 0xDF)) {
utf8_bytes_needed = 1;
utf8_lower_boundary = 0x80;
utf8_code_point = _byte - 0xC0;
} else if (this.inRange(_byte, 0xE0, 0xEF)) {
utf8_bytes_needed = 2;
utf8_lower_boundary = 0x800;
utf8_code_point = _byte - 0xE0;
} else if (this.inRange(_byte, 0xF0, 0xF4)) {
utf8_bytes_needed = 3;
utf8_lower_boundary = 0x10000;
utf8_code_point = _byte - 0xF0;
} else {
this.decoderError(fatal);
}
utf8_code_point = utf8_code_point * Math.pow(64, utf8_bytes_needed);
code_point = null;
}
} else if (!this.inRange(_byte, 0x80, 0xBF)) {
utf8_code_point = 0;
utf8_bytes_needed = 0;
utf8_bytes_seen = 0;
utf8_lower_boundary = 0;
pos--;
code_point = this.decoderError(fatal, _byte);
} else {
utf8_bytes_seen += 1;
utf8_code_point = utf8_code_point + (_byte - 0x80) * Math.pow(64, utf8_bytes_needed - utf8_bytes_seen);
if (utf8_bytes_seen !== utf8_bytes_needed) {
code_point = null;
} else {
let cp = utf8_code_point;
let lower_boundary = utf8_lower_boundary;
utf8_code_point = 0;
utf8_bytes_needed = 0;
utf8_bytes_seen = 0;
utf8_lower_boundary = 0;
if (this.inRange(cp, lower_boundary, 0x10FFFF) && !this.inRange(cp, 0xD800, 0xDFFF)) {
code_point = cp;
} else {
code_point = this.decoderError(fatal, _byte);
}
}
}
}
//Decode string
if (code_point !== null && code_point !== this.EOF_code_point) {
if (code_point <= 0xFFFF) {
if (code_point > 0)result += String.fromCharCode(code_point);
} else {
code_point -= 0x10000;
result += String.fromCharCode(0xD800 + ((code_point >> 10) & 0x3ff));
result += String.fromCharCode(0xDC00 + (code_point & 0x3ff));
}
}
}
return result;
}
`
If you don't mind the navigation div being clipped in the event of an unexpectedly-short content div, there's at least one easy way:
#main {
position: relative;
}
#main #navigation {
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 10em; /* or whatever */
}
#main #content {
margin: 0;
margin-left: 10em; /* or whatever width you set for #navigation */
}
Elsewise there's the faux-columns technique.
Below query worked for me with default value false;
ALTER TABLE cti_contract_account ADD ready_to_audit BIT DEFAULT 0 NOT NULL;
Why do you want to enforce that only a single thread can access the DB at any one time?
It is the job of the database driver to implement any necessary locking, assuming a Connection
is only used by one thread at a time!
Most likely, your database is perfectly capable of handling multiple, parallel access
Just save some one time. I spent 3 hours to find out that it was just html encoding problem. Try this
if(get_magic_quotes_gpc()){
$param = stripslashes($row['your column name']);
}else{
$param = $row['your column name'];
}
$param = json_decode(html_entity_decode($param),true);
$json_errors = array(
JSON_ERROR_NONE => 'No error has occurred',
JSON_ERROR_DEPTH => 'The maximum stack depth has been exceeded',
JSON_ERROR_CTRL_CHAR => 'Control character error, possibly incorrectly encoded',
JSON_ERROR_SYNTAX => 'Syntax error',
);
echo 'Last error : ', $json_errors[json_last_error()], PHP_EOL, PHP_EOL;
print_r($param);
Try this, I think this is a natively way to concatenate strings in Kotlin:
val result = buildString{
append("a")
append("b")
}
println(result)
// you will see "ab" in console.
If the response is in json you could do something like (python3):
import json
import requests as reqs
# Make the HTTP request.
response = reqs.get('http://demo.ckan.org/api/3/action/group_list')
# Use the json module to load CKAN's response into a dictionary.
response_dict = json.loads(response.text)
for i in response_dict:
print("key: ", i, "val: ", response_dict[i])
To see everything in the response you can use .__dict__
:
print(response.__dict__)
Try this:
net use * /delete /y
The /y
key makes it select Yes in prompt silently
Final working solution using @Arrigo response and @Samitha Chathuranga comment, I'll put all together to build a full response for this question:
Open Git CMD console and type command 1 from second picture(go to your project folder on your PC)
Type command git init
Type command git add --all
Type command 2 from second picture (git remote add origin YOUR_LINK_TO_REPO
)
Type command git commit -m "my first commit"
Type command git push -u origin master
Note: if you get error unable to detect email or name, just type following commands after 5th step:
git config --global user.email "yourEmail" #your email at Bitbucket
git config --global user.name "yourName" #your name at Bitbucket
Constructor overriding is not possible because of following reason.
Constructor name must be the same name of class name. In Inheritance practice you need to create two classes with different names hence two constructors must have different names. So constructor overriding is not possible and that thought not even make sense.
I think you should try with this API
http://code.google.com/p/php-excel/source/browse/trunk/php-excel.class.php
With This
Create a quick export from a database table into Excel
Compile some statistical records with a few calculations and deliver
the result in an Excel worksheet
Gather the items off your (web-based) todo list, put them in a
worksheet and use it as a foundation for some more statistics
magic.**
You can also handle index yourself if You need the index, it will not work if You need the key.
let i = 0;
for (const item of iterableItems) {
// do something with index
console.log(i);
i++;
}
Your code works as is for me. I'm verifying this by using netcat on Linux.
Using netcat, I can do nc -ul 127.0.0.1 5005
which will listen for packets at:
That being said, here's the output that I see when I run your script, while having netcat running.
[9:34am][wlynch@watermelon ~] nc -ul 127.0.0.1 5005
Hello, World!
You need module.exports:
Exports
An object which is shared between all instances of the current module and made accessible through require(). exports is the same as the module.exports object. See src/node.js for more information. exports isn't actually a global but rather local to each module.
For example, if you would like to expose variableName
with value "variableValue"
on sourceFile.js
then you can either set the entire exports as such:
module.exports = { variableName: "variableValue" };
Or you can set the individual value with:
module.exports.variableName = "variableValue";
To consume that value in another file, you need to require(...)
it first (with relative pathing):
const sourceFile = require('./sourceFile');
console.log(sourceFile.variableName);
Alternatively, you can deconstruct it.
const { variableName } = require('./sourceFile');
// current directory --^
// ../ would be one directory down
// ../../ is two directories down
If all you want out of the file is variableName
then
const variableName = 'variableValue'
module.exports = variableName
const variableName = require('./sourceFile')
Since Node.js version 8.9.0, you can also use ECMAScript Modules with varying levels of support. The documentation.
--experimental-modules
Node.js will treat the following as ES modules when passed to node as the initial input, or when referenced by import statements within ES module code:
- Files ending in
.mjs
.
.js
when the nearest parent package.json
file contains a top-level field "type"
with a value of "module"
.--eval
or --print
, or piped to node via STDIN, with the flag --input-type=module
.Once you have it setup, you can use import
and export
.
Using the example above, there are two approaches you can take
// This is a named export of variableName
export const variableName = 'variableValue'
// Alternatively, you could have exported it as a default.
// For sake of explanation, I'm wrapping the variable in an object
// but it is not necessary.
// You can actually omit declaring what variableName is here.
// { variableName } is equivalent to { variableName: variableName } in this case.
export default { variableName: variableName }
// There are three ways of importing.
// If you need access to a non-default export, then
// you use { nameOfExportedVariable }
import { variableName } from './sourceFile'
console.log(variableName) // 'variableValue'
// Otherwise, you simply provide a local variable name
// for what was exported as default.
import sourceFile from './sourceFile'
console.log(sourceFile.variableName) // 'variableValue'
// The third way of importing is for situations where there
// isn't a default export but you want to warehouse everything
// under a single variable. Say you have:
export const a = 'A'
export const b = 'B'
// Then you can import all exports under a single variable
// with the usage of * as:
import * as sourceFileWithoutDefault from './sourceFileWithoutDefault'
console.log(sourceFileWithoutDefault.a) // 'A'
console.log(sourceFileWithoutDefault.b) // 'B'
// You can use this approach even if there is a default export:
import * as sourceFile from './sourceFile'
// Default exports are under the variable default:
console.log(sourceFile.default) // { variableName: 'variableValue' }
// As well as named exports:
console.log(sourceFile.variableName) // 'variableValue
I found this one more helpful and simple
DECLARE @StartTime datetime,@EndTime datetime
SELECT @StartTime=GETDATE()
--Your Query to be run goes here--
SELECT @EndTime=GETDATE()
SELECT DATEDIFF(ms,@StartTime,@EndTime) AS [Duration in milliseconds]
<strong>
and <em>
add extra semantic meaning to your document. It just so happens that they also give a bold and italic style to your text.
You could of course override their styling with CSS.
<b>
and <i>
on the other hand only apply font styling and should no longer be used. (Because you're supposed to format with CSS, and if the text was actually important then you would probably make it "strong" or "emphasised" anyway!)
Hope that makes sense.
In case the precision is not known until runtime, this other formatting option is useful:
>>> n = 9
>>> '%.*f' % (n, numvar)
'135.123456789'
You probably want egrep. Try:
egrep '^[d-]rwx.*[0-9]$' usrLog.txt
This code work correctly only when u put into button click because at that time user put values into editable text and then when user clicks button it fetch the data and convert into string
EditText dob=(EditText)findviewbyid(R.id.edit_id);
String str=dob.getText().toString();
This error also occurs if you have a block with no statements in it
For example:
def my_function():
for i in range(1,10):
def say_hello():
return "hello"
Notice that the for
block is empty. You can use the pass statement if you want to test the remaining code in the module.
As karim79 mentioned, the first is the most concise. However I could argue that the second is more understandable as it is not obvious/known to some Javascript/jQuery programmers that non-zero/false values are evaluated to true
in if-statements. And because of that, the third method is incorrect.
If you want to concatenate the fields using / as a separator, you can use concat_ws
:
select concat_ws('/', col1, col2, col3) from mytable
You cannot escape listing the columns in the query though. The *-syntax works only in "select * from". You can list the columns and construct the query dynamically though.
In addition to what people have said about 64-bit (or whatever) systems, there are other kinds of pointer than pointer-to-object.
A pointer-to-member might be almost any size, depending how they're implemented by your compiler: they aren't necessarily even all the same size. Try a pointer-to-member of a POD class, and then a pointer-to-member inherited from one of the base classes of a class with multiple bases. What fun.
I'll suggest different approach, If the order of the items inside the list is not important at extraction (and each item should be selected only once), then instead of a List
you can use a ConcurrentBag
which is a thread-safe, unordered collection of objects:
var bag = new ConcurrentBag<string>();
bag.Add("Foo");
bag.Add("Boo");
bag.Add("Zoo");
The EventHandler:
string result;
if (bag.TryTake(out result))
{
MessageBox.Show(result);
}
The TryTake
will attempt to extract an "random" object from the unordered collection.
DateTime#to_date
does exist with ActiveSupport:
$ irb
>> DateTime.new.to_date
NoMethodError: undefined method 'to_date' for #<DateTime: -1/2,0,2299161>
from (irb):1
>> require 'active_support/core_ext'
=> true
>> DateTime.new.to_date
=> Mon, 01 Jan -4712
The values can be retrieved during the parsing:
var yahoo = [], j = `[{"name":"Lenovo Thinkpad 41A4298","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41A2222","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41Awww33","website":"yahoo"},_x000D_
{"name":"Lenovo Thinkpad 41A424448","website":"google"},_x000D_
{"name":"Lenovo Thinkpad 41A429rr8","website":"ebay"},_x000D_
{"name":"Lenovo Thinkpad 41A429ff8","website":"ebay"},_x000D_
{"name":"Lenovo Thinkpad 41A429ss8","website":"rediff"},_x000D_
{"name":"Lenovo Thinkpad 41A429sg8","website":"yahoo"}]`_x000D_
_x000D_
var data = JSON.parse(j, function(key, value) { _x000D_
if ( value.website === "yahoo" ) yahoo.push(value); _x000D_
return value; })_x000D_
_x000D_
console.log( yahoo )
_x000D_
Sooooo, I had this same question. here's my answer: COUNTIFS(sheet1!$A:$A,">="&D1,sheet1!$A:$A,"<="&D2)
you don't need to specify A2:A50, unless there are dates beyond row 50 that you wish to exclude. this is cleaner in the sense that you don't have to go back and adjust the rows as more PO data comes in on sheet1.
also, the reference to D1 and D2 are start and end dates (respectively) for each month. On sheet2, you could have a hidden column that translates April to 4/1/2014, May into 5/1/2014, etc. THen, D1 would reference the cell that contains 4/1/2014, and D2 would reference the cell that contains 5/1/2014.
if you want to sum, it works the same way, except that the first argument is the sum array (column or row) and then the rest of the ranges/arrays and arguments are the same as the countifs formula.
btw-this works in excel AND google sheets. cheers
I think this is an appropriate solution:
<select id="test" name="form_select" onchange="showDiv(this)">
<option value="0">No</option>
<option value="1">Yes</option>
</select>
<div id="hidden_div" style="display:none;">Hello hidden content</div>
<script type="text/javascript">
function showDiv(select){
if(select.value==1){
document.getElementById('hidden_div').style.display = "block";
} else{
document.getElementById('hidden_div').style.display = "none";
}
}
</script>
_x000D_
The git checkout master
of the answer by Woland isn't needed. Instead use the "Checkout to specific local branch" in the "Additional Behaviors" section to set the "Branch name" to master.
The git commit -am "blah"
is still needed.
Now you can use the "Git Publisher" under "Post-build Actions" to push the changes. Be sure to specify the "Branches" to push ("Branch to push" = master, "Target remote name" = origin).
"Merge Results" isn't needed.
After a lot of trials I found the following solution.
This will work if you copied all phpmyadmin files in /var/www
go to your copied location of phpmyadmin folder in /var/www
copy the config.sample.inc.php file as config.inc.php
edit in config.inc.php the following line:
$cfg['Servers'][$i]['AllowNoPassword'] = true;
(In original file it was false, change it as true and save it.)
Then you will be able to login phpmyadmin without password.
I am assuming you're using Chrome.
If so, the root problem is a certificate mismatch / expired certificate.
You can see this for yourself in the code here.
Note in particular the use of the very constant you reference in the code on line 48 of the C++ file I sent you:
case net::ERR_INSECURE_RESPONSE:
The current version of this file is here. The error status ERR_INSECURE_RESPONSE may not any longer be on line 48 but the error code still exists in the SSL certificate portion of the code.
Note: Make sure to use the hostname which is listed in the SSL certificate, chrome automatically switches to the right hostname if you are browsing but not when using javascript.
Android:autoText attribute also makes TextView auto focusable.
You can try this
SELECT * FROM Buses
WHERE BusID
in (1,2,3,4,...)
Wrap the linear layout with a <ScrollView>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- Content here -->
</LinearLayout>
</ScrollView>
</LinearLayout>
Note: fill_parent is deprecated and renamed to match_parent in API Level 8 and higher.
For anyone else that reads this!!!!
HEIGHT is defined as the number of nodes in the longest path from the root node to a leaf node. Therefore: a tree with only a root node has a height of 1 and not 0.
The LEVEL of a given node is the distance from the root plus 1. Therefore: The root is on level 1, its child nodes are on level 2 and so on.
(Information courtesy of Data Structures: Abstraction and Design Using Java, 2nd Edition, by Elliot B. Koffman & Paul A. T. Wolfgang) - Book used in Data Structures Course I am currently taking at Columbus State University.
I have fixed this issue using the proxy command option of gem install. It has the following format:
$ gem install --http-proxy http://201.187.107.19:8080 rubygame
Note, the IP address and the port number refers to a proxy. You should search for a proxy list and use one of the proxies there.
This is site with proxies: http://www.cybersyndrome.net/pla5.html
Also, I have to try 7 or 8 different proxies in order to succeed. Do not give up.
if ('undefined' == typeof window.jQuery) {
// jQuery not present
} else {
// jQuery present
}
The following should work but it wouldn't be SEO compatible. It's best to put the title in the title tag.
<script type="text/javascript">
$(document).ready(function() {
document.title = 'blah';
});
</script>
The declaration and initialization
char *array = "One good thing about music";
declares a pointer array
and make it point to a constant array of 31 characters.
The declaration and initialization
char array[] = "One, good, thing, about, music";
declares an array of characters, containing 31 characters.
And yes, the size of the arrays is 31, as it includes the terminating '\0'
character.
Laid out in memory, it will be something like this for the first:
+-------+ +------------------------------+ | array | --> | "One good thing about music" | +-------+ +------------------------------+
And like this for the second:
+------------------------------+ | "One good thing about music" | +------------------------------+
Arrays decays to pointers to the first element of an array. If you have an array like
char array[] = "One, good, thing, about, music";
then using plain array
when a pointer is expected, it's the same as &array[0]
.
That mean that when you, for example, pass an array as an argument to a function it will be passed as a pointer.
Pointers and arrays are almost interchangeable. You can not, for example, use sizeof(pointer)
because that returns the size of the actual pointer and not what it points to. Also when you do e.g. &pointer
you get the address of the pointer, but &array
returns a pointer to the array. It should be noted that &array
is very different from array
(or its equivalent &array[0]
). While both &array
and &array[0]
point to the same location, the types are different. Using the arrat above, &array
is of type char (*)[31]
, while &array[0]
is of type char *
.
For more fun: As many knows, it's possible to use array indexing when accessing a pointer. But because arrays decays to pointers it's possible to use some pointer arithmetic with arrays.
For example:
char array[] = "Foobar"; /* Declare an array of 7 characters */
With the above, you can access the fourth element (the 'b
' character) using either
array[3]
or
*(array + 3)
And because addition is commutative, the last can also be expressed as
*(3 + array)
which leads to the fun syntax
3[array]
You can also use awk:
awk 'END {print NR,"lines"}' filename
Or
awk 'END {print NR}' filename
It appears that your format is incorrect:
If you want to share a locally created repository, or you want to take contributions from someone elses repository - if you want to interact in any way with a new repository, it's generally easiest to add it as a remote. You do that by running git remote add [alias] [url]. That adds [url] under a local remote named [alias].
#example
$ git remote
$ git remote add github [email protected]:schacon/hw.git
$ git remote -v
Via css. Put this inside the <head>
tag.
<style type="text/css" media="screen">
table{
border-collapse:collapse;
border:1px solid #FF0000;
}
table td{
border:1px solid #FF0000;
}
</style>
You can in fact use range
without referencing it's return values by using for range
against your type:
arr := make([]uint8, 5)
i,j := 0,0
for range arr {
fmt.Println("Array Loop",i)
i++
}
for range "bytes" {
fmt.Println("String Loop",j)
j++
}
Put in your js file
var url = window.location.href;
console.log(url);
console.log(~url.indexOf("#product-consulation"));
if (~url.indexOf("#product-consulation")) {
console.log('YES');
// $('html, body').animate({
// scrollTop: $('#header').offset().top - 80
// }, 1000);
} else {
console.log('NOPE');
}
You can do this with css transforms, though be careful with container height/width. Also you may need to position it lower:
input[type="range"] {_x000D_
position: absolute;_x000D_
top: 40%;_x000D_
transform: rotate(270deg);_x000D_
}
_x000D_
<input type="range"/>
_x000D_
or the 3d transform equivalent:
input[type="range"] {
transform: rotateZ(270deg);
}
You can also use this to switch the direction of the slide by setting it to 180deg or 90deg for horizontal or vertical respectively.
If you have PHP >= 5.1:
function isWeekend($date) {
return (date('N', strtotime($date)) >= 6);
}
otherwise:
function isWeekend($date) {
$weekDay = date('w', strtotime($date));
return ($weekDay == 0 || $weekDay == 6);
}
Since it's a POD struct, you could always memset it to 0 - this might be the easiest way to get the fields initialized (assuming that is appropriate).
You are calling:
JSON.parse(scatterSeries)
But when you defined scatterSeries
, you said:
var scatterSeries = [];
When you try to parse it as JSON it is converted to a string (""
), which is empty, so you reach the end of the string before having any of the possible content of a JSON text.
scatterSeries
is not JSON. Do not try to parse it as JSON.
data
is not JSON either (getJSON
will parse it as JSON automatically).
ch
is JSON … but shouldn't be. You should just create a plain object in the first place:
var ch = {
"name": "graphe1",
"items": data.results[1]
};
scatterSeries.push(ch);
In short, for what you are doing, you shouldn't have JSON.parse
anywhere in your code. The only place it should be is in the jQuery library itself.
The answer is to create a span with the property
{display:none;}
You can find an example at this site
Unique pointers are guaranteed to destroy the object they manage when they go out of scope. http://en.cppreference.com/w/cpp/memory/unique_ptr
In this case:
unique_ptr<double> uptr2 (pd);
pd
will be destroyed when uptr2
goes out of scope. This facilitates memory management by automatic deletion.
The case of unique_ptr<int> uptr (new int(3));
is not different, except that the raw pointer is not assigned to any variable here.
This is what worked for me perfectly:-
// slide the view from its current position to below itself
public void slideUp(final View view, final View llDomestic){
ObjectAnimator animation = ObjectAnimator.ofFloat(view, "translationY",0f);
animation.setDuration(100);
llDomestic.setVisibility(View.GONE);
animation.start();
}
// slide the view from below itself to the current position
public void slideDown(View view,View llDomestic){
llDomestic.setVisibility(View.VISIBLE);
ObjectAnimator animation = ObjectAnimator.ofFloat(view, "translationY", 0f);
animation.setDuration(100);
animation.start();
}
llDomestic : The view which you want to hide. view: The view which you want to move down or up.
To do this, I would strongly consider wrapping a Text
component in a TouchableOpacity
. When a TouchableOpacity
is touched, it fades (becomes less opaque). This gives the user immediate feedback when touching the text and provides for an improved user experience.
You can use the onPress
property on the TouchableOpacity
to make the link happen:
<TouchableOpacity onPress={() => Linking.openURL('http://google.com')}>
<Text style={{color: 'blue'}}>
Google
</Text>
</TouchableOpacity>
Is this logically possible??.. I guess the approach that you must take is this way :
Str1 ="test123.00"
Str2 ="yes50.00"
This will be impossible to tackle unless you have delimiter in between test
and 123.00
eg: Str1 = "test-123.00"
Then you can split this way
Str2 = Str1.split("-");
This will return you an array of words split with "-"
Then you can do parseFloat(Str2[1])
to get the floating value i.e 123.00
Both JBoss and Tomcat are Java servlet application servers, but JBoss is a whole lot more. The substantial difference between the two is that JBoss provides a full Java Enterprise Edition (Java EE) stack, including Enterprise JavaBeans and many other technologies that are useful for developers working on enterprise Java applications.
Tomcat is much more limited. One way to think of it is that JBoss is a Java EE stack that includes a servlet container and web server, whereas Tomcat, for the most part, is a servlet container and web server.
I know this is SUPER old... but just for fun I decided to give this a try:
@Echo OFF
setlocal
set testpath=%path: =#%
FOR /F "tokens=* delims=;" %%P in ("%testpath%") do call :loop %%P
:loop
if '%1'=='' goto endloop
set testpath=%1
set testpath=%testpath:#= %
echo %testpath%
SHIFT
goto :loop
:endloop
pause
endlocal
exit
This doesn't require a count and will go until it finishes. I had the same problem with spaces but it made it through the entire variable. The key to this is the loop labels and the SHIFT
function.
This one will give you date no time:
=FormatDateTime(DateAdd("m", -1, DateSerial(Year(Today()), Month(Today()), 1)),
DateFormat.ShortDate)
This one will give you datetime:
=dateadd("m",-1,dateserial(year(Today),month(Today),1))
If you want to cancel pending requests on stateChangeStart with ui-router, you can use something like this:
// in service
var deferred = $q.defer();
var scope = this;
$http.get(URL, {timeout : deferred.promise, cancel : deferred}).success(function(data){
//do something
deferred.resolve(dataUsage);
}).error(function(){
deferred.reject();
});
return deferred.promise;
// in UIrouter config
$rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) {
//To cancel pending request when change state
angular.forEach($http.pendingRequests, function(request) {
if (request.cancel && request.timeout) {
request.cancel.resolve();
}
});
});
int mid = 10;
for (double j = 2 * mid; j >= 0; j = j - 0.1) {
if (j == mid) {
System.out.println("Never happens"); // is NOT printed
}
if (Double.compare(j, mid) == 0) {
System.out.println("No way!"); // is NOT printed
}
if (Math.abs(j - mid) < 1e-6) {
System.out.println("Ha!"); // printed
}
}
System.out.println("Gotcha!");
You can do both in code and XML. Only 4 basic things to be set.
e.g.
android:shadowColor="@color/text_shadow_color"
android:shadowDx="-2"
android:shadowDy="2"
android:shadowRadius="0.01"
This draws a prominent shadow on left-lower side of text. In code, you can add something like this;
TextView item = new TextView(getApplicationContext());
item.setText(R.string.text);
item.setTextColor(getResources().getColor(R.color.general_text_color));
item.setShadowLayer(0.01f, -2, 2, getResources().getColor(R.color.text_shadow_color));
I was also going through this annoying problem while running my test cases, so I tried many ways to get across it. But the way works for me is to run your test runner from the directory which contains your main file which includes your nodejs spawn function something like this:
nodeProcess = spawn('node',params, {cwd: '../../node/', detached: true });
For example, this file name is test.js, so just move to the folder which contains it. In my case, it is test folder like this:
cd root/test/
then from run your test runner in my case its mocha so it will be like this:
mocha test.js
I have wasted my more than one day to figure it out. Enjoy!!
The compiler isn't smart enough to know that at least one of your if
blocks will be executed. Therefore, it doesn't see that variables like annualRate
will be assigned no matter what. Here's how you can make the compiler understand:
if (creditPlan == "0")
{
// ...
}
else if (creditPlan == "1")
{
// ...
}
else if (creditPlan == "2")
{
// ...
}
else
{
// ...
}
The compiler knows that with an if/else block, one of the blocks is guaranteed to be executed, and therefore if you're assigning the variable in all of the blocks, it won't give the compiler error.
By the way, you can also use a switch
statement instead of if
s to maybe make your code cleaner.
Thinking of things that actually need a stack:
If we consider the pattern of recursion as:
if(task can be done directly) {
return result of doing task directly
} else {
split task into two or more parts
solve for each part (possibly by recursing)
return result constructed by combining these solutions
}
For example, the classic Tower of Hanoi
if(the number of discs to move is 1) {
just move it
} else {
move n-1 discs to the spare peg
move the remaining disc to the target peg
move n-1 discs from the spare peg to the target peg, using the current peg as a spare
}
This can be translated into a loop working on an explicit stack, by restating it as:
place seed task on stack
while stack is not empty
take a task off the stack
if(task can be done directly) {
Do it
} else {
Split task into two or more parts
Place task to consolidate results on stack
Place each task on stack
}
}
For Tower of Hanoi this becomes:
stack.push(new Task(size, from, to, spare));
while(! stack.isEmpty()) {
task = stack.pop();
if(task.size() = 1) {
just move it
} else {
stack.push(new Task(task.size() -1, task.spare(), task,to(), task,from()));
stack.push(new Task(1, task.from(), task.to(), task.spare()));
stack.push(new Task(task.size() -1, task.from(), task.spare(), task.to()));
}
}
There is considerable flexibility here as to how you define your stack. You can make your stack a list of Command
objects that do sophisticated things. Or you can go the opposite direction and make it a list of simpler types (e.g. a "task" might be 4 elements on a stack of int
, rather than one element on a stack of Task
).
All this means is that the memory for the stack is in the heap rather than in the Java execution stack, but this can be useful in that you have more control over it.
Use CALL
as in
CALL nameOfOtherFile.bat
This will block (pause) the execution of the current batch file, and it will wait until the CALL
ed one completes.
If you don't want it to block, use START
instead.
Get the nitty-gritty details by using CALL /?
or START /?
from the cmd prompt.
Best way to send html formatted Email
This code will be in "Customer.htm"
<table>
<tr>
<td>
Dealer's Company Name
</td>
<td>
:
</td>
<td>
#DealerCompanyName#
</td>
</tr>
</table>
Read HTML file Using System.IO.File.ReadAllText. get all HTML code in string variable.
string Body = System.IO.File.ReadAllText(HttpContext.Current.Server.MapPath("EmailTemplates/Customer.htm"));
Replace Particular string to your custom value.
Body = Body.Replace("#DealerCompanyName#", _lstGetDealerRoleAndContactInfoByCompanyIDResult[0].CompanyName);
call SendEmail(string Body) Function and do procedure to send email.
public static void SendEmail(string Body)
{
MailMessage message = new MailMessage();
message.From = new MailAddress(Session["Email"].Tostring());
message.To.Add(ConfigurationSettings.AppSettings["RequesEmail"].ToString());
message.Subject = "Request from " + SessionFactory.CurrentCompany.CompanyName + " to add a new supplier";
message.IsBodyHtml = true;
message.Body = Body;
SmtpClient smtpClient = new SmtpClient();
smtpClient.UseDefaultCredentials = true;
smtpClient.Host = ConfigurationSettings.AppSettings["SMTP"].ToString();
smtpClient.Port = Convert.ToInt32(ConfigurationSettings.AppSettings["PORT"].ToString());
smtpClient.EnableSsl = true;
smtpClient.Credentials = new System.Net.NetworkCredential(ConfigurationSettings.AppSettings["USERNAME"].ToString(), ConfigurationSettings.AppSettings["PASSWORD"].ToString());
smtpClient.Send(message);
}
What you need is called a "geo-IP database". Most of them cost some money (albeit not too expensive), especially fairly precise ones. One of the most widely used is MaxMind's database. They have a fairly good free version of IP-to-city database called GeoLity City - it has lots of restrictions, but if you can cope with that that would be probably your best choice, unless you have some money to spare for a subscription to more accurate product.
And, yeah, they do have a C# API to query geo-IP databases available.
First, if you are able to locate your
bootstrap.css file
and
bootstrap.min.js file
in your computer, then what you just do is
First download your favorite theme i.e. from http://bootswatch.com/
Copy the downloaded bootstrap.css and bootstrap.min.js files
Then in your computer locate the existing files and replace them with the new downloaded files.
NOTE: ensure your downloaded files are renamed to what is in your folder
i.e.
Then you are good to go.
sometimes result may not display immediately. your may need to run the css on your browser as a way of refreshing
ps -eo pid,etime,cmd|sort -n -k2
The simplest I've found is using background jobs in the shell:
for d in /main/files/*; do
rsync -a "$d" remote:/main/files/ &
done
Beware it doesn't limit the amount of jobs! If you're network-bound this is not really a problem but if you're waiting for spinning rust this will be thrashing the disk.
You could add
while [ $(jobs | wc -l | xargs) -gt 10 ]; do sleep 1; done
inside the loop for a primitive form of job control.
objects are passed by reference, primitives are passed by value.
String is not a primitive, it is an object, and it is a special case of object.
This is for memory-saving purpose. In JVM, there is a string pool. For every string created, JVM will try to see if the same string exist in the string pool, and point to it if there were already one.
public class TestString
{
private static String a = "hello world";
private static String b = "hello world";
private static String c = "hello " + "world";
private static String d = new String("hello world");
private static Object o1 = new Object();
private static Object o2 = new Object();
public static void main(String[] args)
{
System.out.println("a==b:"+(a == b));
System.out.println("a==c:"+(a == c));
System.out.println("a==d:"+(a == d));
System.out.println("a.equals(d):"+(a.equals(d)));
System.out.println("o1==o2:"+(o1 == o2));
passString(a);
passString(d);
}
public static void passString(String s)
{
System.out.println("passString:"+(a == s));
}
}
/* OUTPUT */
a==b:true
a==c:true
a==d:false
a.equals(d):true
o1==o2:false
passString:true
passString:false
the == is checking for memory address (reference), and the .equals is checking for contents (value)
I've found one difference between the two constructions that bit me pretty hard.
Let's say I have:
function MyClass(){
this.property1=[];
this.property2=new Array();
};
var MyObject1=new MyClass();
var MyObject2=new MyClass();
In real life, if I do this:
MyObject1.property1.push('a');
MyObject1.property2.push('b');
MyObject2.property1.push('c');
MyObject2.property2.push('d');
What I end up with is this:
MyObject1.property1=['a','c']
MyObject1.property2=['b']
MyObject2.property1=['a','c']
MyObject2.property2=['d']
I don't know what the language specification says is supposed to happen, but if I want my two objects to have unique property arrays in my objects, I have to use new Array()
.
Another trick for getting sequential pieces (beyond the seq solution already mentioned) is to use a short logical vector and use vector recycling:
foo[ c( rep(FALSE, 5), TRUE ) ]
the "problem view" mentioned in previous answers was helpful, but i saw it didn't catch all the errors in project. After running application, it began populating other classes that had issues but didn't appear at first in that problems view.
You can do this with one simple command:
npm ci
Documentation:
npm ci
Install a project with a clean slate
You can use the getName()
method of FragmentManager.BackStackEntry
which was introduced in API level 14. This method will return a tag which was the one you used when you added the Fragment to the backstack with addTobackStack(tag)
.
int index = getActivity().getFragmentManager().getBackStackEntryCount() - 1
FragmentManager.BackStackEntry backEntry = getFragmentManager().getBackStackEntryAt(index);
String tag = backEntry.getName();
Fragment fragment = getFragmentManager().findFragmentByTag(tag);
You need to make sure that you added the fragment to the backstack like this:
fragmentTransaction.addToBackStack(tag);
Just simply the css style using white-space:nowrap
works very well to avoid text wrapping in cells. And ofcourse you can use the text-overflow:ellipsis
and overflow:hidden
for truncating text with ellipsis effect.
<td style="white-space:nowrap">Cell Value</td>
To add to the others, var_export might be handy too:
$email_text = var_export($_POST, true);
<img id="uxcMyImageId" src"myImage" width="100" height="100" />
specifying width and height in the image tag is a good practice..this way when the page loads there is space allocated for the image and the layout does not suffer any jerks even if the image takes a long time to load.
As your list is an ArrayList
, it can be assumed that it is unsorted. Therefore, there is no way to search for your element that is faster than O(n).
If you can, you should think about changing your list into a Set
(with HashSet
as implementation) with a specific Comparator
for your sample class.
Another possibility would be to use a HashMap
. You can add your data as Sample
(please start class names with an uppercase letter) and use the string you want to search for as key. Then you could simply use
Sample samp = myMap.get(myKey);
If there can be multiple samples per key, use Map<String, List<Sample>>
, otherwise use Map<String, Sample>
. If you use multiple keys, you will have to create multiple maps that hold the same dataset. As they all point to the same objects, space shouldn't be that much of a problem.
Check out this answer https://stackoverflow.com/a/5344074/746491 .
In short, JSON.parse(JSON.stringify(obj))
is a fast way to copy your objects, if your objects can be serialized to json.
Nice article for elevation options - http://www.novell.com/support/kb/doc.php?id=7010269
Configuring Applications to Always Request Elevated Rights:
Programs can be configured to always request elevation on the user level via registry settings under HKCU
. These registry settings are effective on the fly, so they can be set immediately prior to launching a particular application and even removed as soon as the application is launched, if so desired. Simply create a "String Value"
under "HKCU\Software\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers"
for the full path to an executable with a value of "RUN AS ADMIN"
. Below is an example for CMD.
Windows Registry Editor Version 5.00
[HKEY_Current_User\SOFTWARE\Microsoft\Windows NT\CurrentVersion\AppCompatFlags\Layers]
"c:\\windows\\system32\\cmd.exe"="RUNASADMIN"
For Android 5 (lollipop) you will have to use android:actionBarPopupTheme to set the textColor for the overflow menu.
The identity
section goes under the system.web
section, not under authentication
:
<system.web>
<authentication mode="Windows"/>
<identity impersonate="true" userName="foo" password="bar"/>
</system.web>
It is possible.
When you use Return inside a procedure, the control is transferred to the calling program which calls the procedure. It is like an exit in loops.
It won't return any value.
It has to be a constant - the value has to be computable at the time that the procedure is created, and that one computation has to provide the value that will always be used.
Look at the definition of sys.all_parameters
:
default_value
sql_variant
Ifhas_default_value
is 1, the value of this column is the value of the default for the parameter; otherwise,NULL
.
That is, whatever the default for a parameter is, it has to fit in that column.
As Alex K pointed out in the comments, you can just do:
CREATE PROCEDURE [dbo].[problemParam]
@StartDate INT = NULL,
@EndDate INT = NULL
AS
BEGIN
SET @StartDate = COALESCE(@StartDate,CONVERT(INT,(CONVERT(CHAR(8),GETDATE()-130,112))))
provided that NULL
isn't intended to be a valid value for @StartDate
.
As to the blog post you linked to in the comments - that's talking about a very specific context - that, the result of evaluating GETDATE()
within the context of a single query is often considered to be constant. I don't know of many people (unlike the blog author) who would consider a separate expression inside a UDF to be part of the same query as the query that calls the UDF.
public static class MyGlobals
{
public static string Global1 = "Hello";
public static string Global2 = "World";
}
public class Foo
{
private void Method1()
{
string example = MyGlobals.Global1;
//etc
}
}
The accepted answer doesn't work for multi-line text.
I updated the JSfiddle to show CSS multiline text vertical align as explained here:
<div id="column-content">
<div>yet another text content that should be centered vertically</div>
</div>
#column-content {
border: 1px solid red;
height: 200px;
width: 100px;
}
div {
display: table-cell;
vertical-align:middle;
text-align: center;
}
It also works with <br />
in "yet another..."
window.location
adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.
window.location.replace
replaces the current history item so you can't go back to it.
See window.location
:
assign(url)
: Load the document at the provided URL.
replace(url)
:Replace the current document with the one at the provided URL. The difference from theassign()
method is that after usingreplace()
the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.
Oh and generally speaking:
window.location.href = url;
is favoured over:
window.location = url;
SHOW INDEX FROM mytable FROM mydb;
SHOW INDEX FROM mydb.mytable;
See documentation.
If you have two columns with the same name. One simple way is to manually rename the columns like this:-
df.columns = ['column1', 'column2', 'column3']
Then you can drop via column index as you requested, like this:-
df.drop(df.columns[1], axis=1, inplace=True)
df.column[1]
will drop index 1.
Remember axis 1 = columns and axis 0 = rows.
The suggested technique above in Dave's answer is certainly a good design practice, and yes ultimately the required permission must be set in the AndroidManifest.xml file to access the external storage.
However, the Mono-esque way to add most (if not all, not sure) "manifest options" is through the attributes of the class implementing the activity (or service).
The Visual Studio Mono plugin automatically generates the manifest, so its best not to manually tamper with it (I'm sure there are cases where there is no other option).
For example:
[Activity(Label="MonoDroid App", MainLauncher=true, Permission="android.permission.WRITE_EXTERNAL_STORAGE")]
public class MonoActivity : Activity
{
protected override void OnCreate(Bundle bindle)
{
base.OnCreate(bindle);
}
}
If you need a directive more advanced, I recomend the solution that I implemnted, correctly tested on Internet Explorer 11, Chrome and FireFox.
I hope it, will be helpfull.
HTML :
<a href="#" class="btn btn-default" file-name="'fileName.extension'" ng-click="getFile()" file-download="myBlobObject"><i class="fa fa-file-excel-o"></i></a>
DIRECTIVE :
directive('fileDownload',function(){
return{
restrict:'A',
scope:{
fileDownload:'=',
fileName:'=',
},
link:function(scope,elem,atrs){
scope.$watch('fileDownload',function(newValue, oldValue){
if(newValue!=undefined && newValue!=null){
console.debug('Downloading a new file');
var isFirefox = typeof InstallTrigger !== 'undefined';
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
var isIE = /*@cc_on!@*/false || !!document.documentMode;
var isEdge = !isIE && !!window.StyleMedia;
var isChrome = !!window.chrome && !!window.chrome.webstore;
var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
var isBlink = (isChrome || isOpera) && !!window.CSS;
if(isFirefox || isIE || isChrome){
if(isChrome){
console.log('Manage Google Chrome download');
var url = window.URL || window.webkitURL;
var fileURL = url.createObjectURL(scope.fileDownload);
var downloadLink = angular.element('<a></a>');//create a new <a> tag element
downloadLink.attr('href',fileURL);
downloadLink.attr('download',scope.fileName);
downloadLink.attr('target','_self');
downloadLink[0].click();//call click function
url.revokeObjectURL(fileURL);//revoke the object from URL
}
if(isIE){
console.log('Manage IE download>10');
window.navigator.msSaveOrOpenBlob(scope.fileDownload,scope.fileName);
}
if(isFirefox){
console.log('Manage Mozilla Firefox download');
var url = window.URL || window.webkitURL;
var fileURL = url.createObjectURL(scope.fileDownload);
var a=elem[0];//recover the <a> tag from directive
a.href=fileURL;
a.download=scope.fileName;
a.target='_self';
a.click();//we call click function
}
}else{
alert('SORRY YOUR BROWSER IS NOT COMPATIBLE');
}
}
});
}
}
})
IN CONTROLLER:
$scope.myBlobObject=undefined;
$scope.getFile=function(){
console.log('download started, you can show a wating animation');
serviceAsPromise.getStream({param1:'data1',param1:'data2', ...})
.then(function(data){//is important that the data was returned as Aray Buffer
console.log('Stream download complete, stop animation!');
$scope.myBlobObject=new Blob([data],{ type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
},function(fail){
console.log('Download Error, stop animation and show error message');
$scope.myBlobObject=[];
});
};
IN SERVICE:
function getStream(params){
console.log("RUNNING");
var deferred = $q.defer();
$http({
url:'../downloadURL/',
method:"PUT",//you can use also GET or POST
data:params,
headers:{'Content-type': 'application/json'},
responseType : 'arraybuffer',//THIS IS IMPORTANT
})
.success(function (data) {
console.debug("SUCCESS");
deferred.resolve(data);
}).error(function (data) {
console.error("ERROR");
deferred.reject(data);
});
return deferred.promise;
};
BACKEND(on SPRING):
@RequestMapping(value = "/downloadURL/", method = RequestMethod.PUT)
public void downloadExcel(HttpServletResponse response,
@RequestBody Map<String,String> spParams
) throws IOException {
OutputStream outStream=null;
outStream = response.getOutputStream();//is important manage the exceptions here
ObjectThatWritesOnOutputStream myWriter= new ObjectThatWritesOnOutputStream();// note that this object doesn exist on JAVA,
ObjectThatWritesOnOutputStream.write(outStream);//you can configure more things here
outStream.flush();
return;
}
Just adding some talking points as someone who uses Firebug / Chrome Inspector every day:
At the time of writing, there's only Google DOM inspector and no it doesn't have all the features of Firebug
Inspector is a 'lite' version of Firebug: The interface is not as good IMO, element inspection in both recent versions is now clunky, but Firebug is still better; I find myself trying to find the love for Chrome (since it's a better, faster browser experience), but for development work, it still just sucks for me.
Live preview / modification of DOM / CSS is still way better in Firebug; calculated CSS and box model view are better in Firebug;
Somehow it's just easier to read/use Firebug maybe because of the ease of navigating, manipulating/modifying the document in several key areas? Who knows. I'm used to the interface and I think Chrome Inspector is not as good although this is a subjective thing I admit.
The Cookies/Net tab are extremely useful to me in Firebug. Maybe Chrome Inspector has this now? Last time I checked it did not, because Chrome updates itself in the background without your intervention (gets your consent by default like all good overlords).
Last point: The day that Google Chrome gets a fully-featured Firebug is the day Firefox basically dies for developers because Firefox had 3 years to make Firefox's layout engine Gecko as fast as WebKit and they didn't. Sorry to put it so bluntly but it's the truth.
You see, now everyone wants to move away from Flash in lieu of jQuery motivated by mobile accessibility and interactivity (iPhone, iPad, Android) and JavaScript is 'suddenly' a big deal (that's sarcasm), so that ship has sailed, Firefox. And that makes me sad, as a Mozilla fanperson. Chrome is simply a better browser until Firefox upgrades their JavaScript engine.
If I am not mistaken, it will be onunload event.
"Occurs when the application is about to be unloaded." - MSDN
You can use the following approach:
[lower + x*(upper-lower)/length for x in range(length)]
lower and/or upper must be assigned as floats for this approach to work.
Use zip(*list)
:
>>> l = [(1,2), (3,4), (8,9)]
>>> list(zip(*l))
[(1, 3, 8), (2, 4, 9)]
The zip()
function pairs up the elements from all inputs, starting with the first values, then the second, etc. By using *l
you apply all tuples in l
as separate arguments to the zip()
function, so zip()
pairs up 1
with 3
with 8
first, then 2
with 4
and 9
. Those happen to correspond nicely with the columns, or the transposition of l
.
zip()
produces tuples; if you must have mutable list objects, just map()
the tuples to lists or use a list comprehension to produce a list of lists:
map(list, zip(*l)) # keep it a generator
[list(t) for t in zip(*l)] # consume the zip generator into a list of lists
1) You can put your favicon where you want and add this tag to your page head
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
although some browsers will try to get the favicon from /favicon.ico by default, so you should use the IgnoreRoute.
2) If a browser makes a request for the favicon in another directory it will get a 404 error wich is fine and if you have the link tag in answer 1 in your master page the browser will get the favicon you want.
A useful shortcut from inside Sublime Text:
cmd-shift-P --> Browse Packages Now open user folder.
Its better to understand by trying your own code...
Read more
http://www.stupidcodes.com/2014/04/convert-string-to-uppercase-proper-case.html
1) Convert a String to Uppercase
string lower = "converted from lowercase";
Console.WriteLine(lower.ToUpper());
2) Convert a String to Lowercase
string upper = "CONVERTED FROM UPPERCASE";
Console.WriteLine(upper.ToLower());
3) Convert a String to TitleCase
CultureInfo cultureInfo = Thread.CurrentThread.CurrentCulture;
TextInfo textInfo = cultureInfo.TextInfo;
string txt = textInfo.ToTitleCase(TextBox1.Text());
If you are not too worried about browser support, there is a way to rebind the 'this' reference in the function called by the event. It will normally point to the element that generated the event when the function is executed, which is not always what you want. The tricky part is to at the same time be able to remove the very same event listener, as shown in this example: http://jsfiddle.net/roenbaeck/vBYu3/
/*
Testing that the function returned from bind is rereferenceable,
such that it can be added and removed as an event listener.
*/
function MyImportantCalloutToYou(message, otherMessage) {
// the following is necessary as calling bind again does
// not return the same function, so instead we replace the
// original function with the one bound to this instance
this.swap = this.swap.bind(this);
this.element = document.createElement('div');
this.element.addEventListener('click', this.swap, false);
document.body.appendChild(this.element);
}
MyImportantCalloutToYou.prototype = {
element: null,
swap: function() {
// now this function can be properly removed
this.element.removeEventListener('click', this.swap, false);
}
}
The code above works well in Chrome, and there's probably some shim around making "bind" compatible with other browsers.
Here 2 ways to do it:
set.seed(1)
tt <- sample(letters,100,rep=TRUE)
## using table
table(tt)
tt
a b c d e f g h i j k l m n o p q r s t u v w x y z
2 3 3 3 2 4 6 1 6 5 6 4 7 2 2 2 5 4 5 3 8 4 5 4 3 1
## using tapply
tapply(tt,tt,length)
a b c d e f g h i j k l m n o p q r s t u v w x y z
2 3 3 3 2 4 6 1 6 5 6 4 7 2 2 2 5 4 5 3 8 4 5 4 3 1
You may add a div with position:absolute
within a table/div with position:relative
. For example, if you want your overlay div to be shown at the bottom right of the main text div (width and height can be removed):
<div style="position:relative;width:300px;height:300px;background-color:#eef">
<div style="position:absolute;bottom:0;right:0;width:100px;height:100px;background-color:#fee">
I'm over you!
</div>
Your main text
</div>
See it here: http://jsfiddle.net/bptvt5kb/
It is indeed possible to change a div
elements' width in jQuery:
$("#div").css("width", "300px");
However, what you're describing can be better and more effectively achieved in CSS by setting a width as a percentage:
#div {
width: 75%;
/* You can also specify min/max widths */
min-width: 300px;
max-width: 960px;
}
This div will then always be 75% the width of the screen, unless the screen width means the div will be smaller than 300px, or bigger than 960px.
You are assigning a numeric value to a text field. You have to convert the numeric value to a string with:
String.valueOf(variable)
Try setting contentPadding
ListTile(
contentPadding: EdgeInsets.all(0.0),
...
)
As of Jquery 3.0 and above .bind has been deprecated and they prefer using .on instead. As @Blazemonger answered earlier that it may be removed and its for sure that it will be removed. For the older versions .bind would also call .on internally and there is no difference between them. Please also see the api for more detail.
If in addition you want to pipe the output to a separate file, you can do:
On a Sun JVM:
-Xloggc:C:\whereever\jvm.log -verbose:gc -XX:+PrintGCDateStamps
ON an IBM JVM:
-Xverbosegclog:C:\whereever\jvm.log
The invalid hostname indicates that the actual site you configured in the IIS Express configuration file is (most likely) not running. IIS Express doesn't have a process model like IIS does.
For your site to run it would need to be started explicitly (either by opening and accessing from webmatrix, or from command line calling iisexpress.exe (from it's installation directory) with the /site parameter.
In general, the steps to allow fully qualified DNS names to be used for local access are Let's use your example of the DNS name dev.example.com
Configure IIS Express binding for your site (eg:Site1) to include dev.example.com. Administrative privilege will be needed to use the binding. Alternatively, a one-time URL reservation can be made with http.sys using
netsh http add urlacl url=http://dev.example.com:<port>/ user=<user_name>
start iisexpress /site:Site1
or open Site1 in WebMatrix
Go to the "Database" option you mentioned.
Copied from here.
The gradle included with Android Studio is located in /Applications/Android Studio.app/plugins/gradle/lib
To go into the Android Studio.app directory I did cd "Android Studio.app"
or you could just do cd /Applications/Android\ Studio.app/plugins/gradle/lib
You can also use the "custom options" support from the request library. This format allows you to create a multi-part form upload, but with a combined entry for both the file and extra form information, like filename or content-type. I have found that some libraries expect to receive file uploads using this format, specifically libraries like multer.
This approach is officially documented in the forms section of the request docs - https://github.com/request/request#forms
//toUpload is the name of the input file: <input type="file" name="toUpload">
let fileToUpload = req.file;
let formData = {
toUpload: {
value: fs.createReadStream(path.join(__dirname, '..', '..','upload', fileToUpload.filename)),
options: {
filename: fileToUpload.originalname,
contentType: fileToUpload.mimeType
}
}
};
let options = {
url: url,
method: 'POST',
formData: formData
}
request(options, function (err, resp, body) {
if (err)
cb(err);
if (!err && resp.statusCode == 200) {
cb(null, body);
}
});
You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.
Have you tried using System.Net.IPAddress just in case?
System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1"); //127.0.0.1 as an example
The docs on Microsoft's site have a complete example which works fine on my machine.
Minor variation of phillfri's answer which was already a variation of Geoff's answer: I added the ability to handle completely empty tables that contain no data for the Array Code.
Sub AddDataRow(tableName As String, NewData As Variant)
Dim sheet As Worksheet
Dim table As ListObject
Dim col As Integer
Dim lastRow As Range
Set sheet = Range(tableName).Parent
Set table = sheet.ListObjects.Item(tableName)
'First check if the last row is empty; if not, add a row
If table.ListRows.Count > 0 Then
Set lastRow = table.ListRows(table.ListRows.Count).Range
If Application.CountBlank(lastRow) < lastRow.Columns.Count Then
table.ListRows.Add
End If
End If
'Iterate through the last row and populate it with the entries from values()
If table.ListRows.Count = 0 Then 'If table is totally empty, set lastRow as first entry
table.ListRows.Add Position:=1
Set lastRow = table.ListRows(1).Range
Else
Set lastRow = table.ListRows(table.ListRows.Count).Range
End If
For col = 1 To lastRow.Columns.Count
If col <= UBound(NewData) + 1 Then lastRow.Cells(1, col) = NewData(col - 1)
Next col
End Sub
I was facing the same problem. I used e.getCause().getCause() then I found that it was because of wrong parameters I was passing. There was nullPointerException in fetching the value of one of the parameters. Hope this will help you.
I had dialog showing function:
void showDialog(){
new AlertDialog.Builder(MyActivity.this)
...
.show();
}
I was getting this error and i just had to check isFinishing()
before calling this dialog showing function.
if(!isFinishing())
showDialog();
I recommend trying Kestrel, it's fast and simple as Beanstalk but supports fanout queues. Speaks memcached. It's built using Scala and used at Twitter.
From the MSDN page:
OPENQUERY does not accept variables for its arguments
Fundamentally, this means you cannot issue a dynamic query. To achieve what your sample is attempting, try this:
SELECT * FROM
OPENQUERY([NameOfLinkedSERVER], 'SELECT * FROM TABLENAME') T1
INNER JOIN
MYSQLSERVER.DATABASE.DBO.TABLENAME T2 ON T1.PK = T2.PK
where
T1.field1 = @someParameter
Clearly if your TABLENAME table contains a large amount of data, this will go across the network too and performance might be poor. On the other hand, for a small amount of data, this works well and avoids the dynamic sql construction overheads (sql injection, escaping quotes) that an exec
approach might require.
You should use a KeyGenerator to generate the Key,
AES key lengths are 128, 192, and 256 bit depending on the cipher you want to use.
Take a look at the tutorial here
Here is the code for Password Based Encryption, this has the password being entered through System.in you can change that to use a stored password if you want.
PBEKeySpec pbeKeySpec;
PBEParameterSpec pbeParamSpec;
SecretKeyFactory keyFac;
// Salt
byte[] salt = {
(byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c,
(byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99
};
// Iteration count
int count = 20;
// Create PBE parameter set
pbeParamSpec = new PBEParameterSpec(salt, count);
// Prompt user for encryption password.
// Collect user password as char array (using the
// "readPassword" method from above), and convert
// it into a SecretKey object, using a PBE key
// factory.
System.out.print("Enter encryption password: ");
System.out.flush();
pbeKeySpec = new PBEKeySpec(readPassword(System.in));
keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);
// Create PBE Cipher
Cipher pbeCipher = Cipher.getInstance("PBEWithMD5AndDES");
// Initialize PBE Cipher with key and parameters
pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
// Our cleartext
byte[] cleartext = "This is another example".getBytes();
// Encrypt the cleartext
byte[] ciphertext = pbeCipher.doFinal(cleartext);
The below code works for all the screens :
.jumbotron {
background: url('backgroundimage.jpg') no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
background-size: cover;
-o-background-size: cover;
}
The cover property will resize the background image to cover the entire container, even if it has to stretch the image or cut a little bit off one of the edges.
Not valid HTML, anyway pretty much every browser seems to consider just the second instance.
Tested under the last versions of FF and Google Chrome under Fedora, and FF, Opera, IE, and Chrome under XP.
If you get "undefined" to all of your console.log calls, that probably means you still have an old firebuglite loaded (firebug.js). It will override all the valid functions of IE8's console.log even though they do exist. This is what happened to me anyway.
Check for other code overriding the console object.
hasOwnProperty
is a normal JavaScript function that takes a string argument.
When you call shape1.hasOwnProperty(name)
you are passing it the value of the name
variable (which doesn't exist), just as it would if you wrote alert(name)
.
You need to call hasOwnProperty
with a string containing name
, like this: shape1.hasOwnProperty("name")
.
Don't forget the !important
declaration, for a better result
button:focus {outline:0 !important;}
A rule that has the !important property will always be applied no matter where that rule appears in the CSS document.
This already has good answers for most purposes, but I'll add mine which is more specific.
In English, normally when we alphabetise, we ignore the word "the" at the beginning of a phrase. So "The United States" would be ordered under "U" and not "T".
This does that for you.
It would probably be best to put these in categories.
// Sort an array of NSStrings alphabetically, ignoring the word "the" at the beginning of a string.
-(NSArray*) sortArrayAlphabeticallyIgnoringThes:(NSArray*) unsortedArray {
NSArray * sortedArray = [unsortedArray sortedArrayUsingComparator:^NSComparisonResult(NSString* a, NSString* b) {
//find the strings that will actually be compared for alphabetical ordering
NSString* firstStringToCompare = [self stringByRemovingPrecedingThe:a];
NSString* secondStringToCompare = [self stringByRemovingPrecedingThe:b];
return [firstStringToCompare compare:secondStringToCompare];
}];
return sortedArray;
}
// Remove "the"s, also removes preceding white spaces that are left as a result. Assumes no preceding whitespaces to start with. nb: Trailing white spaces will be deleted too.
-(NSString*) stringByRemovingPrecedingThe:(NSString*) originalString {
NSString* result;
if ([[originalString substringToIndex:3].lowercaseString isEqualToString:@"the"]) {
result = [[originalString substringFromIndex:3] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
}
else {
result = originalString;
}
return result;
}
It's about Shebang
#!usr/bin/python
This will tell which interpreter to wake up to run the code written in file.
The answer by @chepner will copy all the sub-directories irrespective of the fact if it contains the file or not. If you need to exclude the sub-directories that dont contain the file and still retain the directory structure, use
rsync -zarv --prune-empty-dirs --include "*/" --include="*.sh" --exclude="*" "$from" "$to"
Another thing use "", there is a difference between "\r\n" and '\r\n'.
This ought to work:
^\d+\s?(\([^\)]+\)\s?)?Z$
Haven't tested it though, but let me give you the breakdown, so if there are any bugs left they should be pretty straightforward to find:
First the beginning:
^ = beginning of string
\d+ = one or more decimal characters
\s? = one optional whitespace
Then this part:
(\([^\)]+\)\s?)?
Is actually:
(.............)?
Which makes the following contents optional, only if it exists fully
\([^\)]+\)\s?
\( = an opening bracket
[^\)]+ = a series of at least one character that is not a closing bracket
\) = followed by a closing bracket
\s? = followed by one optional whitespace
And the end is made up of
Z$
Where
Z = your constant string
$ = the end of the string
You need to call p.Start() to actually run the process after you set the StartInfo. As it is, your function is probably hanging on the WaitForExit() call because the process was never actually started.
You shouldn't be closing the serial port in Python between writing and reading. There is a chance that the port is still closed when the Arduino responds, in which case the data will be lost.
while running:
# Serial write section
setTempCar1 = 63
setTempCar2 = 37
setTemp1 = str(setTempCar1)
setTemp2 = str(setTempCar2)
print ("Python value sent: ")
print (setTemp1)
ard.write(setTemp1)
time.sleep(6) # with the port open, the response will be buffered
# so wait a bit longer for response here
# Serial read section
msg = ard.read(ard.inWaiting()) # read everything in the input buffer
print ("Message from arduino: ")
print (msg)
The Python Serial.read
function only returns a single byte by default, so you need to either call it in a loop or wait for the data to be transmitted and then read the whole buffer.
On the Arduino side, you should consider what happens in your loop
function when no data is available.
void loop()
{
// serial read section
while (Serial.available()) // this will be skipped if no data present, leading to
// the code sitting in the delay function below
{
delay(30); //delay to allow buffer to fill
if (Serial.available() >0)
{
char c = Serial.read(); //gets one byte from serial buffer
readString += c; //makes the string readString
}
}
Instead, wait at the start of the loop
function until data arrives:
void loop()
{
while (!Serial.available()) {} // wait for data to arrive
// serial read section
while (Serial.available())
{
// continue as before
EDIT 2
Here's what I get when interfacing with your Arduino app from Python:
>>> import serial
>>> s = serial.Serial('/dev/tty.usbmodem1411', 9600, timeout=5)
>>> s.write('2')
1
>>> s.readline()
'Arduino received: 2\r\n'
So that seems to be working fine.
In testing your Python script, it seems the problem is that the Arduino resets when you open the serial port (at least my Uno does), so you need to wait a few seconds for it to start up. You are also only reading a single line for the response, so I've fixed that in the code below also:
#!/usr/bin/python
import serial
import syslog
import time
#The following line is for serial over GPIO
port = '/dev/tty.usbmodem1411' # note I'm using Mac OS-X
ard = serial.Serial(port,9600,timeout=5)
time.sleep(2) # wait for Arduino
i = 0
while (i < 4):
# Serial write section
setTempCar1 = 63
setTempCar2 = 37
ard.flush()
setTemp1 = str(setTempCar1)
setTemp2 = str(setTempCar2)
print ("Python value sent: ")
print (setTemp1)
ard.write(setTemp1)
time.sleep(1) # I shortened this to match the new value in your Arduino code
# Serial read section
msg = ard.read(ard.inWaiting()) # read all characters in buffer
print ("Message from arduino: ")
print (msg)
i = i + 1
else:
print "Exiting"
exit()
Here's the output of the above now:
$ python ardser.py
Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1
Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1
Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1
Python value sent:
63
Message from arduino:
Arduino received: 63
Arduino sends: 1
Exiting
You can do a LEFT JOIN and assert the joined column is NULL.
Example:
SELECT * FROM employees a LEFT JOIN eotm_dyn b on (a.joinfield=b.joinfield) WHERE b.name IS NULL
/*
Include this after bootstrap.css
Add a class of 'col-xs-offset-*' and
if you want to disable the offset at a larger size add in 'col-*-offset-0'
Examples:
All display sizes (xs,sm,md,lg) have an offset of 1
<div class="col-xs-11 col-xs-offset-1 col-sm-3">
xs has an offset of 1
<div class="col-xs-11 col-xs-offset-1 col-sm-offset-0 col-sm-3">
xs and sm have an offset of 1
<div class="col-xs-11 col-xs-offset-1 col-md-offset-0 col-sm-3">
xs, sm and md will have an offset of 1
<div class="col-xs-11 col-xs-offset-1 col-lg-offset-0 col-sm-3">
*/
.col-xs-offset-12 {
margin-left: 100%;
}
.col-xs-offset-11 {
margin-left: 91.66666666666666%;
}
.col-xs-offset-10 {
margin-left: 83.33333333333334%;
}
.col-xs-offset-9 {
margin-left: 75%;
}
.col-xs-offset-8 {
margin-left: 66.66666666666666%;
}
.col-xs-offset-7 {
margin-left: 58.333333333333336%;
}
.col-xs-offset-6 {
margin-left: 50%;
}
.col-xs-offset-5 {
margin-left: 41.66666666666667%;
}
.col-xs-offset-4 {
margin-left: 33.33333333333333%;
}
.col-xs-offset-3 {
margin-left: 25%;
}
.col-xs-offset-2 {
margin-left: 16.666666666666664%;
}
.col-xs-offset-1 {
margin-left: 8.333333333333332%;
}
.col-xs-offset-0 {
margin-left: 0;
}
/* Ensure that all of the zero offsets are available - recent SASS version did not include .col-sm-offset-0 */
@media (min-width: 768px) {
.col-sm-offset-0,
.col-md-offset-0,
.col-lg-offset-0 {
margin-left: 0;
}
}
You must create a migration, where you will specify default value for a new field, since you don't want it to be null. If null is not required, simply add null=True
and create and run migration.
Well, usually it is good to avoid asynchronous file operations. Here is the short (i.e. no error handling) sync example:
var fs = require('fs');
fs.writeFileSync(targetFile, fs.readFileSync(sourceFile));
You can use tools own browser (Firefox, IE, Chrome...) to debug your JavaScript.
As for resizing, Firefox/Chrome has own resources accessible via Ctrl + Shift + I OR F12. Going tab "style editor" and clicking "adaptive/responsive design" icon.
Old Firefox versions
New Firefox/Firebug
Chrome
*Another way is to install an addon like "Web Developer"
We weren't happy with any of the purposed solutions.
So we've created a complete char counter solution for JQuery, built on top of jquery-jeditable. It's a textarea
plugin extension that can count to both ways, displays a custom message, limits char count and also supports jquery-datatables.
You can test it right away on JSFiddle.
GitHub link: https://github.com/HippotecLTD/realworld_jquery_jeditable_charcount
Add these lines to your HTML:
<script async src="https://cdn.jsdelivr.net/gh/HippotecLTD/[email protected]/dist/jquery.jeditable.charcounter.realworld.min.js"></script>
<script async src="https://cdn.jsdelivr.net/gh/HippotecLTD/[email protected]/dist/jquery.charcounter.realworld.min.js"></script>
And then:
$("#myTextArea4").charCounter();
<div id="clockbox" style="font:14pt Arial; color:#FF0000;text-align: center; border:1px solid red;background:cyan; height:50px;padding-top:12px;"></div>
I was using pgAdmin to create my tables and while I was not using reserved words, the generated table had a quote in the name and a couple of columns had quotes in them. Here is an example of the generated SQL.
CREATE TABLE public."Test"
(
id serial NOT NULL,
data text NOT NULL,
updater character varying(50) NOT NULL,
"updateDt" time with time zone NOT NULL,
CONSTRAINT test_pk PRIMARY KEY (id)
)
TABLESPACE pg_default;
ALTER TABLE public."Test"
OWNER to svc_newnews_app;
All of these quotes were inserted at "random". I just needed to drop and re-create the table again without the quotes.
Tested on pgAdmin 4.26
for jQuery
we can use below:
by input name:
$('input[name="textboxname"]').val('some value');
by input class:
$('input[type=text].textboxclass').val('some value');
by input id:
$('#textboxid').val('some value');
This is common problem for asterisk and this works for me
sudo su
/etc/init.d/asterisk start
asterisk -rvvv
If not working stop it
sudo su
/etc/init.d/asterisk stop
Start it again
sudo su
/etc/init.d/asterisk start
asterisk -rvvv
That is all
Calendar cal = Calendar.getInstance();
cal.add(Calendar.MONTH, 1);
java.util.Date dt = cal.getTime();
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.
<TextBlock Text="Stuff on line1
Stuff on line 2"/>
You can use any hexadecimally encoded value to represent a literal. In this case, I used the line feed (char 10). If you want to do "classic" vbCrLf
, then you can use 

By the way, note the syntax: It's the ampersand, a pound, the letter x, then the hex value of the character you want, and then finally a semi-colon.
ALSO: For completeness, you can bind to a text that already has the line feeds embedded in it like a constant in your code behind, or a variable constructed at runtime.
Java objects reside in an area called the heap, while metadata such as class objects and method objects reside in the permanent generation or Perm Gen area. The permanent generation is not part of the heap.
The heap is created when the JVM starts up and may increase or decrease in size while the application runs. When the heap becomes full, garbage is collected. During the garbage collection objects that are no longer used are cleared, thus making space for new objects.
-Xmssize Specifies the initial heap size.
-Xmxsize Specifies the maximum heap size.
-XX:MaxPermSize=size Sets the maximum permanent generation space size. This option was deprecated in JDK 8, and superseded by the -XX:MaxMetaspaceSize option.
Sizes are expressed in bytes. Append the letter k
or K
to indicate kilobytes, m
or M
to indicate megabytes, g
or G
to indicate gigabytes.
How is the java memory pool divided?
Java (JVM) Memory Model – Memory Management in Java
Suppose this is your json
{
"date":"11/05/2016",
"venue": "{\"ID\":12,\"CITY\":Delhi}"
}
if you again want deserialize venue, modify json as below
{
"date":"11/05/2016",
"venue": "{\"ID\":\"12\",\"CITY\":\"Delhi\"}"
}
then try to deserialize to respective class by taking the value of venue
If you can use apache.commons.lang in your project, the easiest way would be just to use the method provided there:
public static boolean containsWhitespace(CharSequence seq)
Check whether the given CharSequence contains any whitespace characters.
Parameters:
seq - the CharSequence to check (may be null)
Returns:
true if the CharSequence is not empty and contains at least 1 whitespace character
It handles empty and null parameters and provides the functionality at a central place.
Below code(jQuery.isEmptyObject(anyObject) function is already provided) works perfectly fine, no need to write one of your own.
// works for any Object Including JSON(key value pair) or Array.
// var arr = [];
// var jsonObj = {};
if (jQuery.isEmptyObject(anyObjectIncludingJSON))
{
console.log("Empty Object");
}
Go to the folder in which you have Node and NPM (such as C:\Program Files (x86)\nodejs\
) and type the following:
> set path=%PATH%;%CD%
> setx path "%PATH%"
From http://www.hacksparrow.com/install-node-js-and-npm-on-windows.html
Another way of doing this is using Uri.EscapeUriString(stringToEscape)
.
One NuGet package can reference another NuGet package. So, please be very careful about inter-package dependencies. I just uninstalled a Google map package and it subsequently uninstalled underlying packages like Newtonsoft, Entity Framework, etc.
So, manually deleting particular package from packages folder would be safer.
Jon Skeet has written a library called morelinq which has a DistinctBy()
operator. See here for the implementation. Your code would look like
IEnumerable<Note> distinctNotes = Notes.DistinctBy(note => note.Author);
Update: After re-reading your question, Kirk has the correct answer if you're just looking for a distinct set of Authors.
Added sample, several fields in DistinctBy:
res = res.DistinctBy(i => i.Name).DistinctBy(i => i.ProductId).ToList();
This is the pattern I usually follow when setting up a harness for testing an abstract class:
public abstract class MyBase{
/*...*/
public abstract void VoidMethod(object param1);
public abstract object MethodWithReturn(object param1);
/*,,,*/
}
And the version I use under test:
public class MyBaseHarness : MyBase{
/*...*/
public Action<object> VoidMethodFunction;
public override void VoidMethod(object param1){
VoidMethodFunction(param1);
}
public Func<object, object> MethodWithReturnFunction;
public override object MethodWithReturn(object param1){
return MethodWihtReturnFunction(param1);
}
/*,,,*/
}
If the abstract methods are called when I don't expect it, the tests fail. When arranging the tests, I can easily stub out the abstract methods with lambdas that perform asserts, throw exceptions, return different values, etc.
If it is just about the color and there is no specific need for JavaScript, you could also convert them to a font. This link gives you an opportunity to create a font based on the SVG. However, it is not possible to use img attributes afterwards - like "alt". This also limits the accessibility of your website for blind people and so on.
Make sure that your IntelliJ Idea (IDE) is aware of all the necessary spring configurations that your module is being inspected against.
You can check this under
File > Project Structure > Modules > [your project name in the right panel] > Spring
Sometimes, we need to explicitly tell the IDE that the spring configuration is coming from a dependency (a jar present in your project classpath)
By default, on many platforms the short will be aligned to an offset at a multiple of 2, so there will be a padding byte added after the char.
To disable this, use: struct.unpack("=BH", data)
. This will use standard alignment, which doesn't add padding:
>>> struct.calcsize('=BH')
3
The =
character will use native byte ordering. You can also use <
or >
instead of =
to force little-endian or big-endian byte ordering, respectively.
When I had to solve this problem, I created a hard-coded data dictionary to map between numbers and their associated words. For example, the following might represent a few entries in the dictionary:
{1, "one"}
{2, "two"}
{30, "thirty"}
You really only need to worry about mapping numbers in the 10^0 (1,2,3, etc.) and 10^1 (10,20,30) positions because once you get to 100, you simply have to know when to use words like hundred, thousand, million, etc. in combination with your map. For example, when you have a number like 3,240,123, you get: three million two hundred forty thousand one hundred twenty three.
After you build your map, you need to work through each digit in your number and figure out the appropriate nomenclature to go with it.
The most comfortable way to preview HTML files on GitHub is to go to https://htmlpreview.github.io/ or just prepend it to the original URL, i.e.: https://htmlpreview.github.io/?https://github.com/bartaz/impress.js/blob/master/index.html
Most windows users won't have that font on their computers. Also, you can't just submit it to your server and call it using font-face because this isn't a free font...
And last, but not least, answering the question that nobody mentioned yet, Helvetica and Helvetica Neue do not render well on screen unless they have a really big font-size
. You'll find a lot of pages using this font, and in all of them you'll see that the top border of a line of text looks wavy and that some letters look taller than others. In my opinion this is the main reason why you shouldn't use it. There are other options for you to use, like Open Sans.
None of the above solutions worked for me. But this did:
myImage.Source = new BitmapImage(new Uri(@"/Images/foo.png", UriKind.Relative));
If what you need is that it will look like a button, with emphasis on the gradient image, you can do this:
<a href="www.yourlink.com" class="btn btn-gradient"><i class="fa fa-home"> Button Text</i></a>
"put" has been deprecated, refrain from using it, use .of instead
ImmutableMap<String, String> myMap = ImmutableMap.of(
"city1", "Seattle",
"city2", "Delhi"
);
To complement the existing, helpful answers; tip of the hat to QZ Support for encouraging me to post a separate answer:
Two distinct mechanisms come into play here:
(a) whether cut
itself requires the delimiter (space, in this case) passed to the -d
option to be a separate argument or whether it's acceptable to append it directly to -d
.
(b) how the shell generally parses arguments before passing them to the command being invoked.
(a) is answered by a quote from the POSIX guidelines for utilities (emphasis mine)
If the SYNOPSIS of a standard utility shows an option with a mandatory option-argument [...] a conforming application shall use separate arguments for that option and its option-argument. However, a conforming implementation shall also permit applications to specify the option and option-argument in the same argument string without intervening characters.
In other words: In this case, because -d
's option-argument is mandatory, you can choose whether to specify the delimiter as:
-d
.Once you've chosen (s) or (d), it is the shell's string-literal parsing - (b) - that matters:
With approach (s), all of the following forms are EQUIVALENT:
-d ' '
-d " "
-d \<space> # <space> used to represent an actual space for technical reasons
With approach (d), all of the following forms are EQUIVALENT:
-d' '
-d" "
"-d "
'-d '
d\<space>
The equivalence is explained by the shell's string-literal processing:
All solutions above result in the exact same string (in each group) by the time cut
sees them:
(s): cut
sees -d
, as its own argument, followed by a separate argument that contains a space char - without quotes or \
prefix!.
(d): cut
sees -d
plus a space char - without quotes or \
prefix! - as part of the same argument.
The reason the forms in the respective groups are ultimately identical is twofold, based on how the shell parses string literals:
'...'
is taken literally and forms a single argument"..."
also forms a single argument, but is subject to interpolation (expands variable references such as $var
, command substitutions ($(...)
or `...`
), or arithmetic expansions ($(( ... ))
).\
-quoting of individual characters: a \
preceding a single character causes that character to be interpreted as a literal.'...'
or "..."
or \
instances) - thus, the command being invoked never sees the quote characters.Found the port esp32 was connected to by -
ls /dev/*
You would get a long list and you can find the port you need
You can use MATCH
for instance.
Select the column from the first cell, for example cell A2 to cell A100 and insert a conditional formatting, using 'New Rule...' and the option to conditional format based on a formula.
In the entry box, put:
=MATCH(A2, 'Sheet2'!A:A, 0)
Pick the desired formatting (change the font to red or fill the cell background, etc) and click OK.
MATCH
takes the value A2
from your data table, looks into 'Sheet2'!A:A
and if there's an exact match (that's why there's a 0
at the end), then it'll return the row number.
Note: Conditional formatting based on conditions from other sheets is available only on Excel 2010 onwards. If you're working on an earlier version, you might want to get the list of 'Don't check' in the same sheet.
EDIT: As per new information, you will have to use some reverse matching. Instead of the above formula, try:
=SUM(IFERROR(SEARCH('Sheet2'!$A$1:$A$44, A2),0))
When using ES6 you can also do this:
var name = prompt("what is your name?");
console.log(`story ${name} story`);
Note: You need to use backticks `` instead of "" or '' to do it like this.
A more simple way is to use fire fox dev tools, console.log(yourObject) -> right click on object -> select "copy object" -> paste results into notepad
thanks.
A working example in widespread use is in modded Minecraft. See EnumHelper.addEnum() methods on Github
However, note that in rare situations practical experience has shown that adding Enum members can lead to some issues with the JVM optimiser. The exact issues may vary with different JVMs. But broadly it seems the optimiser may assume that some internal fields of an Enum, specifically the size of the Enum's .values()
array, will not change. See issue discussion. The recommended solution there is not to make .values()
a hotspot for the optimiser. So if adding to an Enum's members at runtime, it should be done once and once only when the application is initialised, and then the result of .values()
should be cached to avoid making it a hotspot.
The way the optimiser works and the way it detects hotspots is obscure and may vary between different JVMs and different builds of the JVM. If you don't want to take the risk of this type of issue in production code, then don't change Enums at runtime.