Try .replace(/ /g,"_");
Edit: or .split(' ').join('_')
if you have an aversion to REs
Edit: John Resig said:
If you're searching and replacing through a string with a static search and a static replace it's faster to perform the action with .split("match").join("replace") - which seems counter-intuitive but it manages to work that way in most modern browsers. (There are changes going in place to grossly improve the performance of .replace(/match/g, "replace") in the next version of Firefox - so the previous statement won't be the case for long.)
The API provides component
for this purpose.
<Button
variant="contained"
component="label"
>
Upload File
<input
type="file"
hidden
/>
</Button>
This is what I typically do:
File outputDir = context.getCacheDir(); // context being the Activity pointer
File outputFile = File.createTempFile("prefix", "extension", outputDir);
As for their deletion, I am not complete sure either. Since I use this in my implementation of a cache, I manually delete the oldest files till the cache directory size comes down to my preset value.
Just add to the CommandArgument
parameter and read it out on the Click
handler:
<asp:LinkButton ID="ENameLinkBtn" runat="server"
style="font-weight: 700; font-size: 8pt;" CommandArgument="YourValueHere"
OnClick="ENameLinkBtn_Click" >
Then in your click event:
protected void ENameLinkBtn_Click(object sender, EventArgs e)
{
LinkButton btn = (LinkButton)(sender);
string yourValue = btn.CommandArgument;
// do what you need here
}
Also you can set the CommandArgument
argument when binding if you are using the LinkButton
in any bindable controls by doing:
CommandArgument='<%# Eval("SomeFieldYouNeedArguementFrom") %>'
I know already answered but who looking for 'Fri' like this
for Fri -
SimpleDateFormat sdf = new SimpleDateFormat("EEE");
Date d = new Date();
String dayOfTheWeek = sdf.format(d);
and who wants full date string they can use 4E for Friday
For Friday-
SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
Date d = new Date();
String dayOfTheWeek = sdf.format(d);
Enjoy...
In swift you can do:
button.setImage(UIImage(named: "selected"),
forState: UIControlState.selected.union(.highlighted))
Here you can find info on how to upgrade to v3: http://tosbourn.com/2013/08/javascript/upgrading-from-bootstraps-typeahead-to-typeahead-js/
Here are some examples too: http://twitter.github.io/typeahead.js/examples/
Usually you can plug a Query's result (which is basically a table) as the FROM clause source of another query, so something like this will be written:
SELECT COUNT(*), SUM(SUBQUERY.AGE) from
(
SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age
FROM availables
INNER JOIN rooms
ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
GROUP BY availables.bookdate
) AS SUBQUERY
instead of this
UPDATE staff SET salary = 1200 WHERE name = 'Bob';
UPDATE staff SET salary = 1200 WHERE name = 'Jane';
UPDATE staff SET salary = 1200 WHERE name = 'Frank';
UPDATE staff SET salary = 1200 WHERE name = 'Susan';
UPDATE staff SET salary = 1200 WHERE name = 'John';
you can use
UPDATE staff SET salary = 1200 WHERE name IN ('Bob', 'Frank', 'John');
Try this solution, it takes an array of soundtracks and plays all of them, playlist-style, and even loops the playlist. The following uses a little Jquery to shorten getting the audio element. If you do not wish to use Jquery, replace the first line of the javascript with var audio = document.getElementById("audio");
and it will work the same.
Javascript:
var audio = $("#audio")[0];
var tracks = {
list: ["track_01.mp3", "track_02.mp3", "track_03.mp3"], //Put any tracks you want in this array
index: 0,
next: function() {
if (this.index == this.list.length - 1) this.index = 0;
else {
this.index += 1;
}
},
play: function() {
return this.list[this.index];
}
}
audio.onended = function() {
tracks.next();
audio.src = tracks.play();
audio.load();
audio.play();
}
audio.src = tracks.play();
HTML:
<audio id="audio" controls>
<source src="" />
</audio>
This will allow you to play as many songs as you want, in playlist style. Each song will start as soon as the previous one finishes. I do not believe this will work in Internet Explorer, but it's time to move on from that ancient thing anyways!
Just put any songs you want into the array tracks.list
and it will play all of them one after the other. It also loops back to the first song once it's finished with the last one.
It's shorter than many of the answers, it accounts for as many tracks as you want, it's easily understandable, and it actually loads the audio before playing it (so it actually works), so I thought I would include it here. I could not find any sound files to use in a running snippet, but I tested it with 3 of my own soundtracks on Chrome and it works. The onended
method, which detects the ended
event, also works on all browsers except Internet Explorer according to caniuse.
NOTE: Just to be clear, this works with both audio and video.
You can do it like this:
String.prototype.toDOM=function(){
var d=document
,i
,a=d.createElement("div")
,b=d.createDocumentFragment();
a.innerHTML=this;
while(i=a.firstChild)b.appendChild(i);
return b;
};
var foo="<img src='//placekitten.com/100/100'>foo<i>bar</i>".toDOM();
document.body.appendChild(foo);
It is best practice to always supply the permission when registering the receiver, otherwise you will receive for any application that sends a matching intent. This can allow malicious apps to broadcast to your receiver.
What you need is xml comments - basically, they follow this syntax (as vaguely described by Solmead):
C#
///<summary>
///This is a description of my function.
///</summary>
string myFunction() {
return "blah";
}
VB
'''<summary>
'''This is a description of my function.
'''</summary>
Function myFunction() As String
Return "blah"
End Function
If you would like to execute the parent controller's parentmethod function inside a child controller, call it:
$scope.$parent.parentmethod();
You can try it over here
The spec says seconds:
http://tools.ietf.org/html/draft-ietf-oauth-v2-22#section-4.2.2
expires_in
OPTIONAL. The lifetime in seconds of the access token. For
example, the value "3600" denotes that the access token will
expire in one hour from the time the response was generated.
I agree with OP that it's careless for Google to not document this.
No, that's not really possible, as
The goal of the MD5 and its family of hashing functions is
Think that you can get the MD5 of any string, even very long. And the MD5 is only 16 bytes long (32 if you write it in hexa to store or distribute it more easily). If you could reverse them, you'd have a magical compacting scheme.
This being said, as there aren't so many short strings (passwords...) used in the world, you can test them from a dictionary (that's called "brute force attack") or even google for your MD5. If the word is common and wasn't salted, you have a reasonable chance to succeed...
The required
property is boolean
:
$('form#register').find('input').each(function(){
if(!$(this).prop('required')){
console.log("NR");
} else {
console.log("IR");
}
});
Reference: HTMLInputElement
In IntelliJ IDEA:
In File Menu
? Project Structure
? Project
, change Project Language Level
to 8.0 - Lambdas, type annotations etc.
For Android 3.0+ Go File
? Project Structure
? Module
? app
and In Properties Tab set Source Compatibility
and Target Compatibility
to 1.8 (Java 8)
Screenshot:
The new versions of jQuery require this file http://code.jquery.com/jquery-1.10.2.min.map
The usability of this file is described here http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/
Update:
jQuery 1.11.0/2.1.0
// sourceMappingURL comment is not included in the compressed file.
The Key Differences Between Classification and Clustering are: Classification is the process of classifying the data with the help of class labels. On the other hand, Clustering is similar to classification but there are no predefined class labels. Classification is geared with supervised learning. As against, clustering is also known as unsupervised learning. Training sample is provided in the classification method while in the case of clustering training data is not provided.
Hope this will help!
Add this to <system.webServer>
in your web.config:
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
<remove name="OPTIONSVerbHandler"/>
<remove name="TRACEVerbHandler"/>
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0"/>
</handlers>
Adding <modules runAllManagedModulesForAllRequests="true" />
also works but is not recommended due performance issues.
netstat -ano | findstr :3010
taskkill /F /PID
But it won't work for me
then I tried taskkill -PID <processorid> -F
Example:- taskkill -PID 33192 -F
Here 33192 is the processorid and it works
As Shubham Jain stated, this is working to me: driver.findElement(By.id("invoice_supplier_id")).sendKeys("value"??, "new value");
Basically it contains all the attributes which describe the object in question. It can be used to alter or read the attributes.
Quoting from the documentation for __dict__
A dictionary or other mapping object used to store an object's (writable) attributes.
Remember, everything is an object in Python. When I say everything, I mean everything like functions, classes, objects etc (Ya you read it right, classes. Classes are also objects). For example:
def func():
pass
func.temp = 1
print(func.__dict__)
class TempClass:
a = 1
def temp_function(self):
pass
print(TempClass.__dict__)
will output
{'temp': 1}
{'__module__': '__main__',
'a': 1,
'temp_function': <function TempClass.temp_function at 0x10a3a2950>,
'__dict__': <attribute '__dict__' of 'TempClass' objects>,
'__weakref__': <attribute '__weakref__' of 'TempClass' objects>,
'__doc__': None}
Try this one
var NewDate = Convert.ToDateTime(DateTime.Now.ToString("dd/MMM/yyyy")+" "+"10:15 PM")/*Add your time here*/;
May be you used notepad++ for creating/updating this file.
EOL(Edit->EOL Conversion) Conversion by default is Windows.
Change EOL Conversion in Notepad++
Edit -> EOL Conversion -> Unix (LF)
Support for TLS 1.0 and 1.1 was dropped for PyPI. If your system does not use a more recent version, it could explain your error.
Could you try reinstalling pip system-wide, to update your system dependencies to a newer version of TLS?
This seems to be related to Unable to install Python libraries
See Dominique Barton's answer:
Apparently pip is trying to access PyPI via HTTPS (which is encrypted and fine), but with an old (insecure) SSL version. Your system seems to be out of date. It might help if you update your packages.
On Debian-based systems I'd try:
apt-get update && apt-get upgrade python-pip
On Red Hat Linux-based systems:
yum update python-pip # (or python2-pip, at least on Red Hat Linux 7)
On Mac:
sudo easy_install -U pip
You can also try to update
openssl
separately.
Since version 2.10, one can use Scala's string interpolation feature:
implicit class RegexOps(sc: StringContext) {
def r = new util.matching.Regex(sc.parts.mkString, sc.parts.tail.map(_ => "x"): _*)
}
scala> "123" match { case r"\d+" => true case _ => false }
res34: Boolean = true
Even better one can bind regular expression groups:
scala> "123" match { case r"(\d+)$d" => d.toInt case _ => 0 }
res36: Int = 123
scala> "10+15" match { case r"(\d\d)${first}\+(\d\d)${second}" => first.toInt+second.toInt case _ => 0 }
res38: Int = 25
It is also possible to set more detailed binding mechanisms:
scala> object Doubler { def unapply(s: String) = Some(s.toInt*2) }
defined module Doubler
scala> "10" match { case r"(\d\d)${Doubler(d)}" => d case _ => 0 }
res40: Int = 20
scala> object isPositive { def unapply(s: String) = s.toInt >= 0 }
defined module isPositive
scala> "10" match { case r"(\d\d)${d @ isPositive()}" => d.toInt case _ => 0 }
res56: Int = 10
An impressive example on what's possible with Dynamic
is shown in the blog post Introduction to Type Dynamic:
object T {
class RegexpExtractor(params: List[String]) {
def unapplySeq(str: String) =
params.headOption flatMap (_.r unapplySeq str)
}
class StartsWithExtractor(params: List[String]) {
def unapply(str: String) =
params.headOption filter (str startsWith _) map (_ => str)
}
class MapExtractor(keys: List[String]) {
def unapplySeq[T](map: Map[String, T]) =
Some(keys.map(map get _))
}
import scala.language.dynamics
class ExtractorParams(params: List[String]) extends Dynamic {
val Map = new MapExtractor(params)
val StartsWith = new StartsWithExtractor(params)
val Regexp = new RegexpExtractor(params)
def selectDynamic(name: String) =
new ExtractorParams(params :+ name)
}
object p extends ExtractorParams(Nil)
Map("firstName" -> "John", "lastName" -> "Doe") match {
case p.firstName.lastName.Map(
Some(p.Jo.StartsWith(fn)),
Some(p.`.*(\\w)$`.Regexp(lastChar))) =>
println(s"Match! $fn ...$lastChar")
case _ => println("nope")
}
}
onreadystatechange Stores a function (or the name of a function) to be called automatically each time the readyState property changes readyState Holds the status of the XMLHttpRequest. Changes from 0 to 4:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
status 200: "OK"
404: Page not found
I use Ubuntu linux, and in my case the error was caused by incorrect statement syntax (which I found out by typing perror 150 at the terminal, which gives
MySQL error code 150: Foreign key constraint is incorrectly formed
Changing the syntax of the query from
alter table scale add constraint foreign key (year_id) references year.id;
to
alter table scale add constraint foreign key (year_id) references year(id);
fixed it.
I like the answer given here:
http://stupidpythonideas.blogspot.com/2013/08/defaultdict-vs-setdefault.html
In short, the decision (in non-performance-critical apps) should be made on the basis of how you want to handle lookup of empty keys downstream (viz. KeyError
versus default value).
Design patterns are just tools--kind of like library functions. If you know that they are there and their approximate function, you can go dig them out of a book when needed.
There is nothing magic about design patterns, and any good programmer figured 90% of them out for themselves before any books came out. For the most part I consider the books to be most useful at simply defining names for the various patterns so we can discuss them more easily.
Any custom file extension can be associated with standard syntax highlighting with
custom files association
in User Settings as follows.
Note that this will be a permanent setting. In order to set for the current session alone, type in the preferred language in
Select Language Mode
box (without changingfile association
settings)
If the required syntax package is not available by default, you can add them via the Extension Marketplace (Ctrl+Shift+X) and search for the language package.
You can further reproduce the above steps to map the file extensions with the new syntax package.
I had the same issue because my file was called email.py. I renamed the file and the issue disappeared.
try out like this
body {
background: #fff url("!--MIZO-PRO--!") no-repeat center 15px top 15px/100px;
}
/* 100px is the background size */
Adding on to the answer from @Ohmen, you could also add an external
flag to create the data volume outside of docker compose. This way docker compose would not attempt to create it. Also you wouldn't have to worry about losing the data inside the data-volume in the event of $ docker-compose down -v
.
The below example is from the official page.
version: "3.8"
services:
db:
image: postgres
volumes:
- data:/var/lib/postgresql/data
volumes:
data:
external: true
Everyone else's method doesn't account for whitespaces. Obviously nobody really considers a whitespace a special character.
Use this method to detect special characters not including whitespaces:
import re
def detect_special_characer(pass_string):
regex= re.compile('[@_!#$%^&*()<>?/\|}{~:]')
if(regex.search(pass_string) == None):
res = False
else:
res = True
return(res)
In my case, I was mistaken the function parameters, which are:
context.drawImage(image, left, top);
context.drawImage(image, left, top, width, height);
If you expect them to be
context.drawImage(image, width, height);
you will place the image just outside the canvas with the same effects as described in the question.
The value for an annotation must be a compile time constant, so there is no simple way of doing what you are trying to do.
See also here: How to supply value to an annotation from a Constant java
It is possible to use some compile time tools (ant, maven?) to config it if the value is known before you try to run the program.
In English:
ContentType
: When sending data to the server, use this content type. Default is application/x-www-form-urlencoded; charset=UTF-8
, which is fine for most cases.Accepts
: The content type sent in the request header that tells the server what kind of response it will accept in return. Depends on DataType
.DataType
: The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response. Can be text, xml, html, script, json, jsonp
.Code Runner Extension will only let you "run" java files.
To truly debug 'Java' files follow the quick one-time setup:
.vscode
in the same folder..vscode
folder: tasks.json
and launch.json
tasks.json
:{ "version": "2.0.0", "type": "shell", "presentation": { "echo": true, "reveal": "always", "focus": false, "panel": "shared" }, "isBackground": true, "tasks": [ { "taskName": "build", "args": ["-g", "${file}"], "command": "javac" } ] }
launch.json
:{ "version": "0.2.0", "configurations": [ { "name": "Debug Java", "type": "java", "request": "launch", "externalConsole": true, //user input dosen't work if set it to false :( "stopOnEntry": true, "preLaunchTask": "build", // Runs the task created above before running this configuration "jdkPath": "${env:JAVA_HOME}/bin", // You need to set JAVA_HOME enviroment variable "cwd": "${workspaceRoot}", "startupClass": "${workspaceRoot}${file}", "sourcePath": ["${workspaceRoot}"], // Indicates where your source (.java) files are "classpath": ["${workspaceRoot}"], // Indicates the location of your .class files "options": [], // Additional options to pass to the java executable "args": [] // Command line arguments to pass to the startup class } ], "compounds": [] }
You are all set to debug java files, open any java file and press F5 (Debug->Start Debugging).
Tip: *To hide .class files in the side explorer of VS code, open settings
of VS code and paste the below config:
"files.exclude": {
"*.class": true
}
User proper model in your controller file.
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\User;
You can also use START WITH
to start a sequence from a particular point, although setval accomplishes the same thing, as in Euler's answer, eg,
SELECT MAX(a) + 1 FROM foo;
CREATE SEQUENCE foo_a_seq START WITH 12345; -- replace 12345 with max above
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');
There are probably some commands to resolve it, but I would start by looking in your .git/config
file for references to that branch, and removing them.
The data.table
package also has unique
and duplicated
methods of it's own with some additional features.
Both the unique.data.table
and the duplicated.data.table
methods have an additional by
argument which allows you to pass a character
or integer
vector of column names or their locations respectively
library(data.table)
DT <- data.table(id = c(1,1,1,2,2,2),
val = c(10,20,30,10,20,30))
unique(DT, by = "id")
# id val
# 1: 1 10
# 2: 2 10
duplicated(DT, by = "id")
# [1] FALSE TRUE TRUE FALSE TRUE TRUE
Another important feature of these methods is a huge performance gain for larger data sets
library(microbenchmark)
library(data.table)
set.seed(123)
DF <- as.data.frame(matrix(sample(1e8, 1e5, replace = TRUE), ncol = 10))
DT <- copy(DF)
setDT(DT)
microbenchmark(unique(DF), unique(DT))
# Unit: microseconds
# expr min lq mean median uq max neval cld
# unique(DF) 44708.230 48981.8445 53062.536 51573.276 52844.591 107032.18 100 b
# unique(DT) 746.855 776.6145 2201.657 864.932 919.489 55986.88 100 a
microbenchmark(duplicated(DF), duplicated(DT))
# Unit: microseconds
# expr min lq mean median uq max neval cld
# duplicated(DF) 43786.662 44418.8005 46684.0602 44925.0230 46802.398 109550.170 100 b
# duplicated(DT) 551.982 558.2215 851.0246 639.9795 663.658 5805.243 100 a
FAT32
along with FAT16
and FAT12
are File System Types, but vfat
along with umsdos
and msdos
are drivers, used to mount the FAT file systems in Linux. The choosing of the driver determines how some of the features are applied to the file system, for example, systems mounted with msdos
driver don't have long filenames (they are 8.3 format). vfat
is the most common driver for mounting FAT32 file systems nowadays.
Source: this wikipedia article
Output of commands like df
and lsblk
indeed show vfat
as the File System Type. But sudo file -sL /dev/<partition>
shows FAT (32 bit)
if a File System is FAT32.
You can confirm vfat
is a module and not a File System Type by running modinfo vfat
.
If you want the container to be started even if no user has performed a login (like the VirtualBox VM that I only start and don't want to login each time). Here are the steps I performed to for Ubuntu 16.04 LTS. As an example, I installed a oracle db container:
$ docker pull alexeiled/docker-oracle-xe-11g
$ docker run -d --name=MYPROJECT_oracle_db --shm-size=2g -p 1521:1521 -p 8080:8080 alexeiled/docker-oracle-xe-11g
$ vim /etc/systemd/system/docker-MYPROJECT-oracle_db.service
and add the following content:
[Unit]
Description=Redis container
Requires=docker.service
After=docker.service
[Service]
Restart=always
ExecStart=/usr/bin/docker start -a MYPROJECT_oracle_db
ExecStop=/usr/bin/docker stop -t 2 MYPROJECT_oracle_db
[Install]
WantedBy=default.target
and enable the service at startup
sudo systemctl enable docker-MYPROJECT-oracle_db.service
For more informations https://docs.docker.com/engine/admin/host_integration/
Typically, a cache should keep objects around some time and shall expose of them some time later. What is a good time to hold an object depends on the use case. I wanted this thing to be simple, no threads or schedulers. This approach works for me. Unlike SoftReference
s, objects are guaranteed to be available some minimum amount of time. However, the do not stay around in memory until the sun turns into a red giant.
As useage example think of a slowly responding system that shall be able to check if a request has been done quite recently, and in that case not to perform the requested action twice, even if a hectic user hits the button several times. But, if the same action is requested some time later, it shall be performed again.
class Cache<T> {
long avg, count, created, max, min;
Map<T, Long> map = new HashMap<T, Long>();
/**
* @param min minimal time [ns] to hold an object
* @param max maximal time [ns] to hold an object
*/
Cache(long min, long max) {
created = System.nanoTime();
this.min = min;
this.max = max;
avg = (min + max) / 2;
}
boolean add(T e) {
boolean result = map.put(e, Long.valueOf(System.nanoTime())) != null;
onAccess();
return result;
}
boolean contains(Object o) {
boolean result = map.containsKey(o);
onAccess();
return result;
}
private void onAccess() {
count++;
long now = System.nanoTime();
for (Iterator<Entry<T, Long>> it = map.entrySet().iterator(); it.hasNext();) {
long t = it.next().getValue();
if (now > t + min && (now > t + max || now + (now - created) / count > t + avg)) {
it.remove();
}
}
}
}
I use this, it works fine.
from django.utils import simplejson
from django.http import HttpResponse
def some_view(request):
to_json = {
"key1": "value1",
"key2": "value2"
}
return HttpResponse(simplejson.dumps(to_json), mimetype='application/json')
Alternative:
from django.utils import simplejson
class JsonResponse(HttpResponse):
"""
JSON response
"""
def __init__(self, content, mimetype='application/json', status=None, content_type=None):
super(JsonResponse, self).__init__(
content=simplejson.dumps(content),
mimetype=mimetype,
status=status,
content_type=content_type,
)
In Django 1.7 JsonResponse objects have been added to the Django framework itself which makes this task even easier:
from django.http import JsonResponse
def some_view(request):
return JsonResponse({"key": "value"})
Another way of hiding the container div when a click happens in a not children element;
$(document).on('click', function(e) {
if(!$.contains($('.yourContainer').get(0), e.target)) {
$('.yourContainer').hide();
}
});
To address the question more generally...
Keep in mind that using synchronized on methods is really just shorthand (assume class is SomeClass):
synchronized static void foo() {
...
}
is the same as
static void foo() {
synchronized(SomeClass.class) {
...
}
}
and
synchronized void foo() {
...
}
is the same as
void foo() {
synchronized(this) {
...
}
}
You can use any object as the lock. If you want to lock subsets of static methods, you can
class SomeClass {
private static final Object LOCK_1 = new Object() {};
private static final Object LOCK_2 = new Object() {};
static void foo() {
synchronized(LOCK_1) {...}
}
static void fee() {
synchronized(LOCK_1) {...}
}
static void fie() {
synchronized(LOCK_2) {...}
}
static void fo() {
synchronized(LOCK_2) {...}
}
}
(for non-static methods, you would want to make the locks be non-static fields)
Try This one
select * from
(
select name,salary,ROW_NUMBER() over( order by Salary desc) as
rownum from employee
) as t where t.rownum=2
It is not guaranteed that the slicing returns a view or a copy. You can do
df['column'] = df['column'].fillna(value)
If you are using Microsoft windows environment then you can set a variable named HTTP_PROXY
, FTP_PROXY
, or HTTPS_PROXY
depending on the requirement.
I have used following settings for allowing my commands at windows command prompt to use the browser proxy to access internet.
set HTTP_PROXY=http://proxy_userid:proxy_password@proxy_ip:proxy_port
The parameters on right must be replaced with actual values.
Once the variable HTTP_PROXY
is set, all our subsequent commands executed at windows command prompt will be able to access internet through the proxy along with the authentication provided.
Additionally if you want to use ftp and https as well to use the same proxy then you may like to the following environment variables as well.
set FTP_PROXY=%HTTP_PROXY%
set HTTPS_PROXY=%HTTP_PROXY%
I had the same problem. I installed Eclipse 3.7 into a new folder, and created a new workspace. I launch Eclipse with a -data argument to reference the new workspace.
When I attempt to connect to the marketplace to get the SVN and Maven plugins, I get the same issues described in OP.
After a few more tries, I cleared the proxy settings for SOCKS protocol, and I was able to connect to the marketplace.
So the solution for me was to configure the manual settings for HTTP and HTTPS proxy, clear the settings for SOCKS, and restart Eclipse.
I do not like use pure "a" tag, too much typing. So I come with solution. In view it look
<%: Html.ActionLink(node.Name, "Show", "Browse",
Dic.Route("id", node.Id), Dic.New("data-nodeId", node.Id)) %>
Implementation of Dic class
public static class Dic
{
public static Dictionary<string, object> New(params object[] attrs)
{
var res = new Dictionary<string, object>();
for (var i = 0; i < attrs.Length; i = i + 2)
res.Add(attrs[i].ToString(), attrs[i + 1]);
return res;
}
public static RouteValueDictionary Route(params object[] attrs)
{
return new RouteValueDictionary(Dic.New(attrs));
}
}
setTimeout(expression, timeout);
runs the code/function once after the timeout.
setInterval(expression, timeout);
runs the code/function in intervals, with the length of the timeout between them.
Example:
var intervalID = setInterval(alert, 1000); // Will alert every second.
// clearInterval(intervalID); // Will clear the timer.
setTimeout(alert, 1000); // Will alert once, after a second.
Why don't just use The Round-trip ("O", "o") Format Specifier?
The "O" or "o" standard format specifier represents a custom date and time format string using a pattern that preserves time zone information and emits a result string that complies with ISO 8601. For DateTime values, this format specifier is designed to preserve date and time values along with the DateTime.Kind property in text. The formatted string can be parsed back by using the DateTime.Parse(String, IFormatProvider, DateTimeStyles) or DateTime.ParseExact method if the styles parameter is set to DateTimeStyles.RoundtripKind.
The "O" or "o" standard format specifier corresponds to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string for DateTime values and to the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffzzz" custom format string for DateTimeOffset values. In this string, the pairs of single quotation marks that delimit individual characters, such as the hyphens, the colons, and the letter "T", indicate that the individual character is a literal that cannot be changed. The apostrophes do not appear in the output string.
The O" or "o" standard format specifier (and the "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK" custom format string) takes advantage of the three ways that ISO 8601 represents time zone information to preserve the Kind property of DateTime values:
public class Example
{
public static void Main()
{
DateTime dat = new DateTime(2009, 6, 15, 13, 45, 30,
DateTimeKind.Unspecified);
Console.WriteLine("{0} ({1}) --> {0:O}", dat, dat.Kind);
DateTime uDat = new DateTime(2009, 6, 15, 13, 45, 30,
DateTimeKind.Utc);
Console.WriteLine("{0} ({1}) --> {0:O}", uDat, uDat.Kind);
DateTime lDat = new DateTime(2009, 6, 15, 13, 45, 30,
DateTimeKind.Local);
Console.WriteLine("{0} ({1}) --> {0:O}\n", lDat, lDat.Kind);
DateTimeOffset dto = new DateTimeOffset(lDat);
Console.WriteLine("{0} --> {0:O}", dto);
}
}
// The example displays the following output:
// 6/15/2009 1:45:30 PM (Unspecified) --> 2009-06-15T13:45:30.0000000
// 6/15/2009 1:45:30 PM (Utc) --> 2009-06-15T13:45:30.0000000Z
// 6/15/2009 1:45:30 PM (Local) --> 2009-06-15T13:45:30.0000000-07:00
//
// 6/15/2009 1:45:30 PM -07:00 --> 2009-06-15T13:45:30.0000000-07:00
select isnull(nullif(CAR_OWNER_TEL, ''), 'NULLLLL') PHONE from TABLE
will replace CAR_OWNER_TEL if empty by NULLLLL (MS SQL)
You can add script tags in your HTML document, ideally inside the which points to your javascript files. Order of the script tags are important. Load the jQuery before your script files if you want to use jQuery from your script.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="relative/path/to/your/javascript.js"></script>
Then in your javascript file you can refer to jQuery either using $
sign or jQuery
.
Example:
jQuery.each(arr, function(i) { console.log(i); });
Even though above answers are correct, I wanna add a notice to distinguish types of storage:
Here is the link to source code for cases I mentioned above: https://github.com/mttdat/utils/blob/master/utils/src/main/java/mttdat/utils/FileUtils.java
I think, you can use objects as params-transportes, too.
$myParam = new stdClass();
$myParam->optParam2 = 'something';
$myParam->optParam8 = 3;
theFunction($myParam);
function theFunction($fparam){
return "I got ".$fparam->optParam8." of ".$fparam->optParam2." received!";
}
Of course, you have to set default values for "optParam8" and "optParam2" in this function, in other case you will get "Notice: Undefined property: stdClass::$optParam2"
If using arrays as function parameters, I like this way to set default values:
function theFunction($fparam){
$default = array(
'opt1' => 'nothing',
'opt2' => 1
);
if(is_array($fparam)){
$fparam = array_merge($default, $fparam);
}else{
$fparam = $default;
}
//now, the default values are overwritten by these passed by $fparam
return "I received ".$fparam['opt1']." and ".$fparam['opt2']."!";
}
You can do like below:
var command = "Put your command here";
System.Diagnostics.ProcessStartInfo procStartInfo = new System.Diagnostics.ProcessStartInfo("cmd", "/c " + command);
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
procStartInfo.WorkingDirectory = @"C:\Program Files\IIS\Microsoft Web Deploy V3";
procStartInfo.CreateNoWindow = true; //whether you want to display the command window
System.Diagnostics.Process proc = new System.Diagnostics.Process();
proc.StartInfo = procStartInfo;
proc.Start();
string result = proc.StandardOutput.ReadToEnd();
label1.Text = result.ToString();
you can use LINQ
string abc = "abc";
char getresult = abc.Where((item, index) => index == 2).Single();
There is a generic solution:
Lets say you have a controller named Admin where you put content for authorized users.
Then, you can override the Initialize
or OnAuthorization
methods of Admin controller and write redirect to login page logic on session timeout in these methods as described:
protected override void OnAuthorization(System.Web.Mvc.AuthorizationContext filterContext)
{
//lets say you set session value to a positive integer
AdminLoginType = Convert.ToInt32(filterContext.HttpContext.Session["AdminLoginType"]);
if (AdminLoginType == 0)
{
filterContext.HttpContext.Response.Redirect("~/login");
}
base.OnAuthorization(filterContext);
}
I downgrade the support
previously it was
implementation 'com.android.support:appcompat-v7:27.0.2'
Use it
implementation 'com.android.support:appcompat-v7:27.1.0'
implementation 'com.android.support:design:27.1.0'
Its Working Happy Codng
Middleware of the following is removed from Express.
When you use the middleware directly like you did in express 3.0. You will get the following error:
Error: Most middleware (like urlencoded) is no longer bundled with Express and
must be installed separately.
In order to utilize those middleware, now you need to do npm for each middleware separately.
Since bodyParser is marked as deprecated, so I recommend the following way using json, urlencode and multipart parser like formidable, connect-multiparty. (Multipart middleware is deprecated as well).
Also remember, just defining urlencode + json, the form data will not be parsed and req.body will be undefined. You need to define a middleware handle the multipart request.
var urlencode = require('urlencode');
var json = require('json-middleware');
var multipart = require('connect-multiparty');
var multipartMiddleware = multipart();
app.use(json);
app.use(urlencode);
app.use('/url/that/accepts/form-data', multipartMiddleware);
Assuming int is a 16 bit integer (which depends on the C implementation, most are 32 bit nowadays) the bit representation differs like the following:
5 = 0000000000000101
-5 = 1111111111111011
if binary 1111111111111011 would be set to an unsigned int, it would be decimal 65531.
You dont need to define option tags, you can do this using the ngOptions directive: https://docs.angularjs.org/api/ng/directive/ngOptions
<select class="form-control" ng-change="unitChanged()" ng-model="data.unit" ng-options="unit.id as unit.label for unit in units"></select>
I'm using this on my site (for example here), but I'm using some extra stuff to do lazy loading, meaning extracting the code isn't as straightforward as I would like it to be for putting it in a fiddle.
Also, my templating engine is smarty, but I'm sure you get the idea.
The meat...
Updating the indicators:
<ol class="carousel-indicators">
{assign var='walker' value=0}
{foreach from=$item["imagearray"] key="key" item="value"}
<li data-target="#myCarousel" data-slide-to="{$walker}"{if $walker == 0} class="active"{/if}>
<img src='http://farm{$value["farm"]}.static.flickr.com/{$value["server"]}/{$value["id"]}_{$value["secret"]}_s.jpg'>
</li>
{assign var='walker' value=1 + $walker}
{/foreach}
</ol>
Changing the CSS related to the indicators:
.carousel-indicators {
bottom:-50px;
height: 36px;
overflow-x: hidden;
white-space: nowrap;
}
.carousel-indicators li {
text-indent: 0;
width: 34px !important;
height: 34px !important;
border-radius: 0;
}
.carousel-indicators li img {
width: 32px;
height: 32px;
opacity: 0.5;
}
.carousel-indicators li:hover img, .carousel-indicators li.active img {
opacity: 1;
}
.carousel-indicators .active {
border-color: #337ab7;
}
When the carousel has slid, update the list of thumbnails:
$('#myCarousel').on('slid.bs.carousel', function() {
var widthEstimate = -1 * $(".carousel-indicators li:first").position().left + $(".carousel-indicators li:last").position().left + $(".carousel-indicators li:last").width();
var newIndicatorPosition = $(".carousel-indicators li.active").position().left + $(".carousel-indicators li.active").width() / 2;
var toScroll = newIndicatorPosition + indicatorPosition;
var adjustedScroll = toScroll - ($(".carousel-indicators").width() / 2);
if (adjustedScroll < 0)
adjustedScroll = 0;
if (adjustedScroll > widthEstimate - $(".carousel-indicators").width())
adjustedScroll = widthEstimate - $(".carousel-indicators").width();
$('.carousel-indicators').animate({ scrollLeft: adjustedScroll }, 800);
indicatorPosition = adjustedScroll;
});
And, when your page loads, set the initial scroll position of the thumbnails:
var indicatorPosition = 0;
From http://ora-01438.ora-code.com/ (the definitive resource outside of Oracle Support):
ORA-01438: value larger than specified precision allowed for this column
Cause: When inserting or updating records, a numeric value was entered that exceeded the precision defined for the column.
Action: Enter a value that complies with the numeric column's precision, or use the MODIFY option with the ALTER TABLE command to expand the precision.
http://ora-06512.ora-code.com/:
ORA-06512: at stringline string
Cause: Backtrace message as the stack is unwound by unhandled exceptions.
Action: Fix the problem causing the exception or write an exception handler for this condition. Or you may need to contact your application administrator or DBA.
In the parent process, fork()'s return value is the process ID of the child process. Stuff that value away somewhere for when you need to terminate the child process. fork() returns zero(0) in the child process.
When you need to terminate the child process, use the kill(2) function with the process ID returned by fork(), and the signal you wish to deliver (e.g. SIGTERM).
Remember to call wait() on the child process to prevent any lingering zombies.
following steps might help any one
Just use the result from the FOR
command. For example (inside a batch file):
for /F "delims=" %%I in ('dir /b /a-d /od FILESA*') do (echo %%I)
You can use the %%I
as the value you want. Just like this: %%I
.
And in advance the %%I
does not have any spaces or CR characters and can be used for comparisons!!
Easiest way would be to use the serialize
function.
It serializes any variable for storage or transfer. You can read about it in the php manual - serialize
The variable can be restored by using unserialize
So in the passing to the URL you use:
$url = urlencode(serialize($array))
and to restore the variable you use
$var = unserialize(urldecode($_GET['array']))
Be careful here though. The maximum size of a GET request is limited to 4k, which you can easily exceed by passing arrays in a URL.
Also, its really not quite the safest way to pass data! You should probably look into using sessions instead.
<TL;DR> The problem is rather simple, actually: you are not matching the declared encoding (in the XML declaration) with the datatype of the input parameter. If you manually added <?xml version="1.0" encoding="utf-8"?><test/>
to the string, then declaring the SqlParameter
to be of type SqlDbType.Xml
or SqlDbType.NVarChar
would give you the "unable to switch the encoding" error. Then, when inserting manually via T-SQL, since you switched the declared encoding to be utf-16
, you were clearly inserting a VARCHAR
string (not prefixed with an upper-case "N", hence an 8-bit encoding, such as UTF-8) and not an NVARCHAR
string (prefixed with an upper-case "N", hence the 16-bit UTF-16 LE encoding).
The fix should have been as simple as:
encoding="utf-8"
: simply don't add the XML declaration.encoding="utf-16"
: either
SqlDbType.NVarChar
instead of SqlDbType.VarChar
:-) (or possibly even switch to using SqlDbType.Xml
)(Detailed response is below)
All of the answers here are over-complicated and unnecessary (regardless of the 121 and 184 up-votes for Christian's and Jon's answers, respectively). They might provide working code, but none of them actually answer the question. The issue is that nobody truly understood the question, which ultimately is about how the XML datatype in SQL Server works. Nothing against those two clearly intelligent people, but this question has little to nothing to do with serializing to XML. Saving XML data into SQL Server is much easier than what is being implied here.
It doesn't really matter how the XML is produced as long as you follow the rules of how to create XML data in SQL Server. I have a more thorough explanation (including working example code to illustrate the points outlined below) in an answer on this question: How to solve “unable to switch the encoding” error when inserting XML into SQL Server, but the basics are:
NVARCHAR(MAX)
or XML
/ SqlDbType.NVarChar
(maxsize = -1) or SqlDbType.Xml
, or if using a string literal then it must be prefixed with an upper-case "N".VARCHAR(MAX)
/ SqlDbType.VarChar
(maxsize = -1), or if using a string literal then it must not be prefixed with an upper-case "N".With the points outlined above in mind, and given that strings in .NET are always UTF-16 LE / UCS-2 LE (there is no difference between those in terms of encoding), we can answer your questions:
Is there a reason why I shouldn't use StringWriter to serialize an Object when I need it as a string afterwards?
No, your StringWriter
code appears to be just fine (at least I see no issues in my limited testing using the 2nd code block from the question).
Wouldn't setting the encoding to UTF-16 (in the xml tag) work then?
It isn't necessary to provide the XML declaration. When it is missing, the encoding is assumed to be UTF-16 LE if you pass the string into SQL Server as NVARCHAR
(i.e. SqlDbType.NVarChar
) or XML
(i.e. SqlDbType.Xml
). The encoding is assumed to be the default 8-bit Code Page if passing in as VARCHAR
(i.e. SqlDbType.VarChar
). If you have any non-standard-ASCII characters (i.e. values 128 and above) and are passing in as VARCHAR
, then you will likely see "?" for BMP characters and "??" for Supplementary Characters as SQL Server will convert the UTF-16 string from .NET into an 8-bit string of the current Database's Code Page before converting it back into UTF-16 / UCS-2. But you shouldn't get any errors.
On the other hand, if you do specify the XML declaration, then you must pass into SQL Server using the matching 8-bit or 16-bit datatype. So if you have a declaration stating that the encoding is either UCS-2 or UTF-16, then you must pass in as SqlDbType.NVarChar
or SqlDbType.Xml
. Or, if you have a declaration stating that the encoding is one of the 8-bit options (i.e. UTF-8
, Windows-1252
, iso-8859-1
, etc), then you must pass in as SqlDbType.VarChar
. Failure to match the declared encoding with the proper 8 or 16 -bit SQL Server datatype will result in the "unable to switch the encoding" error that you were getting.
For example, using your StringWriter
-based serialization code, I simply printed the resulting string of the XML and used it in SSMS. As you can see below, the XML declaration is included (because StringWriter
does not have an option to OmitXmlDeclaration
like XmlWriter
does), which poses no problem so long as you pass the string in as the correct SQL Server datatype:
-- Upper-case "N" prefix == NVARCHAR, hence no error:
DECLARE @Xml XML = N'<?xml version="1.0" encoding="utf-16"?>
<string>Test ?</string>';
SELECT @Xml;
-- <string>Test ?</string>
As you can see, it even handles characters beyond standard ASCII, given that ?
is BMP Code Point U+1234, and is Supplementary Character Code Point U+1F638. However, the following:
-- No upper-case "N" prefix on the string literal, hence VARCHAR:
DECLARE @Xml XML = '<?xml version="1.0" encoding="utf-16"?>
<string>Test ?</string>';
results in the following error:
Msg 9402, Level 16, State 1, Line XXXXX
XML parsing: line 1, character 39, unable to switch the encoding
Ergo, all of that explanation aside, the full solution to your original question is:
You were clearly passing the string in as SqlDbType.VarChar
. Switch to SqlDbType.NVarChar
and it will work without needing to go through the extra step of removing the XML declaration. This is preferred over keeping SqlDbType.VarChar
and removing the XML declaration because this solution will prevent data loss when the XML includes non-standard-ASCII characters. For example:
-- No upper-case "N" prefix on the string literal == VARCHAR, and no XML declaration:
DECLARE @Xml2 XML = '<string>Test ?</string>';
SELECT @Xml2;
-- <string>Test ???</string>
As you can see, there is no error this time, but now there is data-loss 🙀.
print("imageURLString = " + imageURLString!)
just use !
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).
A rather obscure, yet potentially important case when layoutSubviews
never gets called is:
import UIKit
class View: UIView {
override class var layerClass: AnyClass { return Layer.self }
class Layer: CALayer {
override func layoutSublayers() {
// if we don't call super.layoutSublayers()...
print(type(of: self), #function)
}
}
override func layoutSubviews() {
// ... this method never gets called by the OS!
print(type(of: self), #function)
}
}
let view = View(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
You could make it absolute
and put zeros to top
and bottom
that is:
#fullHeightDiv {
position: absolute;
top: 0;
bottom: 0;
}
Seems you need to use JToggleButton
:
JToggleButton tb = new JToggleButton("push me");
tb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JToggleButton btn = (JToggleButton) e.getSource();
btn.setText(btn.isSelected() ? "pushed" : "push me");
}
});
I would do it like this:
SELECT top(100)* into #tmpFerdeen
FROM Customers
Insert into #tmpFerdeen
SELECT top(100)*
FROM CustomerEurope
Insert into #tmpFerdeen
SELECT top(100)*
FROM CustomerAsia
Insert into #tmpFerdeen
SELECT top(100)*
FROM CustomerAmericas
path.resolve('.')
is also a reliable and clean option, because we almost always require('path')
. It will give you absolute path of the directory from where it is called.
For those using AppCompact...Try this
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.content.Intent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.net.Uri;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button startBtn = (Button) findViewById(R.id.db);
startBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
makeCall();
}
});
}
protected void makeCall() {
EditText num = (EditText)findViewById(R.id.Dail);
String phone = num.getText().toString();
String d = "tel:" + phone ;
Log.i("Make call", "");
Intent phoneIntent = new Intent(Intent.ACTION_CALL);
phoneIntent.setData(Uri.parse(d));
try {
startActivity(phoneIntent);
finish();
Log.i("Finished making a call", "");
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(this, "Call faild, please try again later.", Toast.LENGTH_SHORT).show();
}
}
}
Then add this to your manifest,,,
<uses-permission android:name="android.permission.CALL_PHONE" />
I have created a double-lookup class:
/// <summary>
/// dictionary with double key lookup
/// </summary>
/// <typeparam name="T1">primary key</typeparam>
/// <typeparam name="T2">secondary key</typeparam>
/// <typeparam name="TValue">value type</typeparam>
public class cDoubleKeyDictionary<T1, T2, TValue> {
private struct Key2ValuePair {
internal T2 key2;
internal TValue value;
}
private Dictionary<T1, Key2ValuePair> d1 = new Dictionary<T1, Key2ValuePair>();
private Dictionary<T2, T1> d2 = new Dictionary<T2, T1>();
/// <summary>
/// add item
/// not exacly like add, mote like Dictionary[] = overwriting existing values
/// </summary>
/// <param name="key1"></param>
/// <param name="key2"></param>
public void Add(T1 key1, T2 key2, TValue value) {
lock (d1) {
d1[key1] = new Key2ValuePair {
key2 = key2,
value = value,
};
d2[key2] = key1;
}
}
/// <summary>
/// get key2 by key1
/// </summary>
/// <param name="key1"></param>
/// <param name="key2"></param>
/// <returns></returns>
public bool TryGetValue(T1 key1, out TValue value) {
if (d1.TryGetValue(key1, out Key2ValuePair kvp)) {
value = kvp.value;
return true;
} else {
value = default;
return false;
}
}
/// <summary>
/// get key1 by key2
/// </summary>
/// <param name="key2"></param>
/// <param name="key1"></param>
/// <remarks>
/// 2x O(1) operation
/// </remarks>
/// <returns></returns>
public bool TryGetValue2(T2 key2, out TValue value) {
if (d2.TryGetValue(key2, out T1 key1)) {
return TryGetValue(key1, out value);
} else {
value = default;
return false;
}
}
/// <summary>
/// get key1 by key2
/// </summary>
/// <param name="key2"></param>
/// <param name="key1"></param>
/// <remarks>
/// 2x O(1) operation
/// </remarks>
/// <returns></returns>
public bool TryGetKey1(T2 key2, out T1 key1) {
return d2.TryGetValue(key2, out key1);
}
/// <summary>
/// get key1 by key2
/// </summary>
/// <param name="key2"></param>
/// <param name="key1"></param>
/// <remarks>
/// 2x O(1) operation
/// </remarks>
/// <returns></returns>
public bool TryGetKey2(T1 key1, out T2 key2) {
if (d1.TryGetValue(key1, out Key2ValuePair kvp1)) {
key2 = kvp1.key2;
return true;
} else {
key2 = default;
return false;
}
}
/// <summary>
/// remove item by key 1
/// </summary>
/// <param name="key1"></param>
public void Remove(T1 key1) {
lock (d1) {
if (d1.TryGetValue(key1, out Key2ValuePair kvp)) {
d1.Remove(key1);
d2.Remove(kvp.key2);
}
}
}
/// <summary>
/// remove item by key 2
/// </summary>
/// <param name="key2"></param>
public void Remove2(T2 key2) {
lock (d1) {
if (d2.TryGetValue(key2, out T1 key1)) {
d1.Remove(key1);
d2.Remove(key2);
}
}
}
/// <summary>
/// clear all items
/// </summary>
public void Clear() {
lock (d1) {
d1.Clear();
d2.Clear();
}
}
/// <summary>
/// enumerator on key1, so we can replace Dictionary by cDoubleKeyDictionary
/// </summary>
/// <param name="key1"></param>
/// <returns></returns>
public TValue this[T1 key1] {
get => d1[key1].value;
}
/// <summary>
/// enumerator on key1, so we can replace Dictionary by cDoubleKeyDictionary
/// </summary>
/// <param name="key1"></param>
/// <returns></returns>
public TValue this[T1 key1, T2 key2] {
set {
lock (d1) {
d1[key1] = new Key2ValuePair {
key2 = key2,
value = value,
};
d2[key2] = key1;
}
}
}
Try a query like
INSERT INTO NEW_TABLENAME SELECT * FROM OLD_TABLENAME;
Using System.Text.Json
:
https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/
public static T DeepCopy<T>(this T source)
{
return source == null ? default : JsonSerializer.Parse<T>(JsonSerializer.ToString(source));
}
The new API is using Span<T>
. This should be fast, would be nice to do some benchmarks.
Note: there's no need for ObjectCreationHandling.Replace
like in Json.NET as it will replace collection values by default. You should forget about Json.NET now as everything is going to be replaced with the new official API.
I'm not sure this will work with private fields.
the below codes helped me with the same problem. Let me know if it helped.
<!DOCTYPE html>
<html>
<body>
<audio controls>
<source src="YOUR AUDIO FILE" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
</body>
</html>
Had the exact same problem and none of the answers here helped me. Till I find this thread and post
Short: win32 modules are not guaranted to install correctly with pip. Install them directly from packages provided by developpers on github. It works like a charm.
This sometimes can be thrown before the actual log4j2 configuration file found on the web servlet. at least for my case I think so. Cuz I already have in my web.xml
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>classpath:log4j2-app.xml</param-value>
</context-param>
and checking the log4j-web source; in class
org.apache.logging.log4j.web.Log4jWebInitializerImpl
there is the line;
String location = this.substitutor
.replace(this.servletContext.getInitParameter("log4jConfiguration"));
all those makes me think that this is temporary log before configuration found.
Not sure about getting an IntPtr to an array, but you can copy the data for use with unmanaged code by using Mashal.Copy:
IntPtr unmanagedPointer = Marshal.AllocHGlobal(bytes.Length);
Marshal.Copy(bytes, 0, unmanagedPointer, bytes.Length);
// Call unmanaged code
Marshal.FreeHGlobal(unmanagedPointer);
Alternatively you could declare a struct with one property and then use Marshal.PtrToStructure, but that would still require allocating unmanaged memory.
Edit: Also, as Tyalis pointed out, you can also use fixed if unsafe code is an option for you
Because lists are mutable, dict
keys (and set
members) need to be hashable, and hashing mutable objects is a bad idea because hash values should be computed on the basis of instance attributes.
In this answer, I will give some concrete examples, hopefully adding value on top of the existing answers. Every insight applies to the elements of the set
datastructure as well.
Example 1: hashing a mutable object where the hash value is based on a mutable characteristic of the object.
>>> class stupidlist(list):
... def __hash__(self):
... return len(self)
...
>>> stupid = stupidlist([1, 2, 3])
>>> d = {stupid: 0}
>>> stupid.append(4)
>>> stupid
[1, 2, 3, 4]
>>> d
{[1, 2, 3, 4]: 0}
>>> stupid in d
False
>>> stupid in d.keys()
False
>>> stupid in list(d.keys())
True
After mutating stupid
, it cannot be found in the dict any longer because the hash changed. Only a linear scan over the list of the dict's keys finds stupid
.
Example 2: ... but why not just a constant hash value?
>>> class stupidlist2(list):
... def __hash__(self):
... return id(self)
...
>>> stupidA = stupidlist2([1, 2, 3])
>>> stupidB = stupidlist2([1, 2, 3])
>>>
>>> stupidA == stupidB
True
>>> stupidA in {stupidB: 0}
False
That's not a good idea as well because equal objects should hash identically such that you can find them in a dict
or set
.
Example 3: ... ok, what about constant hashes across all instances?!
>>> class stupidlist3(list):
... def __hash__(self):
... return 1
...
>>> stupidC = stupidlist3([1, 2, 3])
>>> stupidD = stupidlist3([1, 2, 3])
>>> stupidE = stupidlist3([1, 2, 3, 4])
>>>
>>> stupidC in {stupidD: 0}
True
>>> stupidC in {stupidE: 0}
False
>>> d = {stupidC: 0}
>>> stupidC.append(5)
>>> stupidC in d
True
Things seem to work as expected, but think about what's happening: when all instances of your class produce the same hash value, you will have a hash collision whenever there are more than two instances as keys in a dict
or present in a set
.
Finding the right instance with my_dict[key]
or key in my_dict
(or item in my_set
) needs to perform as many equality checks as there are instances of stupidlist3
in the dict's keys (in the worst case). At this point, the purpose of the dictionary - O(1) lookup - is completely defeated. This is demonstrated in the following timings (done with IPython).
Some Timings for Example 3
>>> lists_list = [[i] for i in range(1000)]
>>> stupidlists_set = {stupidlist3([i]) for i in range(1000)}
>>> tuples_set = {(i,) for i in range(1000)}
>>> l = [999]
>>> s = stupidlist3([999])
>>> t = (999,)
>>>
>>> %timeit l in lists_list
25.5 µs ± 442 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> %timeit s in stupidlists_set
38.5 µs ± 61.2 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> %timeit t in tuples_set
77.6 ns ± 1.5 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
As you can see, the membership test in our stupidlists_set
is even slower than a linear scan over the whole lists_list
, while you have the expected super fast lookup time (factor 500) in a set without loads of hash collisions.
TL; DR: you can use tuple(yourlist)
as dict
keys, because tuples are immutable and hashable.
You could try specifying an HTTP response code using an optional parameter:
header('HTTP/1.0 404 Not Found', true, 404);
You're returning a tuple
. Index it.
obj=list_benefits()
print obj[0] + " is a benefit of functions!"
print obj[1] + " is a benefit of functions!"
print obj[2] + " is a benefit of functions!"
Agree with iLoveTux , applying too many things (many colors and backgrounds) nothing worked , but here's what started working, Apply these properties to its css:
-webkit-appearance: none;
-moz-appearance: none;
-o-appearance: none;
appearance:none;
and then css styling started working on checkbox :)
I achieved it using some extension methods
private const string endFieldPattern = "^(.*?)>";
public static MvcHtmlString IsDisabled(this MvcHtmlString htmlString, bool disabled)
{
string rawString = htmlString.ToString();
if (disabled)
{
rawString = Regex.Replace(rawString, endFieldPattern, "$1 disabled=\"disabled\">");
}
return new MvcHtmlString(rawString);
}
public static MvcHtmlString IsReadonly(this MvcHtmlString htmlString, bool @readonly)
{
string rawString = htmlString.ToString();
if (@readonly)
{
rawString = Regex.Replace(rawString, endFieldPattern, "$1 readonly=\"readonly\">");
}
return new MvcHtmlString(rawString);
}
and then....
@Html.TextBoxFor(model => model.Name, new { @class= "someclass"}).IsDisabled(Model.ExpireDate == null)
When you add subfolders and files in subfolders the DLL files in Bin folder also may have changed. When I uploaded the updated DLL file in Bin folder it solved the issue. Thanks to Mayank Modi who suggested that or hinted that.
While this is one of the most voted feature requests, there is one plugin available, by Victor Kropp, that adds support to makefiles:
Makefile support plugin for IntelliJ IDEA
You can install directly from the official repository:
Settings > Plugins > search for makefile
> Search in repositories > Install > Restart
There are at least three different ways to run:
It opens a pane named Run target with the output.
You can get the pids
of all child processes of a given parent process <pid>
by reading the /proc/<pid>/task/<tid>/children
entry.
This file contain the pids of first level child processes.
For more information head over to https://lwn.net/Articles/475688/
Its much better to use java.util.LinkedList, because it's probably much more optimized, than the one that you will write.
var myStringArray = ["hello", "World"];
myStringArray.forEach(function(val, index){
console.log(val, index);
})
I figured it out...finally found another article on it.
string start = Request.QueryString["start"];
string end = Request.QueryString["end"];
Use the Task manager to find the Service and kill it from there using End Task. Always does the trick for me.
If you have made the service yourself, consider removing Long running operations from the OnStart event, usually that is what causes the Service to be non responsive.
SimpleDateFormat will not work if he is starting with LocalDate which is new in Java 8. From what I can see, you will have to use DateTimeFormatter, http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html.
LocalDate localDate = LocalDate.now();//For reference
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd LLLL yyyy");
String formattedString = localDate.format(formatter);
That should print 05 May 1988. To get the period after the day and before the month, you might have to use "dd'.LLLL yyyy"
try:
%matplotlib notebook
EDIT for JupyterLab users:
Follow the instructions to install jupyter-matplotlib
Then the magic command above is no longer needed, as in the example:
# Enabling the `widget` backend.
# This requires jupyter-matplotlib a.k.a. ipympl.
# ipympl can be install via pip or conda.
%matplotlib widget
# aka import ipympl
import matplotlib.pyplot as plt
plt.plot([0, 1, 2, 2])
plt.show()
Finally, note Maarten Breddels' reply; IMHO ipyvolume is indeed very impressive (and useful!).
Your version of Linux doesn't support this kind of functionality please go for another suitable version i.e. Kali Linux or Red Hat.
For the second part of your question, you can also use shift
, for example:
df['t-1'] = df['t'].shift(1)
t-1
would then contain the values from t one row above.
http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.shift.html
Step 1: Implement an interface with your activity class
public class AuthenticatedMainActivity extends Activity implements FragmentManager.OnBackStackChangedListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
.............
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().add(R.id.frame_container,fragment, "First").addToBackStack(null).commit();
}
private void switchFragment(Fragment fragment){
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.frame_container, fragment).addToBackStack("Tag").commit();
}
@Override
public void onBackStackChanged() {
FragmentManager fragmentManager = getFragmentManager();
System.out.println("@Class: SummaryUser : onBackStackChanged "
+ fragmentManager.getBackStackEntryCount());
int count = fragmentManager.getBackStackEntryCount();
// when a fragment come from another the status will be zero
if(count == 0){
System.out.println("again loading user data");
// reload the page if user saved the profile data
if(!objPublicDelegate.checkNetworkStatus()){
objPublicDelegate.showAlertDialog("Warning"
, "Please check your internet connection");
}else {
objLoadingDialog.show("Refreshing data...");
mNetworkMaster.runUserSummaryAsync();
}
// IMPORTANT: remove the current fragment from stack to avoid new instance
fragmentManager.removeOnBackStackChangedListener(this);
}// end if
}
}
Step 2: When you call the another fragment add this method:
String backStateName = this.getClass().getName();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.addOnBackStackChangedListener(this);
Fragment fragmentGraph = new GraphFragment();
Bundle bundle = new Bundle();
bundle.putString("graphTag", view.getTag().toString());
fragmentGraph.setArguments(bundle);
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragmentGraph)
.addToBackStack(backStateName)
.commit();
The problem in your code is that you can't store the memory address of a local variable (local to a function, for example) in a globlar variable:
RectInvoice rect(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(&rect);
There, &rect
is a temporary address (stored in the function's activation registry) and will be destroyed when that function end.
The code should create a dynamic variable:
RectInvoice *rect = new RectInvoice(vect,im,x, y, w ,h);
this->rectInvoiceVector.push_back(rect);
There you are using a heap address that will not be destroyed in the end of the function's execution. Tell me if it worked for you.
Cheers
In the repository, click Admin
, then go to the Collaborators
tab.
It may be because your web folder (as mentioned "/Applications/MAMP/htdocs/mysite/web") is empty.
My suggestion is first to make your project and then work on making the virtual host.
I went with a similar situation. I was using an empty folder in the DocumentRoot in httpd-vhosts.confiz and I couldn't access my shahg101.com site.
It is:
<%=Html.ActionLink("Home", "Index", MyRouteValObj, new with {.class = "tab" })%>
In VB.net you set an anonymous type using
new with {.class = "tab" }
and, as other point out, your third parameter should be an object (could be an anonymous type, also).
If you just want the content as string
, then the simple solution is to use the ReadFile
function from the io/ioutil
package. This function returns a slice of bytes
which you can easily convert to a string
.
package main
import (
"fmt"
"io/ioutil"
)
func main() {
b, err := ioutil.ReadFile("file.txt") // just pass the file name
if err != nil {
fmt.Print(err)
}
fmt.Println(b) // print the content as 'bytes'
str := string(b) // convert content to a 'string'
fmt.Println(str) // print the content as a 'string'
}
I had similar issue when I entered very big port here:
But when I corrected it to something smaller which is in offset range:
Issue was resolved.
executes a command and never returns.
It's like a return
statement in a function.
If the command is not found exec
returns false.
It never returns true, because if the command is found it never returns at all.
There is also no point in returning STDOUT
, STDERR
or exit status of the command.
You can find documentation about it in perlfunc
,
because it is a function.
executes a command and your Perl script is continued after the command has finished.
The return value is the exit status of the command.
You can find documentation about it in perlfunc
.
like system
executes a command and your perl script is continued after the command has finished.
In contrary to system
the return value is STDOUT
of the command.
qx//
is equivalent to backticks.
You can find documentation about it in perlop
, because unlike system
and exec
it is an operator.
What is missing from the above is a way to execute a command asynchronously.
That means your perl script and your command run simultaneously.
This can be accomplished with open
.
It allows you to read STDOUT
/STDERR
and write to STDIN
of your command.
It is platform dependent though.
There are also several modules which can ease this tasks.
There is IPC::Open2
and IPC::Open3
and IPC::Run
, as well as
Win32::Process::Create
if you are on windows.
even adding a return statement brings up this exception, for which only solution is this code:
if(!response.isCommitted())
// Place another redirection
I believe you need to set the cascade option in your mapping via xml/annotation. Refer to Hibernate reference example here.
In case you are using annotation, you need to do something like this,
@OneToMany(cascade = CascadeType.PERSIST) // Other options are CascadeType.ALL, CascadeType.UPDATE etc..
This is now supported in Chrome by the "Pause on all exceptions" button.
To enable it:
Note that this button has multiple states. Keep clicking the button to switch between
Html
<img id="imgElem"></img>
Js
string baseStr64="/9j/4AAQSkZJRgABAQE...";
imgElem.setAttribute('src', "data:image/jpg;base64," + baseStr64);
The way I get an element to go 100% width of the device is use negative left and right margins on it. The body has a padding of 24px, so that's what you can use negative margins for:
element{
margin-left: -24px;
margin-right: -24px;
padding-left: 24px;
padding-right: 24px;
}
The reason it prints "three" is because you didnt define your array. The equivalent to what you're doing is:
arr = []
for i in array :
if i == "two" :
arr.push(i)
print(i)
You are asking for the last element it looked through, which is not what you should be doing. You need to be storing the array to a variable in order to get the element.
The english equivalent of what you are doing is:
You: "I need you to print all the elements in this array that equal two, but in an array. And each time you cycle through the list, define the current element as I."
Computer: "Here: ["two"]"
You: "Now tell me 'i'"
Computer: "'i' is equal to "three"
You: "Why?"
The reason 'i' is equal to "three" is because three was the last thing that was defined as I
the computer did:
i = "one"
i = "two"
i = "three"
print(["two"])
Because you asked it to.
If you want the index, go here If you want the values in an array, define the array, like this:
MyArray = [(i) for i in my_list if i=="two"]
A bit involved. Easiest would be to refer to this SQL Fiddle I created for you that produces the exact result. There are ways you can improve it for performance or other considerations, but this should hopefully at least be clearer than some alternatives.
The gist is, you get a canonical ranking of your data first, then use that to segment the data into groups, then find an end date for each group, then eliminate any intermediate rows. ROW_NUMBER() and CROSS APPLY help a lot in doing it readably.
EDIT 2019:
The SQL Fiddle does in fact seem to be broken, for some reason, but it appears to be a problem on the SQL Fiddle site. Here's a complete version, tested just now on SQL Server 2016:
CREATE TABLE Source
(
EmployeeID int,
DateStarted date,
DepartmentID int
)
INSERT INTO Source
VALUES
(10001,'2013-01-01',001),
(10001,'2013-09-09',001),
(10001,'2013-12-01',002),
(10001,'2014-05-01',002),
(10001,'2014-10-01',001),
(10001,'2014-12-01',001)
SELECT *,
ROW_NUMBER() OVER (PARTITION BY EmployeeID ORDER BY DateStarted) AS EntryRank,
newid() as GroupKey,
CAST(NULL AS date) AS EndDate
INTO #RankedData
FROM Source
;
UPDATE #RankedData
SET GroupKey = beginDate.GroupKey
FROM #RankedData sup
CROSS APPLY
(
SELECT TOP 1 GroupKey
FROM #RankedData sub
WHERE sub.EmployeeID = sup.EmployeeID AND
sub.DepartmentID = sup.DepartmentID AND
NOT EXISTS
(
SELECT *
FROM #RankedData bot
WHERE bot.EmployeeID = sup.EmployeeID AND
bot.EntryRank BETWEEN sub.EntryRank AND sup.EntryRank AND
bot.DepartmentID <> sup.DepartmentID
)
ORDER BY DateStarted ASC
) beginDate (GroupKey);
UPDATE #RankedData
SET EndDate = nextGroup.DateStarted
FROM #RankedData sup
CROSS APPLY
(
SELECT TOP 1 DateStarted
FROM #RankedData sub
WHERE sub.EmployeeID = sup.EmployeeID AND
sub.DepartmentID <> sup.DepartmentID AND
sub.EntryRank > sup.EntryRank
ORDER BY EntryRank ASC
) nextGroup (DateStarted);
SELECT * FROM
(
SELECT *, ROW_NUMBER() OVER (PARTITION BY GroupKey ORDER BY EntryRank ASC) AS GroupRank FROM #RankedData
) FinalRanking
WHERE GroupRank = 1
ORDER BY EntryRank;
DROP TABLE #RankedData
DROP TABLE Source
This is my code hope this help
private void KCOPY(string source, string destination)
{
if (IsFile(source))
{
string target = Path.Combine(destination, Path.GetFileName(source));
File.Copy(source, target, true);
}
else
{
string fileName = Path.GetFileName(source);
string target = System.IO.Path.Combine(destination, fileName);
if (!System.IO.Directory.Exists(target))
{
System.IO.Directory.CreateDirectory(target);
}
List<string> files = GetAllFileAndFolder(source);
foreach (string file in files)
{
KCOPY(file, target);
}
}
}
private List<string> GetAllFileAndFolder(string path)
{
List<string> allFile = new List<string>();
foreach (string dir in Directory.GetDirectories(path))
{
allFile.Add(dir);
}
foreach (string file in Directory.GetFiles(path))
{
allFile.Add(file);
}
return allFile;
}
private bool IsFile(string path)
{
if ((File.GetAttributes(path) & FileAttributes.Directory) == FileAttributes.Directory)
{
return false;
}
return true;
}
you can do make App in FullScreen Mode form just one line code. i am using this in my code.
just set AppTheme -> Theme.AppCompat.Light.NoActionBar in your style.xml
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
It will work in all pages..
I had a need to request permission for WRITE_EXTERNAL_STORAGE
but was not getting a pop-up despite trying all of the different suggestions mentioned.
The culprit in the end was HockeyApp. It uses manifest merging to include its own permission for WRITE_EXTERNAL_STORAGE
except it applies a max sdk version onto it.
The way to get around this problem is to include it in your Manifest file but with a replace against it, to override the HockeyApp's version and success!
4.7.2 Other dependencies requesting the external storage permission (SDK version 5.0.0 and later) To be ready for Android O, HockeySDK-Android 5.0.0 and later limit the
WRITE_EXTERNAL_STORAGE
permission with the maxSdkVersion filter. In some use cases, e.g. where an app contains a dependency that requires this permission, maxSdkVersion makes it impossible for those dependencies to grant or request the permission. The solution for those cases is as follows:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" tools:node="replace"/>
It will cause that other attributes from low priority manifests will be replaced instead of being merged.
These are Open Source projects (or developers) which can use donations to fund to help support their business.
In npm the command npm fund
will list the urls where you can fund
In composer the command composer fund
will do the same.
While there are options mentioned above using which one can use to get rid of the funding message, but try to support the cause if you can.
Another solution is to use linear layouts and set dividers between rows and cells like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#8000"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<View
android:layout_width="@dimen/border"
android:layout_height="match_parent"
android:background="#8000"
android:layout_marginTop="1px"
android:layout_marginBottom="1px"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
></LinearLayout>
<View
android:layout_width="@dimen/border"
android:layout_height="match_parent"
android:background="#8000"
android:layout_marginTop="1px"
android:layout_marginBottom="1px"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"></LinearLayout>
<View
android:layout_width="@dimen/border"
android:layout_height="match_parent"
android:background="#8000"
android:layout_marginTop="1px"
android:layout_marginBottom="1px"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#8000"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<View
android:layout_width="@dimen/border"
android:layout_height="match_parent"
android:background="#8000"
android:layout_marginTop="1px"
android:layout_marginBottom="1px"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
></LinearLayout>
<View
android:layout_width="@dimen/border"
android:layout_height="match_parent"
android:background="#8000"
android:layout_marginTop="1px"
android:layout_marginBottom="1px"/>
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"></LinearLayout>
<View
android:layout_width="@dimen/border"
android:layout_height="match_parent"
android:background="#8000"
android:layout_marginTop="1px"
android:layout_marginBottom="1px"/>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#8000"/>
</LinearLayout>
It's a dirty solution, but it's simple and also works with transparent background and borders.
There are several possible methods, but for you, there is already a builtin parse_str
function
$array = array();
parse_str($string, $array);
var_dump($array);
directory
is neither an existing file nor directory. As it turns out, the real name is directory.1
as revealed by ls -la $HOME/Desktop/
.
The complete working command is
cp -R $HOME/directory.1/file.bundle /library/application\ support/directory/
with the -R
parameter for recursive copy (compulsory for copying directories).
You can use markersize to specify the size of the circle in plot method
import numpy as np
import matplotlib.pyplot as plt
x1 = np.random.randn(20)
x2 = np.random.randn(20)
plt.figure(1)
# you can specify the marker size two ways directly:
plt.plot(x1, 'bo', markersize=20) # blue circle with size 10
plt.plot(x2, 'ro', ms=10,) # ms is just an alias for markersize
plt.show()
From here
You can use a grid
layout to vertically center the image.
.frame {
display: grid;
grid-template-areas: "."
"img"
"."
grid-template-rows: 1fr auto 1fr;
grid-template-columns: auto;
}
.frame img {
grid-area: img;
}
This will create a 3 row 1 column grid layout with unnamed 1 fraction wide spacers at the top and bottom, and an area named img
of auto
height (size of the content).
The img
will use the space it prefers, and the spacers at top and bottom will use the remaining height split to two equal fractions, resulting in the img
element to be vertically centered.
Click File >> Recent Projects > and you should be able to use edit it again. Hope it helps :)
As King King said, you must add the browser specific prefix. This should cover most browsers:
@keyframes flickerAnimation {_x000D_
0% { opacity:1; }_x000D_
50% { opacity:0; }_x000D_
100% { opacity:1; }_x000D_
}_x000D_
@-o-keyframes flickerAnimation{_x000D_
0% { opacity:1; }_x000D_
50% { opacity:0; }_x000D_
100% { opacity:1; }_x000D_
}_x000D_
@-moz-keyframes flickerAnimation{_x000D_
0% { opacity:1; }_x000D_
50% { opacity:0; }_x000D_
100% { opacity:1; }_x000D_
}_x000D_
@-webkit-keyframes flickerAnimation{_x000D_
0% { opacity:1; }_x000D_
50% { opacity:0; }_x000D_
100% { opacity:1; }_x000D_
}_x000D_
.animate-flicker {_x000D_
-webkit-animation: flickerAnimation 1s infinite;_x000D_
-moz-animation: flickerAnimation 1s infinite;_x000D_
-o-animation: flickerAnimation 1s infinite;_x000D_
animation: flickerAnimation 1s infinite;_x000D_
}
_x000D_
<div class="animate-flicker">Loading...</div>
_x000D_
Another thing to note that if you have a symbolic link from a non public location which hosts your project code to say public_html - running php artisan
in the symbolic link location (public_html) will result in this error.
You seem to need to be in the actual project directory for php artisan
to work.
You can run javascript code at any time. AFAIK it is executed at the moment the browser reaches the <script> tag where it is in. But you cannot access elements that are not loaded yet.
So if you need access to elements, you should wait until the DOM is loaded (this does not mean the whole page is loaded, including images and stuff. It's only the structure of the document, which is loaded much earlier, so you usually won't notice a delay), using the DOMContentLoaded
event or functions like $.ready
in jQuery.
Actually, I've got a bit more precise solution, which might be useful if you don't want to change/delete anything else.
Run regedit
, and at the HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome
key you should have a PasswordManagerEnabled
property, which probably is set to 0
.
Simply change it to 1
.
Edit: I tried it on some other computer and it didn't want to work, so I rebooted my computer, made sure Chrome is closed, then changed it in the registry, and finally it worked. So make sure Chrome is closed when you do this.
In applicationContext.xml file:
<bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- This makes /META-INF/persistence.xml is no longer necessary -->
<property name="packagesToScan" value="com.howtodoinjava.demo.model" />
<!-- JpaVendorAdapter implementation for Hibernate EntityManager.
Exposes Hibernate's persistence provider and EntityManager extension interface -->
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
</property>
<property name="jpaProperties">
<props>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
</props>
</property>
</bean>
print date('H:i');
You have to set the correct timezone in php.ini
.
Look for these lines:
[Date]
; Defines the default timezone used by the date functions
;date.timezone =
It will be something like :
date.timezone ="Europe/Lisbon"
Don't forget to restart your webserver.
Shiva's answer doesn't apply anymore. The API call "/users/{user-id}/follows" is not supported by Instagram for some time (it was disabled in 2016).
For a while you were able to get only your own followers/followings with "/users/self/follows" endpoint, but Instagram disabled that feature in April 2018 (with the Cambridge Analytica issue). You can read about it here.
As far as I know (at this moment) there isn't a service available (official or unofficial) where you can get the followers/followings of a user (even your own).
For me was helpful next:
> apt-get install python-dev python3-dev
Edit: Warning! This answer worked on my XAMPP OsX environment, but when I deployed it to AWS EC2 it did NOT prevent the upload attempt.
I was tempted to delete this answer as it is WRONG But instead I will explain what tripped me up
My file upload field is named 'upload' so I was getting "The upload failed to upload.". This message comes from this line in validation.php:
in resources/lang/en/validaton.php:
'uploaded' => 'The :attribute failed to upload.',
And this is the message displayed when the file is larger than the limit set by PHP.
I want to over-ride this message, which you normally can do by passing a third parameter $messages array to Validator::make() method.
However I can't do that as I am calling the POST from a React Component, which renders the form containing the csrf field and the upload field.
So instead, as a super-dodgy-hack, I chose to get into my view that displays the messages and replace that specific message with my friendly 'file too large' message.
Here is what works if the file to smaller than the PHP file size limit:
In case anyone else is using Laravel FormRequest class, here is what worked for me on Laravel 5.7:
This is how I set a custom error message and maximum file size:
I have an input field <input type="file" name="upload">
. Note the CSRF token is required also in the form (google laravel csrf_field for what this means).
<?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class Upload extends FormRequest
{
...
...
public function rules() {
return [
'upload' => 'required|file|max:8192',
];
}
public function messages()
{
return [
'upload.required' => "You must use the 'Choose file' button to select which file you wish to upload",
'upload.max' => "Maximum file size to upload is 8MB (8192 KB). If you are uploading a photo, try to reduce its resolution to make it under 8MB"
];
}
}
It usually happens because one of the following reasons:
After doing so, you may still need to update in the Entity Framework designer (or alternatively delete the entity and then add it) before you stop getting the error.
C# equivalent of your code is
class Imagedata : PDFStreamEngine
{
// C# uses "base" keyword whenever Java uses "super"
// so instead of super(...) in Java we should call its C# equivalent (base):
public Imagedata()
: base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true))
{ }
// Java methods are virtual by default, when C# methods aren't.
// So we should be sure that processOperator method in base class
// (that is PDFStreamEngine)
// declared as "virtual"
protected override void processOperator(PDFOperator operations, List arguments)
{
base.processOperator(operations, arguments);
}
}
<select id="my_select">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>
var my_value = 2;
$('#my_select option').each(function(){
var $this = $(this); // cache this jQuery object to avoid overhead
if ($this.val() == my_value) { // if this option's value is equal to our value
$this.prop('selected', true); // select this option
return false; // break the loop, no need to look further
}
});
Well, PHP can do this easily.
It can be done with the PHP mail()
function. Here's what a simple function would look like:
<?php
$to_email = '[email protected]';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail function';
$headers = 'From: [email protected]';
mail($to_email,$subject,$message,$headers);
?>
This will send a background e-mail to the recipient specified in the $to_email
.
The above example uses hard coded values in the source code for the email address and other details for simplicity.
Let’s assume you have to create a contact us form for users fill in the details and then submit.
Let’s create a custom function that validates and sanitizes the email address using the filter_var()
built in function.
Here's an example code:
<?php
function sanitize_my_email($field) {
$field = filter_var($field, FILTER_SANITIZE_EMAIL);
if (filter_var($field, FILTER_VALIDATE_EMAIL)) {
return true;
} else {
return false;
}
}
$to_email = '[email protected]';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail ';
$headers = 'From: [email protected]';
//check if the email address is invalid $secure_check
$secure_check = sanitize_my_email($to_email);
if ($secure_check == false) {
echo "Invalid input";
} else { //send email
mail($to_email, $subject, $message, $headers);
echo "This email is sent using PHP Mail";
}
?>
We will now let this be a separate PHP file, for example sendmail.php
.
Then, will use this file on form submission, using the action
attribute of the form, like:
<form action="sendmail.php" method="post">
<input type="text" value="Your Name: ">
<input type="password" value="Set Up A Passworrd">
<input type="submit" value="Signup">
<input type="reset" value="Reset Form">
</form>
Hope I could help
If you don't mind jQuery, I am using this:
<table id="metaConfigTable">
<caption>This is your target table</caption>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</table>
<script>
function tabelajzing(a){
// takes (key, value) pairs from and array and returns
// corresponding html, i.e. [ [1,2], [3,4], [5,6] ]
return [
"<tr>\n<th>",
a.map(function (e, i) {
return e.join("</th>\n<td>")
}).join("</td></tr>\n<tr>\n<th>"),
"</td>\n</tr>\n"
].join("")
}
$('#metaConfigTable').find("tr").after(
tabelajzing( [ [1,2],[3,4],[5,6] ])
);
</script>
You can try Guava Ordering:
Function<Item, Date> getStartDate = new Function<Item, Date>() {
public Date apply(Item item) {
return item.getStartDate();
}
};
List<Item> orderedItems = Ordering.natural().onResultOf(getStartDate).
sortedCopy(items);
We spent months looking into this issue with several our of child projects. We found that AVAILABLE_PLATFORMS
was being set to "appletvos appletvsimulator iphoneos iphonesimulator macosx watchos watchsimulator"
which was causing multiple platforms to be built, which would lead to the "Multiple commands produce error." For instance, "Foo" platform was building for both iOS and TVOS, and thus multiple build commands were creating a Foo.framework
file.
As soon as we set
AVAILABLE_PLATFORMS = iphoneos iphonesimulator
in our root xcconfig
file, this problem went away all child projects.
Run
xcodebuild -project FitbitMobile.xcodeproj -target "FitbitMobile" -showBuildSettings > BuildSettings.txt
See if the output is being set to what you'd expect. If you're an iOS app and you're building for tvOS, you'll want to update your config.
running the following command helps me running https web-page, with iframe which has ws (unsecured) connection
chrome.exe --user-data-dir=c:\temp-chrome --disable-web-security --allow-running-insecure-content
AdBlockers usually have some rules, i.e. they match the URIs against some type of expression (sometimes they also match the DOM against expressions, not that this matters in this case).
Having rules and expressions that just operate on a tiny bit of text (the URI) is prone to create some false-positives...
Besides instructing your users to disable their extensions (at least on your site) you can also get the extension and test which of the rules/expressions blocked your stuff, provided the extension provides enough details about that. Once you identified the culprit, you can either try to avoid triggering the rule by using different URIs, report the rule as incorrect or overly-broad to the team that created it, or both. Check the docs for a particular add-on on how to do that.
For example, AdBlock Plus has a Blockable items view that shows all blocked items on a page and the rules that triggered the block. And those items also including XHR requests.
Every one please avoid modifying post buffer and advising it to others. It may help in some cases but it breaks others. If you have modified your post buffer for pushing your large project. Undo it using following command.
git config --global --unset http.postBuffer
git config --local --unset http.postBuffer
I modified my post buffer to fix one of the issues I had with git but it was the reason for my future problems with git.
You can query Active directory via JNDI and run LDAP operations
http://docs.oracle.com/javase/tutorial/jndi/ldap/authentication.html
http://docs.oracle.com/javase/tutorial/jndi/ldap/operations.html
http://mhimu.wordpress.com/2009/03/18/active-directory-authentication-using-javajndi/
Did you try setting the style:
input {
text-align:right;
}
Just tested, this works fine (in FF3 at least):
<html>
<head>
<title>Blah</title>
<style type="text/css">
input { text-align:right; }
</style>
</head>
<body>
<input type="text" value="2">
</body>
</html>
You'll probably want to throw a class on these inputs, and use that class as the selector. I would shy away from "rightAligned" or something like that. In a class name, you want to describe what the element's function is, not how it should be rendered. "numeric" might be good, or perhaps the business function of the text boxes.
The international numbering plan is based on the ITU E.164 numbering plan. I guess that's the starting point to your regular expression.
I'll update this if I get around to create a regular expression based on the ITU E.164 numbering.
There are many better answers here, but for completeness I will mention the method I used to use before reading some of the great answers mentioned above.
Suppose you want to delete from lines 24-39. You can use the ex command
:24,39d
You can also yank lines using
:24,39y
And find and replace just over lines 24-39 using
:24,39s/find/replace/g
$( "#sortable" ).sortable({
change: function(event, ui) {
var pos = ui.helper.index() < ui.placeholder.index()
? { start: ui.helper.index(), end: ui.placeholder.index() }
: { start: ui.placeholder.index(), end: ui.helper.index() }
$(this)
.children().removeClass( 'highlight' )
.not( ui.helper ).slice( pos.start, pos.end ).addClass( 'highlight' );
},
stop: function(event, ui) {
$(this).children().removeClass( 'highlight' );
}
});
An example of how it could be done inside change event without storing arbitrary data into element storage. Since the element where drag starts is ui.helper
, and the element of current position is ui.placeholder
, we can take the elements between those two indexes and highlight them. Also, we can use this
inside handler since it refers to the element that the widget is attached. The example works with dragging in both directions.
I use ? (0x25B8) for the right arrow, often to show a collapsed list; and I pair it with ? (0x25BE) to show the list opened up. Both are unobtrusive.
Supplemental answer
I was originally having trouble getting a reference to the ViewPager
from other class methods because the addOnTabSelectedListener
made an anonymous inner class, which in turn required the ViewPager
variable to be declared final
. The solution was to use a class member variable and not use the anonymous inner class.
public class MainActivity extends AppCompatActivity {
TabLayout tabLayout;
ViewPager viewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
// don't use an anonymous inner class here
tabLayout.addOnTabSelectedListener(tabListener);
}
TabLayout.OnTabSelectedListener tabListener = new TabLayout.OnTabSelectedListener() {
@Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
@Override
public void onTabUnselected(TabLayout.Tab tab) {
}
@Override
public void onTabReselected(TabLayout.Tab tab) {
}
};
// The view pager can now be accessed here, too.
public void someMethod() {
viewPager.setCurrentItem(0);
}
}
Okay, so this question is old... but I wanted to do something similar and I found a solution that works for me. Maybe it might help someone else.
I have a List<QuestionType>
that I fill a drop down with. I want to put that selection into the QuestionType
property on the Question
object that I'm creating in the form. I'm using Knockout.js
for the select binding. This sets the self.QuestionType
knockout observable property to a QuestionType
object when the user selects one.
<select class="form-control form-control-sm"
data-bind="options: QuestionTypes, optionsText: 'QuestionTypeText', value: QuestionType, optionsCaption: 'Choose...'">
</select>
I have a hidden field that will hold this object:
@Html.Hidden("NewQuestion.QuestionTypeJson", Model.NewQuestion.QuestionTypeJson)
In the subscription for the observable, I set the hidden field to a JSON.stringify
-ed version of the object.
self.QuestionType.subscribe(function(newValue) {
if (newValue !== null && newValue !== undefined) {
document.getElementById('NewQuestion_QuestionTypeJson').value = JSON.stringify(newValue);
}
});
In the Question
object, I have a field called QuestionTypeJson
that is filled when the user selects a question type. I use this field to get the QuestionType
in the Question
object like this:
public string QuestionTypeJson { get; set; }
private QuestionType _questionType = new QuestionType();
public QuestionType QuestionType
{
get => string.IsNullOrEmpty(QuestionTypeJson) ? _questionType : JsonConvert.DeserializeObject<QuestionType>(QuestionTypeJson);
set => _questionType = value;
}
So if the QuestionTypeJson
field contains something, it will deserialize that and use it for QuestionType
, otherwise it'll just use what is in the backing field.
I have essentially 'passed' a JavaScript object to my model without using Razor
or an Ajax
call. You can probably do something similar to this without using Knockout.js
, but that's what I'm using so...
The __del__
method (note spelling!) is called when your object is finally destroyed. Technically speaking (in cPython) that is when there are no more references to your object, ie when it goes out of scope.
If you want to delete your object and thus call the __del__
method use
del obj1
which will delete the object (provided there weren't any other references to it).
I suggest you write a small class like this
class T:
def __del__(self):
print "deleted"
And investigate in the python interpreter, eg
>>> a = T()
>>> del a
deleted
>>> a = T()
>>> b = a
>>> del b
>>> del a
deleted
>>> def fn():
... a = T()
... print "exiting fn"
...
>>> fn()
exiting fn
deleted
>>>
Note that jython and ironpython have different rules as to exactly when the object is deleted and __del__
is called. It isn't considered good practice to use __del__
though because of this and the fact that the object and its environment may be in an unknown state when it is called. It isn't absolutely guaranteed __del__
will be called either - the interpreter can exit in various ways without deleteting all objects.
As complement to Mark's answer, the compile function does not have access to scope, but the link function does.
I really recommend this video; Writing Directives by Misko Hevery (the father of AngularJS), where he describes differences and some techniques. (Difference between compile function and link function at 14:41 mark in the video).
Returning falsy value in the render() function will render nothing. So you can just do
render() {
let finalClasses = "" + (this.state.classes || "");
return !isTimeout && <div>{this.props.children}</div>;
}
For ubunto , what made it happen and was real simple is to install mongodb package:
sudo apt-get install mongodb
If you want to browse to a folder by default: For example "D:\Default_Folder" just initialise the "InitialFileName" attribute
Dim diaFolder As FileDialog
' Open the file dialog
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
diaFolder.InitialFileName = "D:\Default_Folder"
diaFolder.Show
I'm not sure about bash-like environment. You might try some simple wrapper programs in Java (with program arguments) that invoke your MBeans on the remote server. You can then call these wrappers from the shell script
If you can use something like Python or Perl, you might be interested in JSR-262 which allows you to expose JMX operations over web services. This is scheduled to be included in Java 7 but you might be able to use a release candidate of the reference implementation
This works for me:
$("#dateselector").datepicker("option", "defaultDate", new Date(2008,9,3));
To undo git checkout
do git checkout -
, similarly to cd
and cd -
in shell.
This can be done using ServerSocket, same as on JavaSE. This class is available on Android. android.permission.INTERNET
is required.
The only more tricky part, you need a separate thread wait on the ServerSocket, servicing sub-sockets that come from its accept
method. You also need to stop and resume this thread as needed. The simplest approach seems to kill the waiting thread by closing the ServerSocket.
If you only need a server while your activity is on the top, starting and stopping ServerSocket thread can be rather elegantly tied to the activity life cycle methods. Also, if the server has multiple users, it may be good to service requests in the forked threads. If there is only one user, this may not be necessary.
If you need to tell the user on which IP is the server listening,use NetworkInterface.getNetworkInterfaces(), this question may tell extra tricks.
Finally, here there is possibly the complete minimal Android server that is very short, simple and may be easier to understand than finished end user applications, recommended in other answers.
This piece of code is incorrect.
while 1:
(clientsocket, address) = serversocket.accept()
print ("connection found!")
data = clientsocket.recv(1024).decode()
print (data)
r='REceieve'
clientsocket.send(r.encode())
The call on accept()
on the serversocket
blocks until there's a client connection. When you first connect to the server from the client, it accepts the connection and receives data. However, when it enters the loop again, it is waiting for another connection and thus blocks as there are no other clients that are trying to connect.
That's the reason the recv
works correct only the first time. What you should do is find out how you can handle the communication with a client that has been accepted - maybe by creating a new Thread to handle communication with that client and continue accepting new clients in the loop, handling them in the same way.
Tip: If you want to work on creating your own chat application, you should look at a networking engine like Twisted. It will help you understand the whole concept better too.
Create a constructor of FeedAdapter :
Context context; //global
public FeedAdapter(Context context)
{
this.context = context;
}
and in Activity
FeedAdapter obj = new FeedAdapter(this);
Recently I came across a very elegant solution that take in random JSON that you have no idea the structure:
[HttpPost]
public JsonResult Test([FromBody] JsonElement json)
{
return Json(json);
}
Just that easy.
Sometimes it's knowing what to ask. I didn't know as I am a developer who has taken on some DevOps work.
Apparently 'passwordless' or NOPASSWD login is a thing which you need to put in the /etc/sudoers file.
The answer to my question is at Ansible: best practice for maintaining list of sudoers.
The Ansible playbook code fragment looks like this from my problem:
- name: Make sure we have a 'wheel' group
group:
name: wheel
state: present
- name: Allow 'wheel' group to have passwordless sudo
lineinfile:
dest: /etc/sudoers
state: present
regexp: '^%wheel'
line: '%wheel ALL=(ALL) NOPASSWD: ALL'
validate: 'visudo -cf %s'
- name: Add sudoers users to wheel group
user:
name=deployer
groups=wheel
append=yes
state=present
createhome=yes
- name: Set up authorized keys for the deployer user
authorized_key: user=deployer key="{{item}}"
with_file:
- /home/railsdev/.ssh/id_rsa.pub
And the best part is that the solution is idempotent. It doesn't add the line
%wheel ALL=(ALL) NOPASSWD: ALL
to /etc/sudoers when the playbook is run a subsequent time. And yes...I was able to ssh into the server as "deployer" and run sudo commands without having to give a password.
This is another solution in PHP 7.1
/**
* @param array $input Input array to add items to
* @param array $items Items to insert (as an array)
* @param int $position Position to inject items from (starts from 0)
*
* @return array
*/
function arrayInject( array $input, array $items, int $position ): array
{
if (0 >= $position) {
return array_merge($items, $input);
}
if ($position >= count($input)) {
return array_merge($input, $items);
}
return array_merge(
array_slice($input, 0, $position, true),
$items,
array_slice($input, $position, null, true)
);
}
Normaly you can GET and POST parameters in a servlet the same way:
request.getParameter("cmd");
But only if the POST data is encoded as key-value pairs of content type: "application/x-www-form-urlencoded" like when you use a standard HTML form.
If you use a different encoding schema for your post data, as in your case when you post a json data stream, you need to use a custom decoder that can process the raw datastream from:
BufferedReader reader = request.getReader();
Json post processing example (uses org.json package )
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
StringBuffer jb = new StringBuffer();
String line = null;
try {
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null)
jb.append(line);
} catch (Exception e) { /*report an error*/ }
try {
JSONObject jsonObject = HTTP.toJSONObject(jb.toString());
} catch (JSONException e) {
// crash and burn
throw new IOException("Error parsing JSON request string");
}
// Work with the data using methods like...
// int someInt = jsonObject.getInt("intParamName");
// String someString = jsonObject.getString("stringParamName");
// JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName");
// JSONArray arr = jsonObject.getJSONArray("arrayParamName");
// etc...
}
Finally decided to downgrade the junit 5 to junit 4 and rebuild the testing environment.
To remove any doubt, my solution was to make a deep copy of the slice instead of a regular copy. This may not be applicable depending on your context (Memory constraints / size of the slice, potential for performance degradation - especially if the copy occurs in a loop like it did for me, etc...)
To be clear, here is the warning I received:
/opt/anaconda3/lib/python3.6/site-packages/ipykernel/__main__.py:54:
SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame
See the caveats in the documentation:
http://pandas.pydata.org/pandas-docs/stable/indexing.html#indexing-view-versus-copy
I had doubts that the warning was thrown because of a column I was dropping on a copy of the slice. While not technically trying to set a value in the copy of the slice, that was still a modification of the copy of the slice. Below are the (simplified) steps I have taken to confirm the suspicion, I hope it will help those of us who are trying to understand the warning.
We knew that already but this is a healthy reminder. This is NOT what the warning is about.
>> data1 = {'A': [111, 112, 113], 'B':[121, 122, 123]}
>> df1 = pd.DataFrame(data1)
>> df1
A B
0 111 121
1 112 122
2 113 123
>> df2 = df1
>> df2
A B
0 111 121
1 112 122
2 113 123
# Dropping a column on df1 affects df2
>> df1.drop('A', axis=1, inplace=True)
>> df2
B
0 121
1 122
2 123
It is possible to avoid changes made on df1 to affect df2. Note: you can avoid importing copy.deepcopy
by doing df.copy()
instead.
>> data1 = {'A': [111, 112, 113], 'B':[121, 122, 123]}
>> df1 = pd.DataFrame(data1)
>> df1
A B
0 111 121
1 112 122
2 113 123
>> import copy
>> df2 = copy.deepcopy(df1)
>> df2
A B
0 111 121
1 112 122
2 113 123
# Dropping a column on df1 does not affect df2
>> df1.drop('A', axis=1, inplace=True)
>> df2
A B
0 111 121
1 112 122
2 113 123
This actually illustrates the warning.
>> data1 = {'A': [111, 112, 113], 'B':[121, 122, 123]}
>> df1 = pd.DataFrame(data1)
>> df1
A B
0 111 121
1 112 122
2 113 123
>> df2 = df1
>> df2
A B
0 111 121
1 112 122
2 113 123
# Dropping a column on df2 can affect df1
# No slice involved here, but I believe the principle remains the same?
# Let me know if not
>> df2.drop('A', axis=1, inplace=True)
>> df1
B
0 121
1 122
2 123
It is possible to avoid changes made on df2 to affect df1
>> data1 = {'A': [111, 112, 113], 'B':[121, 122, 123]}
>> df1 = pd.DataFrame(data1)
>> df1
A B
0 111 121
1 112 122
2 113 123
>> import copy
>> df2 = copy.deepcopy(df1)
>> df2
A B
0 111 121
1 112 122
2 113 123
>> df2.drop('A', axis=1, inplace=True)
>> df1
A B
0 111 121
1 112 122
2 113 123
Cheers!
I have hard time when trying to
So I made 2020 answer here
My directory looks like this
+-- docker-compose.yml
+-- mongo-entrypoint
+-- entrypoint.js
My docker-compose.yml
looks like this
version: '3.4'
services:
mongo-container:
# If you need to connect to your db from outside this container
network_mode: host
image: mongo:4.2
environment:
- MONGO_INITDB_ROOT_USERNAME=admin
- MONGO_INITDB_ROOT_PASSWORD=pass
ports:
- "27017:27017"
volumes:
- "$PWD/mongo-entrypoint/:/docker-entrypoint-initdb.d/"
command: mongod
Please change admin
and pass
with your need.
Inside mongo-entrypoint
, I have entrypoint.js
file with this content:
var db = connect("mongodb://admin:pass@localhost:27017/admin");
db = db.getSiblingDB('new_db'); // we can not use "use" statement here to switch db
db.createUser(
{
user: "user",
pwd: "pass",
roles: [ { role: "readWrite", db: "new_db"} ],
passwordDigestor: "server",
}
)
Here again you need to change admin:pass
to your root mongo credentials in your docker-compose.yml
that you stated before. In additional you need to change new_db
, user
, pass
to your new database name and credentials that you need.
Now you can:
docker-compose up -d
And connect to this db from localhost, please note that I already have mongo cli, you can install it or you can exec to the container above to use mongo
command:
mongo new_db -u user -p pass
Or you can connect from other computer
mongo host:27017/new_db -u user -p pass
My git repository: https://github.com/sexydevops/docker-compose-mongo
Hope it can help someone, I lost my afternoon for this ;)
As others have noted, you can use SQL Profiler, but you can also leverage it's functionality through sp_trace_* system stored procedures. For example, this SQL snippet will (on 2000 at least; I think it's the same for SQL 2008 but you'll have to double-check) catch RPC:Completed
and SQL:BatchCompleted
events for all queries that take over 10 seconds to run, and save the output to a tracefile that you can open up in SQL profiler at a later date:
DECLARE @TraceID INT
DECLARE @ON BIT
DECLARE @RetVal INT
SET @ON = 1
exec @RetVal = sp_trace_create @TraceID OUTPUT, 2, N'Y:\TraceFile.trc'
print 'This trace is Trace ID = ' + CAST(@TraceID AS NVARCHAR)
print 'Return value = ' + CAST(@RetVal AS NVARCHAR)
-- 10 = RPC:Completed
exec sp_trace_setevent @TraceID, 10, 1, @ON -- Textdata
exec sp_trace_setevent @TraceID, 10, 3, @ON -- DatabaseID
exec sp_trace_setevent @TraceID, 10, 12, @ON -- SPID
exec sp_trace_setevent @TraceID, 10, 13, @ON -- Duration
exec sp_trace_setevent @TraceID, 10, 14, @ON -- StartTime
exec sp_trace_setevent @TraceID, 10, 15, @ON -- EndTime
-- 12 = SQL:BatchCompleted
exec sp_trace_setevent @TraceID, 12, 1, @ON -- Textdata
exec sp_trace_setevent @TraceID, 12, 3, @ON -- DatabaseID
exec sp_trace_setevent @TraceID, 12, 12, @ON -- SPID
exec sp_trace_setevent @TraceID, 12, 13, @ON -- Duration
exec sp_trace_setevent @TraceID, 12, 14, @ON -- StartTime
exec sp_trace_setevent @TraceID, 12, 15, @ON -- EndTime
-- Filter for duration [column 13] greater than [operation 2] 10 seconds (= 10,000ms)
declare @duration bigint
set @duration = 10000
exec sp_trace_setfilter @TraceID, 13, 0, 2, @duration
You can find the ID for each trace-event, columns, etc from Books Online; just search for the sp_trace_create, sp_trace_setevent and sp_trace_setfiler sprocs. You can then control the trace as follows:
exec sp_trace_setstatus 15, 0 -- Stop the trace
exec sp_trace_setstatus 15, 1 -- Start the trace
exec sp_trace_setstatus 15, 2 -- Close the trace file and delete the trace settings
...where '15' is the trace ID (as reported by sp_trace_create, which the first script kicks out, above).
You can check to see what traces are running with:
select * from ::fn_trace_getinfo(default)
The only thing I will say in caution -- I do not know how much load this will put on your system; it will add some, but how big that "some" is probably depends how busy your server is.
I recommend looking at the dataset array.
The dataset array is a data type that ships with Statistics Toolbox. It is specifically designed to store hetrogeneous data in a single container.
The Statistics Toolbox demo page contains a couple vidoes that show some of the dataset array features. The first is titled "An Introduction to Dataset Arrays". The second is titled "An Introduction to Joins".
Encountered this issue quite a few times, note that I'm running laravel via Vagrant. So here are the fixes that work for me:
You may try reloading your server instead of vagrant (ie MAMP)
To make the execution after the boolean has changed and avoid the usage of timeout you can do:
import { ChangeDetectorRef } from '@angular/core';
constructor(private cd: ChangeDetectorRef) {}
showSearch(){
this.show = !this.show;
this.cd.detectChanges();
this.searchElement.nativeElement.focus();
}
Just be aware also that catalina.out can be renamed - it can be set in /bin/catalina.sh with the CATALINA_OUT environment variable.
It's now possible to add a forced line break
with two blank spaces at the end of the line:
line1??
line2
will be formatted as:
line1
line2
Just use "\n" in your strings.xml file as below
<string name="relaxing_sounds">RELAXING\nSOUNDS</string>
Even if it doesn't looks 2 lines on layout actually it is 2 lines. Firstly you can check it on Translation Editor
Click the down button and you will see this image
Moreover if you run the app you will see that it is written in two lines.
You try to instantiate an object of the Friends
class like this:
Friends f = new Friends(friendsName, friendsAge);
The class does not have a constructor that takes parameters. You should either add the constructor, or create the object using the constructor that does exist and then use the set-methods. For example, instead of the above:
Friends f = new Friends();
f.setName(friendsName);
f.setAge(friendsAge);
Thank you for this
Here's what I did:
1.Created an Extensions.cs file in a Utils folder.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace Web.ProjectName.Utils
{
public class Extensions
{
public static IEnumerable<SelectListItem> GetStatesList()
{
IList<SelectListItem> states = new List<SelectListItem>
{
new SelectListItem() {Text="Alabama", Value="AL"},
new SelectListItem() { Text="Alaska", Value="AK"},
new SelectListItem() { Text="Arizona", Value="AZ"},
new SelectListItem() { Text="Arkansas", Value="AR"},
new SelectListItem() { Text="California", Value="CA"},
new SelectListItem() { Text="Colorado", Value="CO"},
new SelectListItem() { Text="Connecticut", Value="CT"},
new SelectListItem() { Text="District of Columbia", Value="DC"},
new SelectListItem() { Text="Delaware", Value="DE"},
new SelectListItem() { Text="Florida", Value="FL"},
new SelectListItem() { Text="Georgia", Value="GA"},
new SelectListItem() { Text="Hawaii", Value="HI"},
new SelectListItem() { Text="Idaho", Value="ID"},
new SelectListItem() { Text="Illinois", Value="IL"},
new SelectListItem() { Text="Indiana", Value="IN"},
new SelectListItem() { Text="Iowa", Value="IA"},
new SelectListItem() { Text="Kansas", Value="KS"},
new SelectListItem() { Text="Kentucky", Value="KY"},
new SelectListItem() { Text="Louisiana", Value="LA"},
new SelectListItem() { Text="Maine", Value="ME"},
new SelectListItem() { Text="Maryland", Value="MD"},
new SelectListItem() { Text="Massachusetts", Value="MA"},
new SelectListItem() { Text="Michigan", Value="MI"},
new SelectListItem() { Text="Minnesota", Value="MN"},
new SelectListItem() { Text="Mississippi", Value="MS"},
new SelectListItem() { Text="Missouri", Value="MO"},
new SelectListItem() { Text="Montana", Value="MT"},
new SelectListItem() { Text="Nebraska", Value="NE"},
new SelectListItem() { Text="Nevada", Value="NV"},
new SelectListItem() { Text="New Hampshire", Value="NH"},
new SelectListItem() { Text="New Jersey", Value="NJ"},
new SelectListItem() { Text="New Mexico", Value="NM"},
new SelectListItem() { Text="New York", Value="NY"},
new SelectListItem() { Text="North Carolina", Value="NC"},
new SelectListItem() { Text="North Dakota", Value="ND"},
new SelectListItem() { Text="Ohio", Value="OH"},
new SelectListItem() { Text="Oklahoma", Value="OK"},
new SelectListItem() { Text="Oregon", Value="OR"},
new SelectListItem() { Text="Pennsylvania", Value="PA"},
new SelectListItem() { Text="Rhode Island", Value="RI"},
new SelectListItem() { Text="South Carolina", Value="SC"},
new SelectListItem() { Text="South Dakota", Value="SD"},
new SelectListItem() { Text="Tennessee", Value="TN"},
new SelectListItem() { Text="Texas", Value="TX"},
new SelectListItem() { Text="Utah", Value="UT"},
new SelectListItem() { Text="Vermont", Value="VT"},
new SelectListItem() { Text="Virginia", Value="VA"},
new SelectListItem() { Text="Washington", Value="WA"},
new SelectListItem() { Text="West Virginia", Value="WV"},
new SelectListItem() { Text="Wisconsin", Value="WI"},
new SelectListItem() { Text="Wyoming", Value="WY"}
};
return states;
}
}
}
2.In my model, where state will be abbreviated (e.g. "AL", "NY", etc.):
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
namespace Web.ProjectName.Models
{
public class ContactForm
{
...
[Required]
[Display(Name = "State")]
[RegularExpression("[A-Z]{2}")]
public string State { get; set; }
...
}
}
2.In my view I referenced it:
@model Web.ProjectName.Models.ContactForm
...
@Html.LabelFor(x => x.State, new { @class = "form-label" })
@Html.DropDownListFor(x => x.State, Web.ProjectName.Utils.Extensions.GetStatesList(), new { @class = "form-control" })
...
The columns in the result set of a select
query with group by
clause must be:
group by
criteria , or ...So, you can't do what you want to do in a single, simple query. The first thing to do is state your problem statement in a clear way, something like:
I want to find the individual claim row bearing the most recent creation date within each group in my claims table
Given
create table dbo.some_claims_table
(
claim_id int not null ,
group_id int not null ,
date_created datetime not null ,
constraint some_table_PK primary key ( claim_id ) ,
constraint some_table_AK01 unique ( group_id , claim_id ) ,
constraint some_Table_AK02 unique ( group_id , date_created ) ,
)
The first thing to do is identify the most recent creation date for each group:
select group_id ,
date_created = max( date_created )
from dbo.claims_table
group by group_id
That gives you the selection criteria you need (1 row per group, with 2 columns: group_id and the highwater created date) to fullfill the 1st part of the requirement (selecting the individual row from each group. That needs to be a virtual table in your final select
query:
select *
from dbo.claims_table t
join ( select group_id ,
date_created = max( date_created )
from dbo.claims_table
group by group_id
) x on x.group_id = t.group_id
and x.date_created = t.date_created
If the table is not unique by date_created
within group_id
(AK02), you you can get duplicate rows for a given group.
Is Viewstate turned on?
Edit: Perhaps you should reconsider overriding the rendering function
protected override void RenderContents(HtmlTextWriter output)
{
ddlCountries.RenderControl(output);
ddlStates.RenderControl(output);
}
and instead add the dropdownlists to the control and render the control using the default RenderContents.
Edit: See the answer from Dennis which I alluded to in my previous comment:
Controls.Add ( ddlCountries );
Controls.Add ( ddlStates );
This is a tricky question.
There a set of problems about file permissions. If you can do this at the command line
$ sudo chown myaccount /path/to/file
then you have a standard permissions problem. Make sure you own the file and have permission to modify the directory.
If you cannnot get permissions, then you have probably mounted a FAT-32 filesystem. If you ls -l
the file, and you find it is owned by root and a member of the "plugdev" group, then you are certain its the issue. FAT-32 permissions are set at the time of mounting, using the line of /etc/fstab file. You can set the uid/gid of all the files like this:
UUID=C14C-CE25 /big vfat utf8,umask=007,uid=1000,gid=1000 0 1
Also, note that the FAT-32 won't take symbolic links.
Wrote the whole thing up at http://www.charlesmerriam.com/blog/2009/12/operation-not-permitted-and-the-fat-32-system/
The OP implied that Java 7 was the need. And Java 6 is in fact no longer being 'supported' so 7 is the version you should be installing at this point unless you have legacy app concerns.
You can get it here: http://java.com/en/download/mac_download.jsp?locale=en
Here's a less involved trick to deal with media queries. Cross browser support is a bit limiting as it doesn't support mobile IE.
if (window.matchMedia('(max-width: 694px)').matches)
{
//do desired changes
}
See Mozilla documentation for more details.
I have a suspicion that this is related to the parser that BS will use to read the HTML. They document is here, but if you're like me (on OSX) you might be stuck with something that requires a bit of work:
You'll notice that in the BS4 documentation page above, they point out that by default BS4 will use the Python built-in HTML parser. Assuming you are in OSX, the Apple-bundled version of Python is 2.7.2 which is not lenient for character formatting. I hit this same problem, so I upgraded my version of Python to work around it. Doing this in a virtualenv will minimize disruption to other projects.
If doing that sounds like a pain, you can switch over to the LXML parser:
pip install lxml
And then try:
soup = BeautifulSoup(html, "lxml")
Depending on your scenario, that might be good enough. I found this annoying enough to warrant upgrading my version of Python. Using virtualenv, you can migrate your packages fairly easily.
This is a version of Ben James's answer, above:
>>> import datetime
>>> x = datetime.date.today()
>>> print x
2013-01-11
>>>
>>>
>>> print "Today's date is %s ..." % x
Today's date is 2013-01-11 ...
>>>
>>> print "Today's date is %r ..." % x
Today's date is datetime.date(2013, 1, 11) ...
>>>
When I ran this, it helped me see the usefulness of %r.
No it is not possible to override a constructor. If we try to do this then compiler error will come. And it is never possible in Java. Lets see the example. It will ask please write a return type o the method. means it will treat that overriden constructor as a method not as a constructor.
package com.sample.test;
class Animal{
public static void showMessage()
{
System.out.println("we are in Animal class");
}
}
class Dog extends Animal{
public void DogShow()
{
System.out.println("we are in Dog show class");
}
public static void showMessage()
{
System.out.println("we are in overriddn method of dog class");
}
}
public class AnimalTest {
public static void main(String [] args)
{
Animal animal = new Animal();
animal.showMessage();
Dog dog = new Dog();
dog.DogShow();
Animal animal2 = new Dog();
animal2.showMessage();
}
}
Try this more succinct code:
Sub LoopOverEachColumn()
Dim WS As Worksheet
For Each WS In ThisWorkbook.Worksheets
ResizeColumns WS
Next WS
End Sub
Private Sub ResizeColumns(WS As Worksheet)
Dim StrSize As String
Dim ColIter As Long
StrSize = "20.14;9.71;35.86;30.57;23.57;21.43;18.43;23.86;27.43;36.71;30.29;31.14;31;41.14;33.86"
For ColIter = 1 To 15
WS.Columns(ColIter).ColumnWidth = Split(StrSize, ";")(ColIter - 1)
Next ColIter
End Sub
If you want additional columns, just change 1 to 15
to 1 to X
where X
is the column index of the column you want, and append the column size you want to StrSize
.
For example, if you want P:P
to have a width of 25
, just add ;25
to StrSize
and change ColIter...
to ColIter = 1 to 16
.
Hope this helps.