Try setting these values, it solves problem in fast-cgi
fastcgi_buffer_size 16k;
fastcgi_buffers 4 16k;
I have a problem of running different versions of STS this morning, the application crash with the similar way as the question did.
Excerpt of my log file.
A fatal error has been detected by the Java Runtime Environment:
#a
# SIGSEGV (0xb) at pc=0x00007f459db082a1, pid=4577, tid=139939015632640
#
# JRE version: 6.0_30-b12
# Java VM: Java HotSpot(TM) 64-Bit Server VM
(20.5-b03 mixed mode linux-amd64 compressed oops)
# Problematic frame:
# C [libsoup-2.4.so.1+0x6c2a1] short+0x11
note that exception occured at # C [libsoup-2.4.so.1+0x6c2a1] short+0x11
Okay then little below the line:
R9 =0x00007f461829e550: <offset 0xa85550> in /usr/share/java/jdk1.6.0_30/jre/lib/amd64/server/libjvm.so at 0x00007f4617819000
R10=0x00007f461750f7c0 is pointing into the stack for thread: 0x00007f4610008000
R11=0x00007f459db08290: soup_session_feature_detach+0 in /usr/lib/x86_64-linux-gnu/libsoup-2.4.so.1 at 0x00007f459da9c000
R12=0x0000000000000000 is an unknown value
R13=0x000000074404c840 is an oop
{method}
This line tells you where the actual bug or crash is to investigate more on this crash issue please use below links to see more, but let's continue the crash investigation and how I resolved it and the novelty of this bug :)
links are :
a fATAL ERROR JAVA THIS ONE IS GREAT LOTS OF USER!
Okay, after that here's what I found out to casue this case and why it happens as general advise.
Most of the time, check that if you have installed, updated recently on Ubunu and Windows there are libraries like libsoup in linux which were the casuse of my crash.
Check also for a new hardware problem and try to investigate the Logfile
which STS
or Java
generated and also syslog
in linux
by
tail - f /var/lib/messages or some other file
Then by carfully looking at those files the one you have the crash log for ... you can really solve the issue as follows:
sudo unlink /usr/lib/i386-linux-gnu/libsoup-2.4.so.1
or
sudo unlink /usr/lib/x86_64-linux-gnu/libsoup-2.4.so.1
Done !! Cheers!!
If you are trying to do that in a Portable Class Library PCL (like me), then here is how you can do it :)
public class Foo
{
public string A {get;set;}
[Special]
public string B {get;set;}
}
var type = typeof(Foo);
var specialProperties = type.GetRuntimeProperties()
.Where(pi => pi.PropertyType == typeof (string)
&& pi.GetCustomAttributes<Special>(true).Any());
You can then check on the number of properties that have this special property if you need to.
James Sulak asked,
Is there any way I can make Python automatically print a ? instead of failing in this situation?
Other solutions recommend we attempt to modify the Windows environment or replace Python's print()
function. The answer below comes closer to fulfilling Sulak's request.
Under Windows 7, Python 3.5 can be made to print Unicode without throwing a UnicodeEncodeError
as follows:
In place of:
print(text)
substitute:
print(str(text).encode('utf-8'))
Instead of throwing an exception, Python now displays unprintable Unicode characters as \xNN hex codes, e.g.:
Halmalo n\xe2\x80\x99\xc3\xa9tait plus qu\xe2\x80\x99un point noir
Instead of
Halmalo n’était plus qu’un point noir
Granted, the latter is preferable ceteris paribus, but otherwise the former is completely accurate for diagnostic messages. Because it displays Unicode as literal byte values the former may also assist in diagnosing encode/decode problems.
Note: The str()
call above is needed because otherwise encode()
causes Python to reject a Unicode character as a tuple of numbers.
char_seen = []
for char in string:
if char not in char_seen:
char_seen.append(char)
print(''.join(char_seen))
This will preserve the order in which alphabets are coming,
output will be
abcd
Here is my solution.
Tested with IE, Opera, Chrome, FireFox, Safari, as Phonegap WebApp on IOS 8 and as Phonegap WebApp on Android 4.4.2
This solution isn't working with FireFox on localhost.
=================================================================================
onlineCheck.js (filepath: "root/js/onlineCheck.js ):
var isApp = false;
function onLoad() {
document.addEventListener("deviceready", onDeviceReady, false);
}
function onDeviceReady() {
isApp = true;
}
function isOnlineTest() {
alert(checkOnline());
}
function isBrowserOnline(no,yes){
//Didnt work local
//Need "firefox.php" in root dictionary
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
xhr.onload = function(){
if(yes instanceof Function){
yes();
}
}
xhr.onerror = function(){
if(no instanceof Function){
no();
}
}
xhr.open("GET","checkOnline.php",true);
xhr.send();
}
function checkOnline(){
if(isApp)
{
var xhr = new XMLHttpRequest();
var file = "http://dexheimer.cc/apps/kartei/neu/dot.png";
try {
xhr.open('HEAD', file , false);
xhr.send(null);
if (xhr.status >= 200 && xhr.status < 304) {
return true;
} else {
return false;
}
} catch (e)
{
return false;
}
}else
{
var tmpIsOnline = false;
tmpIsOnline = navigator.onLine;
if(tmpIsOnline || tmpIsOnline == "undefined")
{
try{
//Didnt work local
//Need "firefox.php" in root dictionary
var xhr = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHttp');
xhr.onload = function(){
tmpIsOnline = true;
}
xhr.onerror = function(){
tmpIsOnline = false;
}
xhr.open("GET","checkOnline.php",false);
xhr.send();
}catch (e){
tmpIsOnline = false;
}
}
return tmpIsOnline;
}
}
=================================================================================
index.html (filepath: "root/index.html"):
<!DOCTYPE html>
<html>
<head>
...
<script type="text/javascript" src="js/onlineCheck.js" ></script>
...
</head>
...
<body onload="onLoad()">
...
<div onclick="isOnlineTest()">
Online?
</div>
...
</body>
</html>
=================================================================================
checkOnline.php (filepath: "root"):
<?php echo 'true'; ?>
Add flutter_just_toast to your dependencies in your Pubspecs.yaml
dependencies:
flutter_just_toast: ^1.0.1
Next import package into your class:
import 'package:flutter_just_toast/flutter_just_toast.dart';
Implement Toast with message
Toast.show( message: "Your toast message",
duration: Delay.SHORT,
textColor: Colors.black);
From React's documentation:
setState()
does not immediately mutatethis.state
but creates a pending state transition. Accessingthis.state
after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls tosetState
and calls may be batched for performance gains.
If you want a function to be executed after the state change occurs, pass it in as a callback.
this.setState({value: event.target.value}, function () {
console.log(this.state.value);
});
str = str[0...-n]
Check out curljson
$ pip install curljson
$ curljson -i <the-json-api-url>
You could create a dict comprehension of just the elements whose values are None, and then update back into the original:
tmp = dict((k,"") for k,v in mydict.iteritems() if v is None)
mydict.update(tmp)
Update - did some performance tests
Well, after trying dicts of from 100 to 10,000 items, with varying percentage of None values, the performance of Alex's solution is across-the-board about twice as fast as this solution.
Here's a workaround for installing the 64-bit version of the Microsoft Access Database Engine 2010 redistributable on a system with a 32-bit MS Office version installed:
Now you can start a 32-bit MS Office application without the "re-configuring" issue. Note that the "mso.dll" registry value will already be present if a 64-bit version of MS Office is installed. In this case the value should not be deleted or renamed.
Also if you do not want to use the "/passive" command line parameter you can edit the AceRedist.msi file to remove the MS Office architecture check:
You can now use this file to install the Microsoft Access Database Engine 2010 redistributable on a system where a "conflicting" version of MS Office is installed (e.g. 64-bit version on system with 32-bit MS Office version) Make sure that you rename the "mso.dll" registry value as explained above (if needed).
I rename in code
echo off
setlocal EnableDelayedExpansion
for %%a in (*.txt) do (
REM echo %%a
set x=%%a
set mes=!x:~17,3!
if !mes!==JAN (
set mes=01
)
if !mes!==ENE (
set mes=01
)
if !mes!==FEB (
set mes=02
)
if !mes!==MAR (
set mes=03
)
if !mes!==APR (
set mes=04
)
if !mes!==MAY (
set mes=05
)
if !mes!==JUN (
set mes=06
)
if !mes!==JUL (
set mes=07
)
if !mes!==AUG (
set mes=08
)
if !mes!==SEP (
set mes=09
)
if !mes!==OCT (
set mes=10
)
if !mes!==NOV (
set mes=11
)
if !mes!==DEC (
set mes=12
)
ren %%a !x:~20,4!!mes!!x:~15,2!.txt
echo !x:~20,4!!mes!!x:~15,2!.txt
)
c(df$x, df$y)
# returns: 26 21 20 34 29 28
if the particular order is important then:
M = as.matrix(df)
c(m[1,], c[2,], c[3,])
# returns 26 34 21 29 20 28
Or more generally:
m = as.matrix(df)
q = c()
for (i in seq(1:nrow(m))){
q = c(q, m[i,])
}
# returns 26 34 21 29 20 28
The CSS Lists and Counters Module Level 3 introduces the ::marker
pseudo-element. From what I've understood it would allow such a thing. Unfortunately, no browser seems to support it.
What you can do is add some padding to the parent ul
and pull the icon into that padding:
ul {_x000D_
list-style: none;_x000D_
padding: 0;_x000D_
}_x000D_
li {_x000D_
padding-left: 1.3em;_x000D_
}_x000D_
li:before {_x000D_
content: "\f00c"; /* FontAwesome Unicode */_x000D_
font-family: FontAwesome;_x000D_
display: inline-block;_x000D_
margin-left: -1.3em; /* same as padding-left set on li */_x000D_
width: 1.3em; /* same as padding-left set on li */_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">_x000D_
<ul>_x000D_
<li>Item one</li>_x000D_
<li>Item two</li>_x000D_
</ul>
_x000D_
Adjust the padding/font-size/etc to your liking, and that's it. Here's the usual fiddle: http://jsfiddle.net/joplomacedo/a8GxZ/
=====
This works with any type of iconic font. FontAwesome, however, provides their own way to deal with this 'problem'. Check out Darrrrrren's answer below for more details.
SELECT [ReportId],
SUBSTRING(d.EmailList,1, LEN(d.EmailList) - 1) EmailList
FROM
(
SELECT DISTINCT [ReportId]
FROM Table1
) a
CROSS APPLY
(
SELECT [Email] + ', '
FROM Table1 AS B
WHERE A.[ReportId] = B.[ReportId]
FOR XML PATH('')
) D (EmailList)
I have to disagree with Dale... The strong element is actually the wrong element to use, implying something about the meaning, use, or emphasis of the content while you are simply intending to provide style to the element.
Ideally you would be able to accomplish this with a pseudo-class and your stylesheet, but as that is not possible you should make your markup semantically correct and use <span class="first-word">
.
You can do so by creating an array of dtype=object
. If you try to assign a long string to a normal numpy array, it truncates the string:
>>> a = numpy.array(['apples', 'foobar', 'cowboy'])
>>> a[2] = 'bananas'
>>> a
array(['apples', 'foobar', 'banana'],
dtype='|S6')
But when you use dtype=object
, you get an array of python object references. So you can have all the behaviors of python strings:
>>> a = numpy.array(['apples', 'foobar', 'cowboy'], dtype=object)
>>> a
array([apples, foobar, cowboy], dtype=object)
>>> a[2] = 'bananas'
>>> a
array([apples, foobar, bananas], dtype=object)
Indeed, because it's an array of objects, you can assign any kind of python object to the array:
>>> a[2] = {1:2, 3:4}
>>> a
array([apples, foobar, {1: 2, 3: 4}], dtype=object)
However, this undoes a lot of the benefits of using numpy, which is so fast because it works on large contiguous blocks of raw memory. Working with python objects adds a lot of overhead. A simple example:
>>> a = numpy.array(['abba' for _ in range(10000)])
>>> b = numpy.array(['abba' for _ in range(10000)], dtype=object)
>>> %timeit a.copy()
100000 loops, best of 3: 2.51 us per loop
>>> %timeit b.copy()
10000 loops, best of 3: 48.4 us per loop
You need to set option CURLOPT_PROXYTYPE
to CURLPROXY_SOCKS5_HOSTNAME
, which sadly wasn't defined in old PHP versions, circa pre-5.6; if you have earlier in but you can explicitly use its value, which is equal to 7
:
curl_setopt($ch, CURLOPT_PROXYTYPE, 7);
"The use of the checkbox is to determine what Item in the Listview that I selected"
Just add the tag to checkbox using setTag() method in the Adapter class. and other side using getTag() method.
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
ServiceHelper helper=userServices.get(position);
holder.tvServiceName.setText(helper.getServiceName());
if(!helper.isServiceStatus()){
holder.btnAdd.setVisibility(View.VISIBLE);
holder.btnAdd.setTag(helper.getServiceName());
holder.checkBoxServiceStatus.setVisibility(View.INVISIBLE);
}else{
holder.checkBoxServiceStatus.setVisibility(View.VISIBLE);
//This Line
holder.checkBoxServiceStatus.setTag(helper.getServiceName());
holder.btnAdd.setVisibility(View.INVISIBLE);
}
}
In xml code of the checkbox just put the "android:onClick="your method""attribute.
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="checkboxClicked"
android:id="@+id/checkBox_Service_row"
android:layout_marginRight="5dp"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
In your class Implement that method "your method".
protected void checkboxClicked(View view)
{
CheckBox checkBox=(CheckBox) view;
String tagName="";
if(checkBox.isChecked()){
tagName=checkBox.getTag().toString();
deleteServices.add(tagName);
checkboxArrayList.add(checkBox);
}else {
checkboxArrayList.remove(checkBox);
tagName=checkBox.getTag().toString();
if(deleteServices.size()>0&&deleteServices.contains(tagName)){
deleteServices.remove(tagName);
}
}
}
It's just a 'safety' warning. It is a relatively common idiom, but also a relatively common error when you meant to have ==
in there. You can make the warning go away by adding another set of parentheses:
while ((list = list->next))
**The activity should implements LocationListener
In onCreate(), write the following code **
Boolean network = haveNetworkConnection();
Log.e("network", "---------->" + network);
if (!network) {
Toast.makeText(getApplicationContext(), "Network is not available",
3000).show();
}
SupportMapFragment supportMapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.googleMap);
googleMap = supportMapFragment.getMap();
googleMap.setMyLocationEnabled(true);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 30000, 0, this);
if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
&& !locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
TextView title = new TextView(context);
title.setText("Location Services Not Active");
title.setBackgroundColor(Color.BLACK);
title.setPadding(10, 15, 15, 10);
title.setGravity(Gravity.CENTER);
title.setTextColor(Color.WHITE);
title.setTextSize(22);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setCustomTitle(title);
// builder.setTitle("Location Services Not Active");
builder.setMessage("Please enable Location Services and GPS");
builder.setPositiveButton("Turn on",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface,
int i) {
// Show location settings when the user acknowledges
// the alert dialog
Intent intent = new Intent(
Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
finish();
}
});
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.cancel();
}
});
builder.show();
}
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, true);
Location location = locationManager.getLastKnownLocation(bestProvider);
if (location == null) {
Toast.makeText(getApplicationContext(), "GPS signal not found",
3000).show();
}
if (location != null) {
Log.e("locatin", "location--" + location);
Log.e("latitude at beginning",
"@@@@@@@@@@@@@@@" + location.getLatitude());
onLocationChanged(location);
}
Write a method haveNetworkConnection
private boolean haveNetworkConnection() {
boolean haveConnectedWifi = false;
boolean haveConnectedMobile = false;
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] netInfo = cm.getAllNetworkInfo();
for (NetworkInfo ni : netInfo) {
if (ni.getTypeName().equalsIgnoreCase("WIFI"))
if (ni.isConnected())
haveConnectedWifi = true;
if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
if (ni.isConnected())
haveConnectedMobile = true;
}
return haveConnectedWifi || haveConnectedMobile;
}
@Override
public void onLocationChanged(Location location) {
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions()
.position(latLng)
.title("Current LOC")
.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(17));
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
Tuples will be (are) in .Net 4.0 Until then, you can also use a
Dictionary<key1, Dictionary<key2, TypeObject>>
or, creating a custom collection class to represent this...
public class TwoKeyDictionary<K1, K2, T>:
Dictionary<K1, Dictionary<K2, T>> { }
or, with three keys...
public class ThreeKeyDictionary<K1, K2, K3, T> :
Dictionary<K1, Dictionary<K2, Dictionary<K3, T>>> { }
I ran across the same issue you did but the above answers did not solve my issue. The only way I was able to resolve it - was to make a class and use specific widths to trigger the wrapping for my specific use case. As an example, I provided a snippet below - but I found you will need to adjust it for the table in question - since I typically use multiple colspans depending on the layout. The reasoning I believe Bootstrap is failing - is because it removes the wrapping constraints to get a full table for the scrollbars. THe colspan must be tripping it up.
<style>
@media (max-width: 768px) { /* use the max to specify at each container level */
.specifictd {
width:360px; /* adjust to desired wrapping */
display:table;
white-space: pre-wrap; /* css-3 */
white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
white-space: -pre-wrap; /* Opera 4-6 */
white-space: -o-pre-wrap; /* Opera 7 */
word-wrap: break-word; /* Internet Explorer 5.5+ */
}
}
I hope this helps
<table style='border:1px solid black'>
<tr>
<td>Derp</td>
</tr>
</table>
This should work. I use the shorthand syntax for borders.
Use
position: absolute;
top: ...px;
left: ...px;
To position the div. Make sure it doesn't have a parent tag with position: relative;
You want huge?
Here's a small table: create table foo (id int not null primary key auto_increment, crap char(2000));
insert into foo(crap) values ('');
-- each time you run the next line, the number of rows in foo doubles. insert into foo( crap ) select * from foo;
run it twenty more times, you have over a million rows to play with.
Yes, if he's looking for looks of relations to navigate, this is not the answer. But if by huge he means to test performance and his ability to optimize, this will do it. I did exactly this (and then updated with random values) to test an potential answer I had for another question. (And didn't answer it, because I couldn't come up with better performance than what that asker had.)
Had he asked for "complex", I'd have gien a differnt answer. To me,"huge" implies "lots of rows".
Because you don't need huge to play with tables and relations. Consider a table, by itself, with no nullable columns. How many different kinds of rows can there be? Only one, as all columns must have some value as none can be null.
Every nullable column multiples by two the number of different kinds of rows possible: a row where that column is null, an row where it isn't null.
Now consider the table, not in isolation. Consider a table that is a child table: for every child that has an FK to the parent, that, is a many-to-one, there can be 0, 1 or many children. So we multiply by three times the count we got in the previous step (no rows for zero, one for exactly one, two rows for many). For any grandparent to which the parent is a many, another three.
For many-to-many relations, we can have have no relation, a one-to-one, a one-to-many, many-to-one, or a many-to-many. So for each many-to-many we can reach in a graph from the table, we multiply the rows by nine -- or just like two one-to manys. If the many-to-many also has data, we multiply by the nullability number.
Tables that we can't reach in our graph -- those that we have no direct or indirect FK to, don't multiply the rows in our table.
By recursively multiplying the each table we can reach, we can come up with the number of rows needed to provide one of each "kind", and we need no more than those to test every possible relation in our schema. And we're nowhere near huge.
while(something.hasnext())
do something...
if(contains something to process){
do something...
break;
}
}
Just use the break statement;
For eg:this just prints "Breaking..."
while (true) {
if (true) {
System.out.println("Breaking...");
break;
}
System.out.println("Did this print?");
}
Simple install with NVM...
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
. ~/.nvm/nvm.sh
nvm install node
To install a certain version (such as 12.16.3) of Node change the last line to
nvm install 12.16.3
For more information about how to use NVM visit the docs: https://github.com/nvm-sh/nvm
X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!
There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.
Source: classroomm.com
Whats the value for the SqlException.ErrorCode property? Can you work with that?
When having timeouts, it may be worth checking the code for -2146232060.
I would set this up as a static const in your data code.
In python, you can put ‘j’ or ‘J’ after a number to make it imaginary, so you can write complex literals easily:
>>> 1j
1j
>>> 1J
1j
>>> 1j * 1j
(-1+0j)
The ‘j’ suffix comes from electrical engineering, where the variable ‘i’ is usually used for current. (Reasoning found here.)
The type of a complex number is complex
, and you can use the type as a constructor if you prefer:
>>> complex(2,3)
(2+3j)
A complex number has some built-in accessors:
>>> z = 2+3j
>>> z.real
2.0
>>> z.imag
3.0
>>> z.conjugate()
(2-3j)
Several built-in functions support complex numbers:
>>> abs(3 + 4j)
5.0
>>> pow(3 + 4j, 2)
(-7+24j)
The standard module cmath
has more functions that handle complex numbers:
>>> import cmath
>>> cmath.sin(2 + 3j)
(9.15449914691143-4.168906959966565j)
I think it is best way for you.
You should add this: this.onTodoChange = this.onTodoChange.bind(this)
.
And your function has event param(e)
, and get value:
componentWillMount(){
this.setState({
updatable : false,
name : this.props.name,
status : this.props.status
});
this.onTodoChange = this.onTodoChange.bind(this)
}
<input className="form-control" type="text" value={this.state.name} id={'todoName' + this.props.id} onChange={this.onTodoChange}/>
onTodoChange(e){
const {name, value} = e.target;
this.setState({[name]: value});
}
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--example', nargs='?', const=1, type=int)
args = parser.parse_args()
print(args)
% test.py
Namespace(example=None)
% test.py --example
Namespace(example=1)
% test.py --example 2
Namespace(example=2)
nargs='?'
means 0-or-1 argumentsconst=1
sets the default when there are 0 argumentstype=int
converts the argument to intIf you want test.py
to set example
to 1 even if no --example
is specified, then include default=1
. That is, with
parser.add_argument('--example', nargs='?', const=1, type=int, default=1)
then
% test.py
Namespace(example=1)
t
refers to the text mode. There is no difference between r
and rt
or w
and wt
since text mode is the default.
Documented here:
Character Meaning
'r' open for reading (default)
'w' open for writing, truncating the file first
'x' open for exclusive creation, failing if the file already exists
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)
'U' universal newlines mode (deprecated)
The default mode is 'r'
(open for reading text, synonym of 'rt'
).
1. First should understand the error meaning
Error not enough values to unpack (expected 3, got 2)
means:
a 2 part tuple, but assign to 3 values
and I have written demo code to show for you:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Function: Showing how to understand ValueError 'not enough values to unpack (expected 3, got 2)'
# Author: Crifan Li
# Update: 20191212
def notEnoughUnpack():
"""Showing how to understand python error `not enough values to unpack (expected 3, got 2)`"""
# a dict, which single key's value is two part tuple
valueIsTwoPartTupleDict = {
"name1": ("lastname1", "email1"),
"name2": ("lastname2", "email2"),
}
# Test case 1: got value from key
gotLastname, gotEmail = valueIsTwoPartTupleDict["name1"] # OK
print("gotLastname=%s, gotEmail=%s" % (gotLastname, gotEmail))
# gotLastname, gotEmail, gotOtherSomeValue = valueIsTwoPartTupleDict["name1"] # -> ValueError not enough values to unpack (expected 3, got 2)
# Test case 2: got from dict.items()
for eachKey, eachValues in valueIsTwoPartTupleDict.items():
print("eachKey=%s, eachValues=%s" % (eachKey, eachValues))
# same as following:
# Background knowledge: each of dict.items() return (key, values)
# here above eachValues is a tuple of two parts
for eachKey, (eachValuePart1, eachValuePart2) in valueIsTwoPartTupleDict.items():
print("eachKey=%s, eachValuePart1=%s, eachValuePart2=%s" % (eachKey, eachValuePart1, eachValuePart2))
# but following:
for eachKey, (eachValuePart1, eachValuePart2, eachValuePart3) in valueIsTwoPartTupleDict.items(): # will -> ValueError not enough values to unpack (expected 3, got 2)
pass
if __name__ == "__main__":
notEnoughUnpack()
using VSCode
debug effect:
2. For your code
for name, email, lastname in unpaidMembers.items():
but error
ValueError: not enough values to unpack (expected 3, got 2)
means each item(a tuple value) in unpaidMembers
, only have 1 parts:email
, which corresponding above code
unpaidMembers[name] = email
so should change code to:
for name, email in unpaidMembers.items():
to avoid error.
But obviously you expect extra lastname
, so should change your above code to
unpaidMembers[name] = (email, lastname)
and better change to better syntax:
for name, (email, lastname) in unpaidMembers.items():
then everything is OK and clear.
both works similar but "===" even do case statements
"test" == "test" #=> true
"test" === "test" #=> true
here the difference
String === "test" #=> true
String == "test" #=> false
No need to use the command line.
If you FILE-> "Export Android Application" in the ADK then it will allow you to create a key and then produce your .apk file.
You need to specify all of the names, including those already registered.
I used the following command originally to register some certificates:
/opt/certbot/certbot-auto certonly --webroot --agree-tos -w /srv/www/letsencrypt/ \
--email [email protected] \
--expand -d example.com,www.example.com
... and just now I successfully used the following command to expand my registration to include a new subdomain as a SAN:
/opt/certbot/certbot-auto certonly --webroot --agree-tos -w /srv/www/letsencrypt/ \
--expand -d example.com,www.example.com,click.example.com
From the documentation:
--expand "If an existing cert covers some subset of the requested names, always expand and replace it with the additional names."
Don't forget to restart the server to load the new certificates if you are running nginx.
Rules are used to enhance the behaviour of each test method in a generic way. Junit rule intercept the test method and allows us to do something before a test method starts execution and after a test method has been executed.
For example, Using @Timeout rule we can set the timeout for all the tests.
public class TestApp {
@Rule
public Timeout globalTimeout = new Timeout(20, TimeUnit.MILLISECONDS);
......
......
}
@TemporaryFolder rule is used to create temporary folders, files. Every time the test method is executed, a temporary folder is created and it gets deleted after the execution of the method.
public class TempFolderTest {
@Rule
public TemporaryFolder tempFolder= new TemporaryFolder();
@Test
public void testTempFolder() throws IOException {
File folder = tempFolder.newFolder("demos");
File file = tempFolder.newFile("Hello.txt");
assertEquals(folder.getName(), "demos");
assertEquals(file.getName(), "Hello.txt");
}
}
You can see examples of some in-built rules provided by junit at this link.
Also when scripting, you can specify a name when creating the window with -n <window name>
. For example:
# variable to store the session name
SESSION="my_session"
# set up session
tmux -2 new-session -d -s $SESSION
# create window; split into panes
tmux new-window -t $SESSION:0 -n 'My Window with a Name'
In Spring boot: 2.1.6, you can use like below:
@GetMapping("/orders")
@ApiOperation(value = "retrieve orders", response = OrderResponse.class, responseContainer = "List")
public List<OrderResponse> getOrders(
@RequestParam(value = "creationDateTimeFrom", required = true) String creationDateTimeFrom,
@RequestParam(value = "creationDateTimeTo", required = true) String creationDateTimeTo,
@RequestParam(value = "location_id", required = true) String location_id) {
// TODO...
return response;
@ApiOperation is an annotation that comes from Swagger api, It is used for documenting the apis.
A delegate is a reference to a method. Whereas objects can easily be sent as parameters into methods, constructor or whatever, methods are a bit more tricky. But every once in a while you might feel the need to send a method as a parameter to another method, and that's when you'll need delegates.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DelegateApp {
/// <summary>
/// A class to define a person
/// </summary>
public class Person {
public string Name { get; set; }
public int Age { get; set; }
}
class Program {
//Our delegate
public delegate bool FilterDelegate(Person p);
static void Main(string[] args) {
//Create 4 Person objects
Person p1 = new Person() { Name = "John", Age = 41 };
Person p2 = new Person() { Name = "Jane", Age = 69 };
Person p3 = new Person() { Name = "Jake", Age = 12 };
Person p4 = new Person() { Name = "Jessie", Age = 25 };
//Create a list of Person objects and fill it
List<Person> people = new List<Person>() { p1, p2, p3, p4 };
//Invoke DisplayPeople using appropriate delegate
DisplayPeople("Children:", people, IsChild);
DisplayPeople("Adults:", people, IsAdult);
DisplayPeople("Seniors:", people, IsSenior);
Console.Read();
}
/// <summary>
/// A method to filter out the people you need
/// </summary>
/// <param name="people">A list of people</param>
/// <param name="filter">A filter</param>
/// <returns>A filtered list</returns>
static void DisplayPeople(string title, List<Person> people, FilterDelegate filter) {
Console.WriteLine(title);
foreach (Person p in people) {
if (filter(p)) {
Console.WriteLine("{0}, {1} years old", p.Name, p.Age);
}
}
Console.Write("\n\n");
}
//==========FILTERS===================
static bool IsChild(Person p) {
return p.Age < 18;
}
static bool IsAdult(Person p) {
return p.Age >= 18;
}
static bool IsSenior(Person p) {
return p.Age >= 65;
}
}
}
Children:
Jake, 12 years old
Adults:
John, 41 years old
Jane, 69 years old
Jessie, 25 years old
Seniors:
Jane, 69 years old
I modified the code of @TimWolla to add more options and a some movement functions. Also, added support to crossbrowser with document.body.scrollTop and document.documentElement.scrollTop
// scroll to top
scrollTo(0, 1000);
// Element to move, time in ms to animate
function scrollTo(element, duration) {
var e = document.documentElement;
if(e.scrollTop===0){
var t = e.scrollTop;
++e.scrollTop;
e = t+1===e.scrollTop--?e:document.body;
}
scrollToC(e, e.scrollTop, element, duration);
}
// Element to move, element or px from, element or px to, time in ms to animate
function scrollToC(element, from, to, duration) {
if (duration <= 0) return;
if(typeof from === "object")from=from.offsetTop;
if(typeof to === "object")to=to.offsetTop;
scrollToX(element, from, to, 0, 1/duration, 20, easeOutCuaic);
}
function scrollToX(element, xFrom, xTo, t01, speed, step, motion) {
if (t01 < 0 || t01 > 1 || speed<= 0) {
element.scrollTop = xTo;
return;
}
element.scrollTop = xFrom - (xFrom - xTo) * motion(t01);
t01 += speed * step;
setTimeout(function() {
scrollToX(element, xFrom, xTo, t01, speed, step, motion);
}, step);
}
function easeOutCuaic(t){
t--;
return t*t*t+1;
}
http://jsfiddle.net/forestrf/tPQSv/
Minified version: http://jsfiddle.net/forestrf/tPQSv/139/
// c = element to scroll to or top position in pixels
// e = duration of the scroll in ms, time scrolling
// d = (optative) ease function. Default easeOutCuaic
function scrollTo(c,e,d){d||(d=easeOutCuaic);var a=document.documentElement;if(0===a.scrollTop){var b=a.scrollTop;++a.scrollTop;a=b+1===a.scrollTop--?a:document.body}b=a.scrollTop;0>=e||("object"===typeof b&&(b=b.offsetTop),"object"===typeof c&&(c=c.offsetTop),function(a,b,c,f,d,e,h){function g(){0>f||1<f||0>=d?a.scrollTop=c:(a.scrollTop=b-(b-c)*h(f),f+=d*e,setTimeout(g,e))}g()}(a,b,c,0,1/e,20,d))};
function easeOutCuaic(t){
t--;
return t*t*t+1;
}
This script below should put you on the right track perhaps?
You can keep this html the same (though I changed the method to POST):
<form method="POST" id="subscribeForm">
<fieldset id="cbgroup">
<div><input name="list" id="list0" type="checkbox" value="newsletter0" >zero</div>
<div><input name="list" id="list1" type="checkbox" value="newsletter1" >one</div>
<div><input name="list" id="list2" type="checkbox" value="newsletter2" >two</div>
</fieldset>
<input name="submit" type="submit" value="submit">
</form>
and this javascript validates
function onSubmit()
{
var fields = $("input[name='list']").serializeArray();
if (fields.length === 0)
{
alert('nothing selected');
// cancel submit
return false;
}
else
{
alert(fields.length + " items selected");
}
}
// register event on form, not submit button
$('#subscribeForm').submit(onSubmit)
and you can find a working example of it here
UPDATE (Oct 2012)
Additionally it should be noted that the checkboxes must have a "name" property, or else they will not be added to the array. Only having "id" will not work.
UPDATE (May 2013)
Moved the submit registration to javascript and registered the submit onto the form (as it should have been originally)
UPDATE (June 2016)
Changes == to ===
I would suggest taking a look JetBrains AppCode IDE. It has a Reformat Code command. I have come from a C# background and used Visual Studio with Jetbrains Resharper plugin, so learning AppCode has been a pleasure because many of the features in Resharper also exist in AppCode!
Theres too many features to list here but could well be worth checking out
# -*- coding: utf-8 -*-
is a Python 2 thing. In Python 3+, the default encoding of source files is already UTF-8 and that line is useless.
See: Should I use encoding declaration in Python 3?
pyupgrade
is a tool you can run on your code to remove those comments and other no-longer-useful leftovers from Python 2, like having all your classes inherit from object
.
SINGLE LINE: Adding a column with 'year-month'-paires: ('pd.to_datetime' first changes the column dtype to date-time before the operation)
df['yyyy-mm'] = pd.to_datetime(df['ArrivalDate']).dt.strftime('%Y-%m')?
Accordingly for an extra 'year' or 'month' column:
df['yyyy'] = pd.to_datetime(df['ArrivalDate']).dt.strftime('%Y')?
df['mm'] = pd.to_datetime(df['ArrivalDate']).dt.strftime('%m')?
Here's what I do:
The procedure isn't very quick, but it gives you a good overview.
Try this, it worked for me.
<td><a href="Docs/Chapter 1_ORG.pdf" target="pdf-frame">Chapter-1 Organizational</a></td>
use a shell built-in let
, it is similar to (( expr ))
A=1
B=1
let "C = $A + $B"
echo $C # C == 2
I use this to get the Parent, similarly for child
$( this ).children( 'li.target' ).css("border", "3px double red");
Good Luck
Might be worth checking out --
Is there a Python equivalent to Perl's Data::Dumper?
My recommendation is this --
https://gist.github.com/1071857
Note that perl has a module called Data::Dumper which translates object data back to perl source code (NB: it does NOT translate code back to source, and almost always you don't want to the object method functions in the output). This can be used for persistence, but the common purpose is for debugging.
There are a number of things standard python pprint fails to achieve, in particular it just stops descending when it sees an instance of an object and gives you the internal hex pointer of the object (errr, that pointer is not a whole lot of use by the way). So in a nutshell, python is all about this great object oriented paradigm, but the tools you get out of the box are designed for working with something other than objects.
The perl Data::Dumper allows you to control how deep you want to go, and also detects circular linked structures (that's really important). This process is fundamentally easier to achieve in perl because objects have no particular magic beyond their blessing (a universally well defined process).
This is a recursive version that works with letter drives as well as UNC. I used the error catching to implement it but if anyone can do one without, I would be interested to see it. This approach works from the branches to the root so it will be somewhat usable when you don't have permissions in the root and lower parts of the directory tree.
' Reverse create directory path. This will create the directory tree from the top down to the root.
' Useful when working on network drives where you may not have access to the directories close to the root
Sub RevCreateDir(strCheckPath As String)
On Error GoTo goUpOneDir:
If Len(Dir(strCheckPath, vbDirectory)) = 0 And Len(strCheckPath) > 2 Then
MkDir strCheckPath
End If
Exit Sub
' Only go up the tree if error code Path not found (76).
goUpOneDir:
If Err.Number = 76 Then
Call RevCreateDir(Left(strCheckPath, InStrRev(strCheckPath, "\") - 1))
Call RevCreateDir(strCheckPath)
End If
End Sub
def split_seq(seq, num_pieces):
start = 0
for i in xrange(num_pieces):
stop = start + len(seq[i::num_pieces])
yield seq[start:stop]
start = stop
usage:
seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for seq in split_seq(seq, 3):
print seq
Sorry I dont know Java, but I was faced with the same problem tonight, so I wrote this (it's in c#)
public string IncrementString(string inboundString) {
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(inboundString.ToArray);
bool incrementNext = false;
for (l = -(bytes.Count - 1); l <= 0; l++) {
incrementNext = false;
int bIndex = Math.Abs(l);
int asciiVal = Conversion.Val(bytes(bIndex).ToString);
asciiVal += 1;
if (asciiVal > 57 & asciiVal < 65)
asciiVal = 65;
if (asciiVal > 90) {
asciiVal = 48;
incrementNext = true;
}
bytes(bIndex) = System.Text.Encoding.ASCII.GetBytes({ Strings.Chr(asciiVal) })(0);
if (incrementNext == false)
break; // TODO: might not be correct. Was : Exit For
}
inboundString = System.Text.Encoding.ASCII.GetString(bytes);
return inboundString;
}
change
});
$(document).ready(function () {
$('.smallTabsHeader a').pluginbutton();
});
to
})(jQuery); //<-- ADD THIS
$(document).ready(function () {
$('.smallTabsHeader a').pluginbutton();
});
This is needed because, you need to call the anonymous function that you created with
(function($){
and notice that it expects an argument that it will use internally as $
, so you need to pass a reference to the jQuery object.
Additionally, you will need to change all the this.
to $(this).
, except the first one, in which you do return this.each
In the first one (where you do not need the $()
) it is because in the plugin body, this
holds a reference to the jQuery object matching your selector, but anywhere deeper than that, this
refers to the specific DOM element, so you need to wrap it in $()
.
Full code at http://jsfiddle.net/gaby/NXESk/
its super easy.
You'll need each machine to have it's own copy of ElasticSearch (simply copy the one you have now) -- the reason is that each machine / node whatever is going to keep it's own files that are sharded accross the cluster.
The only thing you really need to do is edit the config file to include the name of the cluster.
If all machines have the same cluster name elasticsearch will do the rest automatically (as long as the machines are all on the same network)
Read here to get you started: https://www.elastic.co/guide/en/elasticsearch/guide/current/deploy.html
When you create indexes (where the data goes) you define at that time how many replicas you want (they'll be distributed around the cluster)
int w =0 , l =0, d=0, i=0;
Scanner sc = new Scanner(System.in);
// try tentimes
while (i<10) {
System.out.println("scissor(1) ,Rock(2),Paper(3) ");
int n = sc.nextInt();
int m =(int)(Math.random()*3+1);
if(n==m){
System.out.println("Com:"+m +"so>>> " + "draw");
d++;
}else if ((n-1)%3==(m%3)){
w++;
System.out.println("Com:"+m +"so>>> " +"win");
}
else if(n >=4 )
{
System.out.println("pleas enter correct number)");
}
else {
System.out.println("Com:"+m +"so>>> " +"lose");
l++;
}
i++;
public static String MD5Hash(String toHash) throws RuntimeException {
try{
return String.format("%032x", // produces lower case 32 char wide hexa left-padded with 0
new BigInteger(1, // handles large POSITIVE numbers
MessageDigest.getInstance("MD5").digest(toHash.getBytes())));
}
catch (NoSuchAlgorithmException e) {
// do whatever seems relevant
}
}
For me, this is the clearest and most intuitive:
values = []
for action in ['Sell','Buy']:
amounts = orders_df['Amounts'][orders_df['Action'==action]].values
if action == 'Sell':
prices = orders_df['Prices'][orders_df['Action'==action]].values
else:
prices = -1*orders_df['Prices'][orders_df['Action'==action]].values
values += list(amounts*prices)
orders_df['Values'] = values
The .values
method returns a numpy array
allowing you to easily multiply element-wise and then you can cumulatively generate a list by 'adding' to it.
I think this code answer your question
RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams)
holder.desc1.getLayoutParams();
params.height = RelativeLayout.LayoutParams.WRAP_CONTENT;
holder.desc1.setLayoutParams(params);
If using Angular >= 1.4, here's the cleanest solution I've found that doesn't rely on anything custom or external:
angular.module('yourModule')
.config(function ($httpProvider, $httpParamSerializerJQLikeProvider){
$httpProvider.defaults.transformRequest.unshift($httpParamSerializerJQLikeProvider.$get());
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=utf-8';
});
And then you can do this anywhere in your app:
$http({
method: 'POST',
url: '/requesturl',
data: {
param1: 'value1',
param2: 'value2'
}
});
And it will correctly serialize the data as param1=value1¶m2=value2
and send it to /requesturl
with the application/x-www-form-urlencoded; charset=utf-8
Content-Type header as it's normally expected with POST requests on endpoints.
I got this error when I made the bonehead mistake of importing MatSnackBar
instead of MatSnackBarModule
in app.module.ts
.
myList.Any(myString.Contains);
Use etree.indent
and etree.tostring
import lxml.etree as etree
root = etree.fromstring('<html><head></head><body><h1>Welcome</h1></body></html>')
etree.indent(root, space=" ")
xml_string = etree.tostring(root, pretty_print=True).decode()
print(xml_string)
output
<html>
<head/>
<body>
<h1>Welcome</h1>
</body>
</html>
Removing namespaces and prefixes
import lxml.etree as etree
def dump_xml(element):
for item in element.getiterator():
item.tag = etree.QName(item).localname
etree.cleanup_namespaces(element)
etree.indent(element, space=" ")
result = etree.tostring(element, pretty_print=True).decode()
return result
root = etree.fromstring('<cs:document xmlns:cs="http://blabla.com"><name>hello world</name></cs:document>')
xml_string = dump_xml(root)
print(xml_string)
output
<document>
<name>hello world</name>
</document>
You can disable it in the ColumnAdded event:
private void dataGridView1_ColumnAdded(object sender, DataGridViewColumnEventArgs e)
{
dataGridView1.Columns[e.Column.Index].SortMode = DataGridViewColumnSortMode.NotSortable;
}
The most fast and cross browser is
for(var i=-1,l=nl.length;++i!==l;arr[i]=nl[i]);
As I compared in
http://jsbin.com/oqeda/98/edit
*Thanks @CMS for the idea!
Easy mode for complex object storage with using Gson google library [1]
public static void setComplexObject(Context ctx, ComplexObject obj){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("COMPLEX_OBJECT",new Gson().toJson(obj));
editor.commit();
}
public static ComplexObject getComplexObject (Context ctx){
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(ctx);
String sobj = preferences.getString("COMPLEX_OBJECT", "");
if(sobj.equals(""))return null;
else return new Gson().fromJson(sobj, ComplexObject.class);
}
If you are looking for interoperability between different systems and languages, I would definately go for REST. I've had a lot of problems trying to get SOAP working between .NET and Java, for example.
A neat Python solution based on the above answers:
class RunningAverage():
def __init__(self):
self.average = 0
self.n = 0
def __call__(self, new_value):
self.n += 1
self.average = (self.average * (self.n-1) + new_value) / self.n
def __float__(self):
return self.average
def __repr__(self):
return "average: " + str(self.average)
usage:
x = RunningAverage()
x(0)
x(2)
x(4)
print(x)
Parsing command line arguments in a primitive way as explained in the above answers is reasonable as long as the number of parameters that you need to deal with is not too much.
I strongly suggest you to use an industrial strength library for handling the command line arguments.
This will make your code more professional.
Such a library for C++ is available in the following website. I have used this library in many of my projects, hence I can confidently say that this one of the easiest yet useful library for command line argument parsing. Besides, since it is just a template library, it is easier to import into your project. http://tclap.sourceforge.net/
A similar library is available for C as well. http://argtable.sourceforge.net/
The best way to set radiobuttons state in jquery:
HTML:
<input type="radio" name="color" value="orange" /> Orange
<input type="radio" name="color" value="pink" /> Pink
<input type="radio" name="color" value="black" /> Black
<input type="radio" name="color" value="pinkish purple" /> Pinkish Purple
Jquery (1.4+) code to pre-select one button :
var presetValue = "black";
$("[name=color]").filter("[value='"+presetValue+"']").attr("checked","checked");
In Jquery 1.6+ code the .prop() method is preferred :
var presetValue = "black";
$("[name=color]").filter("[value='"+presetValue+"']").prop("checked",true);
To unselect the buttons :
$("[name=color]").removeAttr("checked");
Let's define a list first:
lst=[1,2,3]
You can directly write your list to a file:
f=open("filename.txt","w")
f.write(str(lst))
f.close()
To read your list from text file first you read the file and store in a variable:
f=open("filename.txt","r")
lst=f.read()
f.close()
The type of variable lst
is of course string. You can convert this string into array using eval
function.
lst=eval(lst)
.input:focus {
outline: none !important;
border:1px solid red;
box-shadow: 0 0 10px #719ECE;
}
So bottom line is, is there a way to specify a jdk for a single invocation of maven?
Temporarily change the value of your JAVA_HOME
environment variable.
This slide show shows how to get both keys updated June 2013.
http://www.slideshare.net/Tweetganic/generate-twitter-applications
$("#togglebutton").click(function () {
$(".fa-arrow-circle-left").toggleClass("fa-arrow-circle-right");
}
I have a button with the id "togglebutton" and an icon from FontAwesome . This can be a way to toggle it . from left arrow to right arrow icon
Window
is the main JavaScript object root, aka the global object
in a browser, also can be treated as the root of the document object model. You can access it as window
window.screen
or just screen
is a small information object about physical screen dimensions.
window.document
or just document
is the main object of the potentially visible (or better yet: rendered) document object model/DOM.
Since window
is the global object you can reference any properties of it with just the property name - so you do not have to write down window.
- it will be figured out by the runtime.
Go to Run type services.msc.
Check whether or not MySQL services are running. If not, start it manually. Once it is started, type MySQL Show
to test the service.
what I don't like about the accepted solution
arr = [5, 6, 7, 8]
arr.inject{ |sum, el| sum + el }.to_f / arr.size
=> 6.5
is that it does not really work in a purely functional way. we need a variable arr to compute arr.size at the end.
to solve this purely functionally we need to keep track of two values: the sum of all elements, and the number of elements.
[5, 6, 7, 8].inject([0.0,0]) do |r,ele|
[ r[0]+ele, r[1]+1 ]
end.inject(:/)
=> 6.5
Santhosh improved on this solution: instead of the argument r being an array, we could use destructuring to immediatly pick it apart into two variables
[5, 6, 7, 8].inject([0.0,0]) do |(sum, size), ele|
[ sum + ele, size + 1 ]
end.inject(:/)
if you want to see how it works, add some puts:
[5, 6, 7, 8].inject([0.0,0]) do |(sum, size), ele|
r2 = [ sum + ele, size + 1 ]
puts "adding #{ele} gives #{r2}"
r2
end.inject(:/)
adding 5 gives [5.0, 1]
adding 6 gives [11.0, 2]
adding 7 gives [18.0, 3]
adding 8 gives [26.0, 4]
=> 6.5
We could also use a struct instead of an array to contain the sum and the count, but then we have to declare the struct first:
R=Struct.new(:sum, :count)
[5, 6, 7, 8].inject( R.new(0.0, 0) ) do |r,ele|
r.sum += ele
r.count += 1
r
end.inject(:/)
Adding to the above answers: To find the package name of installed apps on any android device: Go to Storage/Android/data/< package-name >
I am new to Rust, but this solution seems to work:
#[macro_use]
extern crate lazy_static;
use std::sync::{Arc, Mutex};
lazy_static! {
static ref GLOBAL: Arc<Mutex<GlobalType> =
Arc::new(Mutex::new(GlobalType::new()));
}
Another solution is to declare a crossbeam channel tx/rx pair as an immutable global variable. The channel should be bounded and can only hold 1 element. When you initialize the global variable, push the global instance into the channel. When using the global variable, pop the channel to acquire it and push it back when done using it.
Both solutions should provide a safe approach to using global variables.
Which version of bootstrap are you using? The early versions of Bootstrap 3 (3.0, 3.0.1) didn't work with this functionality.
col-md-offset-0 should be working as seen in this bootstrap example found here (http://getbootstrap.com/css/#grid-responsive-resets):
<div class="row">
<div class="col-sm-5 col-md-6">.col-sm-5 .col-md-6</div>
<div class="col-sm-5 col-sm-offset-2 col-md-6 col-md-offset-0">.col-sm-5 .col-sm-offset-2 .col-md-6 .col-md-offset-0</div>
</div>
A solution is to add captures for the preceding and following text:
str.replace(/(.*name="\w+)(\d+)(\w+".*)/, "$1!NEW_ID!$3")
It's not generally correct that you can "remove an item from a database" with both methods. To be precise it is like so:
ObjectContext.DeleteObject(entity)
marks the entity as Deleted
in the context. (It's EntityState
is Deleted
after that.) If you call SaveChanges
afterwards EF sends a SQL DELETE
statement to the database. If no referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
EntityCollection.Remove(childEntity)
marks the relationship between parent and childEntity
as Deleted
. If the childEntity
itself is deleted from the database and what exactly happens when you call SaveChanges
depends on the kind of relationship between the two:
If the relationship is optional, i.e. the foreign key that refers from the child to the parent in the database allows NULL
values, this foreign will be set to null and if you call SaveChanges
this NULL
value for the childEntity
will be written to the database (i.e. the relationship between the two is removed). This happens with a SQL UPDATE
statement. No DELETE
statement occurs.
If the relationship is required (the FK doesn't allow NULL
values) and the relationship is not identifying (which means that the foreign key is not part of the child's (composite) primary key) you have to either add the child to another parent or you have to explicitly delete the child (with DeleteObject
then). If you don't do any of these a referential constraint is violated and EF will throw an exception when you call SaveChanges
- the infamous "The relationship could not be changed because one or more of the foreign-key properties is non-nullable" exception or similar.
If the relationship is identifying (it's necessarily required then because any part of the primary key cannot be NULL
) EF will mark the childEntity
as Deleted
as well. If you call SaveChanges
a SQL DELETE
statement will be sent to the database. If no other referential constraints in the database are violated the entity will be deleted, otherwise an exception is thrown.
I am actually a bit confused about the Remarks section on the MSDN page you have linked because it says: "If the relationship has a referential integrity constraint, calling the Remove method on a dependent object marks both the relationship and the dependent object for deletion.". This seems unprecise or even wrong to me because all three cases above have a "referential integrity constraint" but only in the last case the child is in fact deleted. (Unless they mean with "dependent object" an object that participates in an identifying relationship which would be an unusual terminology though.)
Great thing about linux, you're still able to download the source and on most systems have all of the tools to compile the version yourself.
In order to get a python cli from xterm just by typing python
, the python bin directory must be in your system path variable (Red Hat example, Suse example)
I think what the OP is looking for is a simple, windows-like solution.
here ya go:
For simple document, I sometimes use verbatim, but listing is nice for big chunk of code.
If you use static the value of the variable will be the same throughout all of your instances, if changed in one instance the others will change too.
You should read collections framework tutorial first of all.
But to answer your question this is how you should do it:
ArrayList<String> strings = new ArrayList<String>();
strings.add("String1");
strings.add("String2");
// To access a specific element:
System.out.println(strings.get(1));
// To loop through and print all of the elements:
for (String element : strings) {
System.out.println(element);
}
To escape you could just use this from Java 1.5:
Pattern.quote("$test");
You will match exacty the word $test
For Spring Boot 2.+, make sure you are using spring.servlet
instead of spring.http
.
---
spring:
servlet:
multipart:
max-file-size: 10MB
max-request-size: 10MB
If you have to use tomcat, you might end up creating EmbeddedServletContainerCustomizer, which is not really nice thing to do.
If you can live without tomat, you could replace tomcat with e.g. undertow and avoid this issue at all.
Right click project "pom.xml" in eclipse and select Maven Install
.
Right click on the Project -> Maven
-> Update Project
.
Then Refresh.
Besides executeUpdate() on the parentheses, you must also add a variable to use an SQL statement.
For example:
PreparedStatement pst = connection.prepareStatement(sql);
int numRowsChanged = pst.executeUpdate(sql);
My G drive stopped being shared with Docker after a recent Windows 10 update. I was getting the same problem saying it was blocked by the Windows firewall when attempting to reshare it.
Then I had tried to solve this issues by couple of suggestion but i cant resolve that issue after that I have tried to Reset credentials below of Shared Drives and my issue was solved.
So If you want then you can try to do this-
One solution I have used in the past - lets say your site is on mydomain.com, and you need to make an ajax request to foreigndomain.com
Configure an IIS rewrite from your domain to the foreign domain - e.g.
<rewrite>
<rules>
<rule name="ForeignRewrite" stopProcessing="true">
<match url="^api/v1/(.*)$" />
<action type="Rewrite" url="https://foreigndomain.com/{R:1}" />
</rule>
</rules>
</rewrite>
on your mydomain.com site - you can then make a same origin request, and there's no need for any options request :)
I had similar problem while using in postman. for POST request under header section add these as
key:valuepair
Content-Type:application/json Accept:application/json
i hope it will work.
This will dismiss some elements - you should extend it like this in order to support a wider array of controls. For a brief discussion, have a look here
/// <summary>
/// Helper methods for UI-related tasks.
/// </summary>
public static class UIHelper
{
/// <summary>
/// Finds a parent of a given item on the visual tree.
/// </summary>
/// <typeparam name="T">The type of the queried item.</typeparam>
/// <param name="child">A direct or indirect child of the
/// queried item.</param>
/// <returns>The first parent item that matches the submitted
/// type parameter. If not matching item can be found, a null
/// reference is being returned.</returns>
public static T TryFindParent<T>(DependencyObject child)
where T : DependencyObject
{
//get parent item
DependencyObject parentObject = GetParentObject(child);
//we've reached the end of the tree
if (parentObject == null) return null;
//check if the parent matches the type we're looking for
T parent = parentObject as T;
if (parent != null)
{
return parent;
}
else
{
//use recursion to proceed with next level
return TryFindParent<T>(parentObject);
}
}
/// <summary>
/// This method is an alternative to WPF's
/// <see cref="VisualTreeHelper.GetParent"/> method, which also
/// supports content elements. Do note, that for content element,
/// this method falls back to the logical tree of the element!
/// </summary>
/// <param name="child">The item to be processed.</param>
/// <returns>The submitted item's parent, if available. Otherwise
/// null.</returns>
public static DependencyObject GetParentObject(DependencyObject child)
{
if (child == null) return null;
ContentElement contentElement = child as ContentElement;
if (contentElement != null)
{
DependencyObject parent = ContentOperations.GetParent(contentElement);
if (parent != null) return parent;
FrameworkContentElement fce = contentElement as FrameworkContentElement;
return fce != null ? fce.Parent : null;
}
//if it's not a ContentElement, rely on VisualTreeHelper
return VisualTreeHelper.GetParent(child);
}
}
I use Eclipse under Fedora 20 with MinGW for cross compile. Use these settings and the program won't ask for libstdc++-6.dll any more.
Project type - Cross GCC
Cross Settings
Cross GCC Compiler
Command: gcc
All Options: -I/usr/x86_64-w64-mingw32/sys-root/mingw/include -O3 -Wall -c -fmessage-length=0
Includes: /usr/x86_64-w64-mingw32/sys-root/mingw/include
Cross G++ Compiler
Command: g++
All Options: -I/usr/x86_64-w64-mingw32/sys-root/mingw/include -O3 -Wall -c -fmessage-length=0
Includes: /usr/x86_64-w64-mingw32/sys-root/mingw/include
Cross G++ Linker
Command: g++ -static-libstdc++ -static-libgcc
All Options: -L/usr/x86_64-w64-mingw32/sys-root/mingw/lib -L/usr/x86_64-w64-mingw32/sys-root/mingw/bin
Library search path (-L):
/usr/x86_64-w64-mingw32/sys-root/mingw/lib
/usr/x86_64-w64-mingw32/sys-root/mingw/bin
I solved this using JNA: https://github.com/twall/jna
import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Platform;
public class prova {
private interface CLibrary extends Library {
CLibrary INSTANCE = (CLibrary) Native.loadLibrary((Platform.isWindows() ? "msvcrt" : "c"), CLibrary.class);
int system(String cmd);
}
private static int exec(String command) {
return CLibrary.INSTANCE.system(command);
}
public static void main(String[] args) {
exec("ls");
}
}
if ( !driver.findElement(By.id("idOfTheElement")).isSelected() )
{
driver.findElement(By.id("idOfTheElement")).click();
}
my problem was just network connection. using VPN solved the issue.
If you want to mark the type of a dataframe column as a string, you can do:
df['A'].dtype.kind
An example:
In [8]: df = pd.DataFrame([[1,'a',1.2],[2,'b',2.3]])
In [9]: df[0].dtype.kind, df[1].dtype.kind, df[2].dtype.kind
Out[9]: ('i', 'O', 'f')
The answer for your code:
for y in agg.columns:
if(agg[y].dtype.kind == 'f' or agg[y].dtype.kind == 'i'):
treat_numeric(agg[y])
else:
treat_str(agg[y])
Note:
uint
and UInt
are of kind u
, not kind i
.pd.api.types.is_integer_dtype
.Or instead the length you can check if the number is larger or smaller then the desired number.
public void createCard(int cardNumber, int cardStatus, int customerId) throws SQLException {
if(cardDao.checkIfCardExists(cardNumber) == false) {
if(cardDao.createCard(cardNumber, cardStatus, customerId) == true) {
System.out.println("Card created successfully");
} else {
}
} else {
System.out.println("Card already exists, try with another Card Number");
do {
System.out.println("Enter your new Card Number: ");
scan = new Scanner(System.in);
int inputCardNumber = scan.nextInt();
cardNumber = inputCardNumber;
} while(cardNumber < 95000000);
cardDao.createCard(cardNumber, cardStatus, customerId);
}
}
}
A one-liner (no essential difference to the answers above though):
document.body.appendChild(document.createElement('script')).src = 'source.js';
If you want it based on the screen height, and not the window height:
const height = 0.7 * screen.height
// jQuery
$('.header').height(height)
// Vanilla JS
document.querySelector('.header').style.height = height + 'px'
// If you have multiple <div class="header"> elements
document.querySelectorAll('.header').forEach(function(node) {
node.style.height = height + 'px'
})
Sql server
DECLARE @tableName nvarchar(100)
SET @tableName = N'members' -- change with table name
SELECT
[column].*,
COLUMNPROPERTY(object_id([column].[TABLE_NAME]), [column].[COLUMN_NAME], 'IsIdentity') AS [identity]
FROM
INFORMATION_SCHEMA.COLUMNS [column]
WHERE
[column].[Table_Name] = @tableName
There is a workaround.
That's it.
You can use your IP address to get your 'country', 'city', 'isp' etc...
Just use one of the web-services that provide you with a simple api like http://ip-api.com which provide you a JSON service at http://ip-api.com/json. Simple send a Ajax (or Xhr) request and then parse the JSON to get whatever data you need.
var requestUrl = "http://ip-api.com/json";
$.ajax({
url: requestUrl,
type: 'GET',
success: function(json)
{
console.log("My country is: " + json.country);
},
error: function(err)
{
console.log("Request failed, error= " + err);
}
});
string jsonData1=@"[{""name"":""0"",""price"":""40"",""count"":""1"",""productId"":""4"",""catid"":""4"",""productTotal"":""40"",""orderstatus"":""0"",""orderkey"":""123456789""}]";
string jsonData = jsonData1.Replace("\"", "");
DataSet ds = new DataSet();
DataTable dt = new DataTable();
JArray array= JArray.Parse(jsonData);
couldnot parse , if the vaule is a string..
look at name : meals , if name : 1 then it will parse
It works like this:
h4 {
display:inline;
}
h4:after {
content:"\a";
white-space: pre;
}
Example: http://jsfiddle.net/Bb2d7/
The trick comes from here: https://stackoverflow.com/a/66000/509752 (to have more explanation)
Take a look at ?legend
and try this:
legend('topright', names(a)[-1] ,
lty=1, col=c('red', 'blue', 'green',' brown'), bty='n', cex=.75)
I use:
jps
Depending on your installation a running Zookeeper would look like
HQuorumPeer
or sth. with zookeeper in it's name.
Complete snippet would look like the following. It expands @mouad's answer to asserting on error's message (or generally str
representation of its args
), which may be useful.
from unittest import TestCase
class TestNoneTypeError(TestCase):
def setUp(self):
self.testListNone = None
def testListSlicing(self):
with self.assertRaises(TypeError) as ctx:
self.testListNone[:1]
self.assertEqual("'NoneType' object is not subscriptable", str(ctx.exception))
Since I do a lot of dynamic queries, this is a super simple helper function I made.
public static function bindParamArray($prefix, $values, &$bindArray)
{
$str = "";
foreach($values as $index => $value){
$str .= ":".$prefix.$index.",";
$bindArray[$prefix.$index] = $value;
}
return rtrim($str,",");
}
Use it like this:
$bindString = helper::bindParamArray("id", $_GET['ids'], $bindArray);
$userConditions .= " AND users.id IN($bindString)";
Returns a string :id1,:id2,:id3
and also updates your $bindArray
of bindings that you will need when it's time to run your query. Easy!
This is how you do it, with rounded corners and rounded shadows without bothering with paths.
//Inner view with content
[imageView.layer setBorderColor:[[UIColor lightGrayColor] CGColor]];
[imageView.layer setBorderWidth:1.0f];
[imageView.layer setCornerRadius:8.0f];
[imageView.layer setMasksToBounds:YES];
//Outer view with shadow
UIView* shadowContainer = [[UIView alloc] initWithFrame:imageView.frame];
[shadowContainer.layer setMasksToBounds:NO];
[shadowContainer.layer setShadowColor:[[UIColor blackColor] CGColor]];
[shadowContainer.layer setShadowOpacity:0.6f];
[shadowContainer.layer setShadowRadius:2.0f];
[shadowContainer.layer setShadowOffset: CGSizeMake(0.0f, 2.0f)];
[shadowContainer addSubview:imageView];
The view with content, in my case a UIImageView, has a corner radius and therefore has to mask to bounds.
We create another equally sized view for the shadows, set it's maskToBounds to NO and then add the content view to the container view (e.g. shadowContainer).
lol .... all you have to do is make sure that
addKeyListener(this);
is placed correctly in your code.
No where in your question do you mention time zone. What time zone is implied that input string? What time zone do you want for your output? And, UTC is a time zone (or lack thereof depending on your mindset) not a string format.
Your input string is in ISO 8601 format, except that it lacks an offset from UTC.
Here is some example code in Joda-Time 2.3 to show you how to handle time zones. Joda-Time has built-in default formatters for parsing and generating String representations of date-time values.
String input = "2013-10-22T01:37:56";
DateTime dateTimeUtc = new DateTime( input, DateTimeZone.UTC );
DateTime dateTimeMontréal = dateTimeUtc.withZone( DateTimeZone.forID( "America/Montreal" );
String output = dateTimeMontréal.toString();
As for generating string representations in other formats, search StackOverflow for "Joda format".
I think that the URI class is the one that you are looking for.
There is not a really pythonic way of repeating something. However, it is a better way:
map(lambda index:do_something(), xrange(10))
If you need to pass the index then:
map(lambda index:do_something(index), xrange(10))
Consider that it returns the results as a collection. So, if you need to collect the results it can help.
You cannot straightly query mongodb collections by date components like day or month. But its possible by using the special $where javascript expression
db.mydatabase.mycollection.find({$where : function() { return this.date.getMonth() == 11} })
or simply
db.mydatabase.mycollection.find({$where : 'return this.date.getMonth() == 11'})
(But i prefer the first one)
Check out the below shell commands to get the parts of date
>date = ISODate("2011-09-25T10:12:34Z")
> date.getYear()
111
> date.getMonth()
8
> date.getdate()
25
EDIT:
Use $where only if you have no other choice. It comes with the performance problems. Please check out the below comments by @kamaradclimber and @dcrosta. I will let this post open so the other folks get the facts about it.
and check out the link $where Clauses and Functions in Queries for more info
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://example.com/CRM/Service.svc";
private static final String SOAP_ACTION = "http://tempuri.org/Login";
private static final String METHOD_NAME = "Login";
//calling web services method
String loginresult=callService(username,password,usertype);
//calling webservices
String callService(String a1,String b1,Integer c1) throws Exception {
Boolean flag=true;
do
{
try{
System.out.println(flag);
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
PropertyInfo pa1 = new PropertyInfo();
pa1.setName("Username");
pa1.setValue(a1.toString());
PropertyInfo pb1 = new PropertyInfo();
pb1.setName("Password");
pb1.setValue(b1.toString());
PropertyInfo pc1 = new PropertyInfo();
pc1.setName("UserType");
pc1.setValue(c1);
System.out.println(c1+"this is integer****s");
System.out.println("new");
request.addProperty(pa1);
request.addProperty(pb1);
request.addProperty(pc1);
System.out.println("new2");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
System.out.println("new3");
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
System.out.println("new4");
try{
androidHttpTransport.call(SOAP_ACTION, envelope);
}
catch(Exception e)
{
System.out.println(e+" this is exception");
}
System.out.println("new5");
SoapObject response = (SoapObject)envelope.bodyIn;
result = response.getProperty(0).toString();
flag=false;
System.out.println(flag);
}catch (Exception e) {
// TODO: handle exception
flag=false;
}
}
while(flag);
return result;
}
///
Normally one uses the backslash character as the path separator in Windows. So:
ifstream file;
file.open("C:\\Demo.txt", ios::in);
Keep in mind that when written in C++ source code, you must use the double backslash because the backslash character itself means something special inside double quoted strings. So the above refers to the file C:\Demo.txt
.
Assuming I am understanding your question and setup correctly,
If you're trying to use the build number in your script, you have two options:
1) When calling ant, use: ant -Dbuild_parameter=${BUILD_NUMBER}
2) Change your script so that:
<property environment="env" />
<property name="build_parameter" value="${env.BUILD_NUMBER}"/>
an existing folder will FAIL with FileExists
Function FileExists(strFileName)
' Check if a file exists - returns True or False
use instead or in addition:
Function FolderExists(strFolderPath)
' Check if a path exists
Note
Mutation events have been deprecated since this post was written, and may not be supported by all browsers. Instead, use a mutation observer.
Yes you can. DOM L2 Events module defines mutation events; one of them - DOMAttrModified is the one you need. Granted, these are not widely implemented, but are supported in at least Gecko and Opera browsers.
Try something along these lines:
document.documentElement.addEventListener('DOMAttrModified', function(e){
if (e.attrName === 'style') {
console.log('prevValue: ' + e.prevValue, 'newValue: ' + e.newValue);
}
}, false);
document.documentElement.style.display = 'block';
You can also try utilizing IE's "propertychange" event as a replacement to DOMAttrModified
. It should allow to detect style
changes reliably.
You have an error in your syntax here:
this._possessions = new Thing[100]();
This doesn't create an "array of things". To create an array of things, you can simply use the array literal expression:
this._possessions = [];
Of the array constructor if you want to set the length:
this._possessions = new Array(100);
I have created a brief working example you can try in the playground.
module Entities {
class Thing {
}
export class Person {
private _name: string;
private _possessions: Thing[];
private _mostPrecious: Thing;
constructor (name: string) {
this._name = name;
this._possessions = [];
this._possessions.push(new Thing())
this._possessions[100] = new Thing();
}
}
}
try this query below:
Insert into tab1 (tab1.column1,tab1.column2)
select tab2.column1, 'hard coded value'
from tab2
where tab2.column='value';
It could be something like that:
var a = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
var arrays = [], size = 3;
while (a.length > 0)
arrays.push(a.splice(0, size));
console.log(arrays);
_x000D_
See splice Array's method.
to get current router in angular 8 just do this
import {ActivatedRoute} from '@angular/router';
then inject it in constructor like
constructor(private route: ActivatedRoute){}
if you want get current route then use this route.url
if you have multiply name route like /home/pages/list
and you wanna access individual then you can access each of like this route.url.value[0].path
value[0]
will give home, value[1]
will give you pages and value[2]
will give you list
No need to uninstall angular/cli.
C:\Users\yourusername\AppData\Roaming\npm
ng-v
again and should workUsing reversed(array) would be the likely best route.
>>> array = [1,2,3,4]
>>> for item in reversed(array):
>>> print item
Should you need to understand how could implement this without using the built in reversed
.
def reverse(a):
midpoint = len(a)/2
for item in a[:midpoint]:
otherside = (len(a) - a.index(item)) - 1
temp = a[otherside]
a[otherside] = a[a.index(item)]
a[a.index(item)] = temp
return a
This should take O(N) time.
I had similar issue, this is how it was solved
xyz@ip :~/formsProject_SVN$ svn resolved formsProj/templates/search
Resolved conflicted state of 'formsProj/templates/search'
Now update your project
xyz@ip:~/formsProject_SVN$ svn update
Updating '.':
Select: (mc) keep affected local moves, (r) mark resolved (breaks moves), (p) postpone, (q) quit resolution, (h) help: r (select "r" option to resolve)
Resolved conflicted state of 'formsProj/templates/search'
Summary of conflicts: Tree conflicts: 0 remaining (and 1 already resolved)
SET STATISTICS TIME ON
select count(1) from MyTable (nolock) -- table containing 1 million records.
SQL Server Execution Times:
CPU time = 31 ms, elapsed time = 36 ms.
select count(*) from MyTable (nolock) -- table containing 1 million records.
SQL Server Execution Times:
CPU time = 46 ms, elapsed time = 37 ms.
I've ran this hundreds of times, clearing cache every time.. The results vary from time to time as server load varies, but almost always count(*)
has higher cpu time.
Depends on your specific situation, but if the iframe can be deployed after the rest of the page's loading, you can simply use a query string, a la:
<iframe src="some_page.html?somedata=5&more=bacon"></iframe>
And then somewhere in some_page.html:
<script>
var params = location.href.split('?')[1].split('&');
data = {};
for (x in params)
{
data[params[x].split('=')[0]] = params[x].split('=')[1];
}
</script>
What you can do is select everything into a new instance of Course, and afterwards convert them to a List.
var qry = from a in obj.tbCourses
select new Course() {
Course.Property = a.Property
...
};
qry.toList<Course>();
You could also use Rails' with_indifferent_access
method so you could access the body with either symbols or strings.
value = '{"val":"test","val1":"test1","val2":"test2"}'
json = JSON.parse(value).with_indifferent_access
then
json[:val] #=> "test"
json["val"] #=> "test"
I discovered while following the above suggestions that for line in f: does not work for a pandas dataframe (not that anyone said it would) because the end of file in a dataframe is the last column, not the last row. for example if you have a data frame with 3 fields (columns) and 9 records (rows), the for loop will stop after the 3rd iteration, not after the 9th iteration. Teresa
use jquery : $("#id").css("background","red");
for a in range(1):
for b in range(3):
a = b*2
print(a)
As per your question, you want to iterate the outer loop with help of the inner loop.
In the inner loop, we are iterating the 3 digits which are in the multiple of 2, starting from 0.
Output:
0
2
4
Now we know what the actual error is can formulate an answer.
Not allowed to load local resource
is a Security exception built into Chrome and other modern browsers. The wording may be different but in some way shape or form they all have security exceptions in place to deal with this scenario.
In the past you could override certain settings or apply certain flags such as
--disable-web-security --allow-file-access-from-files --allow-file-access
in Chrome (See https://stackoverflow.com/a/22027002/692942)
It's there for a reason
At this point though it's worth pointing out that these security exceptions exist for good reason and trying to circumvent them isn't the best idea.
As you have access to Classic ASP already you could always build a intermediary page that serves the network based files. You do this using a combination of the ADODB.Stream
object and the Response.BinaryWrite()
method. Doing this ensures your network file locations are never exposed to the client and due to the flexibility of the script it can be used to load resources from multiple locations and multiple file types.
Here is a basic example (getfile.asp
);
<%
Option Explicit
Dim s, id, bin, file, filename, mime
id = Request.QueryString("id")
'id can be anything just use it as a key to identify the
'file to return. It could be a simple Case statement like this
'or even pulled from a database.
Select Case id
Case "TESTFILE1"
'The file, mime and filename can be built-up anyway they don't
'have to be hard coded.
file = "\\server\share\Projecten\Protocollen\346\Uitvoeringsoverzicht.xls"
mime = "application/vnd.ms-excel"
'Filename you want to display when downloading the resource.
filename = "Uitvoeringsoverzicht.xls"
'Assuming other files
Case ...
End Select
If Len(file & "") > 0 Then
Set s = Server.CreateObject("ADODB.Stream")
s.Type = adTypeBinary 'adTypeBinary = 1 See "Useful Links"
Call s.Open()
Call s.LoadFromFile(file)
bin = s.Read()
'Clean-up the stream and free memory
Call s.Close()
Set s = Nothing
'Set content type header based on mime variable
Response.ContentType = mime
'Control how the content is returned using the
'Content-Disposition HTTP Header. Using "attachment" forces the resource
'to prompt the client to download while "inline" allows the resource to
'download and display in the client (useful for returning images
'as the "src" of a <img> tag).
Call Response.AddHeader("Content-Disposition", "attachment;filename=" & filename)
Call Response.BinaryWrite(bin)
Else
'Return a 404 if there's no file.
Response.Status = "404 Not Found"
End If
%>
This example is pseudo coded and as such is untested.
This script can then be used in <a>
like this to return the resource;
<a href="/getfile.asp?id=TESTFILE1">Click Here</a>
The could take this approach further and consider (especially for larger files) reading the file in chunks using Response.IsConnected
to check whether the client is still there and s.EOS
property to check for the end of the stream while the chunks are being read. You could also add to the querystring parameters to set whether you want the file to return in-line or prompt to be downloaded.
Using METADATA
to Import DLL Constants - If you are having trouble getting adTypeBinary
to be recongnised, always better then just hard coding 1
.
Content-Disposition:What are the differences between “inline” and “attachment”? - Useful information about how Content-Disposition
behaves on the client.
Using the solution posted by Tim, I created this bash script to facilitate the process (root password is requested, but you can modify the script easily to ask for any other user):
#!/bin/bash
if [ "$1" == "" ];then
echo "Usage: $0 DATABASE TABLE [MYSQL EXTRA COMMANDS]"
exit
fi
DBNAME=$1
TABLE=$2
FNAME=$1.$2.csv
MCOMM=$3
echo "MySQL password:"
stty -echo
read PASS
stty echo
mysql -uroot -p$PASS $MCOMM $DBNAME -B -e "SELECT * FROM $TABLE;" | sed "s/'/\'/;s/\t/\",\"/g;s/^/\"/;s/$/\"/;s/\n//g" > $FNAME
It will create a file named: database.table.csv
according to dr. hipp in a recent list post:
CREATE TABLE whatever(
....
timestamp DATE DEFAULT (datetime('now','localtime')),
...
);
For floating point data, you can use the new ismembertol
function, which computes set membership with a specified tolerance. This is similar to the ismemberf
function found in the File Exchange except that it is now built-in to MATLAB. Example:
>> pi_estimate = 3.14159;
>> abs(pi_estimate - pi)
ans =
5.3590e-08
>> tol = 1e-7;
>> ismembertol(pi,pi_estimate,tol)
ans =
1
Yes, you can achieve this by using the following commands:
sqlite> .headers on
sqlite> .mode column
The result of a select on your table will then look like:
id foo bar age street address
---------- ---------- ---------- ---------- ---------- ----------
1 val1 val2 val3 val4 val5
2 val6 val7 val8 val9 val10
Direct value
should work just fine:
var sel = document.getElementsByName('item');
var sv = sel.value;
alert(sv);
The only reason your code might fail is when there is no item selected, then the selectedIndex
returns -1 and the code breaks.
I have talked to customer support and confirmed that this can not be done on github.com. They have passed the suggestion along to the Github team though, so hopefully it will be possible in the future. If so, I'll be sure to edit this answer.
Meanwhile, Rory O'Kane's answer is a brilliant alternative based on cloc
and a shallow repo clone.
Your problem is that String JSON = "http://www.json-generator.com/j/cglqaRcMSW?indent=4";
is not JSON
.
What you want to do is open an HTTP
connection to "http://www.json-generator.com/j/cglqaRcMSW?indent=4" and parse the JSON response.
String JSON = "http://www.json-generator.com/j/cglqaRcMSW?indent=4";
JSONObject jsonObject = new JSONObject(JSON); // <-- Problem here!
Will not open a connection to the site and retrieve the content.
After searching for this myself wanting several projects with shared dependencies to be DRYer, I’ve found:
require()
require()
bin
and man
paths to $PATH
npm link
(info) lets you use a local install as a source for globals? stick to the Node way and install locally
ref:
There's no need for a parent POM.
You can omit the distributionManagement part entirely in your poms and set it either on your build server or in settings.xml.
To do it on the build server, just pass to the mvn
command:
-DaltSnapshotDeploymentRepository=snapshots::default::https://YOUR_NEXUS_URL/snapshots
-DaltReleaseDeploymentRepository=releases::default::https://YOUR_NEXUS_URL/releases
See https://maven.apache.org/plugins/maven-deploy-plugin/deploy-mojo.html for details which options can be set.
It's also possible to set this in your settings.xml
.
Just create a profile there which is enabled and contains the property.
Example settings.xml:
<settings>
[...]
<profiles>
<profile>
<id>nexus</id>
<properties>
<altSnapshotDeploymentRepository>snapshots::default::https://YOUR_NEXUS_URL/snapshots</altSnapshotDeploymentRepository>
<altReleaseDeploymentRepository>releases::default::https://YOUR_NEXUS_URL/releases</altReleaseDeploymentRepository>
</properties>
</profile>
</profiles>
<activeProfiles>
<activeProfile>nexus</activeProfile>
</activeProfiles>
</settings>
Make sure that credentials for "snapshots" and "releases" are in the <servers>
section of your settings.xml
The properties altSnapshotDeploymentRepository and altReleaseDeploymentRepository are introduced with maven-deploy-plugin version 2.8. Older versions will fail with the error message
Deployment failed: repository element was not specified in the POM inside distributionManagement element or in -DaltDeploymentRepository=id::layout::url parameter
To fix this, you can enforce a newer version of the plug-in:
<build>
<pluginManagement>
<plugins>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8</version>
</plugin>
</plugins>
</pluginManagement>
</build>
Another alternative to restore outline when using the keyboard is to use :focus-visible
. However, this doesn't work on IE :https://caniuse.com/?search=focus-visible.
Here's an example of code which uses the UTL_FILE.PUT and UTL_FILE.PUT_LINE calls:
declare
fHandle UTL_FILE.FILE_TYPE;
begin
fHandle := UTL_FILE.FOPEN('my_directory', 'test_file', 'w');
UTL_FILE.PUT(fHandle, 'This is the first line');
UTL_FILE.PUT(fHandle, 'This is the second line');
UTL_FILE.PUT_LINE(fHandle, 'This is the third line');
UTL_FILE.FCLOSE(fHandle);
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Exception: SQLCODE=' || SQLCODE || ' SQLERRM=' || SQLERRM);
RAISE;
end;
The output from this looks like:
This is the first lineThis is the second lineThis is the third line
Share and enjoy.
The syntax for creating a new table is
CREATE TABLE new_table
AS
SELECT *
FROM old_table
This will create a new table named new_table
with whatever columns are in old_table
and copy the data over. It will not replicate the constraints on the table, it won't replicate the storage attributes, and it won't replicate any triggers defined on the table.
SELECT INTO
is used in PL/SQL when you want to fetch data from a table into a local variable in your PL/SQL block.
I did solved using this jquery for Github
<script src="http://code.jquery.com/jquery-migrate-1.0.0.js"></script>
Please Refer this link for more info. https://github.com/Studio-42/elFinder/issues/469
Use numpy. array. flatten() to convert a 2D NumPy array into a 1D array
print(array_2d)
array_1d = array_2d. flatten() flatten array_2d
print(array_1d)
This doesn't use jQuery UI, but does use jQuery, and may be useful for those who aren't using jQuery UI for whatever reason. Do it like so:
function showDialog(){
$('#dialog').show();
$('*').on('click',function(e){
$('#zoomer').hide();
});
}
$(document).ready(function(){
showDialog();
});
So, once I've shown a dialog, I add a click handler that only looks for the first click on anything.
Now, it would be nicer if I could get it to ignore clicks on anything on #dialog and its contents, but when I tried switching $('*') with $(':not("#dialog,#dialog *")'), it still detected #dialog clicks.
Anyway, I was using this purely for a photo lightbox, so it worked okay for that purpose.
/**
* Set cursor to end of text in edittext when user clicks Next on Keyboard.
*/
View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean b) {
if (b) {
((EditText) view).setSelection(((EditText) view).getText().length());
}
}
};
mEditFirstName.setOnFocusChangeListener(onFocusChangeListener);
mEditLastName.setOnFocusChangeListener(onFocusChangeListener);
It work good for me!
You can do this with JSONP like this:
function insertReply(content) {
document.getElementById('output').innerHTML = content;
}
// create script element
var script = document.createElement('script');
// assing src with callback name
script.src = 'http://url.to.json?callback=insertReply';
// insert script to document and load content
document.body.appendChild(script);
But source must be aware that you want it to call function passed as callback parameter to it.
With google API it would look like this:
function insertReply(content) {
document.getElementById('output').innerHTML = content;
}
// create script element
var script = document.createElement('script');
// assing src with callback name
script.src = 'https://www.googleapis.com/freebase/v1/text/en/bob_dylan?callback=insertReply';
// insert script to document and load content
document.body.appendChild(script);
Check how data looks like when you pass callback to google api: https://www.googleapis.com/freebase/v1/text/en/bob_dylan?callback=insertReply
Here is quite good explanation of JSONP: http://en.wikipedia.org/wiki/JSONP
use fastcopy, a free tool. it has a delete option that is a lot faster then the way windows deletes files.
More space:
android:letterSpacing="0.1"
Less space:
android:letterSpacing="-0.07"
Request.Redirect(url,false);
false
indicates whether execution of current page should terminate.
You may need to upgrade your mongo shell. I had version 2.4.9 of the mongo shell locally, and I got this error trying to connect to a mongo 3 database. Upgrading the shell version to 3 solved the problem.
if ($("#Password").val() != $("#ConfirmPassword").val()) {
alert("Passwords do not match.");
}
A JQuery approach that will eliminate needless code.
Are you looking for behavior similar to the x that shows up on the right side of text fields on an iphone that clears the text when tapped? It's called clearButtonMode there. Here is how to create that same functionality in an Android EditText view:
String value = "";//any text you are pre-filling in the EditText
final EditText et = new EditText(this);
et.setText(value);
final Drawable x = getResources().getDrawable(R.drawable.presence_offline);//your x image, this one from standard android images looks pretty good actually
x.setBounds(0, 0, x.getIntrinsicWidth(), x.getIntrinsicHeight());
et.setCompoundDrawables(null, null, value.equals("") ? null : x, null);
et.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (et.getCompoundDrawables()[2] == null) {
return false;
}
if (event.getAction() != MotionEvent.ACTION_UP) {
return false;
}
if (event.getX() > et.getWidth() - et.getPaddingRight() - x.getIntrinsicWidth()) {
et.setText("");
et.setCompoundDrawables(null, null, null, null);
}
return false;
}
});
et.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
et.setCompoundDrawables(null, null, et.getText().toString().equals("") ? null : x, null);
}
@Override
public void afterTextChanged(Editable arg0) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
});
I solved my problem doing the following:
First of all, I am a windows user, but i have faced similar issue. So, I am posting my solution here.
There is one simple reason why sometimes the .gitignore doesn`t work like it is supposed to. It is due to the EOL conversion behavior.
Here is a quick fix for that
Edit > EOL Conversion > Windows Format > Save
You can blame your text editor settings for that.
For example:
As i am a windows developer, I typically use Notepad++ for editing my text unlike Vim users.
So what happens is, when i open my .gitignore file using Notepad++, it looks something like this:
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
##
## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
# See https://help.github.com/ignore-files/ for more about ignoring files.
# User-specific files
*.suo
*.user
*.userosscache
*.sln.docstates
*.dll
*.force
# User-specific files (MonoDevelop/Xamarin Studio)
*.userprefs
If i open the same file using the default Notepad, this is what i get
## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. ## ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore # See https://help.github.com/ignore-files/ for more about ignoring files. # User-specific files *.suo *.user *.userosscache
So, you might have already guessed by looking at the output. Everything in the .gitignore has become a one liner, and since there is a ## in the start, it acts as if everything is commented.
The way to fix this is simple: Just open your .gitignore file with Notepad++ , then do the following
Edit > EOL Conversion > Windows Format > Save
The next time you open the same file with the windows default notepad, everything should be properly formatted. Try it and see if this works for you.
Also the scope is different between viewbag and temptdata. viewbag is based on first view (not shared between action methods) but temptdata can be shared between an action method and just one another.
Use
$ mysqladmin -u <db_user_name> -p create <db_name>
You will be prompted for password. Also make sure the mysql user you use has privileges to create database.
You can easily make this CSS Tool Tip through simple code :-
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
a.info{
position:relative; /*this is the key*/
color:#000;
top:100px;
left:50px;
text-decoration:none;
text-align:center;
}
a.info span{display: none}
a.info:hover span{ /*the span will display just on :hover state*/
display:block;
position:absolute;
top:-60px;
width:15em;
border:5px solid #0cf;
background-color:#cff; color:#000;
text-align: center;
padding:10px;
}
a.info:hover span:after{ /*the span will display just on :hover state*/
content:'';
position:absolute;
bottom:-11px;
width:10px;
height:10px;
border-bottom:5px solid #0cf;
border-right:5px solid #0cf;
background:#cff;
left:50%;
margin-left:-5px;
-moz-transform:rotate(45deg);
-webkit-transform:rotate(45deg);
transform:rotate(45deg);
}
</style>
</head>
<body>
<a href="#" class="info">Shailender Arora <span>TOOLTIP</span></a>
</div>
</body>
</html>
The terms "stress testing" and "load testing" are often used interchangeably by software test engineers but they are really quite different.
Stress testing
In Stress testing we tries to break the system under test by overwhelming its resources or by taking resources away from it (in which case it is sometimes called negative testing). The main purpose behind this madness is to make sure that the system fails and recovers gracefully -- this quality is known as recoverability. OR Stress testing is the process of subjecting your program/system under test (SUT) to reduced resources and then examining the SUT’s behavior by running standard functional tests. The idea of this is to expose problems that do not appear under normal conditions.For example, a multi-threaded program may work fine under normal conditions but under conditions of reduced CPU availability, timing issues will be different and the SUT will crash. The most common types of system resources reduced in stress testing are CPU, internal memory, and external disk space. When performing stress testing, it is common to call the tools which reduce these three resources EatCPU, EatMem, and EatDisk respectively.
While on the other hand Load Testing
In case of Load testing Load testing is the process of subjecting your SUT to heavy loads, typically by simulating multiple users( Using Load runner), where "users" can mean human users or virtual/programmatic users. The most common example of load testing involves subjecting a Web-based or network-based application to simultaneous hits by thousands of users. This is generally accomplished by a program which simulates the users. There are two main purposes of load testing: to determine performance characteristics of the SUT, and to determine if the SUT "breaks" gracefully or not.
In the case of a Web site, you would use load testing to determine how many users your system can handle and still have adequate performance, and to determine what happens with an extreme load — will the Web site generate a "too busy" message for users, or will the Web server crash in flames?
window.location
also affects to the frame,
the best form i found is:
parent.window.location.href
And the worse is:
parent.document.URL
I did a massive browser test, and some rare IE with several plugins get undefined with the second form.
You can override onViewCreated() which is called right after all views had been inflated. It's the right place to fill in your Fragment's member View
variables. Here's an example:
class GalleryFragment extends Fragment {
private Gallery gallery;
(...)
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
gallery = (Gallery) view.findViewById(R.id.gallery);
gallery.setAdapter(adapter);
super.onViewCreated(view, savedInstanceState);
}
}
Using ONLY css is impossbile. In fact, all form elements are impossible to customize to look in the same way on all browsers only with css. You can try niceforms though ;)
You can use just forEach
. No stream at all:
fruits.forEach(fruit -> fruit.setName(fruit.getName() + "s"));
To set a default value to a column, try this:
ALTER TABLE tb_TableName
ALTER COLUMN Record_Status SET DEFAULT 'default value'
I had this problem and just decided to rename one of the programs from python.exe to python2.7.exe. Now I can specify on command prompt which program to run easily without introducing any scripts or changing environmental paths. So i have two programs: python2.7 and python (the latter which is v.3.8 aka default).
Put your default.png in a UIImageView full screen as a subview on the top of your main view thus covering your other UI. Set a timer to remove it after x seconds (possibly with effects) now showing your application.
Use NSJSONSerialization:
NSDictionary *dict;
NSData *dataFromDict = [NSJSONSerialization dataWithJSONObject:dict
options:NSJSONWritingPrettyPrinted
error:&error];
NSDictionary *dictFromData = [NSJSONSerialization JSONObjectWithData:dataFromDict
options:NSJSONReadingAllowFragments
error:&error];
The latest returns id
, so its a good idea to check the returned object type after you cast (here i casted to NSDictionary).
We can use this method:
CONVERT(VARCHAR(10), GETDATE(), 120)
Last parameter changes the format to only to get time or date in specific formats.
you are getting math domain error for either one of the reason : either you are trying to use a negative number inside log function or a zero value.
position: absolute;
color: #ffffff;
font-weight: 500;
top: 0%;
left: 0%;
right: 0%;
text-align: center;
in AndroidManifest.xml set theme holo like this:
<activity
android:name="your Fragment or activity"
android:label="@string/xxxxxx"
android:theme="@android:style/Theme.Holo" >
I had to struggle for a little bit but I found a solution, I added
-Dsonar.coverage.exclusions=**/*.*
and the coverage metric was cancelled from the dashboard at all, so I realized that the problem was the path I was passing, not the property. In my case the path to exclude was java/org/acme/exceptions, so I used :
`-Dsonar.coverage.exclusions=**/exceptions/**/*.*`
and it worked, but since I don't have sub-folders it also works with
-Dsonar.coverage.exclusions=**/exceptions/*.*
If both "document.ready" variants are used they will both fire, in the order of appearance
$(function(){
alert('shorthand document.ready');
});
//try changing places
$(document).ready(function(){
alert('document.ready');
});
Yes, it is possible to run PowerShell through the run window. However, it would be burdensome and you will need to enter in the password for computer. This is similar to how you will need to set up when you run cmd:
runas /user:(ComputerName)\(local admin) powershell.exe
So a basic example would be:
runas /user:MyLaptop\[email protected] powershell.exe
You can find more information on this subject in Runas.
However, you could also do one more thing :
then your system will execute the elevated powershell.
Simply remove the line that rotates it one degree at a time and calls the script forever.
// Animate rotation with a recursive call
setTimeout(function() { rotate(++degree); },65);
Then pass the desired value into the function... in this example 45
for 45 degrees.
$(function() {
var $elie = $("#bkgimg");
rotate(45);
function rotate(degree) {
// For webkit browsers: e.g. Chrome
$elie.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
// For Mozilla browser: e.g. Firefox
$elie.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});
}
});
Change .css()
to .animate()
in order to animate the rotation with jQuery. We also need to add a duration for the animation, 5000 for 5 seconds. And updating your original function to remove some redundancy and support more browsers...
$(function() {
var $elie = $("#bkgimg");
rotate(45);
function rotate(degree) {
$elie.animate({
'-webkit-transform': 'rotate(' + degree + 'deg)',
'-moz-transform': 'rotate(' + degree + 'deg)',
'-ms-transform': 'rotate(' + degree + 'deg)',
'-o-transform': 'rotate(' + degree + 'deg)',
'transform': 'rotate(' + degree + 'deg)',
'zoom': 1
}, 5000);
}
});
EDIT: The standard jQuery CSS animation code above is not working because apparently, jQuery .animate()
does not yet support the CSS3 transforms
.
This jQuery plugin is supposed to animate the rotation:
Answer : I found this and wants to share it with you.
Sub Copier4()
Dim x As Integer
For x = 1 To ActiveWorkbook.Sheets.Count
'Loop through each of the sheets in the workbook
'by using x as the sheet index number.
ActiveWorkbook.Sheets(x).Copy _
After:=ActiveWorkbook.Sheets(ActiveWorkbook.Sheets.Count)
'Puts all copies after the last existing sheet.
Next
End Sub
But the question, can we use it with following code to rename the sheets, if yes, how can we do so?
Sub CreateSheetsFromAList()
Dim MyCell As Range, MyRange As Range
Set MyRange = Sheets("Summary").Range("A10")
Set MyRange = Range(MyRange, MyRange.End(xlDown))
For Each MyCell In MyRange
Sheets.Add After:=Sheets(Sheets.Count) 'creates a new worksheet
Sheets(Sheets.Count).Name = MyCell.Value ' renames the new worksheet
Next MyCell
End Sub
If your application is making heavy use of Date and Calendar objects, you really should use Joda Time, because java.util.Date
is mutable. java.util.Calendar
has performance problems when its fields get updated, and is clunky for datetime arithmetic.
If you save the excel file as a CSV file then you can import it into a mysql database using tools such as PHPMyAdmin
Im not sure if this would help in your situation, but a csv file either manually or programatically would be a lot easier to parse into a database than an excel file I would have thought.
EDIT: I would however suggest looking at the other answers rather than mine since @diEcho answer seems more appropriate.
First of all right click the tale select 'Edit All Rows', select 'Query Designer -> Pane -> SQL ', after that you can edit the query output in the grid.
Sed is a little ugly, you could do it elegantly like so:
hendry@i7 tmp$ cat foo
bar
candy
car
hendry@i7 tmp$ for i in `cat foo`; do echo ${i}bar; done
barbar
candybar
carbar
$(document).on('keypress','#typeyourid',function(e){
if($(e.target).prop('value').length>=10){
if(e.keyCode!=32)
{return false}
}})
Advantage is this works with type="number"
$('#message').css({ width: 550, height: 300, 'font-size': '8pt' });
I needed both the date and time and used:
mkdir %date%-%time:~0,2%.%time:~3,2%.%time:~6,2%
Which created a folder that looked like:
2018-10-23-17.18.34
The time had to be concatenated because it contained :
which is not allowed on Windows.
If you have a path with spaces you must surround it with quotation marks (").
Not sure if that's exactly what you're asking though?
It's been more than 10 years and not sure if anyone still finding this question or answer relevant.
But a quick workaround is just to wrap the asp control
within a html container
<div id="myElement" style="display: inline-block">
<asp:TextBox ID="textBox1" runat="server"></asp:TextBox>
</div>
Whenever the Javascript Event
is triggered, if it needs to be an event by the asp control
, just wrap the asp control
around the div
container.
<div id="testG">
<asp:Button ID="Button2" runat="server" CssClass="btn" Text="Activate" />
</div>
The jQuery Code is below:
$(document).ready(function () {
$("#testG").click(function () {
$("#myElement").css("display", "none");
});
});
An example on how to use that would be great. There is a couple of examples at the Qt forum, but you're right that the official documentation should be expanded.
QJsonDocument
on its own indeed doesn't produce anything, you will have to add the data to it. That's done through the QJsonObject
, QJsonArray
and QJsonValue
classes. The top-level item needs to be either an array or an object (because 1
is not a valid json document, while {foo: 1}
is.)
This post suggests that you should be able to get the IE Developer Toolbar to show you the XPath for an element you click on if you turn on the "select element by click" option. http://blog.balfes.net/?p=62
Alternatively this post suggests either bookmarklets, or IE debugbar: Equivalent of Firebug's "Copy XPath" in Internet Explorer?
By reading online (tables tutorial) it seems tables behave like arrays so you're looking for:
Way1
names = {'John', 'Joe', 'Steve'}
for i = 1,3 do print( names[i] ) end
Way2
names = {'John', 'Joe', 'Steve'}
for k,v in pairs(names) do print(v) end
Way1 uses the table index/key
, on your table names
each element has a key starting from 1, for example:
names = {'John', 'Joe', 'Steve'}
print( names[1] ) -- prints John
So you just make i
go from 1 to 3.
On Way2 instead you specify what table you want to run and assign a variable for its key and value for example:
names = {'John', 'Joe', myKey="myValue" }
for k,v in pairs(names) do print(k,v) end
prints the following:
1 John
2 Joe
myKey myValue
It's safe to just delete the source directory and compiled package file. Find the source directory under $GOPATH/src
and the package file under $GOPATH/pkg/<architecture>
, for example: $GOPATH/pkg/windows_amd64
.
replace()
method doesn't uses regex pattern whereas replaceAll()
method uses regex pattern. So replace()
performs faster than replaceAll()
.
You can use the -v
or --version
flag. For example
gem install bitclock -v '< 0.0.2'
To specify upper AND lower version boundaries you can specify the --version
flag twice
gem install bitclock -v '>= 0.0.1' -v '< 0.0.2'
or use the syntax (for example)
gem install bitclock -v '>= 0.0.1, < 0.0.2'
The other way to do it is
gem install bitclock:'>= 0.0.1'
but with the last option it is not possible to specify upper and lower bounderies simultaneously.
[gem 3.0.3 and ruby 2.6.6]