For properties configuration
# ENDPOINTS CORS CONFIGURATION (EndpointCorsProperties)
endpoints.cors.allow-credentials= # Set whether credentials are supported. When not set, credentials are not supported.
endpoints.cors.allowed-headers= # Comma-separated list of headers to allow in a request. '*' allows all headers.
endpoints.cors.allowed-methods=GET # Comma-separated list of methods to allow. '*' allows all methods.
endpoints.cors.allowed-origins= # Comma-separated list of origins to allow. '*' allows all origins. When not set, CORS support is disabled.
endpoints.cors.exposed-headers= # Comma-separated list of headers to include in a response.
endpoints.cors.max-age=1800 # How long, in seconds, the response from a pre-flight request can be cached by clients.
as header
AUTH=$(echo -ne "$BASIC_AUTH_USER:$BASIC_AUTH_PASSWORD" | base64 --wrap 0)
curl \
--header "Content-Type: application/json" \
--header "Authorization: Basic $AUTH" \
--request POST \
--data '{"key1":"value1", "key2":"value2"}' \
https://example.com/
For making a CORS request one must add headers to the request along with the same he needs to check of mode_header is enabled in Apache.
For enabling headers in Ubuntu:
sudo a2enmod headers
For php server to accept request from different origin use:
Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"
no need to use user and password as part of the URL
you can try this
byte[] encodedBytes = Base64.encodeBase64("user:passwd".getBytes());
String USER_PASS = new String(encodedBytes);
HttpUriRequest request = RequestBuilder.get(url).addHeader("Authorization", USER_PASS).build();
From RFC 1945 (HTTP/1.0) and RFC 2617 (HTTP Authentication referenced by HTTP/1.1)
The realm attribute (case-insensitive) is required for all authentication schemes which issue a challenge. The realm value (case-sensitive), in combination with the canonical root URL of the server being accessed, defines the protection space. These realms allow the protected resources on a server to be partitioned into a set of protection spaces, each with its own authentication scheme and/or authorization database. The realm value is a string, generally assigned by the origin server, which may have additional semantics specific to the authentication scheme.
In short, pages in the same realm should share credentials. If your credentials work for a page with the realm "My Realm", it should be assumed that the same username and password combination should work for another page with the same realm.
I am having same issue. None of the above works for me. The problem is Github has block my write permission. I have changed my password. Now I am able to push.
Putting this information here for future readers' benefit.
401 (Unauthorized) response header -> Request authentication header
Here are several WWW-Authenticate
response headers. (The full list is at IANA: HTTP Authentication Schemes.)
WWW-Authenticate: Basic
-> Authorization: Basic + token - Use for basic authentication WWW-Authenticate: NTLM
-> Authorization: NTLM + token (2 challenges)WWW-Authenticate: Negotiate
-> Authorization: Negotiate + token - used for Kerberos authentication
Negotiate
: This authentication scheme violates both HTTP semantics (being connection-oriented) and syntax (use of syntax incompatible with the WWW-Authenticate and Authorization header field syntax).You can set the Authorization: Basic
header only when you also have the WWW-Authenticate: Basic
header on your 401 challenge.
But since you have WWW-Authenticate: Negotiate
this should be the case for Kerberos based authentication.
When indicating HTTP Basic Authentication we return something like:
WWW-Authenticate: Basic realm="myRealm"
Whereas Basic
is the scheme and the remainder is very much dependent on that scheme. In this case realm just provides the browser a literal that can be displayed to the user when prompting for the user id and password.
You're obviously not using Basic however since there is no point having session expiry when Basic Auth is used. I assume you're using some form of Forms based authentication.
From recollection, Windows Challenge Response uses a different scheme and different arguments.
The trick is that it's up to the browser to determine what schemes it supports and how it responds to them.
My gut feel if you are using forms based authentication is to stay with the 200 + relogin page but add a custom header that the browser will ignore but your AJAX can identify.
For a really good User + AJAX experience, get the script to hang on to the AJAX request that found the session expired, fire off a relogin request via a popup, and on success, resubmit the original AJAX request and carry on as normal.
Avoid the cheat that just gets the script to hit the site every 5 mins to keep the session alive cause that just defeats the point of session expiry.
The other alternative is burn the AJAX request but that's a poor user experience.
setup.py is designed to be run from the command line. You'll need to open your command prompt (In Windows 7, hold down shift while right-clicking in the directory with the setup.py file. You should be able to select "Open Command Window Here").
From the command line, you can type
python setup.py --help
...to get a list of commands. What you are looking to do is...
python setup.py install
here's your amended script
#!/bin/bash
folder="ABC" #no spaces between assignment
useracct='test'
day=$(date "+%d") # use $() to assign return value of date command to variable
month=$(date "+%B")
year=$(date "+%Y")
folderToBeMoved="/users/$useracct/Documents/Archive/Primetime.eyetv"
newfoldername="/Volumes/Media/Network/$folder/$month$day$year"
ECHO "Network is $network" $network
ECHO "day is $day"
ECHO "Month is $month"
ECHO "YEAR is $year"
ECHO "source is $folderToBeMoved"
ECHO "dest is $newfoldername"
mkdir "$newfoldername"
cp -R "$folderToBeMoved" "$newfoldername"
if [ -f "$newfoldername/Primetime.eyetv" ]; then # <-- put a space at square brackets and quote your variables.
rm "$folderToBeMoved";
fi
There are a couple options you can use:
The style attribute for the menu background is android:panelFullBackground
.
Despite what the documentation says, it needs to be a resource (e.g. @android:color/black
or @drawable/my_drawable
), it will crash if you use a color value directly.
This will also get rid of the item borders that I was unable to change or remove using primalpop's solution.
As for the text color, I haven't found any way to set it through styles in 2.2 and I'm sure I've tried everything (which is how I discovered the menu background attribute). You would need to use primalpop's solution for that.
This can also be done in the GUI:
I had the same problem, none of the solutions worked for me, Finally I removed the System.Web.MVC
and added again Then everything was back to normal and my problem solved.
You can also specify noHistory = "true" in the tag for first activity or finish the first activity as soon as you start the second one(as David said).
AFAIK, "force close" kills the process which hosts the JVM in which your application runs and System.exit() terminates the JVM running your application instance. Both are form of abrupt terminations and not advisable for normal application flow.
Just as catching exceptions to cover logic flows that a program might undertake, is not advisable.
On Windows: if you had to mount two directories E:\data\dev & E:\data\dev2
Use:
docker run -v E:\data\dev:c:/downloads -v E:\data\dev2 c:/downloads2 -i --publish 1111:80 -P SomeBuiltContainerName:SomeLabel
It depends on which level you selected in your log4j configuration file.
<Loggers>
<Root level="info">
...
If your level is "info" (by default), logger.debug(...)
will not be printed in your console.
However, if your level is "debug", it will.
Depending on the criticality level of your code, you should use the most accurate level among the following ones :
ALL < TRACE < DEBUG < INFO < WARN < ERROR < FATAL < OFF
With bash version >= 4.2:
printf "%(%H:%M)T\n"
or
printf -v foo "%(%H:%M)T\n"
echo "$foo"
See: man bash
I realize this post is a few years old, but I just wanted to extend this to anyone still struggling through this issue.
The company I work for still uses VS2015 so in turn I still use VS2015. I recently started working on a RPC application using C++ and found the need to download the Win32 Templates. Like many others I was having this "SDK 8.1 was not found" issue. i took the following corrective actions with no luck.
None of the attempts above corrected the issue for me...
I then found this article on social MSDN https://social.msdn.microsoft.com/Forums/office/en-US/5287c51b-46d0-4a79-baad-ddde36af4885/visual-studio-cant-find-windows-81-sdk-when-trying-to-build-vs2015?forum=visualstudiogeneral
Finally what resolved the issue for me was:
I hope this saves anyone else from almost 3 full days of frustration and loss of productivity.
To know SESSION decimal separator, you can use following SQL command:
ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ', ';
select SUBSTR(value,1,1) as "SEPARATOR"
,'using NLS-PARAMETER' as "Explanation"
from nls_session_parameters
where parameter = 'NLS_NUMERIC_CHARACTERS'
UNION ALL
select SUBSTR(0.5,1,1) as "SEPARATOR"
,'using NUMBER IMPLICIT CASTING' as "Explanation"
from DUAL;
The first SELECT command find NLS Parameter defined in NLS_SESSION_PARAMETERS
table. The decimal separator is the first character of the returned value.
The second SELECT command convert IMPLICITELY the 0.5
rational number into a String using (by default) NLS_NUMERIC_CHARACTERS defined at session level.
The both command return same value.
I have already tested the same SQL command in PL/SQL script and this is always the same value COMMA or POINT that is displayed. Decimal Separator displayed in PL/SQL script is equal to what is displayed in SQL.
To test what I say, I have used following SQL commands:
ALTER SESSION SET NLS_NUMERIC_CHARACTERS = ', ';
select 'DECIMAL-SEPARATOR on CLIENT: (' || TO_CHAR(.5,) || ')' from dual;
DECLARE
S VARCHAR2(10) := '?';
BEGIN
select .5 INTO S from dual;
DBMS_OUTPUT.PUT_LINE('DECIMAL-SEPARATOR in PL/SQL: (' || S || ')');
END;
/
The shorter command to know decimal separator is:
SELECT .5 FROM DUAL;
That return 0,5
if decimal separator is a COMMA and 0.5
if decimal separator is a POINT.
A simple one liner using Java-8
Key key = Collections.max(map.entrySet(), Map.Entry.comparingByValue()).getKey();
The following code was used in our html5 game.
$(document).ready(function () {
$(window)
.bind('orientationchange', function(){
if (window.orientation % 180 == 0){
$(document.body).css("-webkit-transform-origin", "")
.css("-webkit-transform", "");
}
else {
if ( window.orientation > 0) { //clockwise
$(document.body).css("-webkit-transform-origin", "200px 190px")
.css("-webkit-transform", "rotate(-90deg)");
}
else {
$(document.body).css("-webkit-transform-origin", "280px 190px")
.css("-webkit-transform", "rotate(90deg)");
}
}
})
.trigger('orientationchange');
});
On Windows, make sure all your apps agree on HOME. Msys will surprisingly NOT do it for you. I had to set an environment variable because ssh and git couldn't seem to agree on where my .ssh directory was.
I know that the question was for Java
. But I want to share a possible solution for Kotlin
because I think it is useful.
With Kotlin you can write an extension function which converts a JSONArray
into an native (Kotlin) array:
fun JSONArray.asArray(): Array<Any> {
return Array(this.length()) { this[it] }
}
Now you can call asArray()
directly on a JSONArray
instance.
if you use a list of widgets you can use this:
class HomePage extends StatelessWidget {
bool notNull(Object o) => o != null;
@override
Widget build(BuildContext context) {
var condition = true;
return Scaffold(
appBar: AppBar(
title: Text("Provider Demo"),
),
body: Center(
child: Column(
children: <Widget>[
condition? Text("True"): null,
Container(
height: 300,
width: MediaQuery.of(context).size.width,
child: Text("Test")
)
].where(notNull).toList(),
)),
);
}
}
There may be 2 spaces after the text, please confirm. You can use LTRIM
and RTRIM
functions also right?
LTRIM(RTRIM(ProductAlternateKey))
Maybe the extra space isn't ordinary spaces (ASCII 32, soft space)? Maybe they are "hard space", ASCII 160?
ltrim(rtrim(replace(ProductAlternateKey, char(160), char(32))))
div {_x000D_
height: 100px;_x000D_
width: 50%;_x000D_
margin: 0 auto;_x000D_
overflow: hidden;_x000D_
}_x000D_
_x000D_
div:hover {_x000D_
overflow-y: scroll;_x000D_
}
_x000D_
<div>_x000D_
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It_x000D_
has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop_x000D_
publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
</p>_x000D_
</div>
_x000D_
Would something like that work?
I had solved it on iPad. Try, if it works also on OSX.
body, html { position: fixed; }
Works only if you have content smaller then screen or you are using some layout framework (Angular Material in my case).
In Angular Material it is great, that you will disable over-scroll effect of whole page, but inner sections <md-content>
can be still scrollable.
I have combined all the above answers into a script that polls the counters and writes the measurements in the terminal:
$totalRam = (Get-CimInstance Win32_PhysicalMemory | Measure-Object -Property capacity -Sum).Sum
while($true) {
$date = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
$cpuTime = (Get-Counter '\Processor(_Total)\% Processor Time').CounterSamples.CookedValue
$availMem = (Get-Counter '\Memory\Available MBytes').CounterSamples.CookedValue
$date + ' > CPU: ' + $cpuTime.ToString("#,0.000") + '%, Avail. Mem.: ' + $availMem.ToString("N0") + 'MB (' + (104857600 * $availMem / $totalRam).ToString("#,0.0") + '%)'
Start-Sleep -s 2
}
This produces the following output:
2020-02-01 10:56:55 > CPU: 0.797%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:56:59 > CPU: 0.447%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:57:03 > CPU: 0.089%, Avail. Mem.: 2,118MB (51.7%)
2020-02-01 10:57:07 > CPU: 0.000%, Avail. Mem.: 2,118MB (51.7%)
You can hit Ctrl+C
to abort the loop.
So, you can connect to any Windows machine with this command:
Enter-PSSession -ComputerName MyServerName -Credential MyUserName
...paste it in, and run it, to get a "live" measurement. If connecting to the machine doesn't work directly, take a look here.
You can create a form in VBA, with code to increase the width of a label control as your code progresses. You can use the width property of a label control to resize it. You can set the background colour property of the label to any colour you choose. This will let you create your own progress bar.
The label control that resizes is a quick solution. However, most people end up creating individual forms for each of their macros. I use the DoEvents function and a modeless form to use a single form for all your macros.
Here is a blog post I wrote about it: http://strugglingtoexcel.wordpress.com/2014/03/27/progress-bar-excel-vba/
All you have to do is import the form and a module into your projects, and call the progress bar with: Call modProgress.ShowProgress(ActionIndex, TotalActions, Title.....)
I hope this helps.
In my case, since I was using AWS_IAM as the Authorization method for API Gateway, I needed to grant my IAM role permissions to hit the endpoint.
I've used something like this with a Bash shell on Ubuntu 12.04 (LTS):
To append a new line with tab,second when first is matched:
sed -i '/first/a \\t second' filename
To replace first with tab,second:
sed -i 's/first/\\t second/g' filename
Let me emphasise that Docker doesn't even allow mixed characters.
Good:
docker build -t myfirstechoimage:0.1 .
Bad:
docker build -t myFirstEchoImage:0.1 .
When you start up or just join a project based on webapplications, the design of interface is maybe good. Otherwise this should be changed. In order to Web 2.0 applications you will work with dynamic contents, many effects and other stuff. All these things are fine, but no one thought about to style up the JavaScript alert and confirm boxes. Here is the they way,.. completely dynamic, JS and CSS driven Create simple html file
<html>
<head>
<title>jsConfirmSyle</title>
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<script type="text/javascript" src="jsConfirmStyle.js"></script>
<script type="text/javascript">
function confirmation() {
var answer = confirm("Wanna visit google?")
if (answer){
window.location = "http://www.google.com/";
}
}
</script>
<style type="text/css">
body {
background-color: white;
font-family: sans-serif;
}
#jsconfirm {
border-color: #c0c0c0;
border-width: 2px 4px 4px 2px;
left: 0;
margin: 0;
padding: 0;
position: absolute;
top: -1000px;
z-index: 100;
}
#jsconfirm table {
background-color: #fff;
border: 2px groove #c0c0c0;
height: 150px;
width: 300px;
}
#jsconfirmtitle {
background-color: #B0B0B0;
font-weight: bold;
height: 20px;
text-align: center;
}
#jsconfirmbuttons {
height: 50px;
text-align: center;
}
#jsconfirmbuttons input {
background-color: #E9E9CF;
color: #000000;
font-weight: bold;
width: 125px;
height: 33px;
padding-left: 20px;
}
#jsconfirmleft{
background-image: url(left.png);
}
#jsconfirmright{
background-image: url(right.png);
}
< /style>
</head>
<body>
<p><br />
<a href="#"
onclick="javascript:showConfirm('Please confirm','Are you really really sure to visit google?','Yes','http://www.google.com','No','#')">JsConfirmStyled</a></p>
<p><a href="#" onclick="confirmation()">standard</a></p>
</body>
</html>
Then create simple js file name jsConfirmStyle.js. Here is simple js code
ie5=(document.getElementById&&document.all&&document.styleSheets)?1:0;
nn6=(document.getElementById&&!document.all)?1:0;
xConfirmStart=800;
yConfirmStart=100;
if(ie5||nn6) {
if(ie5) cs=2,th=30;
else cs=0,th=20;
document.write(
"<div id='jsconfirm'>"+
"<table>"+
"<tr><td id='jsconfirmtitle'></td></tr>"+
"<tr><td id='jsconfirmcontent'></td></tr>"+
"<tr><td id='jsconfirmbuttons'>"+
"<input id='jsconfirmleft' type='button' value='' onclick='leftJsConfirm()' onfocus='if(this.blur)this.blur()'>"+
" "+
"<input id='jsconfirmright' type='button' value='' onclick='rightJsConfirm()' onfocus='if(this.blur)this.blur()'>"+
"</td></tr>"+
"</table>"+
"</div>"
);
}
document.write("<div id='jsconfirmfade'></div>");
function leftJsConfirm() {
document.getElementById('jsconfirm').style.top=-1000;
document.location.href=leftJsConfirmUri;
}
function rightJsConfirm() {
document.getElementById('jsconfirm').style.top=-1000;
document.location.href=rightJsConfirmUri;
}
function confirmAlternative() {
if(confirm("Scipt requieres a better browser!")) document.location.href="http://www.mozilla.org";
}
leftJsConfirmUri = '';
rightJsConfirmUri = '';
/**
* Show the message/confirm box
*/
function showConfirm(confirmtitle,confirmcontent,confirmlefttext,confirmlefturi,confirmrighttext,con firmrighturi) {
document.getElementById("jsconfirmtitle").innerHTML=confirmtitle;
document.getElementById("jsconfirmcontent").innerHTML=confirmcontent;
document.getElementById("jsconfirmleft").value=confirmlefttext;
document.getElementById("jsconfirmright").value=confirmrighttext;
leftJsConfirmUri=confirmlefturi;
rightJsConfirmUri=confirmrighturi;
xConfirm=xConfirmStart, yConfirm=yConfirmStart;
if(ie5) {
document.getElementById("jsconfirm").style.left='25%';
document.getElementById("jsconfirm").style.top='35%';
}
else if(nn6) {
document.getElementById("jsconfirm").style.top='25%';
document.getElementById("jsconfirm").style.left='35%';
}
else confirmAlternative();
}
You may as well use for x in values
rather than for x in values[:]
; the latter makes an unnecessary copy. Also, of course that code checks for a length of 2 rather than of 3...
The code only prints one item per value of x
- and x
is iterating over the elements of values
, which are the sublists. So it will only print each sublist once.
sudo /Library/StartupItems/MySQLCOM/MySQLCOM start
sudo /Library/StartupItems/MySQLCOM/MySQLCOM stop
make alias in .bash_profile
alias start_mysql="/Library/StartupItems/MySQLCOM/MySQLCOM start"
alias stop_mysql="/Library/StartupItems/MySQLCOM/MySQLCOM stop"
and if you are trying to run as root use following safe mode
sudo ./bin/mysqld_safe
if you are still having issues starting, a recommended read: mysql5.58 unstart server in mac os 10.6.5
Following leppie's answer, why not make MetaData
an interface:
public interface IMetaData { }
public class Metadata<DataType> : IMetaData where DataType : struct
{
private DataType mDataType;
}
A simpler solution is to do this rather than using uniform:
$('#check1').prop('checked', true); // will check the checkbox with id check1
$('#check1').prop('checked', false); // will uncheck the checkbox with id check1
This will not trigger any click action defined.
You can also use:
$('#check1').click(); //
This will toggle the check/uncheck for the checkbox but this will also trigger any click action you have defined. So be careful.
EDIT: jQuery 1.6+ uses prop()
not attr()
for checkboxes checked value
no need to do a replacement. the regex will give you what u wanted directly:
"(?<=_)[^_]*\.jpg"
tested with grep:
echo "3.04_somename.jpg"|grep -oP "(?<=_)[^_]*\.jpg"
somename.jpg
1) Open your terminal and type
npm install -g http-server
2) Go to the root folder that you want to serve you files and type:
http-server ./
3)
Read the output of the terminal, something kinda http://localhost:8080
will appear.
Everything on there will be allowed to be got. Example:
background: url('http://localhost:8080/waw.png')
;
In UTF-32 all of characters are coded with 32 bits. The advantage is that you can easily calculate the length of the string. The disadvantage is that for each ASCII characters you waste an extra three bytes.
In UTF-8 characters have variable length, ASCII characters are coded in one byte (eight bits), most western special characters are coded either in two bytes or three bytes (for example € is three bytes), and more exotic characters can take up to four bytes. Clear disadvantage is, that a priori you cannot calculate string's length. But it's takes lot less bytes to code Latin (English) alphabet text, compared to UTF-32.
UTF-16 is also variable length. Characters are coded either in two bytes or four bytes. I really don't see the point. It has disadvantage of being variable length, but hasn't got the advantage of saving as much space as UTF-8.
Of those three, clearly UTF-8 is the most widely spread.
$greatCircleDistance = acos( cos($latitude0) * cos($latitude1) * cos($longitude0 - $longitude1) + sin($latitude0) * sin($latitude1));
with latitude and longitude in radian.
so
SELECT
acos(
cos(radians( $latitude0 ))
* cos(radians( $latitude1 ))
* cos(radians( $longitude0 ) - radians( $longitude1 ))
+ sin(radians( $latitude0 ))
* sin(radians( $latitude1 ))
) AS greatCircleDistance
FROM yourTable;
is your SQL query
to get your results in Km or miles, multiply the result with the mean radius of Earth (3959
miles,6371
Km or 3440
nautical miles)
The thing you are calculating in your example is a bounding box. If you put your coordinate data in a spatial enabled MySQL column, you can use MySQL's build in functionality to query the data.
SELECT
id
FROM spatialEnabledTable
WHERE
MBRWithin(ogc_point, GeomFromText('Polygon((0 0,0 3,3 3,3 0,0 0))'))
You have wrong database design and you should take a time to read something about database normalization (wikipedia / stackoverflow).
I assume your table looks somewhat like this
TABLE
================================
| group_id | user_ids | name |
--------------------------------
| 1 | 1,4,6 | group1 |
--------------------------------
| 2 | 4,5,1 | group2 |
so in your table of user groups, each row represents one group and in user_ids
column you have set of user ids assigned to that group.
Normalized version of this table would look like this
GROUP
=====================
| id | name |
---------------------
| 1 | group1 |
---------------------
| 2 | group2 |
GROUP_USER_ASSIGNMENT
======================
| group_id | user_id |
----------------------
| 1 | 1 |
----------------------
| 1 | 4 |
----------------------
| 1 | 6 |
----------------------
| 2 | 4 |
----------------------
| ...
Then you can easily select all users with assigned group, or all users in group, or all groups of user, or whatever you can think of. Also, your sql query will work:
/* Your query to select assignments */
SELECT * FROM `group_user_assignment` WHERE user_id IN (1,2,3,4);
/* Select only some users */
SELECT * FROM `group_user_assignment` t1
JOIN `group` t2 ON t2.id = t1.group_id
WHERE user_id IN (1,4);
/* Select all groups of user */
SELECT * FROM `group_user_assignment` t1
JOIN `group` t2 ON t2.id = t1.group_id
WHERE t1.`user_id` = 1;
/* Select all users of group */
SELECT * FROM `group_user_assignment` t1
JOIN `group` t2 ON t2.id = t1.group_id
WHERE t1.`group_id` = 1;
/* Count number of groups user is in */
SELECT COUNT(*) AS `groups_count` FROM `group_user_assignment` WHERE `user_id` = 1;
/* Count number of users in group */
SELECT COUNT(*) AS `users_count` FROM `group_user_assignment` WHERE `group_id` = 1;
This way it will be also easier to update database, when you would like to add new assignment, you just simply insert new row in group_user_assignment
, when you want to remove assignment you just delete row in group_user_assignment
.
In your database design, to update assignments, you would have to get your assignment set from database, process it and update and then write back to database.
Here is sqlFiddle to play with.
Answer by the user 'onlyblank' is correct. A small addition to that- You can set more than 1 default values if you want.
Instead of passing on id to the setValue(), pass an array. Example:
var $select = $("#my_input").selectize();
var selectize = $select[0].selectize;
var yourDefaultIds = [1,2]; # find the ids using search as shown by the user onlyblank
selectize.setValue(defaultValueIds);
please try this flower:
/^[a-z0-9\_\.\-]{2,20}\@[a-z0-9\_\-]{2,20}\.[a-z]{2,9}$/.test('[email protected]');
true
Please check the query without using a function:
declare @T table(Insurance varchar(max))
insert into @T values ('wezembeek-oppem')
insert into @T values ('roeselare')
insert into @T values ('BRUGGE')
insert into @T values ('louvain-la-neuve')
select (
select upper(T.N.value('.', 'char(1)'))+
lower(stuff(T.N.value('.', 'varchar(max)'), 1, 1, ''))+(CASE WHEN RIGHT(T.N.value('.', 'varchar(max)'), 1)='-' THEN '' ELSE ' ' END)
from X.InsXML.nodes('/N') as T(N)
for xml path(''), type
).value('.', 'varchar(max)') as Insurance
from
(
select cast('<N>'+replace(
replace(
Insurance,
' ', '</N><N>'),
'-', '-</N><N>')+'</N>' as xml) as InsXML
from @T
) as X
use np.random.randint()
as np.random.random_integers()
is deprecated
random_matrix = np.random.randint(min_val,max_val,(<num_rows>,<num_cols>))
To run once, daily at 10PM you should do something like this:
0 22 * * *
Full size image: http://i.stack.imgur.com/BeXHD.jpg
Source: softpanorama.org
You cannot access a local directory from pl/sql. If you use bfile, you will setup a directory (create directory) on the server where Oracle is running where you will need to put your images.
If you want to insert a handful of images from your local machine, you'll need a client side app to do this. You can write your own, but I typically use Toad for this. In schema browser, click onto the table. Click the data tab, and hit + sign to add a row. Double click the BLOB column, and a wizard opens. The far left icon will load an image into the blob:
SQL Developer has a similar feature. See the "Load" link below:
If you need to pull images over the wire, you can do it using pl/sql, but its not straight forward. First, you'll need to setup ACL list access (for security reasons) to allow a user to pull over the wire. See this article for more on ACL setup.
Assuming ACL is complete, you'd pull the image like this:
declare
l_url varchar2(4000) := 'http://www.oracleimg.com/us/assets/12_c_navbnr.jpg';
l_http_request UTL_HTTP.req;
l_http_response UTL_HTTP.resp;
l_raw RAW(2000);
l_blob BLOB;
begin
-- Important: setup ACL access list first!
DBMS_LOB.createtemporary(l_blob, FALSE);
l_http_request := UTL_HTTP.begin_request(l_url);
l_http_response := UTL_HTTP.get_response(l_http_request);
-- Copy the response into the BLOB.
BEGIN
LOOP
UTL_HTTP.read_raw(l_http_response, l_raw, 2000);
DBMS_LOB.writeappend (l_blob, UTL_RAW.length(l_raw), l_raw);
END LOOP;
EXCEPTION
WHEN UTL_HTTP.end_of_body THEN
UTL_HTTP.end_response(l_http_response);
END;
insert into my_pics (pic_id, pic) values (102, l_blob);
commit;
DBMS_LOB.freetemporary(l_blob);
end;
Hope that helps.
In Visual Studio 2015 From the top menu
Edit -> Advanced -> View White Space
or CTRL + E, S
First of all you have to understand the nature of
response.sendRedirect(newUrl);
It is giving the client (browser) 302 http code response with an URL. The browser then makes a separate GET request on that URL. And that request has no knowledge of headers in the first one.
So sendRedirect won't work if you need to pass a header from Servlet A to Servlet B.
If you want this code to work - use RequestDispatcher in Servlet A (instead of sendRedirect). Also, it is always better to use relative path.
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String userName=request.getParameter("userName");
String newUrl = "ServletB";
response.addHeader("REMOTE_USER", userName);
RequestDispatcher view = request.getRequestDispatcher(newUrl);
view.forward(request, response);
}
========================
public void doPost(HttpServletRequest request, HttpServletResponse response)
{
String sss = response.getHeader("REMOTE_USER");
}
One line closure, copy, reset:
<?php
$fruits = array(4 => 'apple', 7 => 'orange', 13 => 'plum');
echo (function() use ($fruits) { return reset($fruits); })();
Output:
apple
Alternatively the shorter short arrow function:
echo (fn() => reset($fruits))();
This uses by-value variable binding as above. Both will not mutate the original pointer.
playersList.get(0)
Java has limited operator polymorphism. So you use the get()
method on List
objects, not the array index operator ([]
)
According to this site, this is supported in the playbackRate
and defaultPlaybackRate
attributes, accessible via the DOM. Example:
/* play video twice as fast */
document.querySelector('video').defaultPlaybackRate = 2.0;
document.querySelector('video').play();
/* now play three times as fast just for the heck of it */
document.querySelector('video').playbackRate = 3.0;
The above works on Chrome 43+, Firefox 20+, IE 9+, Edge 12+.
I use a JavaScript port of the Mersenne Twister: https://gist.github.com/300494 It allows you to set the seed manually. Also, as mentioned in other answers, the Mersenne Twister is a really good PRNG.
I found using okHttp a lot easier as I could not get any of these solutions to work: https://stackoverflow.com/a/37942387/447549
A fast way of doing this is to clone using the --bare
keyword and then check the log:
git clone --bare git@giturl tmpdir
cd tmpdir
git log branch
I resolved this problem by taking the full and transactional backup. Sometimes, the backup process is not completed and that's one of the reason the .ldf file is not getting shrink. Try this. It worked for me.
You can also use react router dom library useHistory;
`
import { useHistory } from "react-router-dom";
function HomeButton() {
let history = useHistory();
function handleClick() {
history.push("/home");
}
return (
<button type="button" onClick={handleClick}>
Go home
</button>
);
}
`
And one more example, which works great for me:
function validateNumber(event) {
var key = window.event ? event.keyCode : event.which;
if (event.keyCode === 8 || event.keyCode === 46) {
return true;
} else if ( key < 48 || key > 57 ) {
return false;
} else {
return true;
}
};
Also attach to keypress event
$(document).ready(function(){
$('[id^=edit]').keypress(validateNumber);
});
And HTML:
<input type="input" id="edit1" value="0" size="5" maxlength="5" />
Try this piece of code:
NSString *digit = [[sender titlelabel] text];
NSLog(@"%@", digit);
The message means that you have incorrect syntax for using the digit
variable. If you're not sending it any message - you don't need any brackets.
In my case I had to specify the Port Number using
scp -P 2222 username@hostip:/directory/ /localdirectory/
I recently faced this. None of the above solutions worked for me. Seems it wasn't actually Python's problem. When I was running
aws s3 ls
I was getting following error:
dyld: Library not loaded: @executable_path/../.Python
This means, the library aws
executable is pointing towards is either doesn't exist or is corrupted, thus I uninstalled and reinstalled aws-cli
following instructions from this link and it worked!!
Your first formulation, image_url('logo.png')
, is correct. If the image is found, it will generate the path /assets/logo.png
(plus a hash in production). However, if Rails cannot find the image that you named, it will fall back to /images/logo.png
.
The next question is: why isn't Rails finding your image? If you put it in app/assets/images/logo.png, then you should be able to access it by going to http://localhost:3000/assets/logo.png
.
If that works, but your CSS isn't updating, you may need to clear the cache. Delete tmp/cache/assets
from your project directory and restart the server (webrick, etc.).
If that fails, you can also try just using background-image: url(logo.png);
That will cause your CSS to look for files with the same relative path (which in this case is /assets).
ClickOnce apps are designed so that the end user downloads a "downloader" - the ClickOnce app, then when ya run it, it downloads and installs in %LocalAppData%\Apps\2.0..... and then it's random folder names for every OS install you do. Backing up is pointless and so is trying to move the program. The point of ClickOnce is 2-Fold: 1. AutoUpdating of the program 2. The end user has no installer and also can't move the app or it breaks
The %LocalAppData%\Apps\2.0..... folder is the program AND %LocalAppData%\GitHub is the settings folder.
I'm not going to cover how to circumvent this - only stating the above. :P
The best 'tip' I can say legitimately is: You 'can' in some cases move the final folder that all the files are in and use a symlink back, if you are low on space. But, not all apps will work and essentially will delete the symlink once you they run. Then they might reinstall or simply just remove the link. Keep in mind also, other apps may be using that same final folder as well, so move the folder will affect those too.
Even after installing python-tk, python3-tk I was getting error your python is not configured for Tk.
So I additionally installed tk8.6-dev Then I build my Python again, run following again: make, make install.
When I did this I saw messages on screen that it is building _tkinter and related modules. Once that is done, I tried 'import tkinter" and it worked.
Leanest answer (.net 4.5 and later):
static public event EventHandler FilterStringChanged;
static string _filterString;
static public string FilterString
{
get { return _filterString; }
set
{
_filterString= value;
FilterStringChanged?.Invoke(null, EventArgs.Empty);
}
}
and XAML:
<TextBox Text="{Binding Path=(local:VersionManager.FilterString)}"/>
Don't neglect the brackets
This may help : Hide the element by positioning it on far most left position and then check the offsetLeft property. If you want to use jQuery you can simply check the :visible selector and get the visibility state of the element.
HTML :
<div id="myDiv">Hello</div>
CSS :
<!-- for javaScript-->
#myDiv{
position:absolute;
left : -2000px;
}
<!-- for jQuery -->
#myDiv{
visibility:hidden;
}
javaScript :
var myStyle = document.getElementById("myDiv").offsetLeft;
if(myStyle < 0){
alert("Div is hidden!!");
}
jQuery :
if( $("#MyElement").is(":visible") == true )
{
alert("Div is visible!!");
}
The negated set of everything that is not alphanumeric & underscore for ASCII chars:
/[^\W]/g
For email or username validation i've used the following expression that allows 4 standard special characters - _ . @
/^[-.@_a-z0-9]+$/gi
For a strict alphanumeric only expression use:
/^[a-z0-9]+$/gi
Test @ RegExr.com
Starting with AspNetCore 2.0, it's recommended to use ContentResult
instead of the Produce
attribute in this case. See: https://github.com/aspnet/Mvc/issues/6657#issuecomment-322586885
This doesn't rely on serialization nor on content negotiation.
[HttpGet]
public ContentResult Index() {
return new ContentResult {
ContentType = "text/html",
StatusCode = (int)HttpStatusCode.OK,
Content = "<html><body>Hello World</body></html>"
};
}
I built a custom class that extends TextView
and solves this problem... Check out my answer here =)
Use the Path
class from System.IO
. It contains useful calls for manipulating file paths, including GetDirectoryName
which does what you want, returning the directory portion of the file path.
Usage is simple.
string directoryPath = Path.GetDirectoryName(filePath);
int value = 35634646;
DecimalFormat myFormatter = new DecimalFormat("#,###");
String output = myFormatter.format(value);
System.out.println(output);
Output: 35,634,646
I had the same problem. So here is what i did
And it worked.
Collapse all : CTRL + SHIFT + /
Expand all code blocks : CTRL + *
This is a state-of-the-union answer as of Windows PowerShell v5.1 / PowerShell Core v6.2.0:
Andrew Savinykh's ill-fated answer, despite being the accepted one, is, as of this writing, fundamentally flawed (I do hope it gets fixed - there's enough information in the comments - and in the edit history - to do so).
Ansgar Wiecher's helpful answer works well, but requires direct use of the .NET Framework (and reads the entire file into memory, though that could be changed). Direct use of the .NET Framework is not a problem per se, but is harder to master for novices and hard to remember in general.
A future version of PowerShell Core will have a
Convert-TextFile
cmdlet with a -LineEnding
parameter to allow in-place updating of text files with a specific newline style, as being discussed on GitHub.
In PSv5+, PowerShell-native solutions are now possible, because Set-Content
now supports the -NoNewline
switch, which prevents undesired appending of a platform-native newline[1]
:
# Convert CRLFs to LFs only.
# Note:
# * (...) around Get-Content ensures that $file is read *in full*
# up front, so that it is possible to write back the transformed content
# to the same file.
# * + "`n" ensures that the file has a *trailing LF*, which Unix platforms
# expect.
((Get-Content $file) -join "`n") + "`n" | Set-Content -NoNewline $file
The above relies on Get-Content
's ability to read a text file that uses any combination of CR-only, CRLF, and LF-only newlines line by line.
Caveats:
You need to specify the output encoding to match the input file's in order to recreate it with the same encoding. The command above does NOT specify an output encoding; to do so, use -Encoding
; without -Encoding
:
The input file's content as well as its transformed copy must fit into memory as a whole, which can be problematic with large input files.
There's a risk of file corruption, if the process of writing back to the input file gets interrupted.
[1] In fact, if there are multiple strings to write, -NoNewline
also doesn't place a newline between them; in the case at hand, however, this is irrelevant, because only one string is written.
1.Very Simple Code to iterate datatable and get columns in list.
2.code ==>>>
foreach (DataColumn dataColumn in dataTable.Columns)
{
var list = dataTable.Rows.OfType<DataRow>()
.Select(dataRow => dataRow.Field<string>
(dataColumn.ToString())).ToList();
}
Another option is to use the cor.test function, instead of lm:
> x <- c(44.4, 45.9, 41.9, 53.3, 44.7, 44.1, 50.7, 45.2, 60.1)
> y <- c( 2.6, 3.1, 2.5, 5.0, 3.6, 4.0, 5.2, 2.8, 3.8)
> mycor = cor.test(x,y)
> mylm = lm(x~y)
# r and rsquared:
> cor.test(x,y)$estimate ** 2
cor
0.3262484
> summary(lm(x~y))$r.squared
[1] 0.3262484
# P.value
> lmp(lm(x~y)) # Using the lmp function defined in Chase's answer
[1] 0.1081731
> cor.test(x,y)$p.value
[1] 0.1081731
The inspect module provides several useful functions to help get information about live objects such as modules, classes, methods, functions, tracebacks, frame objects, and code objects.
Using getmembers()
you can see all attributes of your class, along with their value. To exclude private or protected attributes use .startswith('_')
. To exclude methods or functions use inspect.ismethod()
or inspect.isfunction()
.
import inspect
class NewClass(object):
def __init__(self, number):
self.multi = int(number) * 2
self.str = str(number)
def func_1(self):
pass
a = NewClass(2)
for i in inspect.getmembers(a):
# Ignores anything starting with underscore
# (that is, private and protected attributes)
if not i[0].startswith('_'):
# Ignores methods
if not inspect.ismethod(i[1]):
print(i)
Note that ismethod()
is used on the second element of i
since the first is simply a string (its name).
Offtopic: Use CamelCase for class names.
Depending on the libc release it could be needed to set both SO_REUSEADDR and SO_REUSEPORT socket options as explained in socket(7) documentation :
SO_REUSEPORT (since Linux 3.9) Permits multiple AF_INET or AF_INET6 sockets to be bound to an identical socket address. This option must be set on each socket (including the first socket) prior to calling bind(2) on the socket. To prevent port hijacking, all of the processes binding to the same address must have the same effective UID. This option can be employed with both TCP and UDP sockets.
As this socket option appears with kernel 3.9 and raspberry use 3.12.x, it will be needed to set SO_REUSEPORT.
You can set theses two options before calling bind like this :
int reuse = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, (const char*)&reuse, sizeof(reuse)) < 0)
perror("setsockopt(SO_REUSEADDR) failed");
#ifdef SO_REUSEPORT
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEPORT, (const char*)&reuse, sizeof(reuse)) < 0)
perror("setsockopt(SO_REUSEPORT) failed");
#endif
Look at www.goo.gl/2SIOJj it is a work in progress but it may help you.
I use cookie to define if i want desktop or responsive version. In the footer of the page you can find two spans and in general.js is the script to handle the clicks.
<div class="col-xs-6" style="text-align:center;"><span class="make_desktop">Desktop</span></div>
<div class="col-xs-6" style="text-align:center;"><span class="make_responsive">Mobile</span></div>
function setMobDeskCookie(c_name, value, exdays) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
var c_value = escape(value) + ((exdays === null) ? "" : "; expires=" + exdate.toUTCString());
document.cookie = c_name + "=" + c_value + "; path=/";
window.location.reload();
}
$(function() {
$(".make_desktop").click(function() {
setMobDeskCookie('deskmob', 1, 3650);
});
$(".make_responsive").click(function() {
setMobDeskCookie('deskmob', 0, 3650);
});
});`enter code here`
i ended up splitting all my custom css into two files i don't use bootstrap navigation but my own so that is majority of my custom styles, so it will not resolve your entire problem but it works for me
and i also created non-responsive.css that forces the grid to maintain the large screen version
in case u select mobile i would load / echo
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<!-- Bootstrap core CSS and JS -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<link href="/themes/responsive_lime/bootstrap-3_1_1/css/bootstrap.css" rel="stylesheet">
<script src="/themes/responsive_lime/bootstrap-3_1_1/js/bootstrap.min.js"></script>
and load these stylesheets
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style.css?modified=14-06-2014-12-27-40" />
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style-responsive.css?modified=1402758346" />
in case you select desktop i would load /echo
<meta name="viewport" content="width=1024">
<!-- Bootstrap core CSS and JS -->
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<link href="/themes/responsive_lime/bootstrap-3_1_1/css/bootstrap.css" rel="stylesheet">
<script src="/themes/responsive_lime/bootstrap-3_1_1/js/bootstrap.min.js"></script>
<!-- Main CSS -->
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/style.css?modified=14-06-2014-12-27-40" />
<link rel="stylesheet" type="text/css" media="screen,print" href="/themes/responsive_lime/css/non-responsive.css?modified=1402758635" />
the non-responsive.css is the one that has overrides for bootstrap my concern is layout so there is not much in there, given that i handle the navigation in my own way so css for it and the other bits is in my other css files
please note that my setup does behave as desktop even on desktop browsers unlike some other solutions i have seen that will only ignore the viewport that seems to have wotked only on mobile devices for me
Yes.
See:
public static void main(String args[]) {
HashMap<String, HashMap<String, Object>> map = new HashMap<String, HashMap<String,Object>>();
map.put("key", new HashMap<String, Object>());
map.get("key").put("key2", "val2");
System.out.println(map.get("key").get("key2"));
}
Go to Tortoise SVN --> Settings --> Saved Data
.
There is an option to clear Authentication Data, click on the clear button, and it will allow you to select which connection you wanted to clear userid/pwd for.
After you do this, any checkout or update activity, it will reprompt for the userid and password.
A little hacky, but I created an array called "console", and anytime I wanted to output to console I pushed to the array. Then whenever I wanted to see the actual output, I just returned console
instead of whatever I was returning before.
//return 'console' //uncomment to output console
return "actual output";
}
The hashcode will be calculated based on the ASCII values of the characters in the String.
This is the implementation in the String Class is as follows
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) {
hash = h = isLatin1() ? StringLatin1.hashCode(value)
: StringUTF16.hashCode(value);
}
return h;
}
Collisions in hashcode are unavoidable. For example, the strings "Ea" and "FB" give the same hashcode as 2236
Have you gave your button a class instead of an id? try the following code
$(".btnSave").attr('value', 'Save');
.php
file and run in destination server<html>
<form method="post">
<input name="url" size="50" />
<input name="submit" type="submit" />
</form>
<?php
// maximum execution time in seconds
set_time_limit (24 * 60 * 60);
if (!isset($_POST['submit'])) die();
// folder to save downloaded files to. must end with slash
$destination_folder = 'downloads/';
$url = $_POST['url'];
$newfname = $destination_folder . basename($url);
$file = fopen ($url, "rb");
if ($file) {
$newf = fopen ($newfname, "wb");
if ($newf)
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8 ), 1024 * 8 );
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
?>
</html>
My basic recursive version, working with older versions of JDK:
public static void deleteFile(File element) {
if (element.isDirectory()) {
for (File sub : element.listFiles()) {
deleteFile(sub);
}
}
element.delete();
}
I successfully followed this answer, but since entitlements have changed, I simply removed the --entitlements "Payload/Application.app/Entitlements.plist"
part of the second to last statement, and it worked like a charm.
Simply saying, any() does this work : according to the condition even if it encounters one fulfilling value in the list, it returns true, else it returns false.
list = [2,-3,-4,5,6]
a = any(x>0 for x in lst)
print a:
True
list = [2,3,4,5,6,7]
a = any(x<0 for x in lst)
print a:
False
MySQL stores DATETIME without timezone information. Let's say you store '2019-01-01 20:00:00' into a DATETIME field, when you retrieve that value you're expected to know what timezone it belongs to.
So in your case, when you store a value into a DATETIME field, make sure it is Tanzania time. Then when you get it out, it will be Tanzania time. Yay!
Now, the hairy question is: When I do an INSERT/UPDATE, how do I make sure the value is Tanzania time? Two cases:
You do INSERT INTO table (dateCreated) VALUES (CURRENT_TIMESTAMP or NOW())
.
You do INSERT INTO table (dateCreated) VALUES (?)
, and specify the current time from your application code.
CASE #1
MySQL will take the current time, let's say that is '2019-01-01 20:00:00' Tanzania time. Then MySQL will convert it to UTC, which comes out to '2019-01-01 17:00:00', and store that value into the field.
So how do you get the Tanzania time, which is '20:00:00', to store into the field? It's not possible. Your code will need to expect UTC time when reading from this field.
CASE #2
It depends on what type of value you pass as ?
. If you pass the string '2019-01-01 20:00:00', then good for you, that's exactly what will be stored to the DB. If you pass a Date object of some kind, then it'll depend on how the db driver interprets that Date object, and ultimate what 'YYYY-MM-DD HH:mm:ss' string it provides to MySQL for storage. The db driver's documentation should tell you.
You can set dbPath in the mongodb.conf file:
storage:
dbPath: "/path/to/your/database/data/db"
It's a YAML-based configuration file format (since Mongodb 2.6 version), so pay attention no tabs only spaces, and space after ": "
usually this file located in the *nix systems here: /etc/mongodb.conf
So then just run
$ mongod -f /etc/mongodb.conf
And mongod process will start...
(on the Windows something like)
> C:\MongoDB\bin\mongod.exe -f C:\MongoDB\mongod.conf
Not tested, but something like this:
var now = new Date();
var str = now.getUTCFullYear().toString() + "/" +
(now.getUTCMonth() + 1).toString() +
"/" + now.getUTCDate() + " " + now.getUTCHours() +
":" + now.getUTCMinutes() + ":" + now.getUTCSeconds();
Of course, you'll need to pad the hours, minutes, and seconds to two digits or you'll sometimes get weird looking times like "2011/12/2 19:2:8."
If you use git LFS, git count-objects does not count your binaries, but only the pointers to them.
If your LFS files are managed by Artifactorys, you should use the REST API:
Use STATS in the BACKUP command if it is just a script.
Inside code it is a bit more complicated. In ODBC for example, you set SQL_ATTR_ASYNC_ENABLE and then look for SQL_STILL_EXECUTING return code, and do some repeated calls of SQLExecDirect until you get a SQL_SUCCESS (or eqiv).
The below code provides the results which replaces NULL to zero in the output.
Table creation and data insertion:
create table test_table
(
date nvarchar(10),
category char(3),
amount money
)
insert into test_table values ('1/1/2012','ABC',1000.00)
insert into test_table values ('2/1/2012','DEF',500.00)
insert into test_table values ('2/1/2012','GHI',800.00)
insert into test_table values ('2/10/2012','DEF',700.00)
insert into test_table values ('3/1/2012','ABC',1100.00)
Query to generate the exact results which also replaces NULL with zeros:
DECLARE @DynamicPivotQuery AS NVARCHAR(MAX),
@PivotColumnNames AS NVARCHAR(MAX),
@PivotSelectColumnNames AS NVARCHAR(MAX)
--Get distinct values of the PIVOT Column
SELECT @PivotColumnNames= ISNULL(@PivotColumnNames + ',','')
+ QUOTENAME(category)
FROM (SELECT DISTINCT category FROM test_table) AS cat
--Get distinct values of the PIVOT Column with isnull
SELECT @PivotSelectColumnNames
= ISNULL(@PivotSelectColumnNames + ',','')
+ 'ISNULL(' + QUOTENAME(category) + ', 0) AS '
+ QUOTENAME(category)
FROM (SELECT DISTINCT category FROM test_table) AS cat
--Prepare the PIVOT query using the dynamic
SET @DynamicPivotQuery =
N'SELECT date, ' + @PivotSelectColumnNames + '
FROM test_table
pivot(sum(amount) for category in (' + @PivotColumnNames + ')) as pvt';
--Execute the Dynamic Pivot Query
EXEC sp_executesql @DynamicPivotQuery
OUTPUT :
What you are looking for is called covariant type parameters. This means that if one type of object can be substituted for another in a method (for instance, Animal
can be replaced with Dog
), the same applies to expressions using those objects (so List<Animal>
could be replaced with List<Dog>
). The problem is that covariance is not safe for mutable lists in general. Suppose you have a List<Dog>
, and it is being used as a List<Animal>
. What happens when you try to add a Cat to this List<Animal>
which is really a List<Dog>
? Automatically allowing type parameters to be covariant breaks the type system.
It would be useful to add syntax to allow type parameters to be specified as covariant, which avoids the ? extends Foo
in method declarations, but that does add additional complexity.
There is no need to use :checkbox
, also replace #activelist
with #inactivelist
:
$('#inactivelist').change(function () {
alert('changed');
});
What do you mean by "initialize an array to zero"? Arrays don't contain "zero" -- they can contain "zero elements", which is the same as "an empty list". Or, you could have an array with one element, where that element is a zero: my @array = (0);
my @array = ();
should work just fine -- it allocates a new array called @array
, and then assigns it the empty list, ()
. Note that this is identical to simply saying my @array;
, since the initial value of a new array is the empty list anyway.
Are you sure you are getting an error from this line, and not somewhere else in your code? Ensure you have use strict; use warnings;
in your module or script, and check the line number of the error you get. (Posting some contextual code here might help, too.)
Are you using a shared hosting provider? It could be master settings overriding anything you're trying to change. Have you tried adding those into your .htaccess?
php_value upload_max_filesize 10M
php_value post_max_size 10M
I managed to install php54w according to Simon's suggestion, but then my sites stopped working perhaps because of an incompatibility with php-mysql or some other module. Even frantically restoring the old situation was not amusing: for anyone in my own situation the sequence is:
sudo yum remove php54w
sudo yum remove php54w-common
sudo yum install php-common
sudo yum install php-mysql
sudo yum install php
It would be nice if someone submitted the full procedure to update all the php packet. That was my production server and my heart is still rapidly beating.
If you really want to use PHP as your backend for WebSockets, these links can get you on your way:
There are some things to be considered in your code.
First, write those headers correctly. You will never see any server sending Content-type:application/pdf
, the header is Content-Type: application/pdf
, spaced, with capitalized first letters etc.
The file name in Content-Disposition
is the file name only, not the full path to it, and altrough I don't know if its mandatory or not, this name comes wrapped in "
not '
. Also, your last '
is missing.
Content-Disposition: inline
implies the file should be displayed, not downloaded. Use attachment
instead.
In addition, make the file extension in upper case to make it compatible with some mobile devices. (Update: Pretty sure only Blackberries had this problem, but the world moved on from those so this may be no longer a concern)
All that being said, your code should look more like this:
<?php
$filename = './pdf/jobs/pdffile.pdf';
$fileinfo = pathinfo($filename);
$sendname = $fileinfo['filename'] . '.' . strtoupper($fileinfo['extension']);
header('Content-Type: application/pdf');
header("Content-Disposition: attachment; filename=\"$sendname\"");
header('Content-Length: ' . filesize($filename));
readfile($filename);
Content-Length
is optional but is also important if you want the user to be able to keep track of the download progress and detect if the download was interrupted. But when using it you have to make sure you won't be send anything along with the file data. Make sure there is absolutely nothing before <?php
or after ?>
, not even an empty line.
I only use Elastic-search. Since I found solr is very hard to start. Elastic-search's features:
In my case, even I created a myapp.profile and set it in xcode manually, and when I chose "show in finder" and located the embedded.mobileprovision and checked to make sure aps-environment is there in the file, the error was still there.
I then went to developer center and found that the status of XC: myapp.profile is invalid. I updated it and installed the XC: myapp.profile and it worked fine.
I think xcode is trying to manage the profile and you need to check the provisioning profile when you submit your binary to store, and ensure it is the correct one. And according to other answers it can be caused for various reasons so it can be really annoying.
UPDATE:
Once you've signed with the downloaded profile and confirmed that aps-environment
was there when you try to submit to App Store
, you should be able to change the profile and code signing entity to automatic and iOS Developer
. Hope it can be improved in Xcode 7.
There are mutiple applications for Java's annotations. First of all, they may used by the compiler (or compiler extensions). Consider for example the Override annotation:
class Foo {
@Override public boolean equals(Object other) {
return ...;
}
}
This one is actually built into the Java JDK. The compiler will signal an error, if some method is tagged with it, which does not override a method inherited from a base class. This annotation may be helpful in order to avoid the common mistake, where you actually intend to override a method, but fail to do so, because the signature given in your method does not match the signature of the method being overridden:
class Foo {
@Override public boolean equals(Foo other) { // Compiler signals an error for this one
return ...;
}
}
As of JDK7, annotations are allowed on any type. This feature can now be used for compiler annotations such as NotNull, like in:
public void processSomething(@NotNull String text) {
...
}
which allows the compiler to warn you about improper/unchecked uses of variables and null values.
Another more advanced application for annotations involves reflection and annotation processing at run-time. This is (I think) what you had in mind when you speak of annotations as "replacement for XML based configuration". This is the kind of annotation processing used, for example, by various frameworks and JCP standards (persistence, dependency injection, you name it) in order to provide the necessary meta-data and configuration information.
you can use toggleClass()
to toggle class it is really handy.
case:1
<div id='mydiv' class="class1"></div>
$('#mydiv').toggleClass('class1 class2');
output: <div id='mydiv' class="class2"></div>
case:2
<div id='mydiv' class="class2"></div>
$('#mydiv').toggleClass('class1 class2');
output: <div id='mydiv' class="class1"></div>
case:3
<div id='mydiv' class="class1 class2 class3"></div>
$('#mydiv').toggleClass('class1 class2');
output: <div id='mydiv' class="class3"></div>
try this:
Sub test()
With Application.WorksheetFunction
Cells(.CountA(Columns("A:A")) + 1, 1).Select
End With
End Sub
Hope this works for you.
My class is not extends to Activiti. I solved the problem this way.
class MyOnBindViewHolder : LogicViewAdapterModel.LogicAdapter {
...
holder.title.setOnClickListener({v->
v.context.startActivity(Intent(context, HomeActivity::class.java))
})
...
}
Using Jure's script I made this, to easily "click" as many elements as you want.
I just used it Google Reader on 1600+ items and it worked perfectly (in Firefox)!
var e = document.createEvent('MouseEvents');
e.initEvent( 'click', true, true );
$(selector).each(function(){this.dispatchEvent(e);});
The following approach is the same as Helge Klein's, except that the popup closes automatically when you click anywhere outside the Popup (including the ToggleButton itself):
<ToggleButton x:Name="Btn" IsHitTestVisible="{Binding ElementName=Popup, Path=IsOpen, Mode=OneWay, Converter={local:BoolInverter}}">
<TextBlock Text="Click here for popup!"/>
</ToggleButton>
<Popup IsOpen="{Binding IsChecked, ElementName=Btn}" x:Name="Popup" StaysOpen="False">
<Border BorderBrush="Black" BorderThickness="1" Background="LightYellow">
<CheckBox Content="This is a popup"/>
</Border>
</Popup>
"BoolInverter" is used in the IsHitTestVisible binding so that when you click the ToggleButton again, the popup closes:
public class BoolInverter : MarkupExtension, IValueConverter
{
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value is bool)
return !(bool)value;
return value;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
return Convert(value, targetType, parameter, culture);
}
}
...which shows the handy technique of combining IValueConverter and MarkupExtension in one.
I did discover one problem with this technique: WPF is buggy when two popups are on the screen at the same time. Specifically, if your toggle button is on the "overflow popup" in a toolbar, then there will be two popups open after you click it. You may then find that the second popup (your popup) will stay open when you click anywhere else on your window. At that point, closing the popup is difficult. The user cannot click the ToggleButton again to close the popup because IsHitTestVisible is false because the popup is open! In my app I had to use a few hacks to mitigate this problem, such as the following test on the main window, which says (in the voice of Louis Black) "if the popup is open and the user clicks somewhere outside the popup, close the friggin' popup.":
PreviewMouseDown += (s, e) =>
{
if (Popup.IsOpen)
{
Point p = e.GetPosition(Popup.Child);
if (!IsInRange(p.X, 0, ((FrameworkElement)Popup.Child).ActualWidth) ||
!IsInRange(p.Y, 0, ((FrameworkElement)Popup.Child).ActualHeight))
Popup.IsOpen = false;
}
};
// Elsewhere...
public static bool IsInRange(int num, int lo, int hi) =>
num >= lo && num <= hi;
May be in a situation where you are creating a new mysqli object.
$MyConnection = new mysqli($hn, $un, $pw, $db);
but even after you close the object
$MyConnection->close();
if you will use print_r()
to check the contents of $MyConnection
, you will get an error as below:
Error:
mysqli Object
Warning: print_r(): Property access is not allowed yet in /path/to/program on line ..
( [affected_rows] => [client_info] => [client_version] =>.................)
in which case you can't use unlink()
because unlink()
will require a path name string but in this case $MyConnection
is an Object.
So you have another choice of setting its value to null:
$MyConnection = null;
now things go right, as you have expected. You don't have any content inside the variable $MyConnection
as well as you already cleaned up the mysqli Object.
It's a recommended practice to close the Object before setting the value of your variable to null
.
Ok, this is old but please let me contribute my solution :)
function sync( callback ){
syncCount--;
if ( syncCount < 1 ) callback();
}
function allFinished(){ .............. }
window.syncCount = 2;
$.ajax({
url: 'url',
success: function(data) {
sync( allFinished );
}
});
someFunctionWithCallback( function(){ sync( allFinished ); } )
It works also with functions that have a callback. You set the syncCount and you call the function sync(...) in the callback of every action.
You can use the storage_path();
function to get storage folder path.
storage_path(); // Return path like: laravel_app\storage
Suppose you want to save your logfile mylog.log
inside Log folder of storage folder. You have to write something like
storage_path() . '/LogFolder/mylog.log'
Open Visual Studio as an Administrator.. It will run.
Here is my code, hope this will help you !
public boolean isDigitOnly(String text){
boolean isDigit = false;
if (text.matches("[0-9]+") && text.length() > 2) {
isDigit = true;
}else {
isDigit = false;
}
return isDigit;
}
You need to open the file in binary mode i.e. wb
instead of w
. If you don't, the end of line characters are auto-converted to OS specific ones.
Here is an excerpt from Python reference about open()
.
The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading.
Use Open XML.
Here is some code to process a spreadsheet with a specific tab or sheet name and dump it to something like CSV. (I chose a pipe instead of comma).
I wish it was easier to get the value from a cell, but I think this is what we are stuck with. You can see that I reference the MSDN documents where I got most of this code. That is what Microsoft recommends.
/// <summary>
/// Got code from: https://msdn.microsoft.com/en-us/library/office/gg575571.aspx
/// </summary>
[Test]
public void WriteOutExcelFile()
{
var fileName = "ExcelFiles\\File_With_Many_Tabs.xlsx";
var sheetName = "Submission Form"; // Existing tab name.
using (var document = SpreadsheetDocument.Open(fileName, isEditable: false))
{
var workbookPart = document.WorkbookPart;
var sheet = workbookPart.Workbook.Descendants<Sheet>().FirstOrDefault(s => s.Name == sheetName);
var worksheetPart = (WorksheetPart)(workbookPart.GetPartById(sheet.Id));
var sheetData = worksheetPart.Worksheet.Elements<SheetData>().First();
foreach (var row in sheetData.Elements<Row>())
{
foreach (var cell in row.Elements<Cell>())
{
Console.Write("|" + GetCellValue(cell, workbookPart));
}
Console.Write("\n");
}
}
}
/// <summary>
/// Got code from: https://msdn.microsoft.com/en-us/library/office/hh298534.aspx
/// </summary>
/// <param name="cell"></param>
/// <param name="workbookPart"></param>
/// <returns></returns>
private string GetCellValue(Cell cell, WorkbookPart workbookPart)
{
if (cell == null)
{
return null;
}
var value = cell.CellFormula != null
? cell.CellValue.InnerText
: cell.InnerText.Trim();
// If the cell represents an integer number, you are done.
// For dates, this code returns the serialized value that
// represents the date. The code handles strings and
// Booleans individually. For shared strings, the code
// looks up the corresponding value in the shared string
// table. For Booleans, the code converts the value into
// the words TRUE or FALSE.
if (cell.DataType == null)
{
return value;
}
switch (cell.DataType.Value)
{
case CellValues.SharedString:
// For shared strings, look up the value in the
// shared strings table.
var stringTable =
workbookPart.GetPartsOfType<SharedStringTablePart>()
.FirstOrDefault();
// If the shared string table is missing, something
// is wrong. Return the index that is in
// the cell. Otherwise, look up the correct text in
// the table.
if (stringTable != null)
{
value =
stringTable.SharedStringTable
.ElementAt(int.Parse(value)).InnerText;
}
break;
case CellValues.Boolean:
switch (value)
{
case "0":
value = "FALSE";
break;
default:
value = "TRUE";
break;
}
break;
}
return value;
}
Caesar's solution is the best in my opinion, but if you still insist to use the strcpy
function, then after you have your strings ready:
string a = "text";
string b = "image";
You can try either:
strcpy(a.data(), b.data());
or
strcpy(a.c_str(), b.c_str());
Just call either the data()
or c_str()
member functions of the std::string
class, to get the char*
pointer of the string object.
The strcpy()
function doesn't have overload to accept two std::string
objects as parameters.
It has only one overload to accept two char*
pointers as parameters.
Both data
and c_str
return what does strcpy()
want exactly.
In the latest version of ggplot2, this can be more easy.
p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
p+ geom_point() + scale_x_continuous(expand = expansion(mult = c(0, 0))) + scale_y_continuous(expand = expansion(mult = c(0, 0)))
See ?expansion()
for more details.
Here's a simple example that can demonstrate the difference.
The main difference is that array will make a copy of the original data and using different object we can modify the data in the original array.
import numpy as np
a = np.arange(0.0, 10.2, 0.12)
int_cvr = np.asarray(a, dtype = np.int64)
The contents in array (a), remain untouched, and still, we can perform any operation on the data using another object without modifying the content in original array.
Here I'm replacing an old value to a new value:
string actual = "Hello World";
string Result = actual.Replace("World", "Stack Overflow");
----------------------
Output : "Hello Stack Overflow"
Use the Counter.most_common()
method, it'll sort the items for you:
>>> from collections import Counter
>>> x = Counter({'a':5, 'b':3, 'c':7})
>>> x.most_common()
[('c', 7), ('a', 5), ('b', 3)]
It'll do so in the most efficient manner possible; if you ask for a Top N instead of all values, a heapq
is used instead of a straight sort:
>>> x.most_common(1)
[('c', 7)]
Outside of counters, sorting can always be adjusted based on a key
function; .sort()
and sorted()
both take callable that lets you specify a value on which to sort the input sequence; sorted(x, key=x.get, reverse=True)
would give you the same sorting as x.most_common()
, but only return the keys, for example:
>>> sorted(x, key=x.get, reverse=True)
['c', 'a', 'b']
or you can sort on only the value given (key, value)
pairs:
>>> sorted(x.items(), key=lambda pair: pair[1], reverse=True)
[('c', 7), ('a', 5), ('b', 3)]
See the Python sorting howto for more information.
In my view, dates and times should be handled as two separate input boxes for it to be most usable and efficient for the user to input. Let the user input one thing at a time is a good principle, imho.
I use the core UI DatePicker, and the following time picker.
This one is inspired by the one Google Calendar uses:
jQuery timePicker:
examples: http://labs.perifer.se/timedatepicker/
project on github: https://github.com/perifer/timePicker
I found it to be the best among all of the alternatives. User can input fast, it looks clean, is simple, and allows user to input specific times down to the minute.
PS: In my view: sliders (used by some alternative time pickers) take too many clicks and require mouse precision from the user (which makes input slower).
IMHO you can't compare SOAP and REST where those are two different things.
SOAP is a protocol and REST is a software architectural pattern. There is a lot of misconception in the internet for SOAP vs REST.
SOAP defines XML based message format that web service-enabled applications use to communicate each other over the internet. In order to do that the applications need prior knowledge of the message contract, datatypes, etc..
REST represents the state(as resources) of a server from an URL.It is stateless and clients should not have prior knowledge to interact with server beyond the understanding of hypermedia.
Given that Windows has no sys/socket.h, you might consider just doing something like this:
#ifdef __WIN32__
# include <winsock2.h>
#else
# include <sys/socket.h>
#endif
I know you indicated that you won't use WinSock, but since WinSock is how TCP networking is done under Windows, I don't see that you have any alternative. Even if you use a cross-platform networking library, that library will be calling WinSock internally. Most of the standard BSD sockets API calls are implemented in WinSock, so with a bit of futzing around, you can make the same sockets-based program compile under both Windows and other OS's. Just don't forget to do a
#ifdef __WIN32__
WORD versionWanted = MAKEWORD(1, 1);
WSADATA wsaData;
WSAStartup(versionWanted, &wsaData);
#endif
at the top of main()... otherwise all of your socket calls will fail under Windows, because the WSA subsystem wasn't initialized for your process.
you need to add jar file in your build path..
commons-dbcp-1.1-RC2.jar
or any version of that..!!!!
ADDED : also make sure you have commons-pool-1.1.jar too in your build path.
ADDED: sorry saw complete list of jar late... may be version clashes might be there.. better check out..!!! just an assumption.
According to the above,i found three ways to solve the problem.
AnotherMongoDocument._id.toString()
JSON.stringify(AnotherMongoDocument._id)
results.userId.equals(AnotherMongoDocument._id)
What about Abseil StrReplaceAll? From the header file:
// This file defines `absl::StrReplaceAll()`, a general-purpose string
// replacement function designed for large, arbitrary text substitutions,
// especially on strings which you are receiving from some other system for
// further processing (e.g. processing regular expressions, escaping HTML
// entities, etc.). `StrReplaceAll` is designed to be efficient even when only
// one substitution is being performed, or when substitution is rare.
//
// If the string being modified is known at compile-time, and the substitutions
// vary, `absl::Substitute()` may be a better choice.
//
// Example:
//
// std::string html_escaped = absl::StrReplaceAll(user_input, {
// {"&", "&"},
// {"<", "<"},
// {">", ">"},
// {"\"", """},
// {"'", "'"}});
This question is old and got many answers.
Now with Java 8 and Official Lambda that are unofficial closure projects, it revives the question.
The answer in Java context (via Lambdas and closures — what’s the difference?):
"A closure is a lambda expression paired with an environment that binds each of its free variables to a value. In Java, lambda expressions will be implemented by means of closures, so the two terms have come to be used interchangeably in the community."
if you are using Glide and Kotlin,
Glide.with(this)
.asBitmap()
.load("https://...")
.addListener(object : RequestListener<Bitmap> {
override fun onLoadFailed(
e: GlideException?,
model: Any?,
target: Target<Bitmap>?,
isFirstResource: Boolean
): Boolean {
Toast.makeText(this@MainActivity, "failed: " + e?.printStackTrace(), Toast.LENGTH_SHORT).show()
return false
}
override fun onResourceReady(
resource: Bitmap?,
model: Any?,
target: Target<Bitmap>?,
dataSource: DataSource?,
isFirstResource: Boolean
): Boolean {
//image is ready, you can get bitmap here
var bitmap = resource
return false
}
})
.into(imageView)
Putting the subquery in the WHERE clause and restricting it to n.control_number means it runs the subquery many times. This is called a correlated subquery, and it's often a performance killer.
It's better to run the subquery once, in the FROM clause, to get the max date per control number.
SELECT n.*
FROM tblpm n
INNER JOIN (
SELECT control_number, MAX(date_updated) AS date_updated
FROM tblpm GROUP BY control_number
) AS max USING (control_number, date_updated);
from http://htmlhelp.com/reference/wilbur/misc/comment.html
Since HTML is officially an SGML application, the comment syntax used in HTML documents is actually the SGML comment syntax. Unfortunately this syntax is a bit unclear at first.
The definition of an SGML comment is basically as follows:
A comment declaration starts withThis means that the following are all legal SGML comments:<!
, followed by zero or more comments, followed by>
. A comment starts and ends with "--
", and does not contain any occurrence of "--
".Note that an "empty" comment tag, with just "
<!-- Hello -->
<!-- Hello -- -- Hello-->
<!---->
<!------ Hello -->
<!>
--
" characters, should always have a multiple of four "-
" characters to be legal. (And yes,<!>
is also a legal comment - it's the empty comment).Not all HTML parsers get this right. For example, "
<!------> hello-->
" is a legal comment, as you can verify with the rule above. It is a comment tag with two comments; the first is empty and the second one contains "> hello". If you try it in a browser, you will find that the text is displayed on screen.There are two possible reasons for this:
There is also the problem with the "
- The browser sees the ">" character and thinks the comment ends there.
- The browser sees the "
-->
" text and thinks the comment ends there.--
" sequence. Some people have a habit of using things like "<!-------------->
" as separators in their source. Unfortunately, in most cases, the number of "-
" characters is not a multiple of four. This means that a browser who tries to get it right will actually get it wrong here and actually hide the rest of the document.For this reason, use the following simple rule to compose valid and accepted comments:
An HTML comment begins with "<!--
", ends with "-->
" and does not contain "--
" or ">
" anywhere in the comment.
I had the same problem. Eventually I found why. I used a code from web to test output of my procedure. At the end it had a call to Drop(procedure)
so I deleted it myself.
If you want an else
you don't want to filter the list comprehension, you want it to iterate over every value. You can use true-value if cond else false-value
as the statement instead, and remove the filter from the end:
table = ''.join(chr(index) if index in ords_to_keep else replace_with for index in xrange(15))
I've got rid of type mismatch by following code:
Sub ConvertToDate()
Dim r As Range
Dim setdate As Range
'in my case I have a header and no blank cells in used range,
'starting from 2nd row, 1st column
Set setdate = Range(Cells(2, 1), Cells(2, 1).End(xlDown))
With setdate
.NumberFormat = "dd.mm.yyyy" 'I have the data in format "dd.mm.yy"
.Value = .Value
End With
For Each r In setdate
r.Value = CDate(r.Value)
Next r
End Sub
But in my particular case, I have the data in format "dd.mm.yy"
Here's how you could do it in Coffee Script (just if anyone is interested).
decodeURIComponent( v.split( "=" )[1] ) if decodeURIComponent( v.split( "=" )[0] ) == name for v in window.location.search.substring( 1 ).split( "&" )
Not a UUID, but this works for me:
UUID.randomUUID().toString().replace("-","").substring(0,8)
If you want to change MSSQL server language, you can use the following QUERY:
EXEC sp_configure 'default language', 'British English';
Subtle point here...
There is an implicit typecast for i+j
when j
is a double and i
is an int.
Java ALWAYS converts an integer into a double when there is an operation between them.
To clarify i+=j
where i
is an integer and j
is a double can be described as
i = <int>(<double>i + j)
See: this description of implicit casting
You might want to typecast j
to (int)
in this case for clarity.
With design patterns, there usually is no "more advantageous" solution that works for all cases. It depends on what you need to implement.
From Wikipedia:
- Builder focuses on constructing a complex object step by step. Abstract Factory emphasizes a family of product objects (either simple or complex). Builder returns the product as a final step, but as far as the Abstract Factory is concerned, the product gets returned immediately.
- Builder often builds a Composite.
- Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed.
- Sometimes creational patterns are complementary: Builder can use one of the other patterns to implement which components get built. Abstract Factory, Builder, and Prototype can use Singleton in their implementations.
Wikipedia entry for factory design pattern: http://en.wikipedia.org/wiki/Factory_method_pattern
Wikipedia entry for builder design pattern: http://en.wikipedia.org/wiki/Builder_pattern
If you know the name of the filters, you can do it in a line.
users = users.filter(obj => obj.name == filter.name && obj.address == filter.address)
Different implementations of the Python DB-API are allowed to use different placeholders, so you'll need to find out which one you're using -- it could be (e.g. with MySQLdb):
cursor.execute("INSERT INTO table VALUES (%s, %s, %s)", (var1, var2, var3))
or (e.g. with sqlite3 from the Python standard library):
cursor.execute("INSERT INTO table VALUES (?, ?, ?)", (var1, var2, var3))
or others yet (after VALUES
you could have (:1, :2, :3)
, or "named styles" (:fee, :fie, :fo)
or (%(fee)s, %(fie)s, %(fo)s)
where you pass a dict instead of a map as the second argument to execute
). Check the paramstyle
string constant in the DB API module you're using, and look for paramstyle at http://www.python.org/dev/peps/pep-0249/ to see what all the parameter-passing styles are!
I had the same problem. Perhaps, the problem is that you have compiled and executed the class with different Java versions.
Make sure the version of the compiler is the same as the command "java":
javac -version
java -version
In Linux, use
sudo update-alternatives --config java
to change the version of Java.
To solve this issue, I pasted my layout into https://www.xmlvalidation.com/, which told me exactly what the error was. As was the case with other answers, my XML had <
in a string.
ul > li > a
selects only the direct children. In this case only the first level <a>
of the first level <li>
inside the <ul>
will be selected.
ul li a
on the other hand will select ALL <a>
-s in ALL <li>
-s in the unordered list
Example of ul > li
ul > li.bg {_x000D_
background: red;_x000D_
}
_x000D_
<ul>_x000D_
<li class="bg">affected</li>_x000D_
<li class="bg">affected</li> _x000D_
<li>_x000D_
<ol>_x000D_
<li class="bg">NOT affected</li>_x000D_
<li class="bg">NOT affected</li>_x000D_
</ol>_x000D_
</li>_x000D_
</ul>
_x000D_
if you'd be using ul li
- ALL of the li
-s would be affected
UPDATE The order of more to less efficient CSS selectors goes thus:
#header
.promo
div
h2 + p
li > ul
ul a
*
[type="text"]
a:hover
So your better bet is to use the children
selector instead of just descendant
. However the difference on a regular page (without tens of thousands elements to go through) might be absolutely negligible.
You're talking about histograms, but this doesn't quite make sense. Histograms and bar charts are different things. An histogram would be a bar chart representing the sum of values per year, for example. Here, you just seem to be after bars.
Here is a complete example from your data that shows a bar of for each required value at each date:
import pylab as pl
import datetime
data = """0 14-11-2003
1 15-03-1999
12 04-12-2012
33 09-05-2007
44 16-08-1998
55 25-07-2001
76 31-12-2011
87 25-06-1993
118 16-02-1995
119 10-02-1981
145 03-05-2014"""
values = []
dates = []
for line in data.split("\n"):
x, y = line.split()
values.append(int(x))
dates.append(datetime.datetime.strptime(y, "%d-%m-%Y").date())
fig = pl.figure()
ax = pl.subplot(111)
ax.bar(dates, values, width=100)
ax.xaxis_date()
You need to parse the date with strptime
and set the x-axis to use dates (as described in this answer).
If you're not interested in having the x-axis show a linear time scale, but just want bars with labels, you can do this instead:
fig = pl.figure()
ax = pl.subplot(111)
ax.bar(range(len(dates)), values)
EDIT: Following comments, for all the ticks, and for them to be centred, pass the range to set_ticks
(and move them by half the bar width):
fig = pl.figure()
ax = pl.subplot(111)
width=0.8
ax.bar(range(len(dates)), values, width=width)
ax.set_xticks(np.arange(len(dates)) + width/2)
ax.set_xticklabels(dates, rotation=90)
Just use:
your_type x;
while (std::cin >> x)
{
// use x
}
operator>>
will skip whitespace by default. You can chain things to read several variables at once:
if (std::cin >> my_string >> my_number)
// use them both
getline()
reads everything on a single line, returning that whether it's empty or contains dozens of space-separated elements. If you provide the optional alternative delimiter ala getline(std::cin, my_string, ' ')
it still won't do what you seem to want, e.g. tabs will be read into my_string
.
Probably not needed for this, but a fairly common requirement that you may be interested in sometime soon is to read a single newline-delimited line, then split it into components...
std::string line;
while (std::getline(std::cin, line))
{
std::istringstream iss(line);
first_type first_on_line;
second_type second_on_line;
third_type third_on_line;
if (iss >> first_on_line >> second_on_line >> third_on_line)
...
}
Go to https://code.google.com/p/google-api-php-client/wiki/OAuth2
Scroll down to where it says 'Visit the Google API Console to generate your developer key, OAuth2 client id, OAuth2 client secret, and register your OAuth2 redirect uri. Copy their values since your will need to input them in your application.'
Click on the 'Google API Console' link.
When it pops up and says 'Welcome to the new Google Developers Console! Prefer the old console? Go back | Dismiss' Click on 'GO BACK'
The purpose of ForeignKey is to prevent the creation of data if the field value does not match its ForeignKey. To accomplish this in MongoDB, we use Schema middlewares that ensure the data consistency.
Please have a look at the documentation. https://mongoosejs.com/docs/middleware.html#pre
For those using gcloud build:
gcloud build
ignores .dockerignore
and looks instead for .gcloudignore
Use:
cp .dockerignore .gcloudignore
This validates date like dd-mm-yyyy
([0-2][0-9]|(3)[0-1])(\-)(((0)[0-9])|((1)[0-2]))(\-)([0-9][0-9][0-9][0-9])
This can use with javascript like angular reactive forms
Yeah, you can do it. Just open Settings -> Live Templates. Create new one with syso
as abbreviation and System.out.println($END$);
as Template text.
The latter alternative is used for methods on mocks that return void
.
Please have a look, for example, here: How to make mock to void methods with mockito
This works in Oracle:
insert into pager (PAG_ID,PAG_PARENT,PAG_NAME,PAG_ACTIVE)
select 8000,0,'Multi 8000',1 from dual
union all select 8001,0,'Multi 8001',1 from dual
The thing to remember here is to use the from dual
statement.
I want columns One and Two to shrink/grow to fit rather than being fixed.
Have you tried: flex-basis: auto
or this:
flex: 1 1 auto
, which is short for:
flex-grow: 1
(grow proportionally)flex-shrink: 1
(shrink proportionally)flex-basis: auto
(initial size based on content size)or this:
main > section:first-child {
flex: 1 1 auto;
overflow-y: auto;
}
main > section:nth-child(2) {
flex: 1 1 auto;
overflow-y: auto;
}
main > section:last-child {
flex: 20 1 auto;
display: flex;
flex-direction: column;
}
Related:
Using Queue :
import threading, queue
def calc_square(num, out_queue1):
l = []
for x in num:
l.append(x*x)
out_queue1.put(l)
arr = [1,2,3,4,5,6,7,8,9,10]
out_queue1=queue.Queue()
t1=threading.Thread(target=calc_square, args=(arr,out_queue1))
t1.start()
t1.join()
print (out_queue1.get())
This might be a bug of the recent anaconda. What works for me:
step1: vim /anaconda/bin/activate
, it shows:
#!/bin/sh
_CONDA_ROOT="/anaconda"
# Copyright (C) 2012 Anaconda, Inc
# SPDX-License-Identifier: BSD-3-Clause
\. "$_CONDA_ROOT/etc/profile.d/conda.sh" || return $?
conda activate "$@"
step2: comment out the last line: # conda activate "$@"
public static void BubbleSort(int[] a)
{
for (int i = 1; i <= a.Length - 1; ++i)
for (int j = 0; j < a.Length - i; ++j)
if (a[j] > a[j + 1])
Swap(ref a[j], ref a[j + 1]);
}
public static void Swap(ref int x, ref int y)
{
int temp = x;
x = y;
y = temp;
}
The problem relates to the .Net runtime version of a referenced class library (expaned references, select the library and check the "Runtime Version". I had a problem with Antlr3.Runtime, after upgrading my visual studio project to v4.5. I used NuGet to uninstall Microsoft ASP.NET Web Optimisation Framework (due to a chain of dependencies that prevented me from uninstalling Antlr3 directly)
I then used NuGet to reinstall the Microsoft ASP.NET Web Optimisation Framework. This reinstalled the correct runtime versions.
Using Java 8 Comparator.comparing:
list.sort(Comparator.comparing(Campaign::getName));
There is no such thing as :touch
in the W3C specifications, http://www.w3.org/TR/CSS2/selector.html#pseudo-class-selectors
:active
should work, I would think.
Order on the :active
/:hover
pseudo class is important for it to function correctly.
Here is a quote from that above link
Interactive user agents sometimes change the rendering in response to user actions. CSS provides three pseudo-classes for common cases:
- The :hover pseudo-class applies while the user designates an element (with some pointing device), but does not activate it. For example, a visual user agent could apply this pseudo-class when the cursor (mouse pointer) hovers over a box generated by the element. User agents not supporting interactive media do not have to support this pseudo-class. Some conforming user agents supporting interactive media may not be able to support this pseudo-class (e.g., a pen device).
- The :active pseudo-class applies while an element is being activated by the user. For example, between the times the user presses the mouse button and releases it.
- The :focus pseudo-class applies while an element has the focus (accepts keyboard events or other forms of text input).
I realise that's not the case here but it might help someone.
Double-check you didn't create the conf file in /etc/apache2/sites-enabled by mistake. You get the same error.
I had the same issue until I added Response.Buffer = False. Try changing the code to the following.
Response.Buffer = False Response.ContentType = "application/vnd.ms-excel" Response.AddHeader "Content-Disposition", "attachment; filename=excelTest.xls"
The only problem I have now is that when Excel opens the file I get the following message.
The file you are trying to open, 'FileName[1].xls', is in a different format than specified by the file extension. Verify that the file is not corrupted and is from a trusted source before opening the file. Do you want to open the file now?
When you open the file the data all appears in separate columns, but the spreadsheet is all white, no borders between the cells.
Hope that helps.
new HashSet<Object>(Arrays.asList(Object[] a));
But I think this would be more efficient:
final Set s = new HashSet<Object>();
for (Object o : a) { s.add(o); }
For the original see doublep answer:
Foo[] a = x.toArray(new Foo[x.size()]);
As for the update:
int i = 0;
Bar[] bars = new Bar[fooCollection.size()];
for( Foo foo : fooCollection ) { // where fooCollection is Collection<Foo>
bars[i++] = new Bar(foo);
}
Out of curiosity, why don't you just use the url for the said folder?
Assuming that the folder never changes location, that would be the easiest way to do it.
What's wrong with DateTime.AddSeconds method where you can add or substract seconds?
You should be able to do this by simply typing npm install -g [email protected]
. If this does not work, I am beginning to wonder what version of node and npm you are on. Try node -v
and npm -v
to find these out. You should be on node >4.5 and npm >3
For those who searches for an answer without parsing and loosing milliseconds,
given dt_obj
is a datetime:
python3 only, elegant
int(dt_obj.timestamp() * 1000)
both python2 and python3 compatible:
import time
int(time.mktime(dt_obj.utctimetuple()) * 1000 + dt_obj.microsecond / 1000)
Be careful all of the other answers have some problem in IE.
Lets have this situation - button with prepended icon. All browsers handles this correctly, but IE takes the width of the element and scales the before content to fit it. JSFiddle
#mydiv1 { width: 200px; height: 30px; background: green; }
#mydiv1:before {
content: url("data:url or /standard/url.svg");
}
Solution is to set size to before element and leave it where it is:
#mydiv2 { width: 200px; height: 30px; background: green; }
#mydiv2:before {
content: url("data:url or /standard/url.svg");
display: inline-block;
width: 16px; //only one size is alright, IE scales uniformly to fit it
}
The background-image
+ background-size
solutions works as well, but is little unhandy, since you have to specify the same sizes twice.
The result in IE11:
[value]="item" using *ngFor also works with Reactive Forms in Angular 2 and 4
<label *ngFor="let item of items">
<input type="radio" formControlName="options" [value]="item">
{{item}}
</label>`
To add to Ivo Wetzel's answer
There seems to be a shorthand syntax for exports ? this
that I can only find documented/mentioned on a Google group posting.
I.e. in a web page to make a function available globally you declare the function again with an @
prefix:
<script type="text/coffeescript">
@aglobalfunction = aglobalfunction = () ->
alert "Hello!"
</script>
<a href="javascript:aglobalfunction()" >Click me!</a>
For ansible, and using hyphen, this worked for me:
- name: free-ud-ssd-space-in-percent
debug:
var: clusterInfo.json.content["free-ud-ssd-space-in-percent"]
There is some cases when you copy and paste the CSS code in somewhere and it breaks the format so Chrome show the yellow warning. You should try to reformat the CSS code again and it should be fine.
What you posted has a syntax error, but it makes no difference as you cannot pass HTTP headers via $.post()
.
Provided you're on jQuery version >= 1.5, switch to $.ajax()
and pass the headers
(docs) option. (If you're on an older version of jQuery, I will show you how to do it via the beforeSend
option.)
$.ajax({
url: 'https://url.com',
type: 'post',
data: {
access_token: 'XXXXXXXXXXXXXXXXXXX'
},
headers: {
Header_Name_One: 'Header Value One', //If your header name has spaces or any other char not appropriate
"Header Name Two": 'Header Value Two' //for object property name, use quoted notation shown in second
},
dataType: 'json',
success: function (data) {
console.info(data);
}
});
This code creates the file temp.xls in the desktop but it uses the SpecialFolders property, which is very useful sometimes!
set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Add()
objWorkbook.SaveAs(strDesktop & "\temp.xls")
getFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
@Override
public void onBackStackChanged() {
if(getFragmentManager().getBackStackEntryCount()==0) {
onResume();
}
}
});
No, there is absolutely nothing wrong with using the !
operator in if..then..else
statements.
The naming of variables, and in your example, methods is what is important. If you are using:
if(!isPerson()) { ... } // Nothing wrong with this
However:
if(!balloons()) { ... } // method is named badly
It all comes down to readability. Always aim for what is the most readable and you won't go wrong. Always try to keep your code continuous as well, for instance, look at Bill the Lizards answer.
Something like this?
foreach ($Offer as $key => $value) {
$offerArray[$key] = $value[4];
}
Swift 5 and ensures the image scales to the size of the button but stays within the buttons bounds.
yourButton.clipsToBounds = true
yourButton.contentMode = .scaleAspectFill
// Use setBackgroundImage or setImage
yourButton.setBackgroundImage(UIImage(named: "yourImage"), for: .normal)
I got the same issue and It got solved by installing Oracle 11g client in my machine..
I have not installed any excclusive drivers for it. I am using windows7 with 64 bit. Interestignly, when I navigate into the path Start > Settings > Control Panel > Administrative Tools > DataSources(ODBC) > Drivers. I found only SQL server in it
Try this
Install
npm install primeng --save
Import
import {FileUploadModule} from 'primeng/primeng';
Html
<p-fileUpload name="myfile[]" url="./upload.php" multiple="multiple"
accept="image/*" auto="auto"></p-fileUpload>
All the technical details have been nicely covered in the other answers. I just want to share a simple analogy that I think nicely illustrates the difference between a class and an instance:
A class is like the blueprint of a house: You only have one blueprint and (usually) you can't do that much with the blueprint alone.
An instance (or an object) is the actual house that you build based on the blueprint: You can build lots of houses from the same blueprint. You can then paint the walls a different color in each of the houses, just as you can independently change the properties of each instance of a class without affecting the other instances.
Here's what I use. If it fails to pretty print the JSON it just returns the original string. Useful for printing HTTP responses that should contain JSON.
import (
"encoding/json"
"bytes"
)
func jsonPrettyPrint(in string) string {
var out bytes.Buffer
err := json.Indent(&out, []byte(in), "", "\t")
if err != nil {
return in
}
return out.String()
}
String
is present in package java.lang
which is imported by default in all java programs.
var myobj = {"A":["Abe"], "B":["Bob"]};
var keysArray = Object.keys(myobj);
var valuesArray = Object.keys(myobj).map(function(k) {
return String(myobj[k]);
});
var mydata = valuesArray[keysArray.indexOf("A")]; // Abe
It is an anchor for links within a page - also known as "anchor tag"
As far as a value of type Number is to be tested whether it is a NaN
or not, the global function isNaN
will do the work
isNaN(any-Number);
For a generic approach which works for all the types in JS, we can use any of the following:
For ECMAScript-5 Users:
#1
if(x !== x) {
console.info('x is NaN.');
}
else {
console.info('x is NOT a NaN.');
}
For people using ECMAScript-6:
#2
Number.isNaN(x);
And For consistency purpose across ECMAScript 5 & 6 both, we can also use this polyfill for Number.isNan
#3
//Polyfill from MDN
Number.isNaN = Number.isNaN || function(value) {
return typeof value === "number" && isNaN(value);
}
// Or
Number.isNaN = Number.isNaN || function(value) {
return value !== value;
}
please check This Answer for more details.
Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.
Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .
if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .
if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .
after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).
if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.
If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.
If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.
If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property.
if you further face any difficulty then you need to provide more information about your web site and sql server .
Here's an easier way of doing this (source: here):
import matplotlib.pyplot as plt
from numpy.random import rand
fig, ax = plt.subplots()
for color in ['red', 'green', 'blue']:
n = 750
x, y = rand(2, n)
scale = 200.0 * rand(n)
ax.scatter(x, y, c=color, s=scale, label=color,
alpha=0.3, edgecolors='none')
ax.legend()
ax.grid(True)
plt.show()
And you'll get this:
Take a look at here for legend properties
Is this what you mean?
SELECT DISTINCT C.valueC
FROM
C
INNER JOIN B ON C.id = B.lookupC
INNER JOIN A ON B.id = A.lookupB
If you don't like to import the full apache.commons, I've extracted the same functionality:
public class StringUtils {
public static String getBaseName(String filename) {
return removeExtension(getName(filename));
}
public static int indexOfLastSeparator(String filename) {
if(filename == null) {
return -1;
} else {
int lastUnixPos = filename.lastIndexOf(47);
int lastWindowsPos = filename.lastIndexOf(92);
return Math.max(lastUnixPos, lastWindowsPos);
}
}
public static String getName(String filename) {
if(filename == null) {
return null;
} else {
int index = indexOfLastSeparator(filename);
return filename.substring(index + 1);
}
}
public static String removeExtension(String filename) {
if(filename == null) {
return null;
} else {
int index = indexOfExtension(filename);
return index == -1?filename:filename.substring(0, index);
}
}
public static int indexOfExtension(String filename) {
if(filename == null) {
return -1;
} else {
int extensionPos = filename.lastIndexOf(46);
int lastSeparator = indexOfLastSeparator(filename);
return lastSeparator > extensionPos?-1:extensionPos;
}
}
}
window.location = myUrl;
Anyway, this is not jQuery: it's plain javascript
you can't make easisly a slideup slidedown with css3 tha's why I've turned JensT script into a plugin with javascript fallback and callback.
in this way if you have a modern brwowser you can use the css3 csstransition. if your browser does not support it gracefuly use the old fashioned slideUp slideDown.
/* css */
.csstransitions .mosneslide {
-webkit-transition: height .4s ease-in-out;
-moz-transition: height .4s ease-in-out;
-ms-transition: height .4s ease-in-out;
-o-transition: height .4s ease-in-out;
transition: height .4s ease-in-out;
max-height: 9999px;
overflow: hidden;
height: 0;
}
the plugin
(function ($) {
$.fn.mosne_slide = function (
options) {
// set default option values
defaults = {
delay: 750,
before: function () {}, // before callback
after: function () {} // after callback;
}
// Extend default settings
var settings = $.extend({},
defaults, options);
return this.each(function () {
var $this = $(this);
//on after
settings.before.apply(
$this);
var height = $this.height();
var width = $this.width();
if (Modernizr.csstransitions) {
// modern browsers
if (height > 0) {
$this.css(
'height',
'0')
.addClass(
"mosne_hidden"
);
} else {
var clone =
$this.clone()
.css({
'position': 'absolute',
'visibility': 'hidden',
'height': 'auto',
'width': width
})
.addClass(
'mosne_slideClone'
)
.appendTo(
'body'
);
var newHeight =
$(
".mosne_slideClone"
)
.height();
$(
".mosne_slideClone"
)
.remove();
$this.css(
'height',
newHeight +
'px')
.removeClass(
"mosne_hidden"
);
}
} else {
//fallback
if ($this.is(
":visible"
)) {
$this.slideUp()
.addClass(
"mosne_hidden"
);
} else {
$this.hide()
.slideDown()
.removeClass(
"mosne_hidden"
);
}
}
//on after
setTimeout(function () {
settings.after
.apply(
$this
);
}, settings.delay);
});
}
})(jQuery);;
how to use it
/* jQuery */
$(".mosneslide").mosne_slide({
delay:400,
before:function(){console.log("start");},
after:function(){console.log("done");}
});
you can find a demo page here http://www.mosne.it/playground/mosne_slide_up_down/
It may be that it's not loading the template you expect. I added a new class that inherited from UpdateView
- I thought it would automatically pick the template from what I named my class, but it actually loaded it based on the model
property on the class, which resulted in another (wrong) template being loaded. Once I explicitly set template_name
for the new class, it worked fine.
Shorter syntax
select 1
WHILE (@@ROWCOUNT > 0)
BEGIN
DELETE TOP (10000) LargeTable
WHERE readTime < dateadd(MONTH,-7,GETDATE())
END
I'm guessing that you don't need to re-increment the existing data so, why can't you just run a simple ALTER TABLE command to change the PK's attributes?
Something like:
ALTER TABLE `content` CHANGE `id` `id` SMALLINT( 5 ) UNSIGNED NOT NULL AUTO_INCREMENT
I've tested this code on my own MySQL database and it works but I have not tried it with any meaningful number of records. Once you've altered the row then you need to reset the increment to a number guaranteed not to interfere with any other records.
ALTER TABLE `content` auto_increment = MAX(`id`) + 1
Again, untested but I believe it will work.
U can do it easier than this answers :
Uri Selected_Image_Uri = data.getData();
ImageView imageView = (ImageView) findViewById(R.id.loadedimg);
imageView.setImageURI(Selected_Image_Uri);
Q:Can't bind to 'pSelectableRow' since it isn't a known property of 'tr'.
A:you need to configure the primeng tabulemodule in ngmodule
If the list is in random order, you can just take the first 50.
Otherwise, use
import random
random.sample(the_list, 50)
random.sample
help text:
sample(self, population, k) method of random.Random instance
Chooses k unique random elements from a population sequence.
Returns a new list containing elements from the population while
leaving the original population unchanged. The resulting list is
in selection order so that all sub-slices will also be valid random
samples. This allows raffle winners (the sample) to be partitioned
into grand prize and second place winners (the subslices).
Members of the population need not be hashable or unique. If the
population contains repeats, then each occurrence is a possible
selection in the sample.
To choose a sample in a range of integers, use xrange as an argument.
This is especially fast and space efficient for sampling from a
large population: sample(xrange(10000000), 60)
Perhaps not in the context that you have it, but you could use
SELECT DISTINCT col1,
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1),
PERCENTILE_CONT(col2) WITHIN GROUP (ORDER BY col2) OVER (PARTITION BY col1, col3),
FROM TableA
You would use this to return different levels of aggregation returned in a single row. The use case would be for when a single grouping would not suffice all of the aggregates needed.
This work for me
<Form>
<TextInput
style={{height: 40}}
placeholder="userName"
onChangeText={(text) => this.userName = text}
/>
<TextInput
style={{height: 40}}
placeholder="Password"
onChangeText={(text) => this.Password = text}
/>
<Button
title="Sign in!"
onPress={this._signInAsync}
/>
</Form>
and
_signInAsync = async () => {
console.log(this.userName)
console.log(this.Password)
};
Since PyYAML's yaml.load()
function parses YAML documents to native Python data structures, you can just access items by key or index. Using the example from the question you linked:
import yaml
with open('tree.yaml', 'r') as f:
doc = yaml.load(f)
To access branch1 text
you would use:
txt = doc["treeroot"]["branch1"]
print txt
"branch1 text"
because, in your YAML document, the value of the branch1
key is under the treeroot
key.
Update January 2016
In addition to other answers, there is sometimes the scenario where you wish to have private modules available in a team context.
Both Github and Bitbucket support the concept of generating a team API Key. This API key can be used as the password to perform API requests as this team.
In your private npm modules add
"private": true
to your package.json
Then to reference the private module in another module, use this in your package.json
{
"name": "myapp",
"dependencies": {
"private-repo":
"git+https://myteamname:[email protected]/myprivate.git",
}
}
where team name = myteamname, and API Key = aQqtcplwFzlumj0mIDdRGCbsAq5d6Xg4
Here I reference a bitbucket repo, but it is almost identical using github too.
Finally, as an alternative, if you really don't mind paying $7 per month (as of writing) then you can now have private NPM modules out of the box.
After hours of frustration... here's what i discovered.
I don't know how such an easy process could have worse documentation. It as if it was written by lawyers.