i have used it in this way and its working fine
quantity=prompt("Please enter the quantity","1");
quantity=parseInt(quantity);
if (!isNaN( quantity ))
{
totalAmount=itemPrice*quantity;
}
return totalAmount;
Abstract: Steps of How to resolve "Serial port 'COM1' not found" in fedora 17.
Today install the packages for Arduino in Fedora 17. (yum install arduino) and I have the same problem: I decided to upload an example to the chip. and got the same error "Serial port 'COM1' not found".
In this case when I run Arduino program, some banner appears which warns me that my user is not in 'dialout' and 'lock' group. Do you want add your user in this groups? I click in add button, but for some reason the program fail and not say nothing.
Step1: recognize the Arduino device unplug your Arduino and list /dev files:
#ls -l /dev
plug your Arduino and go and list /dev files
#ls -l /dev
Find the new file (device) that was not before plugging, for example:
ttyACM0 or ttyUSB1
Read this properties:
ls -l /dev/ttyACM0
crw-rw---- 1 root dialout 166, 0 Dec 24 19:25 /dev/ttyACM0
the first c mean that Arduino is a character device.
user owner: root
group owner: dialout
mayor number: 166
minor number: 0
Step2: set your user as group owner.
If you do:
groups <yourUser>
And you are not in 'dialout' and/or 'lock' group. Add yourself in this groups run as root:
usermod -aG lock <yourUser>
usermod -aG dialout <yourUser>
restart the pc, and set /dev/<yourDeviceFile>
as your serial port before upload.
The answers above will work for changing the values.
If you want to change the number of cells in your list (e.g. I have a list called 'revisions' which has 4 items, I now need 7 items) you will find that you can't simply select your list and amend it on the sheet, So:
go to your 'Formulas' tab
choose "Name Manager"
a pop up box will show what is available for editing. Your list should be in it. Select your list and edit the range.
Replace <?php the_content();?>
by the code below
<?php
$char_limit = 100; //character limit
$content = $post->post_content; //contents saved in a variable
echo substr(strip_tags($content), 0, $char_limit);
?>
i guess you mean System Programs and Application programs
System Programs makes the hardware run , Applications are for specific tasks
an Example for System Programs are Device Drivers
as for the Applications you can say web browsers , word porcessros etc
Bearer token is one or more repetition of alphabet, digit, "-" , "." , "_" , "~" , "+" , "/" followed by 0 or more "=".
RFC 6750 2.1. Authorization Request Header Field (Format is ABNF (Augmented BNF))
The syntax for Bearer credentials is as follows:
b64token = 1*( ALPHA / DIGIT /
"-" / "." / "_" / "~" / "+" / "/" ) *"="
credentials = "Bearer" 1*SP b64token
It looks like Base64 but according to Should the token in the header be base64 encoded?, it is not.
Digging a bit deeper in to "HTTP/1.1, part 7: Authentication"**, however, I see that b64token is just an ABNF syntax definition allowing for characters typically used in base64, base64url, etc.. So the b64token doesn't define any encoding or decoding but rather just defines what characters can be used in the part of the Authorization header that will contain the access token.
This fully addresses the first 3 items in the OP question's list. So I'm extending this answer to address the 4th question, about whether the token must be validated, so @mon feel free to remove or edit:
The authorizer is responsible for accepting or rejecting the http request. If the authorizer says the token is valid, it's up to you to decide what this means:
Here are the high-level differences:
You want:
document.cookie = cookieName +"=" + cookieValue + ";domain=.example.com;path=/;expires=" + myDate;
As per the RFC 2109, to have a cookie available to all subdomains, you must put a .
in front of your domain.
Setting the path=/ will have the cookie be available within the entire specified domain(aka .example.com
).
Using Windows Script:
Set ComputerObj = GetObject("WinNT://MYCOMPUTER")
ComputerObj.Filter = Array("Service")
For Each Service in ComputerObj
WScript.Echo "Service display name = " & Service.DisplayName
WScript.Echo "Service account name = " & Service.ServiceAccountName
WScript.Echo "Service executable = " & Service.Path
WScript.Echo "Current status = " & Service.Status
Next
You can easily filter the above for the specific service you want.
find . ! -name "node_modules" -type d
Building on the excellent responses from previous answers, in Bootstrap 5 with no jQuery, this has worked;
document.querySelector('[data-target="#exampleModal"]').click();
Full snippet:
window.onload = () => {
document.querySelector('[data-target="#exampleModal"]').click();
}
_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" rel="stylesheet" />
<div class="container py-3">
<!-- Button trigger modal -->
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
</div>
_x000D_
User lodash javascript library and use _.debounce function
changeName: _.debounce(function (val) {
console.log(val)
}, 1000)
Docker really needs to implement this as a new feature, but here's another workaround option for situations in which you have an Entrypoint that terminates after success or failure, which can make it difficult to debug.
If you don't already have an Entrypoint script, create one that runs whatever command(s) you need for your container. Then, at the top of this file, add these lines to entrypoint.sh
:
# Run once, hold otherwise
if [ -f "already_ran" ]; then
echo "Already ran the Entrypoint once. Holding indefinitely for debugging."
cat
fi
touch already_ran
# Do your main things down here
To ensure that cat
holds the connection, you may need to provide a TTY. I'm running the container with my Entrypoint script like so:
docker run -t --entrypoint entrypoint.sh image_name
This will cause the script to run once, creating a file that indicates it has already run (in the container's virtual filesystem). You can then restart the container to perform debugging:
docker start container_name
When you restart the container, the already_ran
file will be found, causing the Entrypoint script to stall with cat
(which just waits forever for input that will never come, but keeps the container alive). You can then execute a debugging bash
session:
docker exec -i container_name bash
While the container is running, you can also remove already_ran
and manually execute the entrypoint.sh
script to rerun it, if you need to debug that way.
dt.Columns[0].DataType.Name.ToString()
to add a little more to the answer from b_levitt... on global.asax:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.UI;
namespace LoginPage
{
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
string JQueryVer = "1.11.3";
ScriptManager.ScriptResourceMapping.AddDefinition("jquery", new ScriptResourceDefinition
{
Path = "~/js/jquery-" + JQueryVer + ".min.js",
DebugPath = "~/js/jquery-" + JQueryVer + ".js",
CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + JQueryVer + ".min.js",
CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-" + JQueryVer + ".js",
CdnSupportsSecureConnection = true,
LoadSuccessExpression = "window.jQuery"
});
}
}
}
on your default.aspx
<body>
<form id="UserSectionForm" runat="server">
<asp:ScriptManager ID="ScriptManager" runat="server">
<Scripts>
<asp:ScriptReference Name="jquery" />
</Scripts>
</asp:ScriptManager>
<%--rest of your markup goes here--%>
</form>
</body>
Have you tried gdb -w with cygwin gdb. It is supossed to have a windows interface which works fairly well.
The only problem I found is that on my present machine it didn't run that way until after I installed ddd. I suspect that it requires tcltk which was installed when I installed ddd.
Writing a null character to the first character does just that. If you treat it as a string, code obeying the null termination character will treat it as a null string, but that is not the same as clearing the data. If you want to actually clear the data you'll need to use memset.
Firstly, follow Energya's instruction:
pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
pip install jupyter_nbextensions_configurator
jupyter nbextensions_configurator enable --user
Second is the key: After opening jupiter notebook, click the Nbextension tab. Now Search "colla" from the searching tool provided by Nbextension(not by the web browser), then you will find something called "Collapsible Headings"
This is what you want!
This information is available in the sys.version
string in the sys
module:
>>> import sys
Human readable:
>>> print(sys.version) # parentheses necessary in python 3.
2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
[GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)]
For further processing, use sys.version_info
or sys.hexversion
:
>>> sys.version_info
(2, 5, 2, 'final', 0)
# or
>>> sys.hexversion
34014192
To ensure a script runs with a minimal version requirement of the Python interpreter add this to your code:
assert sys.version_info >= (2, 5)
This compares major and minor version information. Add micro (=0
, 1
, etc) and even releaselevel (='alpha'
,'final'
, etc) to the tuple as you like. Note however, that it is almost always better to "duck" check if a certain feature is there, and if not, workaround (or bail out). Sometimes features go away in newer releases, being replaced by others.
var boxSummary = from b in boxes
group b by b.Owner into g
let nrBoxes = g.Count()
let totalWeight = g.Sum(w => w.Weight)
let totalVolume = g.Sum(v => v.Volume)
select new { Owner = g.Key, Boxes = nrBoxes,
TotalWeight = totalWeight,
TotalVolume = totalVolume }
By searching for my userid in the registry, I found
HKEY_CURRENT_USER\Volatile Environment\Username
Try this.
function getAge(dateString) {
var today = new Date();
var birthDate = new Date(dateString);
var age = today.getFullYear() - birthDate.getFullYear();
var m = today.getMonth() - birthDate.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
age--;
}
return age;
}
I believe the only thing that looked crude on your code was the substr
part.
Swift 4.2
For multiple selections you need to set the UITableView
property allowsMultipleSelection
to true.
myTableView.allowsMultipleSelection = true
In case you subclassed the UITableViewCell, you override setSelected(_ selected: Bool, animated: Bool)
method in your custom cell class.
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
contentView.backgroundColor = UIColor.green
} else {
contentView.backgroundColor = UIColor.blue
}
}
I had to do something like this just now. I ended up doing:
function newWaitImg(id) {
var img = {
"id" : id,
"state" : "on",
"hide" : function () {
$(this.id).hide();
this.state = "off";
},
"show" : function () {
$(this.id).show();
this.state = "on";
},
"toggle" : function () {
if (this.state == "on") {
this.hide();
} else {
this.show();
}
}
};
};
.
.
.
var waitImg = newWaitImg("#myImg");
.
.
.
waitImg.hide(); / waitImg.show(); / waitImg.toggle();
You could use a map function that allows multiple arguments, as does the fork of multiprocessing
found in pathos
.
>>> from pathos.multiprocessing import ProcessingPool as Pool
>>>
>>> def add_and_subtract(x,y):
... return x+y, x-y
...
>>> res = Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))
>>> res
[(-5, 5), (-2, 6), (1, 7), (4, 8), (7, 9), (10, 10), (13, 11), (16, 12), (19, 13), (22, 14)]
>>> Pool().map(add_and_subtract, *zip(*res))
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]
pathos
enables you to easily nest hierarchical parallel maps with multiple inputs, so we can extend our example to demonstrate that.
>>> from pathos.multiprocessing import ThreadingPool as TPool
>>>
>>> res = TPool().amap(add_and_subtract, *zip(*Pool().map(add_and_subtract, range(0,20,2), range(-5,5,1))))
>>> res.get()
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]
Even more fun, is to build a nested function that we can pass into the Pool.
This is possible because pathos
uses dill
, which can serialize almost anything in python.
>>> def build_fun_things(f, g):
... def do_fun_things(x, y):
... return f(x,y), g(x,y)
... return do_fun_things
...
>>> def add(x,y):
... return x+y
...
>>> def sub(x,y):
... return x-y
...
>>> neato = build_fun_things(add, sub)
>>>
>>> res = TPool().imap(neato, *zip(*Pool().map(neato, range(0,20,2), range(-5,5,1))))
>>> list(res)
[(0, -10), (4, -8), (8, -6), (12, -4), (16, -2), (20, 0), (24, 2), (28, 4), (32, 6), (36, 8)]
If you are not able to go outside of the standard library, however, you will have to do this another way. Your best bet in that case is to use multiprocessing.starmap
as seen here: Python multiprocessing pool.map for multiple arguments (noted by @Roberto in the comments on the OP's post)
Get pathos
here: https://github.com/uqfoundation
There is issues with the precision of the accepted answer.
the round(value, decimals) function in this test works. unlike the simple toFixed example.
http://www.jacklmoore.com/notes/rounding-in-javascript/
Number.prototype.format = function(n) {_x000D_
return this.toFixed(Math.max(0, ~~n));_x000D_
};_x000D_
function round(value, decimals) {_x000D_
return Number(Math.round(value+'e'+decimals)+'e-'+decimals);_x000D_
}_x000D_
_x000D_
// can anyone tell me why these are equivalent for 50.005, and 1050.005 through 8150.005 (increments of 50)_x000D_
_x000D_
var round_to = 2;_x000D_
var maxInt = 1500000;_x000D_
var equalRound = '<h1>BEGIN HERE</h1><div class="matches">';_x000D_
var increment = 50;_x000D_
var round_from = 0.005;_x000D_
var expected = 0.01;_x000D_
var lastWasMatch = true;_x000D_
_x000D_
for( var n = 0; n < maxInt; n=n+increment){_x000D_
var data = {};_x000D_
var numberCheck = parseFloat(n + round_from);_x000D_
data.original = numberCheck * 1;_x000D_
data.expected = Number(n + expected) * 1;_x000D_
data.formatIt = Number(numberCheck).format(round_to) * 1;_x000D_
data.roundIt = round(numberCheck, round_to).toFixed(round_to) * 1;_x000D_
data.numberIt = Number(numberCheck).toFixed(round_to) * 1;_x000D_
//console.log(data);_x000D_
_x000D_
if( data.roundIt !== data.formatIt || data.formatIt !== data.numberIt ||_x000D_
data.roundIt !== data.numberIt || data.roundIt != data.expected_x000D_
){_x000D_
if(lastWasMatch){_x000D_
equalRound = equalRound + '</div><div class="errors"> <hr/> Did Not Round UP <hr/>' ;_x000D_
document.write(' <h3>EXAMPLE: Did Not Round UP: ' + numberCheck + '</h3><br /><hr/> ');_x000D_
document.write('expected: '+data.expected + ' :: ' + (typeof data.expected) + '<br />');_x000D_
document.write('format: '+data.formatIt + ' :: ' + (typeof data.formatIt) + '<br />');_x000D_
document.write('round : '+data.roundIt + ' :: ' + (typeof data.roundIt) + '<br />');_x000D_
document.write('number: '+data.numberIt + ' :: ' + (typeof data.numberIt) + '<br />');_x000D_
lastWasMatch=false;_x000D_
}_x000D_
equalRound = equalRound + ', ' + numberCheck;_x000D_
} else {_x000D_
if(!lastWasMatch){_x000D_
equalRound = equalRound + '</div><div class="matches"> <hr/> All Rounded UP! <hr/>' ;_x000D_
} {_x000D_
lastWasMatch=true;_x000D_
}_x000D_
equalRound = equalRound + ', ' + numberCheck;_x000D_
}_x000D_
}_x000D_
document.write('equalRound: '+equalRound + '</div><br />');
_x000D_
export default {_x000D_
methods: {_x000D_
roundFormat: function (value, decimals) {_x000D_
return Number(Math.round(value+'e'+decimals)+'e-'+decimals).toFixed(decimals);_x000D_
},_x000D_
currencyFormat: function (value, decimals, symbol='$') {_x000D_
return symbol + this.roundFormat(value,2);_x000D_
}_x000D_
}_x000D_
}
_x000D_
use below code
Task.WaitAll(Task.Run(async () => await GetResponse<MyObject>("my url")));
C++20 std::format
options <
, ^
and >
According to https://en.cppreference.com/w/cpp/utility/format/formatter#Standard_format_specification the following should hold:
// left: "42 "
std::cout << std::format("{:<6}", 42);
// right: " 42"
std::cout << std::format("{:>6}", 42);
// center: " 42 "
std::cout << std::format("{:^6}", 42);
More information at: std::string formatting like sprintf
If the number of fields in the CSV is constant then you could do something like this:
select a[1], a[2], a[3], a[4]
from (
select regexp_split_to_array('a,b,c,d', ',')
) as dt(a)
For example:
=> select a[1], a[2], a[3], a[4] from (select regexp_split_to_array('a,b,c,d', ',')) as dt(a);
a | a | a | a
---+---+---+---
a | b | c | d
(1 row)
If the number of fields in the CSV is not constant then you could get the maximum number of fields with something like this:
select max(array_length(regexp_split_to_array(csv, ','), 1))
from your_table
and then build the appropriate a[1], a[2], ..., a[M]
column list for your query. So if the above gave you a max of 6, you'd use this:
select a[1], a[2], a[3], a[4], a[5], a[6]
from (
select regexp_split_to_array(csv, ',')
from your_table
) as dt(a)
You could combine those two queries into a function if you wanted.
For example, give this data (that's a NULL in the last row):
=> select * from csvs;
csv
-------------
1,2,3
1,2,3,4
1,2,3,4,5,6
(4 rows)
=> select max(array_length(regexp_split_to_array(csv, ','), 1)) from csvs;
max
-----
6
(1 row)
=> select a[1], a[2], a[3], a[4], a[5], a[6] from (select regexp_split_to_array(csv, ',') from csvs) as dt(a);
a | a | a | a | a | a
---+---+---+---+---+---
1 | 2 | 3 | | |
1 | 2 | 3 | 4 | |
1 | 2 | 3 | 4 | 5 | 6
| | | | |
(4 rows)
Since your delimiter is a simple fixed string, you could also use string_to_array
instead of regexp_split_to_array
:
select ...
from (
select string_to_array(csv, ',')
from csvs
) as dt(a);
Thanks to Michael for the reminder about this function.
You really should redesign your database schema to avoid the CSV column if at all possible. You should be using an array column or a separate table instead.
With lattice
:
library(lattice)
df <- data.frame(time = 1:10,
a = cumsum(rnorm(10)),
b = cumsum(rnorm(10)),
c = cumsum(rnorm(10)))
form <- as.formula(paste(paste(names(df)[- 1], collapse = ' + '),
'time', sep = '~'))
xyplot(form, data = df, type = 'b', outer = TRUE)
To add a very important note on what Mark S. has mentioned in his post. In the specific SQL Script that has been mentioned in the question you can NEVER mention two different file groups for storing your data rows and the index data structure.
The reason why is due to the fact that the index being created in this case is a clustered Index on your primary key column. The clustered index data and the data rows of your table can NEVER be on different file groups.
So in case you have two file groups on your database e.g. PRIMARY and SECONDARY then below mentioned script will store your row data and clustered index data both on PRIMARY file group itself even though I've mentioned a different file group ([SECONDARY]
) for the table data. More interestingly the script runs successfully as well (when I was expecting it to give an error as I had given two different file groups :P). SQL Server does the trick behind the scene silently and smartly.
CREATE TABLE [dbo].[be_Categories](
[CategoryID] [uniqueidentifier] ROWGUIDCOL NOT NULL CONSTRAINT [DF_be_Categories_CategoryID] DEFAULT (newid()),
[CategoryName] [nvarchar](50) NULL,
[Description] [nvarchar](200) NULL,
[ParentID] [uniqueidentifier] NULL,
CONSTRAINT [PK_be_Categories] PRIMARY KEY CLUSTERED
(
[CategoryID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [SECONDARY]
GO
NOTE: Your index can reside on a different file group ONLY if the index being created is non-clustered in nature.
The below script which creates a non-clustered index will get created on [SECONDARY]
file group instead when the table data already resides on [PRIMARY]
file group:
CREATE NONCLUSTERED INDEX [IX_Categories] ON [dbo].[be_Categories]
(
[CategoryName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [Secondary]
GO
You can get more information on how storing non-clustered indexes on a different file group can help your queries perform better. Here is one such link.
Windows 7, conda 4.4.10 python 2.7.6 Downloaded opencv package from Unofficial Windows Binaries for python extensions packages. (picked python 2.4 AMD 64) cd Download pip install opencv_python... python run_some.py (where import cv2 ...) seems to work. YMMV
I had to make some long descriptions ellipse(take only one lane) while being responsive, so my solution was to let the text wrap(instead of white-space: nowrap
) and instead of fixed width I added fixed height:
span {_x000D_
display: inline-block;_x000D_
line-height: 1rem;_x000D_
height: 1rem;_x000D_
overflow: hidden;_x000D_
// OPTIONAL LINES_x000D_
width: 75%;_x000D_
background: green;_x000D_
// white-space: normal; default_x000D_
}
_x000D_
<span>_x000D_
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Commodi quia quod reprehenderit saepe sit. Animi deleniti distinctio dolorum iste molestias reiciendis saepe. Ea eius ex, ipsam iusto laudantium natus obcaecati quas rem repellat temporibus! A alias at, atque deserunt dignissimos dolor earum, eligendi eveniet exercitationem natus non, odit sint sit tempore voluptate. Commodi culpa ex facere id minima nihil nulla omnis praesentium quasi quia quibusdam recusandae repellat sequi ullam, voluptates. Aliquam commodi debitis delectus magnam nulla, omnis sequi sint unde voluptas voluptatum. Adipisci aliquam deserunt dolor enim facilis libero, maxime molestias, nemo neque non nostrum placeat reprehenderit, rerum ullam vel? A atque autem consectetur cum, doloremque doloribus fugiat hic id iste nemo nesciunt officia quaerat quibusdam quidem quisquam similique sit tempora vel. Accusamus aspernatur at au_x000D_
</span>
_x000D_
<color name="blackColorPrimary">#000001</color> (not #000000)
<item name="android:navigationBarColor" tools:targetApi="lollipop">@color/blackColorPrimary</item>
Problem is that android higher version make trasparent for #000000
For me this solution works fine as well:
SELECT tbl.a, tbl.b
FROM (SELECT TOP (select count(1) FROM yourtable) a,b FROM yourtable order by a) tbl
It requires a bit of rearranging, but when
does a good job to replace conditionals above. Here's the example from above written using the declarative syntax. Note that test3
stage is now two different stages. One that runs on the master branch and one that runs on anything else.
stage ('Test 3: Master') {
when { branch 'master' }
steps {
echo 'I only execute on the master branch.'
}
}
stage ('Test 3: Dev') {
when { not { branch 'master' } }
steps {
echo 'I execute on non-master branches.'
}
}
Here is a great one http://download.oracle.com/javase/1.5.0/docs/api/
These languages are big. You cant expect a cheat sheet to fit on a piece of paper
Normally you would select IDs using the ID selector #
, but for more complex matches you can use the attribute-starts-with selector (as a jQuery selector, or as a CSS3 selector):
div[id^="player_"]
If you are able to modify that HTML, however, you should add a class to your player div
s then target that class. You'll lose the additional specificity offered by ID selectors anyway, as attribute selectors share the same specificity as class selectors. Plus, just using a class makes things much simpler.
That works for me: Add Custom Font in React Native
download your fonts and place them in assets/fonts folder, add this line in package.json
"rnpm": {
"assets": ["assets/fonts/Sarpanch"]}
then open terminal and run this command: react-native link
Now your are good to go. For more detailed step. visit the link above mentioned
Hopefully this helps someone else.
In the case when there is a error that something is not json serializable the answers above will not work. If you only want to save it so that is human readable then you need to recursively call string on all the non dictionary elements of your dictionary. If you want to load it later then save it as a pickle file then load it (e.g. torch.save(obj, f)
works fine).
This is what worked for me:
#%%
def _to_json_dict_with_strings(dictionary):
"""
Convert dict to dict with leafs only being strings. So it recursively makes keys to strings
if they are not dictionaries.
Use case:
- saving dictionary of tensors (convert the tensors to strins!)
- saving arguments from script (e.g. argparse) for it to be pretty
e.g.
"""
if type(dictionary) != dict:
return str(dictionary)
d = {k: _to_json_dict_with_strings(v) for k, v in dictionary.items()}
return d
def to_json(dic):
import types
import argparse
if type(dic) is dict:
dic = dict(dic)
else:
dic = dic.__dict__
return _to_json_dict_with_strings(dic)
def save_to_json_pretty(dic, path, mode='w', indent=4, sort_keys=True):
import json
with open(path, mode) as f:
json.dump(to_json(dic), f, indent=indent, sort_keys=sort_keys)
def my_pprint(dic):
"""
@param dic:
@return:
Note: this is not the same as pprint.
"""
import json
# make all keys strings recursively with their naitve str function
dic = to_json(dic)
# pretty print
pretty_dic = json.dumps(dic, indent=4, sort_keys=True)
print(pretty_dic)
# print(json.dumps(dic, indent=4, sort_keys=True))
# return pretty_dic
import torch
# import json # results in non serializabe errors for torch.Tensors
from pprint import pprint
dic = {'x': torch.randn(1, 3), 'rec': {'y': torch.randn(1, 3)}}
my_pprint(dic)
pprint(dic)
output:
{
"rec": {
"y": "tensor([[-0.3137, 0.3138, 1.2894]])"
},
"x": "tensor([[-1.5909, 0.0516, -1.5445]])"
}
{'rec': {'y': tensor([[-0.3137, 0.3138, 1.2894]])},
'x': tensor([[-1.5909, 0.0516, -1.5445]])}
I don't know why returning the string then printing it doesn't work but it seems you have to put the dumps directly in the print statement. Note pprint
as it has been suggested already works too. Note not all objects can be converted to a dict with dict(dic)
which is why some of my code has checks on this condition.
Context:
I wanted to save pytorch strings but I kept getting the error:
TypeError: tensor is not JSON serializable
so I coded the above. Note that yes, in pytorch you use torch.save
but pickle files aren't readable. Check this related post: https://discuss.pytorch.org/t/typeerror-tensor-is-not-json-serializable/36065/3
PPrint also has indent arguments but I didn't like how it looks:
pprint(stats, indent=4, sort_dicts=True)
output:
{ 'cca': { 'all': {'avg': tensor(0.5132), 'std': tensor(0.1532)},
'avg': tensor([0.5993, 0.5571, 0.4910, 0.4053]),
'rep': {'avg': tensor(0.5491), 'std': tensor(0.0743)},
'std': tensor([0.0316, 0.0368, 0.0910, 0.2490])},
'cka': { 'all': {'avg': tensor(0.7885), 'std': tensor(0.3449)},
'avg': tensor([1.0000, 0.9840, 0.9442, 0.2260]),
'rep': {'avg': tensor(0.9761), 'std': tensor(0.0468)},
'std': tensor([5.9043e-07, 2.9688e-02, 6.3634e-02, 2.1686e-01])},
'cosine': { 'all': {'avg': tensor(0.5931), 'std': tensor(0.7158)},
'avg': tensor([ 0.9825, 0.9001, 0.7909, -0.3012]),
'rep': {'avg': tensor(0.8912), 'std': tensor(0.1571)},
'std': tensor([0.0371, 0.1232, 0.1976, 0.9536])},
'nes': { 'all': {'avg': tensor(0.6771), 'std': tensor(0.2891)},
'avg': tensor([0.9326, 0.8038, 0.6852, 0.2867]),
'rep': {'avg': tensor(0.8072), 'std': tensor(0.1596)},
'std': tensor([0.0695, 0.1266, 0.1578, 0.2339])},
'nes_output': { 'all': {'avg': None, 'std': None},
'avg': tensor(0.2975),
'rep': {'avg': None, 'std': None},
'std': tensor(0.0945)},
'query_loss': { 'all': {'avg': None, 'std': None},
'avg': tensor(12.3746),
'rep': {'avg': None, 'std': None},
'std': tensor(13.7910)}}
compare to:
{
"cca": {
"all": {
"avg": "tensor(0.5144)",
"std": "tensor(0.1553)"
},
"avg": "tensor([0.6023, 0.5612, 0.4874, 0.4066])",
"rep": {
"avg": "tensor(0.5503)",
"std": "tensor(0.0796)"
},
"std": "tensor([0.0285, 0.0367, 0.1004, 0.2493])"
},
"cka": {
"all": {
"avg": "tensor(0.7888)",
"std": "tensor(0.3444)"
},
"avg": "tensor([1.0000, 0.9840, 0.9439, 0.2271])",
"rep": {
"avg": "tensor(0.9760)",
"std": "tensor(0.0468)"
},
"std": "tensor([5.7627e-07, 2.9689e-02, 6.3541e-02, 2.1684e-01])"
},
"cosine": {
"all": {
"avg": "tensor(0.5945)",
"std": "tensor(0.7146)"
},
"avg": "tensor([ 0.9825, 0.9001, 0.7907, -0.2953])",
"rep": {
"avg": "tensor(0.8911)",
"std": "tensor(0.1571)"
},
"std": "tensor([0.0371, 0.1231, 0.1975, 0.9554])"
},
"nes": {
"all": {
"avg": "tensor(0.6773)",
"std": "tensor(0.2886)"
},
"avg": "tensor([0.9326, 0.8037, 0.6849, 0.2881])",
"rep": {
"avg": "tensor(0.8070)",
"std": "tensor(0.1595)"
},
"std": "tensor([0.0695, 0.1265, 0.1576, 0.2341])"
},
"nes_output": {
"all": {
"avg": "None",
"std": "None"
},
"avg": "tensor(0.2976)",
"rep": {
"avg": "None",
"std": "None"
},
"std": "tensor(0.0945)"
},
"query_loss": {
"all": {
"avg": "None",
"std": "None"
},
"avg": "tensor(12.3616)",
"rep": {
"avg": "None",
"std": "None"
},
"std": "tensor(13.7976)"
}
}
There are a few problems here.
1: onBlur expects a callback, and you are calling renderPasswordConfirmError
and using the return value, which is null.
2: you need a place to render the error.
3: you need a flag to track "and I validating", which you would set to true on blur. You can set this to false on focus if you want, depending on your desired behavior.
handleBlur: function () {
this.setState({validating: true});
},
render: function () {
return <div>
...
<input
type="password"
placeholder="Password (confirm)"
valueLink={this.linkState('password2')}
onBlur={this.handleBlur}
/>
...
{this.renderPasswordConfirmError()}
</div>
},
renderPasswordConfirmError: function() {
if (this.state.validating && this.state.password !== this.state.password2) {
return (
<div>
<label className="error">Please enter the same password again.</label>
</div>
);
}
return null;
},
One of the options is to use the Javascript.
Here is a quick reference where you can start from.
Memcached client library was just recently released as stable. It is being used by digg ( was developed for digg by Andrei Zmievski, now no longer with digg) and implements much more of the memcached protocol than the older memcache client. The most important features that memcached has are:
All of this points were enough for me to switch to the newest client, and can tell you that it works like a charm. There is that external dependency on the libmemcached library, but have managed to install it nonetheless on Ubuntu and Mac OSX, so no problems there so far.
If you decide to update to the newer library, I suggest you update to the latest server version as well as it has some nice features as well. You will need to install libevent for it to compile, but on Ubuntu it wasn't much trouble.
I haven't seen any frameworks pick up the new memcached client thus far (although I don't keep track of them), but I presume Zend will get on board shortly.
Zend Framework 2 has an adapter for Memcached which can be found here
There are a lot of very nice answers on this page and I googled for some more, but none of the answers ticked all the checkboxes on my wish list:
So I mixed the code of several examples, fixed the things that I needed and here is the result:
I used the following CSS and HTML:
/* Progress Tracker v2 */_x000D_
ol.progress[data-steps="2"] li { width: 49%; }_x000D_
ol.progress[data-steps="3"] li { width: 33%; }_x000D_
ol.progress[data-steps="4"] li { width: 24%; }_x000D_
ol.progress[data-steps="5"] li { width: 19%; }_x000D_
ol.progress[data-steps="6"] li { width: 16%; }_x000D_
ol.progress[data-steps="7"] li { width: 14%; }_x000D_
ol.progress[data-steps="8"] li { width: 12%; }_x000D_
ol.progress[data-steps="9"] li { width: 11%; }_x000D_
_x000D_
.progress {_x000D_
width: 100%;_x000D_
list-style: none;_x000D_
list-style-image: none;_x000D_
margin: 20px 0 20px 0;_x000D_
padding: 0;_x000D_
}_x000D_
_x000D_
.progress li {_x000D_
float: left;_x000D_
text-align: center;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.progress .name {_x000D_
display: block;_x000D_
vertical-align: bottom;_x000D_
text-align: center;_x000D_
margin-bottom: 1em;_x000D_
color: black;_x000D_
opacity: 0.3;_x000D_
}_x000D_
_x000D_
.progress .step {_x000D_
color: black;_x000D_
border: 3px solid silver;_x000D_
background-color: silver;_x000D_
border-radius: 50%;_x000D_
line-height: 1.2;_x000D_
width: 1.2em;_x000D_
height: 1.2em;_x000D_
display: inline-block;_x000D_
z-index: 0;_x000D_
}_x000D_
_x000D_
.progress .step span {_x000D_
opacity: 0.3;_x000D_
}_x000D_
_x000D_
.progress .active .name,_x000D_
.progress .active .step span {_x000D_
opacity: 1;_x000D_
}_x000D_
_x000D_
.progress .step:before {_x000D_
content: "";_x000D_
display: block;_x000D_
background-color: silver;_x000D_
height: 0.4em;_x000D_
width: 50%;_x000D_
position: absolute;_x000D_
bottom: 0.6em;_x000D_
left: 0;_x000D_
z-index: -1;_x000D_
}_x000D_
_x000D_
.progress .step:after {_x000D_
content: "";_x000D_
display: block;_x000D_
background-color: silver;_x000D_
height: 0.4em;_x000D_
width: 50%;_x000D_
position: absolute;_x000D_
bottom: 0.6em;_x000D_
right: 0;_x000D_
z-index: -1;_x000D_
}_x000D_
_x000D_
.progress li:first-of-type .step:before {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.progress li:last-of-type .step:after {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.progress .done .step,_x000D_
.progress .done .step:before,_x000D_
.progress .done .step:after,_x000D_
.progress .active .step,_x000D_
.progress .active .step:before {_x000D_
background-color: yellowgreen;_x000D_
}_x000D_
_x000D_
.progress .done .step,_x000D_
.progress .active .step {_x000D_
border: 3px solid yellowgreen;_x000D_
}
_x000D_
<!-- Progress Tracker v2 -->_x000D_
<ol class="progress" data-steps="4">_x000D_
<li class="done">_x000D_
<span class="name">Foo</span>_x000D_
<span class="step"><span>1</span></span>_x000D_
</li>_x000D_
<li class="done">_x000D_
<span class="name">Bar</span>_x000D_
<span class="step"><span>2</span></span>_x000D_
</li>_x000D_
<li class="active">_x000D_
<span class="name">Baz</span>_x000D_
<span class="step"><span>3</span></span>_x000D_
</li>_x000D_
<li>_x000D_
<span class="name">Quux</span>_x000D_
<span class="step"><span>4</span></span>_x000D_
</li>_x000D_
</ol>
_x000D_
As can be seen in the example above, there are now two list item classes to take note of: active
and done
. Use class="active"
for the current step, use class="done"
for all steps before it.
Also note the data-steps="4"
in the ol
tag; set this to the total number of steps to apply the correct size to all list items.
Feel free to play around with the JSFiddle. Enjoy!
In my case, I wanted a one liner that I could run from the commandline (actually via a Makefile). Here is an example installing "VGAM" and "feather" if they are not already installed:
R -e 'for (p in c("VGAM", "feather")) if (!require(p, character.only=TRUE)) install.packages(p, repos="http://cran.us.r-project.org")'
From within R it would just be:
for (p in c("VGAM", "feather")) if (!require(p, character.only=TRUE)) install.packages(p, repos="http://cran.us.r-project.org")
There is nothing here beyond the previous solutions except that:
repos
parameter (to avoid any popups asking about the mirror to use)Also note the important character.only=TRUE
(without it, the require
would try to load the package p
).
Note :- Do not use script tag in external JavaScript file.
<html>
<head>
</head>
<body>
<p id="cn"> Click on the button to change the light button</p>
<button type="button" onclick="changefont()">Click</button>
<script src="external.js"></script>
</body>
External Java Script file:-
function changefont()
{
var x = document.getElementById("cn");
x.style.fontSize = "25px";
x.style.color = "red";
}
Check out your username and domain is the same as created before. Mysql select account by the two colums in user table.If it is different, mysql may think you want to create a new account by grant,which is not supported after 8.0 version.
My solution: TOOLS > Processor > "old bootloader"
I applied CSS styling to an anchored HREF attribute fully emulating the push button behaviors I needed (hover, active, background-color, etc., etc.). HTML markup is much simpler a-n-d eliminates the get/post complexity associated with using a form-based approach.
<a class="GYM" href="http://www.spufalcons.com/index.aspx?tab=gymnastics&path=gym">Gymnastics</a>
I tray order by with problematic column and i find rows with column.
SELECT
D.UNIT_CODE,
D.CUATM,
D.CAPITOL,
D.RIND,
D.COL1 AS COL1
FROM
VW_DATA_ALL_GC D
WHERE
(D.PERIOADA IN (:pPERIOADA)) AND
(D.FORM = 62)
AND D.COL1 IS NOT NULL
-- AND REGEXP_LIKE (D.COL1, '\[\[:alpha:\]\]')
-- AND REGEXP_LIKE(D.COL1, '\[\[:digit:\]\]')
--AND REGEXP_LIKE(TO_CHAR(D.COL1), '\[^0-9\]+')
GROUP BY
D.UNIT_CODE,
D.CUATM,
D.CAPITOL,
D.RIND ,
D.COL1
ORDER BY
D.COL1
Should be probably changed to
firstName = firstName.trim().replaceAll("\\.", "");
One more thing that might be useful for beginners is , since std::set is not allocated with contiguous memory chunks , if someone want to iterate till kth
element normal way will not work.
example:
std::vector<int > vec{1,2,3,4,5};
int k=3;
for(auto itr=vec.begin();itr<vec.begin()+k;itr++) cout<<*itr<<" ";
std::unordered_set<int > s{1,2,3,4,5};
int k=3;
int index=0;
auto itr=s.begin();
while(true){
if(index==k) break;
cout<<*itr++<<" ";
index++;
}
You have to specify the format (fmt
) of you data in savetxt
, in this case as a string (%s
):
num.savetxt('test.txt', DAT, delimiter=" ", fmt="%s")
The default format is a float, that is the reason it was expecting a float instead of a string and explains the error message.
This is how I do it.
import numpy as np
def dt2cal(dt):
"""
Convert array of datetime64 to a calendar array of year, month, day, hour,
minute, seconds, microsecond with these quantites indexed on the last axis.
Parameters
----------
dt : datetime64 array (...)
numpy.ndarray of datetimes of arbitrary shape
Returns
-------
cal : uint32 array (..., 7)
calendar array with last axis representing year, month, day, hour,
minute, second, microsecond
"""
# allocate output
out = np.empty(dt.shape + (7,), dtype="u4")
# decompose calendar floors
Y, M, D, h, m, s = [dt.astype(f"M8[{x}]") for x in "YMDhms"]
out[..., 0] = Y + 1970 # Gregorian Year
out[..., 1] = (M - Y) + 1 # month
out[..., 2] = (D - M) + 1 # dat
out[..., 3] = (dt - D).astype("m8[h]") # hour
out[..., 4] = (dt - h).astype("m8[m]") # minute
out[..., 5] = (dt - m).astype("m8[s]") # second
out[..., 6] = (dt - s).astype("m8[us]") # microsecond
return out
It's vectorized across arbitrary input dimensions, it's fast, its intuitive, it works on numpy v1.15.4, it doesn't use pandas.
I really wish numpy supported this functionality, it's required all the time in application development. I always get super nervous when I have to roll my own stuff like this, I always feel like I'm missing an edge case.
Always make sure that js file (angular.min.js) is referenced first in the HTML file. For example:
----------------- This reference will THROW error -------------------------
< script src="otherXYZ.js"></script>
< script src="angular.min.js"></script>
----------------- This reference will WORK as expected -------------------
< script src="angular.min.js"></script>
< script src="otherXYZ.js"></script>
Go to inspect element and check if .justify-content-center is listed as a class name under 'Styles' tab. If not, probably you are using bootstrap v3 in which justify-content-center is not defined.
If so, please update bootstrap, worked for me.
You would have to first create your migration for the model basics then you create another migration to modify your previous using the change_column ...
def change
change_column :widgets, :colour, :string, default: 'red'
end
find
builds a list of files. It applies the predicate you supplied to each one and returns those that pass.
This idea that -prune
means exclude from results was really confusing for me. You can exclude a file without prune:
find -name 'bad_guy' -o -name 'good_guy' -print // good_guy
All -prune
does is alter the behavior of the search. If the current match is a directory, it says "hey find
, that file you just matched, dont descend into it". It just removes that tree (but not the file itself) from the list of files to search.
It should be named -dont-descend
.
Are you missing a function declaration?
void ac_search(uint num_patterns, uint pattern_length, const char *patterns,
uint num_records, uint record_length, const char *records, int *matches, Node* trie);
Add it just before your implementation of ac_benchmark_search.
Andrea solution is absolutely right, I will just write another implementation based on the same idea. If you took a look at the THREE.ImageUtils.loadTexture() source you will find it uses the javascript Image object. The $(window).load event is fired after all Images are loaded ! so at that event we can render our scene with the textures already loaded...
CoffeeScript
$(document).ready ->
material = new THREE.MeshLambertMaterial(map: THREE.ImageUtils.loadTexture("crate.gif"))
sphere = new THREE.Mesh(new THREE.SphereGeometry(radius, segments, rings), material)
$(window).load ->
renderer.render scene, camera
JavaScript
$(document).ready(function() {
material = new THREE.MeshLambertMaterial({ map: THREE.ImageUtils.loadTexture("crate.gif") });
sphere = new THREE.Mesh(new THREE.SphereGeometry(radius, segments, rings), material);
$(window).load(function() {
renderer.render(scene, camera);
});
});
Thanks...
Every programming language has its own set of rules and conventions for the kinds of names that you're allowed to use, and the Java programming language is no different. The rules and conventions for naming your variables can be summarized as follows:
Variable names are case-sensitive. A variable's name can be any legal identifier — an unlimited-length sequence of Unicode letters and digits, beginning with a letter, the dollar sign "$", or the underscore character "_". The convention, however, is to always begin your variable names with a letter, not "$" or "_". Additionally, the dollar sign character, by convention, is never used at all. You may find some situations where auto-generated names will contain the dollar sign, but your variable names should always avoid using it. A similar convention exists for the underscore character; while it's technically legal to begin your variable's name with "_", this practice is discouraged. White space is not permitted.
Subsequent characters may be letters, digits, dollar signs, or underscore characters. Conventions (and common sense) apply to this rule as well. When choosing a name for your variables, use full words instead of cryptic abbreviations. Doing so will make your code easier to read and understand. In many cases it will also make your code self-documenting; fields named cadence, speed, and gear, for example, are much more intuitive than abbreviated versions, such as s, c, and g. Also keep in mind that the name you choose must not be a keyword or reserved word.
If the name you choose consists of only one word, spell that word in all lowercase letters. If it consists of more than one word, capitalize the first letter of each subsequent word. The names gearRatio and currentGear are prime examples of this convention. If your variable stores a constant value, such as
static final int NUM_GEARS = 6
, the convention changes slightly, capitalizing every letter and separating subsequent words with the underscore character. By convention, the underscore character is never used elsewhere.
I was using Maven in eclipse and I did not want to have an additional copy of the properties file in the root folder. You can do the following in eclipse:
I think Call SOAP Web Service from Android application will help you a lot.
<UserControl.Resources>
<Style x:Key="myLBStyle" TargetType="{x:Type ListBoxItem}">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
Color="Transparent"/>
</Style.Resources>
</Style>
</UserControl.Resources>
and
<ListBox ItemsSource="{Binding Path=FirstNames}"
ItemContainerStyle="{StaticResource myLBStyle}">
You just override the style of the listboxitem (see the: TargetType is ListBoxItem)
Hi You can use a simple query,
select emp_cd, val1, val2, val3,
(val1+val2+val3) as total
from emp;
In case you need to insert a new row,
insert into emp select emp_cd, val1, val2, val3,
(val1+val2+val3) as total
from emp;
In order to update,
update emp set total = val1+val2+val3;
This will update for all comumns
Traversal over the large map entrySet()
is much better than the keySet()
. Check this tutorial how they optimise the traversal over the large object with the help of entrySet(
) and how it helps for performance tuning.
You could use a radio button/checkbox and set it to hide the button in css and then give it a label with an image.
input[type="radio"] {display: none}
input[type="radio"] + label span {display: block}
Then on the page:
<input type="radio" name="emotion" id="mysubmitradio" />
<label for="mysubmitradio"><img src="images/f.jpg" />
<span>if you need it</span></label>
And then set it to submit using javascript:
document.forms["myform"].submit();
//retrive check box and gender value
$gender=$row['gender'];
$chkhobby=$row['chkhobby'];
<tr>
<th>GENDER</th>
<td>
Male<input type="radio" name="gender" value="1" <?php echo ($gender== '1') ? "checked" : "" ; ?>/>
Female<input type="radio" name="gender" value="0" <?php echo ($gender== '0') ? "checked" : "" ; ?>/>
</td>
</tr>
<tr>
<th>Hobbies</th>
<td>
<pre><?php //print_r($row);
$hby = @explode(",",$row['chkhobby']);
//print_r($hby);
?></pre>
read<input id="check_1" type="checkbox" name="chkhobby[]" value="read" <?php if(in_array("read",$hby)){?> checked="checked"<?php }?>>
write<input id="check_2" type="checkbox" name="chkhobby[]" value="write" <?php if(in_array("write",$hby)){?> checked="checked"<?php }?>>
play<input id="check_4" type="checkbox" name="chkhobby[]" value="play" <?php if(in_array("play",$hby)){?> checked="checked"<?php }?>>
</td>
</tr>
//update
$gender=$_POST['gender'];
$chkhobby = implode(',', $_POST['chkhobby']);
As GvS said, but I also find it useful to use strongly typed views so that I can write something like
@Html.Partial(MVC.Student.Index(), model)
without magic strings.
I wrote a script I call "psh":
#! /usr/bin/perl
while (<>) {
chomp;
my $result = eval;
print "$_ = $result\n";
}
Whatever you type in, it evaluates in Perl:
> gmtime(2**30)
gmtime(2**30) = Sat Jan 10 13:37:04 2004
> $x = 'foo'
$x = 'foo' = foo
> $x =~ s/o/a/g
$x =~ s/o/a/g = 2
> $x
$x = faa
You could use rails d model/controller/migration ...
to destroy or remove the changes generated by using the rails generate
command.
For example:
rails g model Home name:string
creates a model named home
with attribute name
. To remove the files and code generated from that command we can use
rails d model Home
Try following code that worked fine for me
global $current_user;
get_currentuserinfo();
Then, use following code to check whether user has logged in or not.
if ($current_user->ID == '') {
//show nothing to user
}
else {
//write code to show menu here
}
Try following css with addition of white-space
:
span {
display: block;
word-wrap:break-word;
width: 50px;
white-space: normal
}
First you create the branch locally:
git checkout -b your_branch
And then to create the branch remotely:
git push --set-upstream origin your_branch
Note: This works on the latests versions of git:
$ git --version
git version 2.3.0
Cheers!
CONCAT
is new to SQL Server 2012. The link you gave makes this clear, it is not a function on Previous Versions, including 2008 R2.
That it is part of SQL Server 2012 can be seen in the document tree:
SQL Server 2012
Product Documentation
Books Online for SQL Server 2012
Database Engine
Transact-SQL Reference (Database Engine)
Built-in Functions (Transact-SQL)
String Functions (Transact-SQL)
EDIT Martin Smith helpfully points out that SQL Server provides an implementation of ODBC's CONCAT
function.
Beyond compare allows you to do that and much more.
It's one of those tools I can't live without.
Take a look here for a reference on the scripting options
It seems to be possible in iOS 5 using the UIAppearance proxy.
[[UILabel appearance] setFont:[UIFont fontWithName:@"YourFontName" size:17.0]];
That will set the font to be whatever your custom font is for all UILabels in your app. You'll need to repeat it for each control (UIButton, UILabel, etc.).
Remember you'll need to put the UIAppFonts value in your info.plist and include the name of the font you're including.
https://www.programmableweb.com/ -- Great collection of all category API's across web. It not only show cases the API's , but also Developers who use those API's in their applications and code samples, rating of the API and much more. They have more than apis they also have sdk and libraries too.
I'm pretty sure there'll be some C# SDKs / toolkits on Google Code for this. I found this one, but there may be others so it's worth having a browse around.
import com.google.common.collect.Sets;
Sets.newHashSet("a", "b");
or
import com.google.common.collect.ImmutableSet;
ImmutableSet.of("a", "b");
The answer for your question:
You can find out the current key-bindings following this link
You can even edit the key-binding as per your preference.
This is another, though not necessarily "better", way:
Determining Your Current Version
To determine which Oracle client version you have installed on your pc, run sql
*
plus to connect to the DW. The folder names may vary somewhat based on your Oracle setup but should be similar. To run sql*
plus choosestart > programs > Oracle > Oracle - OUDWclient > Application Development > sqlplus
. Enter your DW user name, password, and 'ordj' for the host name or service name. This should connect you to the DW via sqlplus. At this point, you could write your own sql statements to pull information from the DW (if you knew sql). The Oracle client version can be determined in the first line - 'SQL*Plus: Release 10.2.0.1.0'.
[Reference] Oracle Client Information http://www.ohio.edu/technology
Yes you can solve this error by changing the port number of glassfish because the WAMP SERVER or ORACLE database software uses a port number 8080, so there is a conflict of port number.
1)open a path like C:\GlassFish_Server\glassfish\domains\domain1\config\domain.xml.
2)find out the 8080 port number with the help of ctrl+F. You will get the following code...
<network-listener protocol="http-listener-1" port="8080" name="http-listener-1" thread-pool="http-thread-pool" transport="tcp">
3) Change that port number from 8080 to 9090 or 1234 or whatever you like..
4) Save it. Open a Netbeans IDE goto the glassfish server .
5) Right click on the server -> select refresh option.
6) to check the port no. which is given by u just right click on the server-> property.
7) Start the Glassfish server . Yehhh the error is gone...
public async Task<ActionResult> Index()
{
apiTable table = new apiTable();
table.Name = "Asma Nadeem";
table.Roll = "6655";
string str = "";
string str2 = "";
HttpClient client = new HttpClient();
string json = JsonConvert.SerializeObject(table);
StringContent httpContent = new StringContent(json, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("http://YourSite.com/api/apiTables", httpContent);
str = "" + response.Content + " : " + response.StatusCode;
if (response.IsSuccessStatusCode)
{
str2 = "Data Posted";
}
return View();
}
I the list is vary large looping two time over it will take a lot of time and more in the second time you are looping a set not a list and as we know iterating over a set is slower than list.
i think you need the power of generator
and set
.
def first_test():
def loop_one_time(my_list):
# create a set to keep the items.
iterated_items = set()
# as we know iterating over list is faster then list.
for value in my_list:
# as we know checking if element exist in set is very fast not
# metter the size of the set.
if value not in iterated_items:
iterated_items.add(value) # add this item to list
yield value
mylist = [3,1,5,2,4,4,1,4,2,5,1,3]
for v in loop_one_time(mylist):pass
def second_test():
mylist = [3,1,5,2,4,4,1,4,2,5,1,3]
s = set(mylist)
for v in s:pass
import timeit
print(timeit.timeit('first_test()', setup='from __main__ import first_test', number=10000))
print(timeit.timeit('second_test()', setup='from __main__ import second_test', number=10000))
out put:
0.024003583388435043
0.010424674188938422
Note: this technique order is guaranteed
Also, this might help finding the actual location the btsnoop_hci.log is being saved:
adb shell "cat /etc/bluetooth/bt_stack.conf | grep FileName"
Basically "delete" sends a query directly to the database to delete the record. In that case Rails doesn't know what attributes are in the record it is deleting nor if there are any callbacks (such as before_destroy
).
The "destroy" method takes the passed id, fetches the model from the database using the "find" method, then calls destroy on that. This means the callbacks are triggered.
You would want to use "delete" if you don't want the callbacks to be triggered or you want better performance. Otherwise (and most of the time) you will want to use "destroy".
Parsing dates is a pain in JavaScript as there's no extensive native support. However you could do something like the following by relying on the Date(year, month, day [, hour, minute, second, millisecond])
constructor signature of the Date
object.
var dateString = '17-09-2013 10:08',
dateTimeParts = dateString.split(' '),
timeParts = dateTimeParts[1].split(':'),
dateParts = dateTimeParts[0].split('-'),
date;
date = new Date(dateParts[2], parseInt(dateParts[1], 10) - 1, dateParts[0], timeParts[0], timeParts[1]);
console.log(date.getTime()); //1379426880000
console.log(date); //Tue Sep 17 2013 10:08:00 GMT-0400
You could also use a regular expression with capturing groups to parse the date string in one line.
var dateParts = '17-09-2013 10:08'.match(/(\d+)-(\d+)-(\d+) (\d+):(\d+)/);
console.log(dateParts); // ["17-09-2013 10:08", "17", "09", "2013", "10", "08"]
var dataArray = [];
var obj = jQuery.parseJSON(response);
for( key in obj )
dataArray.push([key.toString(), obj [key]]);
};
("Jesse" or "jesse")
The above expression tests whether or not "Jesse"
evaluates to True
. If it does, then the expression will return it; otherwise, it will return "jesse"
. The expression is equivalent to writing:
"Jesse" if "Jesse" else "jesse"
Because "Jesse"
is a non-empty string though, it will always evaluate to True
and thus be returned:
>>> bool("Jesse") # Non-empty strings evaluate to True in Python
True
>>> bool("") # Empty strings evaluate to False
False
>>>
>>> ("Jesse" or "jesse")
'Jesse'
>>> ("" or "jesse")
'jesse'
>>>
This means that the expression:
name == ("Jesse" or "jesse")
is basically equivalent to writing this:
name == "Jesse"
In order to fix your problem, you can use the in
operator:
# Test whether the value of name can be found in the tuple ("Jesse", "jesse")
if name in ("Jesse", "jesse"):
Or, you can lowercase the value of name
with str.lower
and then compare it to "jesse"
directly:
# This will also handle inputs such as "JeSSe", "jESSE", "JESSE", etc.
if name.lower() == "jesse":
A recursive solution. It's not the most efficient but I find it a bit more readable than the other examples and it doesn't rely on functools.
def deep_get(d, keys):
if not keys or d is None:
return d
return deep_get(d.get(keys[0]), keys[1:])
Example
d = {'meta': {'status': 'OK', 'status_code': 200}}
deep_get(d, ['meta', 'status_code']) # => 200
deep_get(d, ['garbage', 'status_code']) # => None
A more polished version
def deep_get(d, keys, default=None):
"""
Example:
d = {'meta': {'status': 'OK', 'status_code': 200}}
deep_get(d, ['meta', 'status_code']) # => 200
deep_get(d, ['garbage', 'status_code']) # => None
deep_get(d, ['meta', 'garbage'], default='-') # => '-'
"""
assert type(keys) is list
if d is None:
return default
if not keys:
return d
return deep_get(d.get(keys[0]), keys[1:], default)
Or, as an alternative to @Chase's code, being a recent plyr fan with a background in databases:
require(plyr)
zz<-join(df1, df2, type="left")
zz[is.na(zz)] <- 0
What solved the issue on my case was go to:
cd C:\Program Files\Python37\Scripts
And run below command:
easy_install.exe pip
Another worthy optimization is the c_str ( ) member of the STL string classes, which returns an immutable null terminated string that can be passed around as a LPCTSTR, e. g., to a custom function that expects a LPCTSTR. Although I haven't traced through the destructor to confirm it, I suspect that the string class looks after the memory in which it creates the copy.
Maybe something like this will fit your needs..
import numpy as np
N = 5
res = []
for i in range(N):
res.append(np.cumsum(np.ones(shape=(2,4))))
res = np.array(res).reshape((10, 4))
print(res)
Which produces the following output
[[ 1. 2. 3. 4.]
[ 5. 6. 7. 8.]
[ 1. 2. 3. 4.]
[ 5. 6. 7. 8.]
[ 1. 2. 3. 4.]
[ 5. 6. 7. 8.]
[ 1. 2. 3. 4.]
[ 5. 6. 7. 8.]
[ 1. 2. 3. 4.]
[ 5. 6. 7. 8.]]
From a powershell prompt, use the gci
cmdlet (alias for Get-ChildItem
) and -filter
option:
gci -recurse -filter "hosts"
This will return an exact match to filename "hosts
".
SteveMustafa points out with current versions of powershell you can use the -File
switch to give the following to recursively search for only files named "hosts
" (and not directories or other miscellaneous file-system entities):
gci -recurse -filter "hosts" -File
The commands may print many red error messages like "Access to the path 'C:\Windows\Prefetch' is denied.
".
If you want to avoid the error messages then set the -ErrorAction
to be silent.
gci -recurse -filter "hosts" -File -ErrorAction SilentlyContinue
An additional helper is that you can set the root to search from using -Path
.
The resulting command to search explicitly search from, for example, the root of the C drive would be
gci -Recurse -Filter "hosts" -File -ErrorAction SilentlyContinue -Path "C:\"
@RequestMapping(value = "so", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String so() {
return "This is a String";
}
using System;
class Program
{
static void Main(string[] args) {
try {
int i = (int) Convert.ToInt64(args[0]);
Console.WriteLine("\n{0} converted to Binary is {1}\n", i, ToBinary(i));
} catch(Exception e) {
Console.WriteLine("\n{0}\n", e.Message);
}
}
public static string ToBinary(Int64 Decimal) {
// Declare a few variables we're going to need
Int64 BinaryHolder;
char[] BinaryArray;
string BinaryResult = "";
while (Decimal > 0) {
BinaryHolder = Decimal % 2;
BinaryResult += BinaryHolder;
Decimal = Decimal / 2;
}
BinaryArray = BinaryResult.ToCharArray();
Array.Reverse(BinaryArray);
BinaryResult = new string(BinaryArray);
return BinaryResult;
}
}
@commonpike's answer is "the right one", but as he goes on to comment...
most browsers nowadays just support
Object.keys()
Yeah.. Object.keys()
is WAY better.
But what's even better? Duh, it's it in coffeescript
!
sortedKeys = (x) -> Object.keys(x).sort (a,b) -> x[a] - x[b]
sortedKeys
'a' : 1
'b' : 3
'c' : 4
'd' : -1
[ 'd', 'a', 'b', 'c' ]
I found the following article which worked great for me and details the use of the following:
var load_this_javascript = function() {
// do some things
}
$(document).ready(load_this_javascript)
$(window).bind('page:change', load_this_javascript)
If you find the 1px jump before expanding and after collapsing when using the CSS solution a bit annoying, here's a simple JavaScript solution for Bootstrap 3...
Just add this somewhere in your code:
$(document).ready(
$('.collapse').on('show.bs.collapse hide.bs.collapse', function(e) {
e.preventDefault();
}),
$('[data-toggle="collapse"]').on('click', function(e) {
e.preventDefault();
$($(this).data('target')).toggleClass('in');
})
);
After coming here for help, I made my own solution and wanted to share it. It's based on user2363986's answer, but I think this is more scalable. Meaning, that if you have 1000 extensions, the code will still look somewhat elegant.
from glob import glob
directoryPath = "C:\\temp\\*."
fileExtensions = [ "jpg", "jpeg", "png", "bmp", "gif" ]
listOfFiles = []
for extension in fileExtensions:
listOfFiles.extend( glob( directoryPath + extension ))
for file in listOfFiles:
print(file) # Or do other stuff
You can import svg and it use it like a image
import chatSVG from '../assets/images/undraw_typing_jie3.svg'
And ise it in img tag
<img src={chatSVG} className='iconChat' alt="Icon chat"/>
Use a BinaryReader object to return a byte array from the stream like:
byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
By using document.getElementById()
function you don't have to pass #
before element's id.
Code:
document.getElementById('_1234').checked = true;
Demo: JSFiddle
It would make sense for CSS to have a way to simply add an additional style (in the head section of your page, for example, which would override the linked style sheet) such as this:
<head>
<style>
#elementId select {
/* turn all styles off (no way to do this) */
}
</style>
</head>
and turn off all previously applied styles, but there is no way to do this. You will have to override the height attribute and set it to a new value in the head section of your pages.
<head>
<style>
#elementId select {
height:1.5em;
}
</style>
</head>
Just use replace()
var values = {"%NAME%":"Mike","%AGE%":"26","%EVENT%":"20"};
var substitutedString = "My Name is %NAME% and my age is %AGE%.".replace("%NAME%", $values["%NAME%"]).replace("%AGE%", $values["%AGE%"]);
The next()
moves the cursor froward one row from its current position in the resultset
. so its evident that if(rs.next())
means that if the next row is not null
(means if it exist), Go Ahead.
Now w.r.t your problem,
ResultSet rs = stmt.executeQuery(sql); //This is wrong
^
note that executeQuery(String) is used in case you use a sql-query as string.
Whereas when you use a PreparedStatement, use executeQuery() which executes the SQL query in this PreparedStatement
object and returns the ResultSet
object generated by the query.
Solution :
Use : ResultSet rs = stmt.executeQuery();
You are echoing outside the body tag of your HTML. Put your echos there, and you should be fine.
Also, remove the onclick="alert()"
from your submit. This is the cause for your first undefined
message.
<?php
$posted = false;
if( $_POST ) {
$posted = true;
// Database stuff here...
// $result = mysql_query( ... )
$result = $_POST['name'] == "danny"; // Dummy result
}
?>
<html>
<head></head>
<body>
<?php
if( $posted ) {
if( $result )
echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
else
echo "<script type='text/javascript'>alert('failed!')</script>";
}
?>
<form action="" method="post">
Name:<input type="text" id="name" name="name"/>
<input type="submit" value="submit" name="submit"/>
</form>
</body>
</html>
At the time of writing, none of the answers used a built-in function for this:
function addScheme($url, $scheme = 'http://')
{
return parse_url($url, PHP_URL_SCHEME) === null ?
$scheme . $url : $url;
}
echo addScheme('google.com'); // "http://google.com"
echo addScheme('https://google.com'); // "https://google.com"
See also: parse_url()
There are two directories that looks like JDK.
C:\Program Files\Java\jdk1.7.0_02
C:\Program Files (x86)\Java\jdk1.7.0_02\
This may be due to both 64 bit and 32 bit JDK installed? What ever may be the case, the java.exe
seen by ant.bat should from the JDK. If the JRE's java.exe
comes first in the path, that will be used to guess the JDK location.
Put 'C:\Program Files (x86)\Java\jdk1.7.0_02\bin' or 'C:\Program Files\Java\jdk1.7.0_02' as the first argument in the path.
Further steps:
You can take output of ant -diagnostics
and look for interesting keys. (assuming Sun/Oracle JDK).
java.class.path
java.library.path
sun.boot.library.path
(in my case tools.jar appears in java.class.path)
It is very simple just look at their names @RequestParam it consist of two parts one is "Request" which means it is going to deal with request and other part is "Param" which itself makes sense it is going to map only the parameters of requests to java objects. Same is the case with @RequestBody it is going to deal with the data that has been arrived with request like if client has send json object or xml with request at that time @requestbody must be used.
I believe you are looking for the setTimeout function.
To make your code a little neater, define a separate function for onclick in a <script>
block:
function myClick() {
setTimeout(
function() {
document.getElementById('div1').style.display='none';
document.getElementById('div2').style.display='none';
}, 5000);
}
then call your function from onclick
onclick="myClick();"
Make the value a list, e.g.
a["abc"] = [1, 2, "bob"]
UPDATE:
There are a couple of ways to add values to key, and to create a list if one isn't already there. I'll show one such method in little steps.
key = "somekey"
a.setdefault(key, [])
a[key].append(1)
Results:
>>> a
{'somekey': [1]}
Next, try:
key = "somekey"
a.setdefault(key, [])
a[key].append(2)
Results:
>>> a
{'somekey': [1, 2]}
The magic of setdefault
is that it initializes the value for that key if that key is not defined, otherwise it does nothing. Now, noting that setdefault
returns the key you can combine these into a single line:
a.setdefault("somekey",[]).append("bob")
Results:
>>> a
{'somekey': [1, 2, 'bob']}
You should look at the dict
methods, in particular the get()
method, and do some experiments to get comfortable with this.
Your CRON should look like this:
*/5 * * * *
CronWTF is really usefull when you need to test out your CRON settings.
Might be a good idea to pipe the output into a log file so you can see if your script is throwing any errors too - since you wont see them in your terminal.
Also try using a shebang at the top of your PHP file, so the system knows where to find PHP. Such as:
#!/usr/bin/php
that way you can call the whole thing like this
*/5 * * * * php /path/to/script.php > /path/to/logfile.log
An advance approach is using Kotlin Extension function
fun Context.getRawInput(@RawRes resourceId: Int): InputStream {
return resources.openRawResource(resourceId)
}
One more interesting thing is extension function use that is defined in Closeable scope
For example you can work with input stream in elegant way without handling Exceptions and memory managing
fun Context.readRaw(@RawRes resourceId: Int): String {
return resources.openRawResource(resourceId).bufferedReader(Charsets.UTF_8).use { it.readText() }
}
Here is the optimized code snippet to remove empty arrays/objects as well:
function removeNullsInObject(obj) {
if( typeof obj === 'string' ){ return; }
$.each(obj, function(key, value){
if (value === "" || value === null){
delete obj[key];
} else if ($.isArray(value)) {
if( value.length === 0 ){ delete obj[key]; return; }
$.each(value, function (k,v) {
removeNullsInObject(v);
});
} else if (typeof value === 'object') {
if( Object.keys(value).length === 0 ){
delete obj[key]; return;
}
removeNullsInObject(value);
}
});
}
Thanks @Alexis king :)
This will list all certificates:
keytool -list -keystore "$JAVA_HOME/jre/lib/security/cacerts"
One option is to use the delete method as follows:
StringBuffer sb = new StringBuffer();
for (int n = 0; n < 10; n++) {
sb.append("a");
// This will clear the buffer
sb.delete(0, sb.length());
}
Another option (bit cleaner) uses setLength(int len):
sb.setLength(0);
See Javadoc for more info:
As you say, local variables and references are stored on the stack. When a method returns, the stack pointer is simply moved back to where it was before the method started, that is, all local data is "removed from the stack". Therefore, there is no garbage collection needed on the stack, that only happens in the heap.
To answer your specific questions:
Some times If you touch the keyboard accidentally and removed a space.
if [ "$myvar" = "something"]; then
do something
fi
Will trigger this error message. Note the space before ']' is required.
base on @Data-Base answer it will not work until make selection mode FullRow
MyDataGridView.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
but if you need to make it work in CellSelect Mode
MyDataGridView.SelectionMode = DataGridViewSelectionMode.CellSelect;
// for cell selection
private void MyDataGridView_MouseDown(object sender, MouseEventArgs e)
{
if(e.Button == MouseButtons.Right)
{
var hit = MyDataGridView.HitTest(e.X, e.Y);
MyDataGridView.ClearSelection();
// cell selection
MyDataGridView[hit.ColumnIndex,hit.RowIndex].Selected = true;
}
}
private void DeleteRow_Click(object sender, EventArgs e)
{
int rowToDelete = MyDataGridView.Rows.GetFirstRow(DataGridViewElementStates.Selected);
MyDataGridView.Rows.RemoveAt(rowToDelete);
MyDataGridView.ClearSelection();
}
I think that your reasoning is sound. But in practice I have found that it is far more common to omit the ===
comparison. I think that there are three reasons for that:
undefined
or null
value. Often you just want your test to fail in such cases. (Though I try to balance this view with the "fail fast" motto).Consider this example:
var someString = getInput();
var normalized = someString && trim(someString);
// trim() removes leading and trailing whitespace
if (normalized) {
submitInput(normalized);
}
I think that this kind of code is not uncommon. It handles cases where getInput()
returns undefined
, null
, or an empty string. Due to the two boolean evaluations submitInput()
is only called if the given input is a string that contains non-whitespace characters.
In JavaScript &&
returns its first argument if it is falsy or its second argument if the first argument is truthy; so normalized
will be undefined
if someString
was undefined and so forth. That means that none of the inputs to the boolean expressions above are actually boolean values.
I know that a lot of programmers who are accustomed to strong type-checking cringe when seeing code like this. But note applying strong typing would likely require explicit checks for null
or undefined
values, which would clutter up the code. In JavaScript that is not needed.
Simplifying from pctroll's answer, similarly based on this blog post.
# look up the commit id in git log or on github, e.g. 42480f3, then do
git checkout master
git checkout your_branch
git revert 42480f3
# a text editor will open, close it with ctrl+x (editor dependent)
git push origin your_branch
# or replace origin with your remote
Try this:
SELECT *
FROM information_schema.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_NAME = 'YourTable';
This should deliver you which Tables have references to the table you want to drop, once you drop these references, or the datasets which reference datasets in this table you will be able to drop the table
you can always convert your varchar-column to bigint as integer might be too short...
select cast([yourvarchar] as BIGINT)
but you should always care for alpha characters
where ISNUMERIC([yourvarchar] +'e0') = 1
the +'e0' comes from http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/isnumeric-isint-isnumber
this would lead to your statement
SELECT
*
FROM
Table
ORDER BY
ISNUMERIC([yourvarchar] +'e0') DESC
, LEN([yourvarchar]) ASC
the first sorting column will put numeric on top. the second sorts by length, so 10 will preceed 0001 (which is stupid?!)
this leads to the second version:
SELECT
*
FROM
Table
ORDER BY
ISNUMERIC([yourvarchar] +'e0') DESC
, RIGHT('00000000000000000000'+[yourvarchar], 20) ASC
the second column now gets right padded with '0', so natural sorting puts integers with leading zeros (0,01,10,0100...) in correct order (correct!) - but all alphas would be enhanced with '0'-chars (performance)
so third version:
SELECT
*
FROM
Table
ORDER BY
ISNUMERIC([yourvarchar] +'e0') DESC
, CASE WHEN ISNUMERIC([yourvarchar] +'e0') = 1
THEN RIGHT('00000000000000000000' + [yourvarchar], 20) ASC
ELSE LTRIM(RTRIM([yourvarchar]))
END ASC
now numbers first get padded with '0'-chars (of course, the length 20 could be enhanced) - which sorts numbers right - and alphas only get trimmed
In my case with PHP7.3 Apache2.4 Ubuntu 18.04 I had to execute:
$ a2enmod actions fastcgi alias proxy_fcgi
try this:
SELECT ReportId, Email =
STUFF((SELECT ', ' + Email
FROM your_table b
WHERE b.ReportId = a.ReportId
FOR XML PATH('')), 1, 2, '')
FROM your_table a
GROUP BY ReportId
check this masterfull timestamp detector regex I built to look for a user-specified timestamp, examples of what it will pickup include, but is most definitely NOT limited to;
8:30-9:40
09:40-09 : 50
09 : 40-09 : 50
09:40 - 09 : 50
08:00to05:00
08 : 00to05 : 00
08:00 to 05:00
8am-09pm
08h00 till 17h00
8pm-5am
08h00,21h00
06pm untill 9am
It'll also pickup many more, as long as the times include digits
If you really want to do this, create an HttpServletRequestWrapper.
public class AddableHttpRequest extends HttpServletRequestWrapper {
private HashMap params = new HashMap();
public AddableingHttpRequest(HttpServletRequest request) {
super(request);
}
public String getParameter(String name) {
// if we added one, return that one
if ( params.get( name ) != null ) {
return params.get( name );
}
// otherwise return what's in the original request
HttpServletRequest req = (HttpServletRequest) super.getRequest();
return validate( name, req.getParameter( name ) );
}
public void addParameter( String name, String value ) {
params.put( name, value );
}
}
In addition to @senderle's here, some might also be wondering how to use the functionality of multiprocessing.Pool
.
The nice thing is that there is a .Pool()
method to the manager
instance that mimics all the familiar API of the top-level multiprocessing
.
from itertools import repeat
import multiprocessing as mp
import os
import pprint
def f(d: dict) -> None:
pid = os.getpid()
d[pid] = "Hi, I was written by process %d" % pid
if __name__ == '__main__':
with mp.Manager() as manager:
d = manager.dict()
with manager.Pool() as pool:
pool.map(f, repeat(d, 10))
# `d` is a DictProxy object that can be converted to dict
pprint.pprint(dict(d))
Output:
$ python3 mul.py
{22562: 'Hi, I was written by process 22562',
22563: 'Hi, I was written by process 22563',
22564: 'Hi, I was written by process 22564',
22565: 'Hi, I was written by process 22565',
22566: 'Hi, I was written by process 22566',
22567: 'Hi, I was written by process 22567',
22568: 'Hi, I was written by process 22568',
22569: 'Hi, I was written by process 22569',
22570: 'Hi, I was written by process 22570',
22571: 'Hi, I was written by process 22571'}
This is a slightly different example where each process just logs its process ID to the global DictProxy
object d
.
It's an old question, but still active as there is no explicit Android feature. And the guys from facebook found a work around - somehow. Today, I found a way that works for me. Not perfect (see remarks at the end of this answer) but it works!
Main idea is, that I update the icon of my app's shortcut, created by the launcher on my home screen. When I want to change something on the shortcut-icon, I remove it first and recreate it with a new bitmap.
Here is the code. It has a button increment
. When pressed, the shortcut is replaced with one that has a new counting number.
First you need these two permissions in your manifest:
<uses-permission android:name="com.android.launcher.permission.INSTALL_SHORTCUT" />
<uses-permission android:name="com.android.launcher.permission.UNINSTALL_SHORTCUT" />
Then you need this two methods for installing and uninstalling shortcuts. The shortcutAdd
method creates a bitmap with a number in it. This is just to demonstrate that it actually changes. You probably want to change that part with something, you want in your app.
private void shortcutAdd(String name, int number) {
// Intent to be send, when shortcut is pressed by user ("launched")
Intent shortcutIntent = new Intent(getApplicationContext(), Play.class);
shortcutIntent.setAction(Constants.ACTION_PLAY);
// Create bitmap with number in it -> very default. You probably want to give it a more stylish look
Bitmap bitmap = Bitmap.createBitmap(100, 100, Bitmap.Config.ARGB_8888);
Paint paint = new Paint();
paint.setColor(0xFF808080); // gray
paint.setTextAlign(Paint.Align.CENTER);
paint.setTextSize(50);
new Canvas(bitmap).drawText(""+number, 50, 50, paint);
((ImageView) findViewById(R.id.icon)).setImageBitmap(bitmap);
// Decorate the shortcut
Intent addIntent = new Intent();
addIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
addIntent.putExtra(Intent.EXTRA_SHORTCUT_ICON, bitmap);
// Inform launcher to create shortcut
addIntent.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
getApplicationContext().sendBroadcast(addIntent);
}
private void shortcutDel(String name) {
// Intent to be send, when shortcut is pressed by user ("launched")
Intent shortcutIntent = new Intent(getApplicationContext(), Play.class);
shortcutIntent.setAction(Constants.ACTION_PLAY);
// Decorate the shortcut
Intent delIntent = new Intent();
delIntent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
delIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
// Inform launcher to remove shortcut
delIntent.setAction("com.android.launcher.action.UNINSTALL_SHORTCUT");
getApplicationContext().sendBroadcast(delIntent);
}
And finally, here are two listener to add the first shortcut and update the shortcut with an incrementing counter.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
findViewById(R.id.add).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
shortcutAdd("changeIt!", count);
}
});
findViewById(R.id.increment).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
shortcutDel("changeIt!");
count++;
shortcutAdd("changeIt!", count);
}
});
}
Remarks:
This way works also if your App controls more shortcuts on the home screen, e.g. with different extra's in the Intent
. They just need different names so that the right one is uninstalled and reinstalled.
The programmatical handling of shortcuts in Android is a well known, widely used but not officially supported Android feature. It seems to work on the default launcher and I never tried it anywhere else. So dont blame me, when you get this user-emails "It does not work on my XYZ, double rooted, super blasted phone"
The launcher writes a Toast
when a shortcut was installad and one when a shortcut was uninstalled. So I get two Toast
s every time I change the icon. This is not perfect, but well, as long as the rest of my app is perfect...
If you know the string will be either "True"
or "False"
, you could just use eval(s)
.
>>> eval("True")
True
>>> eval("False")
False
Only use this if you are sure of the contents of the string though, as it will throw an exception if the string does not contain valid Python, and will also execute code contained in the string.
Im new to RoR this is what I found out. you can directly render a json format
def YOUR_METHOD_HERE
users = User.all
render json: {allUsers: users} # ! rendering all users
END
I've tried using flask instead of a simple apscheduler what you need to install is
pip3 install flask_apscheduler
Below is the sample of my code:
from flask import Flask
from flask_apscheduler import APScheduler
app = Flask(__name__)
scheduler = APScheduler()
def scheduleTask():
print("This test runs every 3 seconds")
if __name__ == '__main__':
scheduler.add_job(id = 'Scheduled Task', func=scheduleTask, trigger="interval", seconds=3)
scheduler.start()
app.run(host="0.0.0.0")
Set the max-width:1250px;
that is currently on your body on your #container. This way your header will be 100% of his parent (body) :)
Do you want to do this?
SELECT id, parent_id, name,
(select Name from tbl where id = t.parent_id) parent_name
FROM tbl t start with id = 1 CONNECT BY PRIOR id = parent_id
Edit Another option based on OMG's one (but I think that will perform equally):
select
t1.id,
t1.parent_id,
t1.name,
t2.name AS parent_name,
t2.id AS parent_id
from
(select id, parent_id, name
from tbl
start with id = 1
connect by prior id = parent_id) t1
left join
tbl t2 on t2.id = t1.parent_id
For elements with dynamic width it's possible to use transform: translateX(-100%);
to counter the horizontal percentage value. This leads to two possible solutions:
Transition from:
transform: translateX(0);
to
transform: translateX(calc(100vw - 100%));
#viewportPendulum {_x000D_
position: fixed;_x000D_
left: 0;_x000D_
top: 0;_x000D_
animation: 2s ease-in-out infinite alternate swingViewport;_x000D_
/* just for styling purposes */_x000D_
background: #c70039;_x000D_
padding: 1rem;_x000D_
color: #fff;_x000D_
font-family: sans-serif;_x000D_
}_x000D_
_x000D_
@keyframes swingViewport {_x000D_
from {_x000D_
transform: translateX(0);_x000D_
}_x000D_
to {_x000D_
transform: translateX(calc(100vw - 100%));_x000D_
}_x000D_
}
_x000D_
<div id="viewportPendulum">Viewport</div>
_x000D_
Transition from:
transform: translateX(0);
left: 0;
to
left: 100%;
transform: translateX(-100%);
#parentPendulum {_x000D_
position: relative;_x000D_
display: inline-block;_x000D_
animation: 2s ease-in-out infinite alternate swingParent;_x000D_
/* just for styling purposes */_x000D_
background: #c70039;_x000D_
padding: 1rem;_x000D_
color: #fff;_x000D_
font-family: sans-serif;_x000D_
}_x000D_
_x000D_
@keyframes swingParent {_x000D_
from {_x000D_
transform: translateX(0);_x000D_
left: 0;_x000D_
}_x000D_
to {_x000D_
left: 100%;_x000D_
transform: translateX(-100%);_x000D_
}_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
padding: 2rem 0;_x000D_
margin: 2rem 15%;_x000D_
background: #eee;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
<div id="parentPendulum">Parent</div>_x000D_
</div>
_x000D_
Note: This approach can easily be extended to work for vertical positioning. Visit example here.
css
has variables as well. You can use them like this:
--primaryColor: #ffffff;
--width: 800px;
body {
width: var(--width);
color: var(--primaryColor);
}
.content{
width: var(--width);
background: var(--primaryColor);
}
I have also receive the same IOException
, but I find the Android system demo: "BluetoothChat" project is worked. I determined the problem is the UUID.
So i replace my UUID.fromString("00001001-0000-1000-8000-00805F9B34FB")
to UUID.fromString("8ce255c0-200a-11e0-ac64-0800200c9a66")
and it worked most scene,only sometimes need to restart the Bluetooth device;
Open up the .csproj file for your solution in wordpad or some text editor. Look for the ProjectTypeGuids. They indicate the required supported types for your solutions. Search the internet these GUIDs to find out what they require. For example E53F8FEA-EAE0-44A6-8774-FFD645390401 means it requires "MVC 3.0"
Also, it`s interesting to set your PATH to reflect the JDK. After adding JAVA_HOME (which can be done with the example cited by 'mipadi'):
export JAVA_HOME=$(/usr/libexec/java_home)
Add also in ~/.profile:
export PATH=${JAVA_HOME}/bin:$PATH
P.S.: For OSX, I generally use .profile in the HOME dir instead of .bashrc
The proposed solution is just to much work for something that can be done like this:
Get-Alias -Definition Write*
"Segmentation fault" means that you tried to access memory that you do not have access to.
The first problem is with your arguments of main
. The main
function should be int main(int argc, char *argv[])
, and you should check that argc
is at least 2 before accessing argv[1]
.
Also, since you're passing in a float
to printf
(which, by the way, gets converted to a double
when passing to printf
), you should use the %f
format specifier. The %s
format specifier is for strings ('\0'
-terminated character arrays).
for those of us that love all things pandas, apply, and of course lambda functions:
df['Col3'] = df[['Col1', 'Col2']].apply(lambda x: ''.join(x), axis=1)
An often-used metaphor to describe Traits is Traits are interfaces with implementation.
This is a good way of thinking about it in most circumstances, but there are a number of subtle differences between the two.
For a start, the instanceof
operator will not work with traits (ie, a trait is not a real object), therefore you can't use that to see if a class has a certain trait (or to see if two otherwise unrelated classes share a trait). That's what they mean by it being a construct for horizontal code re-use.
There are functions now in PHP that will let you get a list of all the traits a class uses, but trait-inheritance means you'll need to do recursive checks to reliably check if a class at some point has a specific trait (there's example code on the PHP doco pages). But yeah, it's certainly not as simple and clean as instanceof
is, and IMHO it's a feature that would make PHP better.
Also, abstract classes are still classes, so they don't solve multiple-inheritance related code re-use problems. Remember you can only extend one class (real or abstract) but implement multiple interfaces.
I've found traits and interfaces are really good to use hand in hand to create pseudo multiple inheritance. Eg:
class SlidingDoor extends Door implements IKeyed
{
use KeyedTrait;
[...] // Generally not a lot else goes here since it's all in the trait
}
Doing this means you can use instanceof
to determine if the particular Door object is Keyed or not, you know you'll get a consistent set of methods, etc, and all the code is in one place across all the classes that use the KeyedTrait.
Was facing similar issue and found below link more helpful then the answers provided here. I guess this is due to the updates to AWS CLI since the answers are provided.
https://serverfault.com/questions/792937/the-config-profile-adminuser-could-not-be-found
Essentially it helps to create two different files (i.e. one for the general config related information and the second for the credentials related information).
As everyone else has said, there's no mapping within a dictionary from value to key.
I've just noticed you wanted to map to from value to multiple keys - I'm leaving this solution here for the single value version, but I'll then add another answer for a multi-entry bidirectional map.
The normal approach to take here is to have two dictionaries - one mapping one way and one the other. Encapsulate them in a separate class, and work out what you want to do when you have duplicate key or value (e.g. throw an exception, overwrite the existing entry, or ignore the new entry). Personally I'd probably go for throwing an exception - it makes the success behaviour easier to define. Something like this:
using System;
using System.Collections.Generic;
class BiDictionary<TFirst, TSecond>
{
IDictionary<TFirst, TSecond> firstToSecond = new Dictionary<TFirst, TSecond>();
IDictionary<TSecond, TFirst> secondToFirst = new Dictionary<TSecond, TFirst>();
public void Add(TFirst first, TSecond second)
{
if (firstToSecond.ContainsKey(first) ||
secondToFirst.ContainsKey(second))
{
throw new ArgumentException("Duplicate first or second");
}
firstToSecond.Add(first, second);
secondToFirst.Add(second, first);
}
public bool TryGetByFirst(TFirst first, out TSecond second)
{
return firstToSecond.TryGetValue(first, out second);
}
public bool TryGetBySecond(TSecond second, out TFirst first)
{
return secondToFirst.TryGetValue(second, out first);
}
}
class Test
{
static void Main()
{
BiDictionary<int, string> greek = new BiDictionary<int, string>();
greek.Add(1, "Alpha");
greek.Add(2, "Beta");
int x;
greek.TryGetBySecond("Beta", out x);
Console.WriteLine(x);
}
}
From the standard
7.5.2 Element identifiers: the id and class attributes
Attribute definitions
id = name [CS]
This attribute assigns a name to an element. This name must be unique in a document.class = cdata-list [CS]
This attribute assigns a class name or set of class names to an element. Any number of elements may be assigned the same class name or names. Multiple class names must be separated by white space characters.
Yes, just put a space between them.
<article class="column wrapper">
Of course, there are many things you can do with CSS inheritance. Here is an article for further reading.
You can Try using :- git ls-files -s
Generators have no length, they aren't collections after all.
Generators are functions with a internal state (and fancy syntax). You can repeatedly call them to get a sequence of values, so you can use them in loop. But they don't contain any elements, so asking for the length of a generator is like asking for the length of a function.
if functions in Python are objects, couldn't I assign the length to a variable of this object that would be accessible to the new generator?
Functions are objects, but you cannot assign new attributes to them. The reason is probably to keep such a basic object as efficient as possible.
You can however simply return (generator, length)
pairs from your functions or wrap the generator in a simple object like this:
class GeneratorLen(object):
def __init__(self, gen, length):
self.gen = gen
self.length = length
def __len__(self):
return self.length
def __iter__(self):
return self.gen
g = some_generator()
h = GeneratorLen(g, 1)
print len(h), list(h)
In Windows 7 on GitHub 2.5.3.0 I found it in C:\Users(user)\AppData\Local\GitHub\PortableGit_(numbers)\mingw32\bin\git.exe
thanks to dir /s git.exe
It seems like you need to use __init__
in Python if you want to correctly initialize mutable attributes of your instances.
See the following example:
>>> class EvilTest(object):
... attr = []
...
>>> evil_test1 = EvilTest()
>>> evil_test2 = EvilTest()
>>> evil_test1.attr.append('strange')
>>>
>>> print "This is evil:", evil_test1.attr, evil_test2.attr
This is evil: ['strange'] ['strange']
>>>
>>>
>>> class GoodTest(object):
... def __init__(self):
... self.attr = []
...
>>> good_test1 = GoodTest()
>>> good_test2 = GoodTest()
>>> good_test1.attr.append('strange')
>>>
>>> print "This is good:", good_test1.attr, good_test2.attr
This is good: ['strange'] []
This is quite different in Java where each attribute is automatically initialized with a new value:
import java.util.ArrayList;
import java.lang.String;
class SimpleTest
{
public ArrayList<String> attr = new ArrayList<String>();
}
class Main
{
public static void main(String [] args)
{
SimpleTest t1 = new SimpleTest();
SimpleTest t2 = new SimpleTest();
t1.attr.add("strange");
System.out.println(t1.attr + " " + t2.attr);
}
}
produces an output we intuitively expect:
[strange] []
But if you declare attr
as static
, it will act like Python:
[strange] [strange]
You can use Postgres' SIMILAR TO
operator which supports alternations, i.e.
select * from table where lower(value) similar to '%(foo|bar|baz)%';
Try this..
using System.Data.OleDb;
OleDbConnection dbConn;
dConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=Registration.accdb;");
Using find
's -regex
argument:
find . -regex '.*/Robert\.\(h\|cpp\)$'
Or just using -name
:
find . -name 'Robert.*' -a \( -name '*.cpp' -o -name '*.h' \)
Elements that are not being rendered (be it through visibility: hidden
, display: none
, opacity: 0.0
, whatever) will not indicate focus. The browser will not draw a focus border around nothing.
If you want the text to be focusable, that's completely doable. You can wrap the whole thing in an element that can receive focus (for example, a hyperlink), or allow another tag to have focus using the tabindex
property:
<label tabindex="0" class="checkbox">
<input type="checkbox" value="valueofcheckbox" style="display:none" checked="checked" />Option Text
</label>
In this case, the <label>
tag above is actually receiving focus and everything within it will have a focus border when it's in focus.
I do question what your goal is. If you're using a hidden checkbox to internally track some sort of state, you might be better off using a <input type="hidden" />
tag instead.
Port: 25 or 587 (some providers block port 25)
I work by changing the port after deploying the app to the server.
$mail->Port = 25;
$mail->Port = 587;
GL
If you are like me just want to print a sequence within a lambda, without get the return value (list of None).
x = range(3)
from __future__ import print_function # if not python 3
pra = lambda seq=x: map(print,seq) and None # pra for 'print all'
pra()
pra('abc')
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
drpCategory.DataSource = CategoryHelper.Categories;
drpCategory.DataTextField = "Name";
drpCategory.DataValueField = "Id";
drpCategory.DataBind();
}
}
I found ljust()
and rjust()
very useful to print a string at a fixed width or fill out a Python string with spaces.
An example
print('123.00'.rjust(9))
print('123456.89'.rjust(9))
# expected output
123.00
123456.89
For your case, you case use fstring
to print
for prefix in unique:
if prefix != "":
print(f"value {prefix.ljust(3)} - num of occurrences = {string.count(str(prefix))}")
Expected Output
value a - num of occurrences = 1
value ab - num of occurrences = 1
value abc - num of occurrences = 1
value b - num of occurrences = 1
value bc - num of occurrences = 1
value bcd - num of occurrences = 1
value c - num of occurrences = 1
value cd - num of occurrences = 1
value d - num of occurrences = 1
You can change 3
to the highest length of your permutation string.
You can use max-height
in an inline style
attribute, as below:
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body" style="max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>
To use scrolling with content that overflows a given max-height
, you can alternatively try the following:
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body" style="max-height: 10;overflow-y: scroll;">fdoinfds sdofjohisdfj</div>
</div>
To restrict the height to a fixed value you can use something like this.
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body" style="min-height: 10; max-height: 10;">fdoinfds sdofjohisdfj</div>
</div>
Specify the same value for both max-height
and min-height
(either in pixels or in points – as long as it’s consistent).
You can also put the same styles in css class in a stylesheet (or a style
tag as shown below) and then include the same in your tag. See below:
Style Code:
.fixed-panel {
min-height: 10;
max-height: 10;
overflow-y: scroll;
}
Apply Style :
<div class="panel panel-primary">
<div class="panel-heading">jhdsahfjhdfhs</div>
<div class="panel-body fixed-panel">fdoinfds sdofjohisdfj</div>
</div>
Hope this helps with your need.
You can use islower()
on your string to see if it contains some lowercase letters (amongst other characters). or
it with isupper()
to also check if contains some uppercase letters:
below: letters in the string: test yields true
>>> z = "(555) 555 - 5555 ext. 5555"
>>> z.isupper() or z.islower()
True
below: no letters in the string: test yields false.
>>> z= "(555).555-5555"
>>> z.isupper() or z.islower()
False
>>>
Not to be mixed up with isalpha()
which returns True
only if all characters are letters, which isn't what you want.
Note that Barm's answer completes mine nicely, since mine doesn't handle the mixed case well.
SELECT is_read_committed_snapshot_on FROM sys.databases
WHERE name= 'YourDatabase'
Return value:
READ_COMMITTED_SNAPSHOT
option is ON. Read operations under the READ COMMITTED
isolation level are based on snapshot scans and do not acquire locks.READ_COMMITTED_SNAPSHOT
option is OFF. Read operations under the READ COMMITTED
isolation level use Shared (S) locks.I think what you want requires an extra wrapper div.
#map {_x000D_
float: left; _x000D_
width: 700px; _x000D_
height: 500px;_x000D_
}_x000D_
#wrapper {_x000D_
float: left;_x000D_
width: 200px;_x000D_
}_x000D_
#list {_x000D_
background: #eee;_x000D_
list-style: none; _x000D_
padding: 0; _x000D_
}_x000D_
#similar {_x000D_
background: #000; _x000D_
}
_x000D_
<div id="map">Lorem Ipsum</div> _x000D_
<div id="wrapper">_x000D_
<ul id="list"><li>Dolor</li><li>Sit</li><li>Amet</li></ul>_x000D_
<div id ="similar">_x000D_
this text should be below, not next to ul._x000D_
</div>_x000D_
</div>
_x000D_
HTML
<div class="close-orange"></div>
CSS
.close-orange {
height: 100px;
width: 100px;
background-color: #FA6900;
border-radius: 5px;
}
.close-orange:before,.close-orange:after{
content:'';
position:absolute;
width: 50px;
height: 4px;
background-color:white;
border-radius:2px;
top: 55px;
}
.close-orange:before{
-webkit-transform:rotate(45deg);
-moz-transform:rotate(45deg);
transform:rotate(45deg);
left: 32.5px;
}
.close-orange:after{
-webkit-transform:rotate(-45deg);
-moz-transform:rotate(-45deg);
transform:rotate(-45deg);
left: 32.5px;
}
Here is my 2 cents:
double dX = x1 - x2;
double dY = y1 - y2;
double multi = dX * dX + dY * dY;
double rad = Math.Round(Math.Sqrt(multi), 3, MidpointRounding.AwayFromZero);
x1, y1 is the first coordinate and x2, y2 the second. The last line is the square root with it rounded to 3 decimal places.
For future reference, in Visual Studio you can try placing the cursor in the method name (for example, WriteLine) and press F1 to pull up help on that context. Digging around should then find you String.Format()
in this case, with lots of helpful information.
Note that highlighting a selection (for example, double-clicking or doing a drag-select) and hitting F1 only does a non-context string search (which tends to suck at finding anything helpful), so make sure you just position the cursor anywhere inside the word without highlighting it.
This is also helpful for documentation on classes and other types.
To elaborate on https://stackoverflow.com/a/59311063/1328979, here is a fully documented, annotated and tested Python 3 implementation for the general case.
from __future__ import annotations # To allow "MinHeap.push -> MinHeap:"
from typing import Generic, List, Optional, TypeVar
from heapq import heapify, heappop, heappush, heapreplace
T = TypeVar('T')
class MinHeap(Generic[T]):
'''
MinHeap provides a nicer API around heapq's functionality.
As it is a minimum heap, the first element of the heap is always the
smallest.
>>> h = MinHeap([3, 1, 4, 2])
>>> h[0]
1
>>> h.peek()
1
>>> h.push(5) # N.B.: the array isn't always fully sorted.
[1, 2, 4, 3, 5]
>>> h.pop()
1
>>> h.pop()
2
>>> h.pop()
3
>>> h.push(3).push(2)
[2, 3, 4, 5]
>>> h.replace(1)
2
>>> h
[1, 3, 4, 5]
'''
def __init__(self, array: Optional[List[T]] = None):
if array is None:
array = []
heapify(array)
self.h = array
def push(self, x: T) -> MinHeap:
heappush(self.h, x)
return self # To allow chaining operations.
def peek(self) -> T:
return self.h[0]
def pop(self) -> T:
return heappop(self.h)
def replace(self, x: T) -> T:
return heapreplace(self.h, x)
def __getitem__(self, i) -> T:
return self.h[i]
def __len__(self) -> int:
return len(self.h)
def __str__(self) -> str:
return str(self.h)
def __repr__(self) -> str:
return str(self.h)
class Reverse(Generic[T]):
'''
Wrap around the provided object, reversing the comparison operators.
>>> 1 < 2
True
>>> Reverse(1) < Reverse(2)
False
>>> Reverse(2) < Reverse(1)
True
>>> Reverse(1) <= Reverse(2)
False
>>> Reverse(2) <= Reverse(1)
True
>>> Reverse(2) <= Reverse(2)
True
>>> Reverse(1) == Reverse(1)
True
>>> Reverse(2) > Reverse(1)
False
>>> Reverse(1) > Reverse(2)
True
>>> Reverse(2) >= Reverse(1)
False
>>> Reverse(1) >= Reverse(2)
True
>>> Reverse(1)
1
'''
def __init__(self, x: T) -> None:
self.x = x
def __lt__(self, other: Reverse) -> bool:
return other.x.__lt__(self.x)
def __le__(self, other: Reverse) -> bool:
return other.x.__le__(self.x)
def __eq__(self, other) -> bool:
return self.x == other.x
def __ne__(self, other: Reverse) -> bool:
return other.x.__ne__(self.x)
def __ge__(self, other: Reverse) -> bool:
return other.x.__ge__(self.x)
def __gt__(self, other: Reverse) -> bool:
return other.x.__gt__(self.x)
def __str__(self):
return str(self.x)
def __repr__(self):
return str(self.x)
class MaxHeap(MinHeap):
'''
MaxHeap provides an implement of a maximum-heap, as heapq does not provide
it. As it is a maximum heap, the first element of the heap is always the
largest. It achieves this by wrapping around elements with Reverse,
which reverses the comparison operations used by heapq.
>>> h = MaxHeap([3, 1, 4, 2])
>>> h[0]
4
>>> h.peek()
4
>>> h.push(5) # N.B.: the array isn't always fully sorted.
[5, 4, 3, 1, 2]
>>> h.pop()
5
>>> h.pop()
4
>>> h.pop()
3
>>> h.pop()
2
>>> h.push(3).push(2).push(4)
[4, 3, 2, 1]
>>> h.replace(1)
4
>>> h
[3, 1, 2, 1]
'''
def __init__(self, array: Optional[List[T]] = None):
if array is not None:
array = [Reverse(x) for x in array] # Wrap with Reverse.
super().__init__(array)
def push(self, x: T) -> MaxHeap:
super().push(Reverse(x))
return self
def peek(self) -> T:
return super().peek().x
def pop(self) -> T:
return super().pop().x
def replace(self, x: T) -> T:
return super().replace(Reverse(x)).x
if __name__ == '__main__':
import doctest
doctest.testmod()
https://gist.github.com/marccarre/577a55850998da02af3d4b7b98152cf4
Add the following line in your .profile
file in your home directory (using vi ~/.profile
):
PATH=$PATH:/home/me/play
export PATH
Then, for the change to take effect, simply type in your terminal:
$ . ~/.profile
Here is a concise answer for future readers. Tensorflow
's logit
is defined as the output of a neuron without applying activation function:
logit = w*x + b,
x: input, w: weight, b: bias. That's it.
The following is irrelevant to this question.
For historical lectures, read other answers. Hats off to Tensorflow
's "creatively" confusing naming convention. In PyTorch
, there is only one CrossEntropyLoss
and it accepts un-activated outputs. Convolutions, matrix multiplications and activations are same level operations. The design is much more modular and less confusing. This is one of the reasons why I switched from Tensorflow
to PyTorch
.
I think the following works best:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
Android 19 has Chromium engine for WebView. I guess it works better with hardware acceleration.
Delete the CMakeCache.txt file and try this:
cmake -G %1 -DBUILD_SHARED_LIBS=ON -DBUILD_STATIC_LIBS=ON -DBUILD_TESTS=ON ..
You have to enter all your command-line definitions before including the path.
You can use:
IF "%~1" == "" GOTO MyLabel
to strip the outer set of quotes. In general, this is a more reliable method than using square brackets because it will work even if the variable has spaces in it.
In loop with .map
work like this:
{
dataForm.map(({ id, placeholder, type }) => {
return <Input
value={this.state.type}
onChangeText={(text) => this.setState({ [type]: text })}
placeholder={placeholder}
key={id} />
})
}
Note the []
in type
parameter.
Hope this helps :)
You want grepl
:
> chars <- "test"
> value <- "es"
> grepl(value, chars)
[1] TRUE
> chars <- "test"
> value <- "et"
> grepl(value, chars)
[1] FALSE
If after install you need to run redis
on all time, just type in terminal:
redis-server &
Running redis using upstart on Ubuntu
I've been trying to understand how to setup systems from the ground up on Ubuntu. I just installed redis
onto the box and here's how I did it and some things to look out for.
To install:
sudo apt-get install redis-server
That will create a redis
user and install the init.d
script for it. Since upstart
is now the replacement for using init.d, I figure I should convert it to run using upstart
.
To disable the default init.d
script for redis
:
sudo update-rc.d redis-server disable
Then create /etc/init/redis-server.conf
with the following script:
description "redis server"
start on runlevel [23]
stop on shutdown
exec sudo -u redis /usr/bin/redis-server /etc/redis/redis.conf
respawn
What this is the script for upstart
to know what command to run to start the process. The last line also tells upstart
to keep trying to respawn if it dies.
One thing I had to change in /etc/redis/redis.conf
is daemonize yes
to daemonize no
. What happens if you don't change it then redis-server
will fork and daemonize itself, and the parent process goes away. When this happens, upstart
thinks that the process has died/stopped and you won't have control over the process from within upstart
.
Now you can use the following commands to control your redis-server
:
sudo start redis-server
sudo restart redis-server
sudo stop redis-server
Hope this was helpful!
How about this:
src = [ 'one', 'two', 'three', 'two', 'three', 'three' ]
result_dict = dict( [ (i, src.count(i)) for i in set(src) ] )
This results in
{'one': 1, 'three': 3, 'two': 2}
use this(assume that your table name is emails):
select * from emails as a
inner join
(select EmailAddress, min(Id) as id from emails
group by EmailAddress ) as b
on a.EmailAddress = b.EmailAddress
and a.Id = b.id
hope this help..
If so simple than many people think, me included :)
cd to Project Folder/src/package
there you should see yourClass.java then run javac yourClass.java
which will create yourClass.class then cd out of the src
folder and into the build
folder there you can run java package.youClass
I am using the Terminal on Mac or you can accomplish the same task using Command Prompt on windows
You basically need to make a HTTP request to the service, and then parse the body of the response. I like to use httplib2 for it:
import httplib2 as http
import json
try:
from urlparse import urlparse
except ImportError:
from urllib.parse import urlparse
headers = {
'Accept': 'application/json',
'Content-Type': 'application/json; charset=UTF-8'
}
uri = 'http://yourservice.com'
path = '/path/to/resource/'
target = urlparse(uri+path)
method = 'GET'
body = ''
h = http.Http()
# If you need authentication some example:
if auth:
h.add_credentials(auth.user, auth.password)
response, content = h.request(
target.geturl(),
method,
body,
headers)
# assume that content is a json reply
# parse content with the json module
data = json.loads(content)
This snippet successfully allows to reuse existing browser instance yet avoiding raising the duplicate browser. Found at Tarun Lalwani's blog.
from selenium import webdriver
from selenium.webdriver.remote.webdriver import WebDriver
# executor_url = driver.command_executor._url
# session_id = driver.session_id
def attach_to_session(executor_url, session_id):
original_execute = WebDriver.execute
def new_command_execute(self, command, params=None):
if command == "newSession":
# Mock the response
return {'success': 0, 'value': None, 'sessionId': session_id}
else:
return original_execute(self, command, params)
# Patch the function before creating the driver object
WebDriver.execute = new_command_execute
driver = webdriver.Remote(command_executor=executor_url, desired_capabilities={})
driver.session_id = session_id
# Replace the patched function with original function
WebDriver.execute = original_execute
return driver
bro = attach_to_session('http://127.0.0.1:64092', '8de24f3bfbec01ba0d82a7946df1d1c3')
bro.get('http://ya.ru/')
Include the phrase:
@echo off
Right at the top of your bat script.
It exists because it is more convenient to use, also it is a whole different ideology using attributes to mark the authorization parameters rather than xml configuration. It wasn't meant to beat general purpose config or any other authorization frameworks, just MVC's way of doing it. I'm saying this, because it seems you are looking for a technical feature advantages which are probably non... just superb convenience.
BobRock already listed the advantages. Just to add to his answer, another scenarios are that you can apply this attribute to whole controller, not just actions, also you can add different role authorization parameters to different actions in same controller to mix and match.
This worked for me:
git branch
Copy the current branch name to clipboard
git pull origin <paste-branch-name>
git push
Deleting/Moving files org.eclipse.jst.server.tomcat.core.prefs and org.eclipse.wst.server.core.prefs worked for me.
In python you would use a dictionary.
It is a very important type in python and often used.
You can create one easily by
name = {}
Dictionaries have many methods:
# add entries:
>>> name['first'] = 'John'
>>> name['second'] = 'Doe'
>>> name
{'first': 'John', 'second': 'Doe'}
# you can store all objects and datatypes as value in a dictionary
# as key you can use all objects and datatypes that are hashable
>>> name['list'] = ['list', 'inside', 'dict']
>>> name[1] = 1
>>> name
{'first': 'John', 'second': 'Doe', 1: 1, 'list': ['list', 'inside', 'dict']}
You can not influence the order of a dict.
try this
<a id="link" href="www.gmail.com" target="_blank" >gmail</a>
As a follow up to Earlz answer, you need a wrapper script that creates a $PID.running file when it starts, and delete when it ends. The wrapper script calls the script you wish to run. The wrapper is necessary in case the target script fails or errors out, the pid file gets deleted..
You could implement a custom IEqualityComparer<Employee>
:
public class Employee
{
public string empName { get; set; }
public string empID { get; set; }
public string empLoc { get; set; }
public string empPL { get; set; }
public string empShift { get; set; }
public class Comparer : IEqualityComparer<Employee>
{
public bool Equals(Employee x, Employee y)
{
return x.empLoc == y.empLoc
&& x.empPL == y.empPL
&& x.empShift == y.empShift;
}
public int GetHashCode(Employee obj)
{
unchecked // overflow is fine
{
int hash = 17;
hash = hash * 23 + (obj.empLoc ?? "").GetHashCode();
hash = hash * 23 + (obj.empPL ?? "").GetHashCode();
hash = hash * 23 + (obj.empShift ?? "").GetHashCode();
return hash;
}
}
}
}
Now you can use this overload of Enumerable.Distinct
:
var distinct = employees.Distinct(new Employee.Comparer());
The less reusable, robust and efficient approach, using an anonymous type:
var distinctKeys = employees.Select(e => new { e.empLoc, e.empPL, e.empShift })
.Distinct();
var joined = from e in employees
join d in distinctKeys
on new { e.empLoc, e.empPL, e.empShift } equals d
select e;
// if you want to replace the original collection
employees = joined.ToList();
Not exactly "exporting," but you can select the rows (or Ctrl-A to select all of them) in the grid you'd like to export, and then copy with Ctrl-C.
The default is tab-delimited. You can paste that into Excel or some other editor and manipulate the delimiters all you like.
Also, if you use Ctrl-Shift-C instead of Ctrl-C, you'll also copy the column headers.
A variation on Jorenko's work above allows the elevated process to use the same console (but see my comment below):
def spawn_as_administrator():
""" Spawn ourself with administrator rights and wait for new process to exit
Make the new process use the same console as the old one.
Raise Exception() if we could not get a handle for the new re-run the process
Raise pywintypes.error() if we could not re-spawn
Return the exit code of the new process,
or return None if already running the second admin process. """
#pylint: disable=no-name-in-module,import-error
import win32event, win32api, win32process
import win32com.shell.shell as shell
if '--admin' in sys.argv:
return None
script = os.path.abspath(sys.argv[0])
params = ' '.join([script] + sys.argv[1:] + ['--admin'])
SEE_MASK_NO_CONSOLE = 0x00008000
SEE_MASK_NOCLOSE_PROCESS = 0x00000040
process = shell.ShellExecuteEx(lpVerb='runas', lpFile=sys.executable, lpParameters=params, fMask=SEE_MASK_NO_CONSOLE|SEE_MASK_NOCLOSE_PROCESS)
hProcess = process['hProcess']
if not hProcess:
raise Exception("Could not identify administrator process to install drivers")
# It is necessary to wait for the elevated process or else
# stdin lines are shared between 2 processes: they get one line each
INFINITE = -1
win32event.WaitForSingleObject(hProcess, INFINITE)
exitcode = win32process.GetExitCodeProcess(hProcess)
win32api.CloseHandle(hProcess)
return exitcode
Put each class into separate files and "require" them.
User.php
<?php
class User {
public $userid;
public $username;
private $password;
public $profile;
public $history;
public function __construct() {
require_once('UserProfile.php');
require_once('UserHistory.php');
$this->profile = new UserProfile();
$this->history = new UserHistory();
}
}
?>
UserProfile.php
<?php
class UserProfile
{
// Some code here
}
?>
UserHistory.php
<?php
class UserHistory
{
// Some code here
}
?>
Despite that the other answers are correct and thoroughly explained, I found some difficulties understanding them. Here is the method I used (Taken from here):
openssl pkcs12 -in filename.pfx -out cert.pem -nodes
Extracts the private key form a PFX to a PEM file:
openssl pkcs12 -in filename.pfx -nocerts -out key.pem
Exports the certificate (includes the public key only):
openssl pkcs12 -in filename.pfx -clcerts -nokeys -out cert.pem
Removes the password (paraphrase) from the extracted private key (optional):
openssl rsa -in key.pem -out server.key
Change
$info=$_POST['id[]'];
to
$info=$_POST['id'];
by adding []
to the end of your form field names, PHP will automatically convert these variables into arrays.
Since typeof
is a compiler extension, there is not really a definition for it, but in the tradition of C it would be an operator, e.g sizeof
and _Alignof
are also seen as an operators.
And you are mistaken, C has dynamic types that are only determined at run time: variable modified (VM) types.
size_t n = strtoull(argv[1], 0, 0);
double A[n][n];
typeof(A) B;
can only be determined at run time.
There's a built-in setting for it. On the ScrollView:
android:fillViewport="true"
In Java,
mScrollView.setFillViewport(true);
Romain Guy explains it in depth here: http://www.curious-creature.org/2010/08/15/scrollviews-handy-trick/
I really like to sort the keys in one liner code:
print "$_ => $my_hash{$_}\n" for (sort keys %my_hash);