The answer for me was to also add this to my build.gradle
file:
configurations.all {
resolutionStrategy.eachDependency { details ->
if (details.requested.group == 'com.android.support'
&& !details.requested.name.contains('multidex') ) {
details.useVersion "26.1.0"
}
}
}
In my case, it was nessisary to enclose the resolution strategy in a configurations.all { .. }
block. I placed the configurations.all
block directly into my app/build.gradle
file (ie configurations.all
was not nested in anything else)
Open gradle-wrapper.properties
distributionUrl=https\://services.gradle.org/distributions/gradle-3.3-all.zip
change it to
distributionUrl=https\://services.gradle.org/distributions/gradle-4.4-all.zip
To replace the old version with the new one, you need to change the link for it. Type that command to terminal.
brew link --force openssl
Check the version of openssl again. It should be changed.
I encountered the same problem in Jupyter Notebook. Add this, and you are good to go.
import os
os.environ['PATH'] = os.environ['PATH']+';'+os.environ['CONDA_PREFIX']+r"\Library\bin\graphviz"
I sometimes encounter the same issue. I can only answer your second bullet, because I am not as expert in R as I am with other languages. I have found that the standard for
loop has some unexpected results. Say x = 0
for (i in 1:x) {
print(i)
}
The output is
[1] 1
[1] 0
Whereas with python, for example
for i in range(x):
print i
does nothing. The loop is not entered.
I expected that if x = 0
that in R, the loop would not be entered. However, 1:0
is a valid range of numbers. I have not yet found a good workaround besides having an if
statement wrapping the for
loop
It is not the asker's problem in this instance but the first troubleshooting step for a generic "AttributeError: __exit__" should be making sure the brackets are there, e.g.
with SomeContextManager() as foo:
#works because a new object is referenced...
not
with SomeContextManager as foo:
#AttributeError because the class is referenced
Catches me out from time to time and I end up here -__-
I created a category around UIButton to be able to set the background color of the button and set the state. You might find this useful.
@implementation UIButton (ButtonMagic)
- (void)setBackgroundColor:(UIColor *)backgroundColor forState:(UIControlState)state {
[self setBackgroundImage:[UIButton imageFromColor:backgroundColor] forState:state];
}
+ (UIImage *)imageFromColor:(UIColor *)color {
CGRect rect = CGRectMake(0, 0, 1, 1);
UIGraphicsBeginImageContext(rect.size);
CGContextRef context = UIGraphicsGetCurrentContext();
CGContextSetFillColorWithColor(context, [color CGColor]);
CGContextFillRect(context, rect);
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
This will be part of a set of helper categories I'm open sourcing this month.
Swift 2.2
extension UIImage {
static func fromColor(color: UIColor) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
}
Swift 3.0
extension UIImage {
static func from(color: UIColor) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor(color.cgColor)
context!.fill(rect)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img!
}
}
Use as
let img = UIImage.from(color: .black)
public extension UIView {
@available(iOS 10.0, *)
public func renderToImage(afterScreenUpdates: Bool = false) -> UIImage {
let rendererFormat = UIGraphicsImageRendererFormat.default()
rendererFormat.opaque = isOpaque
let renderer = UIGraphicsImageRenderer(size: bounds.size, format: rendererFormat)
let snapshotImage = renderer.image { _ in
drawHierarchy(in: bounds, afterScreenUpdates: afterScreenUpdates)
}
return snapshotImage
}
}
This fixes the math to scale to the max size in both width and height rather than just one depending on the width and height of the original.
- (UIImage *) scaleProportionalToSize: (CGSize)size
{
float widthRatio = size.width/self.size.width;
float heightRatio = size.height/self.size.height;
if(widthRatio > heightRatio)
{
size=CGSizeMake(self.size.width*heightRatio,self.size.height*heightRatio);
} else {
size=CGSizeMake(self.size.width*widthRatio,self.size.height*widthRatio);
}
return [self scaleToSize:size];
}
import UIKit
extension CALayer {
func makeSnapshot() -> UIImage? {
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(frame.size, false, scale)
defer { UIGraphicsEndImageContext() }
guard let context = UIGraphicsGetCurrentContext() else { return nil }
render(in: context)
let screenshot = UIGraphicsGetImageFromCurrentImageContext()
return screenshot
}
}
extension UIView {
func makeSnapshot() -> UIImage? {
if #available(iOS 10.0, *) {
let renderer = UIGraphicsImageRenderer(size: frame.size)
return renderer.image { _ in drawHierarchy(in: bounds, afterScreenUpdates: true) }
} else {
return layer.makeSnapshot()
}
}
}
let image = view.makeSnapshot()
Do not forget to add the solution code here
import UIKit
class ViewController: UIViewController {
@IBOutlet var viewForScreenShot: UIView!
@IBOutlet var screenShotRenderer: UIImageView!
@IBAction func makeViewScreenShotButtonTapped2(_ sender: UIButton) {
screenShotRenderer.image = viewForScreenShot.makeSnapshot()
}
}
Main.storyboard
<?xml version="1.0" encoding="UTF-8"?>
<document type="com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB" version="3.0" toolsVersion="11762" systemVersion="16C67" targetRuntime="iOS.CocoaTouch" propertyAccessControl="none" useAutolayout="YES" useTraitCollections="YES" colorMatched="YES" initialViewController="BYZ-38-t0r">
<device id="retina4_7" orientation="portrait">
<adaptation id="fullscreen"/>
</device>
<dependencies>
<deployment identifier="iOS"/>
<plugIn identifier="com.apple.InterfaceBuilder.IBCocoaTouchPlugin" version="11757"/>
<capability name="documents saved in the Xcode 8 format" minToolsVersion="8.0"/>
</dependencies>
<scenes>
<!--View Controller-->
<scene sceneID="tne-QT-ifu">
<objects>
<viewController id="BYZ-38-t0r" customClass="ViewController" customModule="stackoverflow_2214957" customModuleProvider="target" sceneMemberID="viewController">
<layoutGuides>
<viewControllerLayoutGuide type="top" id="y3c-jy-aDJ"/>
<viewControllerLayoutGuide type="bottom" id="wfy-db-euE"/>
</layoutGuides>
<view key="view" contentMode="scaleToFill" id="8bC-Xf-vdC">
<rect key="frame" x="0.0" y="0.0" width="375" height="667"/>
<autoresizingMask key="autoresizingMask" widthSizable="YES" heightSizable="YES"/>
<subviews>
<view contentMode="scaleToFill" translatesAutoresizingMaskIntoConstraints="NO" id="Acg-GO-mMN">
<rect key="frame" x="67" y="28" width="240" height="128"/>
<subviews>
<textField opaque="NO" clipsSubviews="YES" contentMode="scaleToFill" contentHorizontalAlignment="left" contentVerticalAlignment="center" borderStyle="roundedRect" textAlignment="natural" minimumFontSize="17" translatesAutoresizingMaskIntoConstraints="NO" id="4Fr-O3-56t">
<rect key="frame" x="72" y="49" width="96" height="30"/>
<constraints>
<constraint firstAttribute="height" constant="30" id="cLv-es-h7Q"/>
<constraint firstAttribute="width" constant="96" id="ytF-FH-gdm"/>
</constraints>
<nil key="textColor"/>
<fontDescription key="fontDescription" type="system" pointSize="14"/>
<textInputTraits key="textInputTraits"/>
</textField>
</subviews>
<color key="backgroundColor" red="0.0" green="0.47843137250000001" blue="1" alpha="0.49277611300000002" colorSpace="custom" customColorSpace="sRGB"/>
<color key="tintColor" white="0.66666666666666663" alpha="1" colorSpace="calibratedWhite"/>
<constraints>
<constraint firstItem="4Fr-O3-56t" firstAttribute="centerX" secondItem="Acg-GO-mMN" secondAttribute="centerX" id="egj-rT-Gz5"/>
<constraint firstItem="4Fr-O3-56t" firstAttribute="centerY" secondItem="Acg-GO-mMN" secondAttribute="centerY" id="ymi-Ll-WIV"/>
</constraints>
</view>
<button opaque="NO" contentMode="scaleToFill" contentHorizontalAlignment="center" contentVerticalAlignment="center" buttonType="roundedRect" lineBreakMode="middleTruncation" translatesAutoresizingMaskIntoConstraints="NO" id="SQq-IE-pvj">
<rect key="frame" x="109" y="214" width="157" height="30"/>
<state key="normal" title="make view screen shot"/>
<connections>
<action selector="makeViewScreenShotButtonTapped2:" destination="BYZ-38-t0r" eventType="touchUpInside" id="KSY-ec-uvA"/>
</connections>
</button>
<imageView userInteractionEnabled="NO" contentMode="scaleAspectFit" horizontalHuggingPriority="251" verticalHuggingPriority="251" translatesAutoresizingMaskIntoConstraints="NO" id="CEZ-Ju-Tpq">
<rect key="frame" x="67" y="269" width="240" height="128"/>
<constraints>
<constraint firstAttribute="width" constant="240" id="STo-iJ-rM4"/>
<constraint firstAttribute="height" constant="128" id="tfi-zF-zdn"/>
</constraints>
</imageView>
</subviews>
<color key="backgroundColor" red="0.95941069162436543" green="0.95941069162436543" blue="0.95941069162436543" alpha="1" colorSpace="custom" customColorSpace="sRGB"/>
<constraints>
<constraint firstItem="CEZ-Ju-Tpq" firstAttribute="top" secondItem="SQq-IE-pvj" secondAttribute="bottom" constant="25" id="6x1-iB-gKF"/>
<constraint firstItem="Acg-GO-mMN" firstAttribute="leading" secondItem="CEZ-Ju-Tpq" secondAttribute="leading" id="LUp-Be-FiC"/>
<constraint firstItem="SQq-IE-pvj" firstAttribute="top" secondItem="Acg-GO-mMN" secondAttribute="bottom" constant="58" id="Qu0-YT-k9O"/>
<constraint firstItem="Acg-GO-mMN" firstAttribute="centerX" secondItem="8bC-Xf-vdC" secondAttribute="centerX" id="Qze-zd-ajY"/>
<constraint firstItem="Acg-GO-mMN" firstAttribute="trailing" secondItem="CEZ-Ju-Tpq" secondAttribute="trailing" id="b1d-sp-GHD"/>
<constraint firstItem="SQq-IE-pvj" firstAttribute="centerX" secondItem="CEZ-Ju-Tpq" secondAttribute="centerX" id="qCL-AF-Cro"/>
<constraint firstItem="Acg-GO-mMN" firstAttribute="top" secondItem="y3c-jy-aDJ" secondAttribute="bottom" constant="8" symbolic="YES" id="u5Y-eh-oSG"/>
<constraint firstItem="CEZ-Ju-Tpq" firstAttribute="centerY" secondItem="8bC-Xf-vdC" secondAttribute="centerY" id="vkx-JQ-pOF"/>
</constraints>
</view>
<connections>
<outlet property="screenShotRenderer" destination="CEZ-Ju-Tpq" id="8QB-OE-ib6"/>
<outlet property="viewForScreenShot" destination="Acg-GO-mMN" id="jgL-yn-8kk"/>
</connections>
</viewController>
<placeholder placeholderIdentifier="IBFirstResponder" id="dkx-z0-nzr" sceneMemberID="firstResponder"/>
</objects>
<point key="canvasLocation" x="32.799999999999997" y="37.331334332833585"/>
</scene>
</scenes>
</document>
As other people have mentioned, ArrayList has a constructor that takes a collection of items, and adds all of them. Here's the documentation:
http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html#ArrayList%28java.util.Collection%29
So you need to do:
ArrayList<MyNode> myNodeList = new ArrayList<MyNode>(this.getVertices());
However, in another comment you said that was giving you a compiler error. It looks like your class MyGraph is a generic class. And so getVertices() actually returns type V, not type myNode.
I think your code should look like this:
public V getNode(int nodeId){
ArrayList<V> myNodeList = new ArrayList<V>(this.getVertices());
return myNodeList(nodeId);
}
But, that said it's a very inefficient way to extract a node. What you might want to do is store the nodes in a binary tree, then when you get a request for the nth node, you do a binary search.
Each node is named uniquely and knows who it is connected to. The List of connections allows for a Node to be connected to an arbitrary number of other nodes.
public class Node {
public String name;
public List<Edge> connections;
}
Each connection is directed, has a start and an end, and is weighted.
public class Edge {
public Node start;
public Node end;
public double weight;
}
A graph is just your collection of nodes. Instead of List<Node>
consider Map<String, Node>
for fast lookup by name.
public class Graph {
List<Node> nodes;
}
A by far easier approach is to set some layer attributes of the view on initialization:
self.layer.masksToBounds = NO;
self.layer.shadowOffset = CGSizeMake(-15, 20);
self.layer.shadowRadius = 5;
self.layer.shadowOpacity = 0.5;
You need to import QuartzCore.
#import <QuartzCore/QuartzCore.h>
UITableView has a field called 'indexPathsForVisibleRows' that you can use to animate the visible rows using the 'reloadItemsAtIndexPaths' method.
guard let indexPaths = tableView.indexPathsForVisibleRows
else { return }
self.tableView.layoutIfNeeded()
self.tableView.reloadItemsAtIndexPaths(indexPaths, animationStyle: .automatic)
My suggestion:
$http({
method: 'DELETE',
url: '/roles/' + roleid,
data: {
user: userId
},
headers: {
'Content-type': 'application/json;charset=utf-8'
}
})
.then(function(response) {
console.log(response.data);
}, function(rejection) {
console.log(rejection.data);
});
You need to use brackets when using the fileExists
step in an if
condition or assign the returned value to a variable
Using variable:
def exists = fileExists 'file'
if (exists) {
echo 'Yes'
} else {
echo 'No'
}
Using brackets:
if (fileExists('file')) {
echo 'Yes'
} else {
echo 'No'
}
Try to open Services Window, by writing services.msc
into Start->Run and hit Enter.
When window appears, then find SQL Browser service, right click and choose Properties, and then in dropdown list choose Automatic, or Manual, whatever you want, and click OK. Eventually, if not started immediately, you can again press right click on this service and click Start.
From Start | Run open a command window. Assuming your environmental variables are set correctly start with the following:
C:\>sqlplus /nolog
SQL*Plus: Release 10.2.0.1.0 - Production on Tue Aug 26 10:40:44 2008
Copyright (c) 1982, 2005, Oracle. All rights reserved.
SQL> connect
Enter user-name: system
Enter password: <enter password if will not be visible>
Connected.
SQL> Exec DBMS_XDB.SETHTTPPORT(3010); [Assuming you want to have HTTP going to this port]
PL/SQL procedure successfully completed.
SQL>quit
then open browser and use 3010 port.
# Problem: Given c1 and c2:
c1 = [1, 6, 7, 10, 13, 28, 32, 41, 58, 63]
c2 = [[13, 17, 18, 21, 32], [7, 11, 13, 14, 28], [1, 5, 6, 8, 15, 16]]
# how do you get c3 to be [[13, 32], [7, 13, 28], [1, 6]] ?
Here's one way to set c3
that doesn't involve sets:
c3 = []
for sublist in c2:
c3.append([val for val in c1 if val in sublist])
But if you prefer to use just one line, you can do this:
c3 = [[val for val in c1 if val in sublist] for sublist in c2]
It's a list comprehension inside a list comprehension, which is a little unusual, but I think you shouldn't have too much trouble following it.
I solve the problem. So simple. Syntax error.
But I also want to know how to pass a function with parameters to view....
Perhaps the simplest approach:
first = [1,2,3,4,5]
second = [6,7,8,9,10]
three=[]
for i in range(0,5):
three.append(first[i]+second[i])
print(three)
MVW stands for Model-View-Whatever.
For completeness, here are all the acronyms mentioned:
MVC - Model-View-Controller
MVP - Model-View-Presenter
MVVM - Model-View-ViewModel
MVW / MV* / MVx - Model-View-Whatever
And some more:
HMVC - Hierarchical Model-View-Controller
MMV - Multiuse Model View
MVA - Model-View-Adapter
MVI - Model-View-Intent
Use the following. It helped me.
document.getElementById('image_1').offsetTop
See also Get Styles.
Use byte[] ptext = String.getBytes("UTF-8");
instead of getBytes()
. getBytes()
uses so-called "default encoding", which may not be UTF-8.
I often just open the console and look for the solution in the objects methods. Quite often it's already there:
>>> a = "hello ' s"
>>> dir(a)
[ (....) 'partition', 'replace' (....)]
>>> a.replace("'", " ")
'hello s'
Short answer: Use string.replace()
.
If you want a "editable grid" i.e. a table like structure that allows you to make any of the rows a form, use CSS that mimics the TABLE tag's layout: display:table
, display:table-row
, and display:table-cell
.
There is no need to wrap your whole table in a form and no need to create a separate form and table for each apparent row of your table.
Try this instead:
<style>
DIV.table
{
display:table;
}
FORM.tr, DIV.tr
{
display:table-row;
}
SPAN.td
{
display:table-cell;
}
</style>
...
<div class="table">
<form class="tr" method="post" action="blah.html">
<span class="td"><input type="text"/></span>
<span class="td"><input type="text"/></span>
</form>
<div class="tr">
<span class="td">(cell data)</span>
<span class="td">(cell data)</span>
</div>
...
</div>
The problem with wrapping the whole TABLE in a FORM is that any and all form elements will be sent on submit (maybe that is desired but probably not). This method allows you to define a form for each "row" and send only that row of data on submit.
The problem with wrapping a FORM tag around a TR tag (or TR around a FORM) is that it's invalid HTML. The FORM will still allow submit as usual but at this point the DOM is broken. Note: Try getting the child elements of your FORM or TR with JavaScript, it can lead to unexpected results.
Note that IE7 doesn't support these CSS table styles and IE8 will need a doctype declaration to get it into "standards" mode: (try this one or something equivalent)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
Any other browser that supports display:table, display:table-row and display:table-cell should display your css data table the same as it would if you were using the TABLE, TR and TD tags. Most of them do.
Note that you can also mimic THEAD, TBODY, TFOOT by wrapping your row groups in another DIV with display: table-header-group
, table-row-group
and table-footer-group
respectively.
NOTE: The only thing you cannot do with this method is colspan.
Check out this illustration: http://jsfiddle.net/ZRQPP/
This works for DLLs locked by other processes. This routine will not find out for example that a text file is locked by a word process.
C#:
using System.Management;
using System.IO;
static class Module1
{
static internal ArrayList myProcessArray = new ArrayList();
private static Process myProcess;
public static void Main()
{
string strFile = "c:\\windows\\system32\\msi.dll";
ArrayList a = getFileProcesses(strFile);
foreach (Process p in a) {
Debug.Print(p.ProcessName);
}
}
private static ArrayList getFileProcesses(string strFile)
{
myProcessArray.Clear();
Process[] processes = Process.GetProcesses;
int i = 0;
for (i = 0; i <= processes.GetUpperBound(0) - 1; i++) {
myProcess = processes(i);
if (!myProcess.HasExited) {
try {
ProcessModuleCollection modules = myProcess.Modules;
int j = 0;
for (j = 0; j <= modules.Count - 1; j++) {
if ((modules.Item(j).FileName.ToLower.CompareTo(strFile.ToLower) == 0)) {
myProcessArray.Add(myProcess);
break; // TODO: might not be correct. Was : Exit For
}
}
}
catch (Exception exception) {
}
//MsgBox(("Error : " & exception.Message))
}
}
return myProcessArray;
}
}
VB.Net:
Imports System.Management
Imports System.IO
Module Module1
Friend myProcessArray As New ArrayList
Private myProcess As Process
Sub Main()
Dim strFile As String = "c:\windows\system32\msi.dll"
Dim a As ArrayList = getFileProcesses(strFile)
For Each p As Process In a
Debug.Print(p.ProcessName)
Next
End Sub
Private Function getFileProcesses(ByVal strFile As String) As ArrayList
myProcessArray.Clear()
Dim processes As Process() = Process.GetProcesses
Dim i As Integer
For i = 0 To processes.GetUpperBound(0) - 1
myProcess = processes(i)
If Not myProcess.HasExited Then
Try
Dim modules As ProcessModuleCollection = myProcess.Modules
Dim j As Integer
For j = 0 To modules.Count - 1
If (modules.Item(j).FileName.ToLower.CompareTo(strFile.ToLower) = 0) Then
myProcessArray.Add(myProcess)
Exit For
End If
Next j
Catch exception As Exception
'MsgBox(("Error : " & exception.Message))
End Try
End If
Next i
Return myProcessArray
End Function
End Module
I think what's happening, is that, since the wrapper id is relatively position, it just appears on the same position with the body tag, what you should do, is that you can add a Z-index to the wrapper id.
#wrapper {
margin: auto;
text-align: left;
width: 832px;
position: relative;
padding-top: 27px;
z-index: 99; /* added this line */
}
This should make layers above the transparent body tag.
Use:
SELECT t1.Notes,
t2.Name
FROM Table1 t1
JOIN Table2 t2 ON t1.Notes LIKE CONCAT('%', t2.Name ,'%')
$content = $_POST['content_name'];
$lines = explode("\n", $content);
foreach( $lines as $index => $line )
{
$lines[$index] = $line . '<br/>';
}
// $lines contains your lines
If still not works after adding MIME types, please check whether "Anonymous Authentication" is enable in Authentication section in the site and make sure to select "Application pool identity" as per the given screen shot.
Maybe you want set -e
:
www.davidpashley.com/articles/writing-robust-shell-scripts.html#id2382181:
This tells bash that it should exit the script if any statement returns a non-true return value. The benefit of using -e is that it prevents errors snowballing into serious issues when they could have been caught earlier. Again, for readability you may want to use set -o errexit.
@AbdulRahim answer is almost correct. But I suggest the function below as substitute (for futher reference):
function getXY(evt, element) {
var rect = element.getBoundingClientRect();
var scrollTop = document.documentElement.scrollTop?
document.documentElement.scrollTop:document.body.scrollTop;
var scrollLeft = document.documentElement.scrollLeft?
document.documentElement.scrollLeft:document.body.scrollLeft;
var elementLeft = rect.left+scrollLeft;
var elementTop = rect.top+scrollTop;
x = evt.pageX-elementLeft;
y = evt.pageY-elementTop;
return {x:x, y:y};
}
$('#main-canvas').mousemove(function(e){
var m=getXY(e, this);
console.log(m.x, m.y);
});
This solution is based on the one proposed by fei0x but it has the advantages that there is no need to join the value list of constants in the query and constants can be easily listed at the start of the query. It also works in recursive queries.
Basically, every constant is a single-value table declared in a WITH clause which can then be called anywhere in the remaining part of the query.
WITH
constant_1_str AS (VALUES ('Hello World')),
constant_2_int AS (VALUES (100))
SELECT *
FROM some_table
WHERE table_column = (table constant_1_str)
LIMIT (table constant_2_int)
Alternatively you can use SELECT * FROM constant_name
instead of TABLE constant_name
which might not be valid for other query languages different to postgresql.
I got a solution:
a) Example Internet:
![image info e.g. Alt](URL Internet to Images.jpg "Image Description")
b) Example local Image:
![image Info](file:///<Path to your File><image>.jpg "Image Description")
![image Info](file:///C:/Users/<name>/Pictures/<image>.jpg "Image Description")
TurboByte
More stable approach:
<form onsubmit="foo($("#formValueId").val());return false;">
<input type="text" id="formValueId"/>
<input type="submit" value="Text on the button"/>
</form>
The return false;
is to prevent actual form submit (assuming you want that).
You can't. The emulator does not support Bluetooth, as mentioned in the SDK's docs and several other places. Android emulator does not have bluetooth capabilities".
You can only use real devices.
Emulator Limitations
The functional limitations of the emulator include:
Refer to the documentation
You can simplify your code down to
url = "http://worldcup.kimonolabs.com/api/players?apikey=xxx"
json_obj = urllib2.urlopen(url).read
player_json_list = json.loads(json_obj)
for player in readable_json_list:
print player['firstName']
You were trying to access a list element using dictionary syntax. the equivalent of
foo = [1, 2, 3, 4]
foo["1"]
It can be confusing when you have lists of dictionaries and keeping the nesting in order.
If you are working in node.js with lusca try also this:
$.ajax({
url: "http://test.com",
type:"post"
headers: {'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')}
})
You can change the actual width/height attributes like this:
var theImg = document.getElementById('theImgId');
theImg.height = 150;
theImg.width = 150;
if (strstr(request, "favicon") != NULL) {
// contains
}
This is because of lack of Capability .... If you see the Inner Exception you will see this message
"Access is denied.
Access to speech functionality requires ID_CAP_SPEECH_RECOGNITION to be defined in the manifest."
So to get rid of this exception. turn on the capability for Speech Recognition from the Manifest file.
I had the same problem, and It solved my Problem. :)
oImg.setAttribute('width', '1px');
px
is for CSS only. Use either:
oImg.width = '1';
to set a width through HTML, or:
oImg.style.width = '1px';
to set it through CSS.
Note that old versions of IE don't create a proper image with document.createElement()
, and old versions of KHTML don't create a proper DOM Node with new Image()
, so if you want to be fully backwards compatible use something like:
// IEWIN boolean previously sniffed through eg. conditional comments
function img_create(src, alt, title) {
var img = IEWIN ? new Image() : document.createElement('img');
img.src = src;
if ( alt != null ) img.alt = alt;
if ( title != null ) img.title = title;
return img;
}
Also be slightly wary of document.body.appendChild
if the script may execute as the page is in the middle of loading. You can end up with the image in an unexpected place, or a weird JavaScript error on IE. If you need to be able to add it at load-time (but after the <body>
element has started), you could try inserting it at the start of the body using body.insertBefore(body.firstChild)
.
To do this invisibly but still have the image actually load in all browsers, you could insert an absolutely-positioned-off-the-page <div>
as the body's first child and put any tracking/preload images you don't want to be visible in there.
I had the same problem, with a database field with type "SET" which is an enum type.
I tried to add a value which was not in that list.
The value I tried to add had the decimal value 256, but the enum list only had 8 values.
1: 1 -> A
2: 2 -> B
3: 4 -> C
4: 8 -> D
5: 16 -> E
6: 32 -> F
7: 64 -> G
8: 128 -> H
So I just had to add the additional value to the field.
Reading this documentation entry helped me to understand the problem.
MySQL stores SET values numerically, with the low-order bit of the stored value corresponding to the first set member. If you retrieve a SET value in a numeric context, the value retrieved has bits set corresponding to the set members that make up the column value. For example, you can retrieve numeric values from a SET column like this:
mysql> SELECT set_col+0 FROM tbl_name; If a number is stored into a
If a number is stored into a SET column, the bits that are set in the binary representation of the number determine the set members in the column value. For a column specified as SET('a','b','c','d'), the members have the following decimal and binary values.
SET Member Decimal Value Binary Value
'a' 1 0001
'b' 2 0010
'c' 4 0100
'd' 8 1000
If you assign a value of 9 to this column, that is 1001 in binary, so the first and fourth SET value members 'a' and 'd' are selected and the resulting value is 'a,d'.
This can be done in WebKit-based browsers (such as Chrome and Safari) with only CSS:
::-webkit-scrollbar {
width: 2em;
height: 2em
}
::-webkit-scrollbar-button {
background: #ccc
}
::-webkit-scrollbar-track-piece {
background: #888
}
::-webkit-scrollbar-thumb {
background: #eee
}?
References:
In batch file:
1 @echo off(solo)=>output nothing
2 echo off(solo)=> the “echo off” shows in the command line
3 echo off(then echo something) =>
4 @echo off(then echo something)=>
See, echo off(solo), means no output in the command line, but itself shows; @echo off(solo), means no output in the command line, neither itself;
This might not exactly answer your question, but we're using the 3GP or 3GP2 file format. Better even to use the rtsp protocol, but the Android browser will also recognize the 3GP file format.
You can use something like
self.location = URL_OF_YOUR_3GP_FILE
to trigger the video player. The file will be streamed and after playback ends, handling is returned to the browser.
For me this solves a lot of problems with current video tag implementation on android devices.
I had to use a wildcard route at the end of my routes array.
{ path: '**', redirectTo: 'home' }
And the error was resolved.
Without jQuery:
document.getElementById('file').onchange = function(){
var file = this.files[0];
var reader = new FileReader();
reader.onload = function(progressEvent){
// Entire file
console.log(this.result);
// By lines
var lines = this.result.split('\n');
for(var line = 0; line < lines.length; line++){
console.log(lines[line]);
}
};
reader.readAsText(file);
};
HTML:
<input type="file" name="file" id="file">
Remember to put your javascript code after the file field is rendered.
Not very technical answer but just letting you know.
For easy stuff like printing you can define a sort of function in your preprocessors like
#define print(x) cout << x << endl
I needed to explicitly add POST in the CURL command:
curl -X POST http://<user>:<token>@<server>/safeRestart
I also have the SafeRestart Plugin installed, in case that makes a difference.
If you are looking for the last row of a column, use:
Sub SelectFirstColumn()
SelectEntireColumn (1)
End Sub
Sub SelectSecondColumn()
SelectEntireColumn (2)
End Sub
Sub SelectEntireColumn(columnNumber)
Dim LastRow
Sheets("sheet1").Select
LastRow = ActiveSheet.Columns(columnNumber).SpecialCells(xlLastCell).Row
ActiveSheet.Range(Cells(1, columnNumber), Cells(LastRow, columnNumber)).Select
End Sub
Other commands you will need to get familiar with are copy and paste commands:
Sub CopyOneToTwo()
SelectEntireColumn (1)
Selection.Copy
Sheets("sheet1").Select
ActiveSheet.Range("B1").PasteSpecial Paste:=xlPasteValues
End Sub
Finally, you can reference worksheets in other workbooks by using the following syntax:
Dim book2
Set book2 = Workbooks.Open("C:\book2.xls")
book2.Worksheets("sheet1")
For username is same with some modification:
$user=$this->__('Welcome, %s!', Mage::getSingleton('customer/session')->getCustomer()->getName());
echo $user;
function include(file){
return new Promise(function(resolve, reject){
var script = document.createElement('script');
script.src = file;
script.type ='text/javascript';
script.defer = true;
document.getElementsByTagName('head').item(0).appendChild(script);
script.onload = function(){
resolve()
}
script.onerror = function(){
reject()
}
})
/*I HAVE MODIFIED THIS TO BE PROMISE-BASED
HOW TO USE THIS FUNCTION
include('js/somefile.js').then(function(){
console.log('loaded');
},function(){
console.log('not loaded');
})
*/
}
I stumbled upon this question b/c I was trying to find the next sequence value by table. This didn't answer my question however this is how its done, and it may help those looking for the sequence value not by name but by table:
SELECT nextval(pg_get_serial_sequence('<your_table>', 'id')) AS new_id;
Hope it helps :)
def is_float(s):
if s is None:
return False
if len(s) == 0:
return False
digits_count = 0
dots_count = 0
signs_count = 0
for c in s:
if '0' <= c <= '9':
digits_count += 1
elif c == '.':
dots_count += 1
elif c == '-' or c == '+':
signs_count += 1
else:
return False
if digits_count == 0:
return False
if dots_count > 1:
return False
if signs_count > 1:
return False
return True
anUnicode.encode('encoding') results in a string object and can be called on a unicode object
aString.decode('encoding') results in an unicode object and can be called on a string, encoded in given encoding.
Some more explanations:
You can create some unicode object, which doesn't have any encoding set. The way it is stored by Python in memory is none of your concern. You can search it, split it and call any string manipulating function you like.
But there comes a time, when you'd like to print your unicode object to console or into some text file. So you have to encode it (for example - in UTF-8), you call encode('utf-8') and you get a string with '\u<someNumber>' inside, which is perfectly printable.
Then, again - you'd like to do the opposite - read string encoded in UTF-8 and treat it as an Unicode, so the \u360 would be one character, not 5. Then you decode a string (with selected encoding) and get brand new object of the unicode type.
Just as a side note - you can select some pervert encoding, like 'zip', 'base64', 'rot' and some of them will convert from string to string, but I believe the most common case is one that involves UTF-8/UTF-16 and string.
Yes you can change it. but in api 22 and above, using NotificationCompat.Builder and setColorized(true) :
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, context.getPackageName())
.setContentTitle(title)
.setContentText(message)
.setSmallIcon(icon, level)
.setLargeIcon(largeIcon)
.setContentIntent(intent)
.setColorized(true)
.setDefaults(0)
.setCategory(Notification.CATEGORY_SERVICE)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setPriority(NotificationCompat.PRIORITY_HIGH);
You could use .each()
with .children()
and a selector within the parenthesis:
//Grab Each Instance of Box.
$(".box").each(function(i){
//For Each Instance, grab a child called .something1. Fade It Out.
$(this).children(".something1").fadeOut();
});
From the research that I've done, there doesn't appear to be any documentation available for the API you're using. Depending on the data you're trying to get, I'd recommend using Yahoo's YQL API for accessing Yahoo Finance (An example can be found here). Alternatively, you could try using this well documented way to get CSV data from Yahoo Finance.
EDIT:
There has been some discussion on the Yahoo developer forums and it looks like there is no documentation (emphasis mine):
The reason for the lack of documentation is that we don't have a Finance API. It appears some have reverse engineered an API that they use to pull Finance data, but they are breaking our Terms of Service (no redistribution of Finance data) in doing this so I would encourage you to avoid using these webservices.
At the same time, the URL you've listed can be accessed using the YQL console, though I'm not savvy enough to know how to extract URL parameters with it.
string AssemblyID = Assembly.GetEntryAssembly().GetCustomAttribute<GuidAttribute>().Value;
or, VB.NET:
Dim AssemblyID As String = Assembly.GetEntryAssembly.GetCustomAttribute(Of GuidAttribute).Value
You can run the client like this ...
puppet agent --test --debug --noop
with that command you get all the output you can get.
excerpt puppet agent help* --test:
Enable the most common options used for testing. These are 'onetime',
'verbose', 'ignorecache', 'no-daemonize', 'no-usecacheonfailure',
'detailed-exitcodes', 'no-splay', and 'show_diff'.
NOTE: No need to include --verbose
when you use the --test|-t
switch, it implies the --verbose
as well.
I'm surprised nobody has mentioned it before, but FindBin::libs will always find your libs as it searches in all reasonable places relative to the location of your script.
#!/usr/bin/perl
use FindBin::libs;
use <your lib>;
Just do this
props.history.push('/link')
this.props.history.push('/link')
Example:
<button onClick={()=>{props.history.push('/link')}} >Press</button>
react-router-dom: 5.2.0,
react: 16.12.0
I have the same problem with a footer I'm trying to divide up. I found that this worked for me by trying few of above suggestions combined:
footer div ul {
list-style-position: inside;
padding-left: 0;
}
This seems to keep it to the left under my h1 and the bullet points inside the div rather than outside to the left.
It is possible for the TCP socket to be "closing" and your code to not have yet been notified.
Here is a animation for the life cycle. http://tcp.cs.st-andrews.ac.uk/index.shtml?page=connection_lifecycle
Basically, the connection was closed by the client. You already have throws IOException
and SocketException
extends IOException
. This is working just fine. You just need to properly handle IOException
because it is a normal part of the api.
EDIT: The RST
packet occurs when a packet is received on a socket which does not exist or was closed. There is no difference to your application. Depending on the implementation the reset
state may stick and closed
will never officially occur.
I found Code Rocket to be very useful - http://www.getcoderocket.com/
From their website: "Code Rocket is an innovative tool that reveals the inner workings of C#, ... and C/C++ code, for Visual Studio... It makes documentation a seamlessly integrated part of the software development process, plugging directly into your development IDE with minimal overheads, delivering powerful benefits from day one."
This will work
<div style="width:800px;">
<div style="width:300px; float:left;"></div>
<div style="width:300px; float:right;"></div>
</div>
<div style="clear: both;"></div>
On the Mac:
Instead of JAVA_OPTS
and MAVEN_OPTS
, use _JAVA_OPTIONS instead. This works!
A DLL uses the PE executable format, and it's not too tricky to read that information out of the file.
See this MSDN article on the PE File Format for an overview. You need to read the MS-DOS header, then read the IMAGE_NT_HEADERS structure. This contains the IMAGE_FILE_HEADER structure which contains the info you need in the Machine member which contains one of the following values
This information should be at a fixed offset in the file, but I'd still recommend traversing the file and checking the signature of the MS-DOS header and the IMAGE_NT_HEADERS to be sure you cope with any future changes.
You can also use the ImageHelp API to do this - load the DLL with LoadImage and you'll get a LOADED_IMAGE structure which will contain a pointer to an IMAGE_NT_HEADERS structure. Deallocate the LOADED_IMAGE with ImageUnload.
Here's rough Perl script which gets the job done. It checks the file has a DOS header, then reads the PE offset from the IMAGE_DOS_HEADER 60 bytes into the file.
It then seeks to the start of the PE part, reads the signature and checks it, and then extracts the value we're interested in.
#!/usr/bin/perl
#
# usage: petype <exefile>
#
$exe = $ARGV[0];
open(EXE, $exe) or die "can't open $exe: $!";
binmode(EXE);
if (read(EXE, $doshdr, 64)) {
($magic,$skip,$offset)=unpack('a2a58l', $doshdr);
die("Not an executable") if ($magic ne 'MZ');
seek(EXE,$offset,SEEK_SET);
if (read(EXE, $pehdr, 6)){
($sig,$skip,$machine)=unpack('a2a2v', $pehdr);
die("No a PE Executable") if ($sig ne 'PE');
if ($machine == 0x014c){
print "i386\n";
}
elsif ($machine == 0x0200){
print "IA64\n";
}
elsif ($machine == 0x8664){
print "AMD64\n";
}
else{
printf("Unknown machine type 0x%lx\n", $machine);
}
}
}
close(EXE);
In AndroidManifest.xml, don't forget to set:
android:windowSoftInputMode="adjustResize"
and for RelativeLayout inside ScrollView ,set :
android:layout_gravity="center" or android:layout_gravity="bottom"
it will be okay
I needed to load dynamic number of google maps, with dynamic locations. So I ended up with something like this. Hope it helps. I add LatLng as data-attribute on map div.
So, just create divs with class "maps". Every map canvas can than have a various IDs and LatLng like this. Of course you can set up various data attributes for zoom and so...
Maybe the code might be cleaner, but it works for me pretty well.
<div id="map123" class="maps" data-gps="46.1461154,17.1580882"></div>
<div id="map456" class="maps" data-gps="45.1461154,13.1080882"></div>
<script>
var map;
function initialize() {
// Get all map canvas with ".maps" and store them to a variable.
var maps = document.getElementsByClassName("maps");
var ids, gps, mapId = '';
// Loop: Explore all elements with ".maps" and create a new Google Map object for them
for(var i=0; i<maps.length; i++) {
// Get ID of single div
mapId = document.getElementById(maps[i].id);
// Get LatLng stored in data attribute.
// !!! Make sure there is no space in data-attribute !!!
// !!! and the values are separated with comma !!!
gps = mapId.getAttribute('data-gps');
// Convert LatLng to an array
gps = gps.split(",");
// Create new Google Map object for single canvas
map = new google.maps.Map(mapId, {
zoom: 15,
// Use our LatLng array bellow
center: new google.maps.LatLng(parseFloat(gps[0]), parseFloat(gps[1])),
mapTypeId: 'roadmap',
mapTypeControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.RIGHT_TOP
}
});
// Create new Google Marker object for new map
var marker = new google.maps.Marker({
// Use our LatLng array bellow
position: new google.maps.LatLng(parseFloat(gps[0]), parseFloat(gps[1])),
map: map
});
}
}
</script>
I think with np.array()
you can only create C like though you mention the order, when you check using np.isfortran()
it says false. but with np.ndarrray()
when you specify the order it creates based on the order provided.
On Linux you can use gitk for this.
It can be installed using "sudo apt-get install git-gui gitk". It can be used to see commits of a specific file by "gitk <Filename>".
IF your data won't overflow 4000 characters AND you're on SQL Server 2000 or compatibility level of 8 or SQL Server 2000:
UPDATE [CMS_DB_test].[dbo].[cms_HtmlText]
SET Content = CAST(REPLACE(CAST(Content as NVarchar(4000)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%'
For SQL Server 2005+:
UPDATE [CMS_DB_test].[dbo].[cms_HtmlText]
SET Content = CAST(REPLACE(CAST(Content as NVarchar(MAX)),'ABC','DEF') AS NText)
WHERE Content LIKE '%ABC%'
If we don't know the number of elements in the array and when the input is given by the user at the run time. Then we can write the code as
C CODE:
while(scanf("%d",&array[count])==1) {
count++;
}
C++ CODE:
while(cin>>a[count]) {
count++;
}
Now the count will be having the count of number of array elements which are entered.
You can disable the app using enable maintenance mode from the admin panel.
In my case it was Avast Antivirus interfering with the connection. Actions to disable this feature: Avast -> Settings-> Components -> Mail Shield (Customize) -> SSL scanning -> uncheck "Scan SSL connections".
Its a classical problem, when you scroll the modal popup generated on the screen stays at it place and does not scroll along, so the user might be blocked as he might not see the popup on his viewable screen.
The following link also provides CSS only code for generating a modal box along with its absolute position.
npm prune [[<@scope>/]<pkg>...] [--production] [--dry-run] [--json]
This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.
Extraneous packages are packages that are not listed on the parent package's dependencies list.
If the --production flag is specified or the NODE_ENV environment variable is set to production, this command will remove the packages specified in your devDependencies. Setting --no-production will negate NODE_ENV being set to production.
If the --dry-run flag is used then no changes will actually be made.
If the --json flag is used then the changes npm prune made (or would have made with --dry-run) are printed as a JSON object.
In normal operation with package-locks enabled, extraneous modules are pruned automatically when modules are installed and you'll only need this command with the --production flag.
If you've disabled package-locks then extraneous modules will not be removed and it's up to you to run npm prune from time-to-time to remove them.
npm dedupe
npm ddp
Searches the local package tree and attempts to simplify the overall structure by moving dependencies further up the tree, where they can be more effectively shared by multiple dependent packages.
For example, consider this dependency graph:
a
+-- b <-- depends on [email protected]
| `-- [email protected]
`-- d <-- depends on c@~1.0.9
`-- [email protected]
In this case, npm-dedupe will transform the tree to:
a
+-- b
+-- d
`-- [email protected]
Because of the hierarchical nature of node's module lookup, b and d will both get their dependency met by the single c package at the root level of the tree.
The deduplication algorithm walks the tree, moving each dependency as far up in the tree as possible, even if duplicates are not found. This will result in both a flat and deduplicated tree.
You don't have to use Tomcat installation as a server location. It is much easier just to copy the files in the ROOT folder.
Eclipse forgets to copy the default apps (ROOT, examples, etc.) when it creates a Tomcat folder inside the Eclipse workspace. Go to
C:\apache-tomcat-7.0.8\webapps
, R-click on the ROOT folder and copy it. Then go to your Eclipse workspace, go to the.metadata
folder, and search for "wtpwebapps". You should find something likeyour-eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps
(or../tmp1/wtpwebapps
if you already had another server registered in Eclipse). Go to thewtpwebapps
folder, R-click, and paste ROOT (say "yes" if asked if you want to merge/replace folders/files). Then reloadhttp://localhost/
to see the Tomcat welcome page.
Source: HTTP Status 404 error in tomcat
It is now 2019 and the TLS v1.3 has been released. According to Cloudflare, the server name indication (SNI aka the hostname) can be encrypted thanks to TLS v1.3. So, I told myself great! Let's see how it looks within the TCP packets of cloudflare.com So, I caught a "client hello" handshake packet from a response of the cloudflare server using Google Chrome as browser & wireshark as packet sniffer. I still can read the hostname in plain text within the Client hello packet as you can see below. It is not encrypted.
So, beware of what you can read because this is still not an anonymous connection. A middleware application between the client and the server could log every domain that are requested by a client.
So, it looks like the encryption of the SNI requires additional implementations to work along with TLSv1.3
UPDATE June 2020: It looks like the Encrypted SNI is initiated by the browser. Cloudflare has a page for you to check if your browser supports Encrypted SNI:
https://www.cloudflare.com/ssl/encrypted-sni/
At this point, I think Google chrome does not support it. You can activate Encrypted SNI in Firefox manually. When I tried it for some reason, it didn't work instantly. I restarted Firefox twice before it worked:
Type: about:config in the URL field.
Check if network.security.esni.enabled is true. Clear your cache / restart
Go to the website, I mentioned before.
As you can see VPN services are still useful today for people who want to ensure that a coffee shop owner does not log the list of websites that people visit.
In plain C you can use a pointer/size combination in your API.
void doSomething(MyStruct* mystruct, size_t numElements)
{
for (size_t i = 0; i < numElements; ++i)
{
MyStruct current = mystruct[i];
handleElement(current);
}
}
Using pointers is the closest to call-by-reference available in C.
$("#myModal").draggable({
handle: ".modal-header"
});
it works for me. I got it from there. if you give me thanks please give 70% to Andres Ilich
You use the JSON
class and then call the GetData()
function.
/// <summary>
/// This class encodes and decodes JSON strings.
/// Spec. details, see http://www.json.org/
///
/// JSON uses Arrays and Objects. These correspond here to the datatypes ArrayList and Hashtable.
/// All numbers are parsed to doubles.
/// </summary>
using System;
using System.Collections;
using System.Globalization;
using System.Text;
public class JSON
{
public const int TOKEN_NONE = 0;
public const int TOKEN_CURLY_OPEN = 1;
public const int TOKEN_CURLY_CLOSE = 2;
public const int TOKEN_SQUARED_OPEN = 3;
public const int TOKEN_SQUARED_CLOSE = 4;
public const int TOKEN_COLON = 5;
public const int TOKEN_COMMA = 6;
public const int TOKEN_STRING = 7;
public const int TOKEN_NUMBER = 8;
public const int TOKEN_TRUE = 9;
public const int TOKEN_FALSE = 10;
public const int TOKEN_NULL = 11;
private const int BUILDER_CAPACITY = 2000;
/// <summary>
/// Parses the string json into a value
/// </summary>
/// <param name="json">A JSON string.</param>
/// <returns>An ArrayList, a Hashtable, a double, a string, null, true, or false</returns>
public static object JsonDecode(string json)
{
bool success = true;
return JsonDecode(json, ref success);
}
/// <summary>
/// Parses the string json into a value; and fills 'success' with the successfullness of the parse.
/// </summary>
/// <param name="json">A JSON string.</param>
/// <param name="success">Successful parse?</param>
/// <returns>An ArrayList, a Hashtable, a double, a string, null, true, or false</returns>
public static object JsonDecode(string json, ref bool success)
{
success = true;
if (json != null) {
char[] charArray = json.ToCharArray();
int index = 0;
object value = ParseValue(charArray, ref index, ref success);
return value;
} else {
return null;
}
}
/// <summary>
/// Converts a Hashtable / ArrayList object into a JSON string
/// </summary>
/// <param name="json">A Hashtable / ArrayList</param>
/// <returns>A JSON encoded string, or null if object 'json' is not serializable</returns>
public static string JsonEncode(object json)
{
StringBuilder builder = new StringBuilder(BUILDER_CAPACITY);
bool success = SerializeValue(json, builder);
return (success ? builder.ToString() : null);
}
protected static Hashtable ParseObject(char[] json, ref int index, ref bool success)
{
Hashtable table = new Hashtable();
int token;
// {
NextToken(json, ref index);
bool done = false;
while (!done) {
token = LookAhead(json, index);
if (token == JSON.TOKEN_NONE) {
success = false;
return null;
} else if (token == JSON.TOKEN_COMMA) {
NextToken(json, ref index);
} else if (token == JSON.TOKEN_CURLY_CLOSE) {
NextToken(json, ref index);
return table;
} else {
// name
string name = ParseString(json, ref index, ref success);
if (!success) {
success = false;
return null;
}
// :
token = NextToken(json, ref index);
if (token != JSON.TOKEN_COLON) {
success = false;
return null;
}
// value
object value = ParseValue(json, ref index, ref success);
if (!success) {
success = false;
return null;
}
table[name] = value;
}
}
return table;
}
protected static ArrayList ParseArray(char[] json, ref int index, ref bool success)
{
ArrayList array = new ArrayList();
// [
NextToken(json, ref index);
bool done = false;
while (!done) {
int token = LookAhead(json, index);
if (token == JSON.TOKEN_NONE) {
success = false;
return null;
} else if (token == JSON.TOKEN_COMMA) {
NextToken(json, ref index);
} else if (token == JSON.TOKEN_SQUARED_CLOSE) {
NextToken(json, ref index);
break;
} else {
object value = ParseValue(json, ref index, ref success);
if (!success) {
return null;
}
array.Add(value);
}
}
return array;
}
protected static object ParseValue(char[] json, ref int index, ref bool success)
{
switch (LookAhead(json, index)) {
case JSON.TOKEN_STRING:
return ParseString(json, ref index, ref success);
case JSON.TOKEN_NUMBER:
return ParseNumber(json, ref index, ref success);
case JSON.TOKEN_CURLY_OPEN:
return ParseObject(json, ref index, ref success);
case JSON.TOKEN_SQUARED_OPEN:
return ParseArray(json, ref index, ref success);
case JSON.TOKEN_TRUE:
NextToken(json, ref index);
return true;
case JSON.TOKEN_FALSE:
NextToken(json, ref index);
return false;
case JSON.TOKEN_NULL:
NextToken(json, ref index);
return null;
case JSON.TOKEN_NONE:
break;
}
success = false;
return null;
}
protected static string ParseString(char[] json, ref int index, ref bool success)
{
StringBuilder s = new StringBuilder(BUILDER_CAPACITY);
char c;
EatWhitespace(json, ref index);
// "
c = json[index++];
bool complete = false;
while (!complete) {
if (index == json.Length) {
break;
}
c = json[index++];
if (c == '"') {
complete = true;
break;
} else if (c == '\\') {
if (index == json.Length) {
break;
}
c = json[index++];
if (c == '"') {
s.Append('"');
} else if (c == '\\') {
s.Append('\\');
} else if (c == '/') {
s.Append('/');
} else if (c == 'b') {
s.Append('\b');
} else if (c == 'f') {
s.Append('\f');
} else if (c == 'n') {
s.Append('\n');
} else if (c == 'r') {
s.Append('\r');
} else if (c == 't') {
s.Append('\t');
} else if (c == 'u') {
int remainingLength = json.Length - index;
if (remainingLength >= 4) {
// parse the 32 bit hex into an integer codepoint
uint codePoint;
if (!(success = UInt32.TryParse(new string(json, index, 4), NumberStyles.HexNumber, CultureInfo.InvariantCulture, out codePoint))) {
return "";
}
// convert the integer codepoint to a unicode char and add to string
s.Append(Char.ConvertFromUtf32((int)codePoint));
// skip 4 chars
index += 4;
} else {
break;
}
}
} else {
s.Append(c);
}
}
if (!complete) {
success = false;
return null;
}
return s.ToString();
}
protected static double ParseNumber(char[] json, ref int index, ref bool success)
{
EatWhitespace(json, ref index);
int lastIndex = GetLastIndexOfNumber(json, index);
int charLength = (lastIndex - index) + 1;
double number;
success = Double.TryParse(new string(json, index, charLength), NumberStyles.Any, CultureInfo.InvariantCulture, out number);
index = lastIndex + 1;
return number;
}
protected static int GetLastIndexOfNumber(char[] json, int index)
{
int lastIndex;
for (lastIndex = index; lastIndex < json.Length; lastIndex++) {
if ("0123456789+-.eE".IndexOf(json[lastIndex]) == -1) {
break;
}
}
return lastIndex - 1;
}
protected static void EatWhitespace(char[] json, ref int index)
{
for (; index < json.Length; index++) {
if (" \t\n\r".IndexOf(json[index]) == -1) {
break;
}
}
}
protected static int LookAhead(char[] json, int index)
{
int saveIndex = index;
return NextToken(json, ref saveIndex);
}
protected static int NextToken(char[] json, ref int index)
{
EatWhitespace(json, ref index);
if (index == json.Length) {
return JSON.TOKEN_NONE;
}
char c = json[index];
index++;
switch (c) {
case '{':
return JSON.TOKEN_CURLY_OPEN;
case '}':
return JSON.TOKEN_CURLY_CLOSE;
case '[':
return JSON.TOKEN_SQUARED_OPEN;
case ']':
return JSON.TOKEN_SQUARED_CLOSE;
case ',':
return JSON.TOKEN_COMMA;
case '"':
return JSON.TOKEN_STRING;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
case '-':
return JSON.TOKEN_NUMBER;
case ':':
return JSON.TOKEN_COLON;
}
index--;
int remainingLength = json.Length - index;
// false
if (remainingLength >= 5) {
if (json[index] == 'f' &&
json[index + 1] == 'a' &&
json[index + 2] == 'l' &&
json[index + 3] == 's' &&
json[index + 4] == 'e') {
index += 5;
return JSON.TOKEN_FALSE;
}
}
// true
if (remainingLength >= 4) {
if (json[index] == 't' &&
json[index + 1] == 'r' &&
json[index + 2] == 'u' &&
json[index + 3] == 'e') {
index += 4;
return JSON.TOKEN_TRUE;
}
}
// null
if (remainingLength >= 4) {
if (json[index] == 'n' &&
json[index + 1] == 'u' &&
json[index + 2] == 'l' &&
json[index + 3] == 'l') {
index += 4;
return JSON.TOKEN_NULL;
}
}
return JSON.TOKEN_NONE;
}
protected static bool SerializeValue(object value, StringBuilder builder)
{
bool success = true;
if (value is string) {
success = SerializeString((string)value, builder);
} else if (value is Hashtable) {
success = SerializeObject((Hashtable)value, builder);
} else if (value is ArrayList) {
success = SerializeArray((ArrayList)value, builder);
} else if ((value is Boolean) && ((Boolean)value == true)) {
builder.Append("true");
} else if ((value is Boolean) && ((Boolean)value == false)) {
builder.Append("false");
} else if (value is ValueType) {
// thanks to ritchie for pointing out ValueType to me
success = SerializeNumber(Convert.ToDouble(value), builder);
} else if (value == null) {
builder.Append("null");
} else {
success = false;
}
return success;
}
protected static bool SerializeObject(Hashtable anObject, StringBuilder builder)
{
builder.Append("{");
IDictionaryEnumerator e = anObject.GetEnumerator();
bool first = true;
while (e.MoveNext()) {
string key = e.Key.ToString();
object value = e.Value;
if (!first) {
builder.Append(", ");
}
SerializeString(key, builder);
builder.Append(":");
if (!SerializeValue(value, builder)) {
return false;
}
first = false;
}
builder.Append("}");
return true;
}
protected static bool SerializeArray(ArrayList anArray, StringBuilder builder)
{
builder.Append("[");
bool first = true;
for (int i = 0; i < anArray.Count; i++) {
object value = anArray[i];
if (!first) {
builder.Append(", ");
}
if (!SerializeValue(value, builder)) {
return false;
}
first = false;
}
builder.Append("]");
return true;
}
protected static bool SerializeString(string aString, StringBuilder builder)
{
builder.Append("\"");
char[] charArray = aString.ToCharArray();
for (int i = 0; i < charArray.Length; i++) {
char c = charArray[i];
if (c == '"') {
builder.Append("\\\"");
} else if (c == '\\') {
builder.Append("\\\\");
} else if (c == '\b') {
builder.Append("\\b");
} else if (c == '\f') {
builder.Append("\\f");
} else if (c == '\n') {
builder.Append("\\n");
} else if (c == '\r') {
builder.Append("\\r");
} else if (c == '\t') {
builder.Append("\\t");
} else {
int codepoint = Convert.ToInt32(c);
if ((codepoint >= 32) && (codepoint <= 126)) {
builder.Append(c);
} else {
builder.Append("\\u" + Convert.ToString(codepoint, 16).PadLeft(4, '0'));
}
}
}
builder.Append("\"");
return true;
}
protected static bool SerializeNumber(double number, StringBuilder builder)
{
builder.Append(Convert.ToString(number, CultureInfo.InvariantCulture));
return true;
}
}
//parse and show entire json in key-value pair
Hashtable HTList = (Hashtable)JSON.JsonDecode("completejsonstring");
public void GetData(Hashtable HT)
{
IDictionaryEnumerator ienum = HT.GetEnumerator();
while (ienum.MoveNext())
{
if (ienum.Value is ArrayList)
{
ArrayList arnew = (ArrayList)ienum.Value;
foreach (object obj in arnew)
{
Hashtable hstemp = (Hashtable)obj;
GetData(hstemp);
}
}
else
{
Console.WriteLine(ienum.Key + "=" + ienum.Value);
}
}
}
From .Net 3.5 you can use LINQ extension method that (sometimes) makes code flow a bit better.
Usage looks like this:
using System.Linq;
// ...
public void My()
{
var myArray = new[] { "abc", "123", "zyx" };
List<string> myList = myArray.ToList();
}
PS. There's also ToArray()
method that works in other way.
To loop from current record to the end:
While Me.CurrentRecord < Me.Recordset.RecordCount
' ... do something to current record
' ...
DoCmd.GoToRecord Record:=acNext
Wend
To check if it is possible to go to next record:
If Me.CurrentRecord < Me.Recordset.RecordCount Then
' ...
End If
private static string GetSetting(string key)
{
return ConfigurationManager.AppSettings[key];
}
private static void SetSetting(string key, string value)
{
Configuration configuration =
ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
configuration.AppSettings.Settings[key].Value = value;
configuration.Save(ConfigurationSaveMode.Full, true);
ConfigurationManager.RefreshSection("appSettings");
}
You can use nonzero function. it returns the nonzero indices of the given input.
Easy Way
>>> (e > 15).nonzero()
(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
to see the indices more cleaner, use transpose
method:
>>> numpy.transpose((e>15).nonzero())
[[1 6]
[1 7]
[1 8]
[1 9]
[2 0]
...
Not Bad Way
>>> numpy.nonzero(e > 15)
(array([1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2]), array([6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]))
or the clean way:
>>> numpy.transpose(numpy.nonzero(e > 15))
[[1 6]
[1 7]
[1 8]
[1 9]
[2 0]
...
Adding to the above-accepted answer so that it helps those who are using tensorflow 2.0
import tensorflow as tf
# some data
c1 = tf.constant([[1, 1, 1], [2, 2, 2]], dtype=tf.float32)
c2 = tf.constant([[2, 2, 2], [3, 3, 3]], dtype=tf.float32)
c3 = tf.constant([[3, 3, 3], [4, 4, 4]], dtype=tf.float32)
# bake layers x1, x2, x3
x1 = tf.keras.layers.Dense(10)(c1)
x2 = tf.keras.layers.Dense(10)(c2)
x3 = tf.keras.layers.Dense(10)(c3)
# merged layer y1
y1 = tf.keras.layers.Concatenate(axis=1)([x1, x2])
# merged layer y2
y2 = tf.keras.layers.Concatenate(axis=1)([y1, x3])
# print info
print("-"*30)
print("x1", x1.shape, "x2", x2.shape, "x3", x3.shape)
print("y1", y1.shape)
print("y2", y2.shape)
print("-"*30)
Result:
------------------------------
x1 (2, 10) x2 (2, 10) x3 (2, 10)
y1 (2, 20)
y2 (2, 30)
------------------------------
This isn't as elegant or efficient as the accepted solution, but it's quick to write up. First, permute the array randomly, then select the first K elements. In python,
import numpy
N = 20
K = 5
idx = np.arange(N)
numpy.random.shuffle(idx)
print idx[:K]
I understand this isn't what OP asked for, but I still think it is worth to point out how to do it with printf. I almost always prefer using it over std::cout (even with no previous C background).
printf("%.2X", a);
'2' defines the precision, 'X' or 'x' defines case.
I had the same problem, I was storing session data in the database, the connection string had Encrypt=True in it, which I assume told the sql client to connect to the server in secure (SSL) mode, removing this helped!
In simple class declare context and get data from file from res folder
public class FileData
{
private Context context;
public FileData(Context current){
this.context = current;
}
void getData()
{
InputStream in = context.getResources().openRawResource(R.raw.file11);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
//write stuff to get Data
}
}
In the activity class declare like this
public class MainActivity extends AppCompatActivity
{
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FileData fileData=new FileData(this);
}
}
In Android Studio, Gradle is a custom build tool used to build android packages (apk files) by managing dependencies and providing custom build logic.
APK file (Android Application package) is a specially formatted zip file which contains
An apk file gets signed and pushed to the device using ADB(Android Debug Bridge) where it gets executed.
The easiest way is probably just to use list()
, but there is at least one other option as well:
s = "Word to Split"
wordlist = list(s) # option 1,
wordlist = [ch for ch in s] # option 2, list comprehension.
They should both give you what you need:
['W','o','r','d',' ','t','o',' ','S','p','l','i','t']
As stated, the first is likely the most preferable for your example but there are use cases that may make the latter quite handy for more complex stuff, such as if you want to apply some arbitrary function to the items, such as with:
[doSomethingWith(ch) for ch in s]
var requestedURL = "https://accounts.google.com/o/oauth2/token?code=" + code + "&client_id=" + client_id + "&client_secret=" + client_secret + "&redirect_uri=" + redirect_uri + "&grant_type=authorization_code";
HttpWebRequest authRequest = (HttpWebRequest)WebRequest.Create(requestedURL);
authRequest.ContentType = "application/x-www-form-urlencoded";
authRequest.Method = "POST";
//Set content length to 0
authRequest.ContentLength = 0;
WebResponse authResponseTwitter = authRequest.GetResponse();
The ContentLength
property contains the value to send as the Content-length
HTTP header with the request.
Any value other than -1 in the ContentLength
property indicates that the request uploads data and that only methods that upload data are allowed to be set in the Method property.
After the ContentLength
property is set to a value, that number of bytes must be written to the request stream that is returned by calling the GetRequestStream
method or both the BeginGetRequestStream
and the EndGetRequestStream
methods.
for more details click here
This code block uses universal time to convert current DateTime object then converts it back to local DateTime. Works perfect for me I hope it helps!
CreatedDate.ToUniversalTime().ToLocalTime();
SELECT *
FROM reservations
WHERE arrival >= '2012-01-01'
AND arrival < '2013-01-01'
;
BTW if the distribution of values indicates that an index scan will not be the worth (for example if all the values are in 2012), the optimiser could still choose a full table scan. YMMV. Explain is your friend.
I believe that join()
is just a convenience method. Try df1.merge(df2)
instead, which allows you to specify left_on
and right_on
:
In [30]: left.merge(right, left_on="key1", right_on="key2")
Out[30]:
key1 lval key2 rval
0 foo 1 foo 4
1 bar 2 bar 5
Use properties file. Here is a good start: http://www.mkyong.com/java/java-properties-file-examples/
This question is a bit old - as are the answers (and the tutorial as well)
The current api for setting a popupMenu in Swing is
myComponent.setComponentPopupMenu(myPopupMenu);
This way it will be shown automagically, both for mouse and keyboard triggers (the latter depends on LAF). Plus, it supports re-using the same popup across a container's children. To enable that feature:
myChild.setInheritsPopupMenu(true);
The answers seems a bit over complicated. I hope I didn't misunderstand the question.
If you simply want to open a fancy box from a click to an "A" tag. Just set your html to
<a id="my_fancybox" href="#contentdiv">click me</a>
The contents of your box will be inside of a div with id "contentdiv" and in your javascript you can initialize fancybox like this:
$('#my_fancybox').fancybox({
'autoScale': true,
'transitionIn': 'elastic',
'transitionOut': 'elastic',
'speedIn': 500,
'speedOut': 300,
'autoDimensions': true,
'centerOnScroll': true,
});
This will show a fancybox containing "contentdiv" when your anchor tag is clicked.
Many times when I switched to a new Android device, I do see no more logcat messages. Unfortunately, none of the above suggestions worked for me (Eclipse Photon 4.8.0).
I am now using this . It seems to work for different devices.
Do you need the list to be sorted in place, or just an ordered sequence of the contents of the list? The latter is easier:
var peopleInOrder = people.OrderBy(person => person.LastName);
To sort in place, you'd need an IComparer<Person>
or a Comparison<Person>
. For that, you may wish to consider ProjectionComparer
in MiscUtil.
(I know I keep bringing MiscUtil up - it just keeps being relevant...)
Today in my MS-Access 2003 with an ODBC tabla pointing to a SQL Server 2000 with sa password gave me the same error.
I defined a Primary Key on the table in the SQL Server database, and the issue was gone.
Do not use any reserved keyword as the start of any variable name: eg HOSTNAME will fail as HOST {TYPE|NAME} are reserved
Bash 4+ examples. Note: not using quotes will cause issues when words contain spaces, etc. Always quote in Bash, IMO.
Here are some examples in Bash 4+:
Example 1, check for 'yes' in string (case insensitive):
if [[ "${str,,}" == *"yes"* ]] ;then
Example 2, check for 'yes' in string (case insensitive):
if [[ "$(echo "$str" | tr '[:upper:]' '[:lower:]')" == *"yes"* ]] ;then
Example 3, check for 'yes' in string (case sensitive):
if [[ "${str}" == *"yes"* ]] ;then
Example 4, check for 'yes' in string (case sensitive):
if [[ "${str}" =~ "yes" ]] ;then
Example 5, exact match (case sensitive):
if [[ "${str}" == "yes" ]] ;then
Example 6, exact match (case insensitive):
if [[ "${str,,}" == "yes" ]] ;then
Example 7, exact match:
if [ "$a" = "$b" ] ;then
Enjoy.
I use this for every external link:
window.onload = function(){
var anchors = document.getElementsByTagName('a');
for (var i=0; i<anchors.length; i++){
if (anchors[i].hostname != window.location.hostname) {
anchors[i].setAttribute('target', '_blank');
}
}
}
It turns out that the problem really was that the address was busy - the busyness was caused by some other problems in how we are handling network communications. Your inputs have helped me figure this out. Thank you.
EDIT: to be specific, the problems in handling our network communications were that these status updates would be constantly re-sent if the first failed. It was only a matter of time until we had every distributed slave trying to send its status update at the same time, which was over-saturating our network.
in my case it's a maven project
delete the project from eclipse leaving the sources close eclipse delete from filesystem
.target/ .classpath .project .settings/ open eclipse Again Import Maven Projects
This solved the problem
If you're using go run
, do go run *.go
. It will automatically find all go files in the current working directory, compile and then run your main function.
Sometimes if you are using some simple login info like this: username: 'admin' and pass: 'admin', the hosting is seeing you as a potential Brute Force Attack through WP login file, and blocks you IP address or that particularly file.
I had that issue with ixwebhosting and just got that info from their support guy. They must unban your IP in this situation. And you must change your WP admin login info to something more secure.
That solved my problem.
You can disable DHE completely in your jdk, edit jre/lib/security/java.security and make sure DHE is disabled, eg. like
jdk.tls.disabledAlgorithms=SSLv3, DHE
.
if you use Windows 10, this is the directory:
C:\Users<UserName>\AppData\Local\
+
<ProjectName.exe_Url_somedata>\1.0.0.0<filename.config>
This approach has space overhead, but a simpler implementation:
Loop can be identified by storing nodes in a Map. And before putting the node; check if node already exists. If node already exists in the map then it means that Linked List has loop.
public boolean loopDetector(Node<E> first) {
Node<E> t = first;
Map<Node<E>, Node<E>> map = new IdentityHashMap<Node<E>, Node<E>>();
while (t != null) {
if (map.containsKey(t)) {
System.out.println(" duplicate Node is --" + t
+ " having value :" + t.data);
return true;
} else {
map.put(t, t);
}
t = t.next;
}
return false;
}
Step 1 is always to first determine where the problem lies. Your title and most of your question seem to suggest that you're running into quite a low length limit on the length of a string in JavaScript / on browsers, an improbably low limit. You're not. Consider:
var str;
document.getElementById('theButton').onclick = function() {
var build, counter;
if (!str) {
str = "0123456789";
build = [];
for (counter = 0; counter < 900; ++counter) {
build.push(str);
}
str = build.join("");
}
else {
str += str;
}
display("str.length = " + str.length);
};
Repeatedly clicking the relevant button keeps making the string longer. With Chrome, Firefox, Opera, Safari, and IE, I've had no trouble with strings more than a million characters long:
str.length = 9000 str.length = 18000 str.length = 36000 str.length = 72000 str.length = 144000 str.length = 288000 str.length = 576000 str.length = 1152000 str.length = 2304000 str.length = 4608000 str.length = 9216000 str.length = 18432000
...and I'm quite sure I could got a lot higher than that.
So it's nothing to do with a length limit in JavaScript. You haven't show your code for sending the data to the server, but most likely you're using GET
which means you're running into the length limit of a GET request, because GET
parameters are put in the query string. Details here.
You need to switch to using POST
instead. In a POST
request, the data is in the body of the request rather than in the URL, and can be very, very large indeed.
It seems to me the last line of your example code should simply be:
Task<Item> itsMe = o as Task<Item>;
Or am I missing something?
If you are using CollapsibleToolbarLayout
along with Toolbar
then you will need to set title in both the layouts
set your Toolbar as action bar in onCreate
method
protected void setUpToolBar() {
if (mToolbar != null) {
((HomeActivity) getActivity()).setSupportActionBar(mToolbar);
mToolbar.setTitleTextColor(Color.WHITE);
mToolbar.setTitle("List Detail");
mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity()
.getSupportFragmentManager().popBackStack();
}
});
((HomeActivity) getActivity()).getSupportActionBar()
.setDisplayHomeAsUpEnabled(true);
}
}
Later simply update title of toolbar using setTitle
method
mToolbar .setTitle(productFromShoppingList.getProductName()); mCollapsingToolbar.setTitle(productFromShoppingList.getProductName());
document.querySelectorAll
works pretty well and allows you to further narrow down your selection.
https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll
Create and edit the jupyter notebook config file with the following steps:
jupyter notebook --generate-config
notepad path_to_file/jupyter_notebook_config.py
to open it (change path_to_file
)#c.NotebookApp.browser = ''
to c.NotebookApp.browser = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
Jupyter notebook will now use Chrome.
EASY WAY -> Don't install openssl -> USE GIT BASH!
keytool -exportcert -alias androiddebugkey -keystore ~/.android/debug.keystore | openssl sha1 -binary | openssl base64
The default password is "android"
Most of us have Git Bash installed so this is my favorite way.
SHOW CREATE TABLE <tablename>\G
will format it much nicer compared to the output of
SHOW CREATE TABLE <tablename>;
The \G
trick is also useful to remember for many other queries/commands.
This is another way:
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int pos, long arg3) {
// TODO Auto-generated method stub
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
More accurate for Edge (do not include latest IE 15) is:
@supports (display:-ms-grid) { ... }
@supports (-ms-ime-align:auto) { ... }
works for all Edge versions (currently up to IE15).
You would naturally use Integer#to_s(2)
, String#to_i(2)
or "%b"
in a real program, but, if you're interested in how the translation works, this method calculates the binary representation of a given integer using basic operators:
def int_to_binary(x)
p = 0
two_p = 0
output = ""
while two_p * 2 <= x do
two_p = 2 ** p
output << ((two_p & x == two_p) ? "1" : "0")
p += 1
end
#Reverse output to match the endianness of %b
output.reverse
end
To check it works:
1.upto(1000) do |n|
built_in, custom = ("%b" % n), int_to_binary(n)
if built_in != custom
puts "I expected #{built_in} but got #{custom}!"
exit 1
end
puts custom
end
I think the usual use case is to call it when no exception was thrown in a negative test.
Something like the following pseudo-code:
test_addNilThrowsNullPointerException()
{
try {
foo.add(NIL); // we expect a NullPointerException here
fail("No NullPointerException"); // cause the test to fail if we reach this
} catch (NullNullPointerException e) {
// OK got the expected exception
}
}
As you see, that's actually a natural error ..
A typical construct for reading from an Unpickler object would be like this ..
try:
data = unpickler.load()
except EOFError:
data = list() # or whatever you want
EOFError is simply raised, because it was reading an empty file, it just meant End of File ..
Rails 4.x
When you already have users
and uploads
tables and wish to add a new relationship between them.
All you need to do is: just generate a migration using the following command:
rails g migration AddUserToUploads user:references
Which will create a migration file as:
class AddUserToUploads < ActiveRecord::Migration
def change
add_reference :uploads, :user, index: true
end
end
Then, run the migration using rake db:migrate
.
This migration will take care of adding a new column named user_id
to uploads
table (referencing id
column in users
table), PLUS it will also add an index on the new column.
UPDATE [For Rails 4.2]
Rails can’t be trusted to maintain referential integrity; relational databases come to our rescue here. What that means is that we can add foreign key constraints at the database level itself and ensure that database would reject any operation that violates this set referential integrity. As @infoget commented, Rails 4.2 ships with native support for foreign keys(referential integrity). It's not required but you might want to add foreign key(as it's very useful) to the reference that we created above.
To add foreign key to an existing reference, create a new migration to add a foreign key:
class AddForeignKeyToUploads < ActiveRecord::Migration
def change
add_foreign_key :uploads, :users
end
end
To create a completely brand new reference with a foreign key(in Rails 4.2), generate a migration using the following command:
rails g migration AddUserToUploads user:references
which will create a migration file as:
class AddUserToUploads < ActiveRecord::Migration
def change
add_reference :uploads, :user, index: true
add_foreign_key :uploads, :users
end
end
This will add a new foreign key to the user_id
column of the uploads
table. The key references the id
column in users
table.
NOTE: This is in addition to adding a reference so you still need to create a reference first then foreign key (you can choose to create a foreign key in the same migration or a separate migration file). Active Record only supports single column foreign keys and currently only mysql
, mysql2
and PostgreSQL
adapters are supported. Don't try this with other adapters like sqlite3
, etc. Refer to Rails Guides: Foreign Keys for your reference.
If, like me, your goal is get the database host and SID to generate a Oracle JDBC url, as
jdbc:oracle:thin:@<server_host>:1521:<instance_name>
the following commands will help:
Oracle query command to check the SID (or instance name):
select sys_context('userenv','instance_name') from dual;
Oracle query command to check database name (or server host):
select sys_context('userenv', 'server_host') from dual;
Att. Sergio Marcelo
Alternative: Stream.concat()
Stream.concat(map.values().stream(), listContainer.lst.stream())
.collect(Collectors.toList()
Below is working solution using NgModel
Add variable
public Phone:string;
In html add
<input class="input-width" [(ngModel)]="Phone" (keyup)="keyUpEvent($event)"
type="text" class="form-control" placeholder="Enter Mobile Number">
In Ts file
keyUpEvent(event: any) {
const pattern = /[0-9\+\-\ ]/;
let inputChar = String.fromCharCode(event.keyCode);
if (!pattern.test(inputChar)) {
// invalid character, prevent input
if(this.Phone.length>0)
{
this.Phone= this.Phone.substr(0,this.Phone.length-1);
}
}
}
Learn from Apple is the best way.
For example, Apple's keyboard notification:
extension UIResponder {
public class let keyboardWillShowNotification: NSNotification.Name
public class let keyboardDidShowNotification: NSNotification.Name
public class let keyboardWillHideNotification: NSNotification.Name
public class let keyboardDidHideNotification: NSNotification.Name
}
Now I learn from Apple:
extension User {
/// user did login notification
static let userDidLogInNotification = Notification.Name(rawValue: "User.userDidLogInNotification")
}
What's more, NSAttributedString.Key.foregroundColor
:
extension NSAttributedString {
public struct Key : Hashable, Equatable, RawRepresentable {
public init(_ rawValue: String)
public init(rawValue: String)
}
}
extension NSAttributedString.Key {
/************************ Attributes ************************/
@available(iOS 6.0, *)
public static let foregroundColor: NSAttributedString.Key // UIColor, default blackColor
}
Now I learn form Apple:
extension UIFont {
struct Name {
}
}
extension UIFont.Name {
static let SFProText_Heavy = "SFProText-Heavy"
static let SFProText_LightItalic = "SFProText-LightItalic"
static let SFProText_HeavyItalic = "SFProText-HeavyItalic"
}
usage:
let font = UIFont.init(name: UIFont.Name.SFProText_Heavy, size: 20)
Learn from Apple is the way everyone can do and can promote your code quality easily.
This will surely work:
UPDATE table1
SET table1.price=(SELECT table2.price
FROM table2
WHERE table2.id=table1.id AND table2.item=table1.item);
Try this snippet:
jQuery(function($) {
// Your code.
})
It worked for me, maybe it will help you too.
git stash list
to list your stashed changes.
git stash show
to see what n
is in the below commands.
git stash apply
to apply the most recent stash.
git stash apply stash@{n}
to apply an older stash.
https://git-scm.com/book/en/v2/Git-Tools-Stashing-and-Cleaning
You could implement a showfile function which takes in parameters of the data returned from the WEBApi, and a filename for the file you are trying to download. What I did was create a separate browser service identifies the user's browser and then handles the rendering of the file based on the browser. For instance if the target browser is chrome on an ipad, you have to use javascripts FileReader object.
FileService.showFile = function (data, fileName) {
var blob = new Blob([data], { type: 'application/pdf' });
if (BrowserService.isIE()) {
window.navigator.msSaveOrOpenBlob(blob, fileName);
}
else if (BrowserService.isChromeIos()) {
loadFileBlobFileReader(window, blob, fileName);
}
else if (BrowserService.isIOS() || BrowserService.isAndroid()) {
var url = URL.createObjectURL(blob);
window.location.href = url;
window.document.title = fileName;
} else {
var url = URL.createObjectURL(blob);
loadReportBrowser(url, window,fileName);
}
}
function loadFileBrowser(url, window, fileName) {
var iframe = window.document.createElement('iframe');
iframe.src = url
iframe.width = '100%';
iframe.height = '100%';
iframe.style.border = 'none';
window.document.title = fileName;
window.document.body.appendChild(iframe)
window.document.body.style.margin = 0;
}
function loadFileBlobFileReader(window, blob,fileName) {
var reader = new FileReader();
reader.onload = function (e) {
var bdata = btoa(reader.result);
var datauri = 'data:application/pdf;base64,' + bdata;
window.location.href = datauri;
window.document.title = fileName;
}
reader.readAsBinaryString(blob);
}
sudo chmod 777 DIR_NAME
cd DIR_NAME
git clone https://github.com/mygitusername/kivy.git
should work fine
You have to fetch that one record, it will contain the result of Count()
$result = $db->query("SELECT COUNT(*) FROM `table`");
$row = $result->fetch_row();
echo '#: ', $row[0];
Jacob Smullyan wrote a utility called pesterfish which uses effbot's ElementTree to convert XML to JSON.
I have done this in a project a long time ago. The code given below write a whole rows bold with specific column names and all of these columns are written in bold format.
private void WriteColumnHeaders(DataColumnCollection columnCollection, int row, int column)
{
// row represent particular row you want to bold its content.
for (i = 0; i < columnCollection.Count; i++)
{
DataColumn col = columnCollection[i];
xlWorkSheet.Cells[row, column + i + 1] = col.Caption;
// Some Font Styles
xlWorkSheet.Cells[row, column + i + 1].Style.Font.Bold = true;
xlWorkSheet.Cells[row, column + i + 1].Interior.Color = Color.FromArgb(192, 192, 192);
//xlWorkSheet.Columns[i + 1].ColumnWidth = xlWorkSheet.Columns[i+1].ColumnWidth + 10;
}
}
You must pass value of row 0 so that first row of your excel sheets have column headers with bold font size. Just change DataColumnCollection
to your columns name and change col.Caption
to specific column name.
Alternate
You may do this to cell of excel sheet you want bold.
xlWorkSheet.Cells[row, column].Style.Font.Bold = true;
just wanna add another easy way to do this: If your ImageButton remains its background and you don't set it to null, it will work like a normal button and will show the click animation while clicking exactly like other buttons.The way to hide the background while it is still there:
<ImageButton
android:id="@+id/imageButton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingBottom="1dp"
android:paddingLeft="1dp"
android:paddingRight="1dp"
android:paddingTop="1dp"
android:src="@drawable/squareicon" />
The paddings won't let the background be visible and make the button act like other buttons.
Alternative using the Stream API:
list.stream().reduce((first, second) -> second)
Results in an Optional of the last element.
To set the directory selected path and the retrieve the new directory:
dlgBrowseForLogDirectory.SelectedPath = m_LogDirectory;
if (dlgBrowseForLogDirectory.ShowDialog() == DialogResult.OK)
{
txtLogDirectory.Text = dlgBrowseForLogDirectory.SelectedPath;
}
Update:
These articles in my blog describe the differences between the methods in more detail:
NOT IN
vs. NOT EXISTS
vs. LEFT JOIN / IS NULL
: SQL Server
NOT IN
vs. NOT EXISTS
vs. LEFT JOIN / IS NULL
: PostgreSQL
NOT IN
vs. NOT EXISTS
vs. LEFT JOIN / IS NULL
: Oracle
NOT IN
vs. NOT EXISTS
vs. LEFT JOIN / IS NULL
: MySQL
There are three ways to do such a query:
LEFT JOIN / IS NULL
:
SELECT *
FROM common
LEFT JOIN
table1 t1
ON t1.common_id = common.common_id
WHERE t1.common_id IS NULL
NOT EXISTS
:
SELECT *
FROM common
WHERE NOT EXISTS
(
SELECT NULL
FROM table1 t1
WHERE t1.common_id = common.common_id
)
NOT IN
:
SELECT *
FROM common
WHERE common_id NOT IN
(
SELECT common_id
FROM table1 t1
)
When table1.common_id
is not nullable, all these queries are semantically the same.
When it is nullable, NOT IN
is different, since IN
(and, therefore, NOT IN
) return NULL
when a value does not match anything in a list containing a NULL
.
This may be confusing but may become more obvious if we recall the alternate syntax for this:
common_id = ANY
(
SELECT common_id
FROM table1 t1
)
The result of this condition is a boolean product of all comparisons within the list. Of course, a single NULL
value yields the NULL
result which renders the whole result NULL
too.
We never cannot say definitely that common_id
is not equal to anything from this list, since at least one of the values is NULL
.
Suppose we have these data:
common
--
1
3
table1
--
NULL
1
2
LEFT JOIN / IS NULL
and NOT EXISTS
will return 3
, NOT IN
will return nothing (since it will always evaluate to either FALSE
or NULL
).
In MySQL
, in case on non-nullable column, LEFT JOIN / IS NULL
and NOT IN
are a little bit (several percent) more efficient than NOT EXISTS
. If the column is nullable, NOT EXISTS
is the most efficient (again, not much).
In Oracle
, all three queries yield same plans (an ANTI JOIN
).
In SQL Server
, NOT IN
/ NOT EXISTS
are more efficient, since LEFT JOIN / IS NULL
cannot be optimized to an ANTI JOIN
by its optimizer.
In PostgreSQL
, LEFT JOIN / IS NULL
and NOT EXISTS
are more efficient than NOT IN
, sine they are optimized to an Anti Join
, while NOT IN
uses hashed subplan
(or even a plain subplan
if the subquery is too large to hash)
I needed this same solution, but if you use the native ListObject.Add()
method then you avoid the risk of clashing with any data immediately below the table. The below routine checks the last row of the table, and adds the data in there if it's blank; otherwise it adds a new row to the end of the table:
Sub AddDataRow(tableName As String, values() As Variant)
Dim sheet As Worksheet
Dim table As ListObject
Dim col As Integer
Dim lastRow As Range
Set sheet = ActiveWorkbook.Worksheets("Sheet1")
Set table = sheet.ListObjects.Item(tableName)
'First check if the last row is empty; if not, add a row
If table.ListRows.Count > 0 Then
Set lastRow = table.ListRows(table.ListRows.Count).Range
For col = 1 To lastRow.Columns.Count
If Trim(CStr(lastRow.Cells(1, col).Value)) <> "" Then
table.ListRows.Add
Exit For
End If
Next col
Else
table.ListRows.Add
End If
'Iterate through the last row and populate it with the entries from values()
Set lastRow = table.ListRows(table.ListRows.Count).Range
For col = 1 To lastRow.Columns.Count
If col <= UBound(values) + 1 Then lastRow.Cells(1, col) = values(col - 1)
Next col
End Sub
To call the function, pass the name of the table and an array of values, one value per column. You can get / set the name of the table from the Design
tab of the ribbon, in Excel 2013 at least:
Example code for a table with three columns:
Dim x(2)
x(0) = 1
x(1) = "apple"
x(2) = 2
AddDataRow "Table1", x
First activate Google+ API, then you will get "Simple API access" box, from there you can get developer key as API key https://code.google.com/apis/console/?api=plus or read this: http://code.google.com/p/google-api-php-client/wiki/OAuth2
private static void Render(IList<ListData> list, IDataReader reader)
{
while (reader.Read())
{
listData.DownUrl = (reader.GetSchemaTable().Columns["DownUrl"] != null) ? Convert.ToString(reader["DownUrl"]) : null;
//??????,????null
list.Add(listData);
}
reader.Close();
}
Carry Flag is a flag set when:
a) two unsigned numbers were added and the result is larger than "capacity" of register where it is saved. Ex: we wanna add two 8 bit numbers and save result in 8 bit register. In your example: 255 + 9 = 264 which is more that 8 bit register can store. So the value "8" will be saved there (264 & 255 = 8) and CF flag will be set.
b) two unsigned numbers were subtracted and we subtracted the bigger one from the smaller one. Ex: 1-2 will give you 255 in result and CF flag will be set.
Auxiliary Flag is used as CF but when working with BCD. So AF will be set when we have overflow or underflow on in BCD calculations. For example: considering 8 bit ALU unit, Auxiliary flag is set when there is carry from 3rd bit to 4th bit i.e. carry from lower nibble to higher nibble. (Wiki link)
Overflow Flag is used as CF but when we work on signed numbers. Ex we wanna add two 8 bit signed numbers: 127 + 2. the result is 129 but it is too much for 8bit signed number, so OF will be set. Similar when the result is too small like -128 - 1 = -129 which is out of scope for 8 bit signed numbers.
You can read more about flags on wikipedia
I searched for a solution as well, and none of the answers I encountered solved the error, Until I found the answer of "ViRuSTriNiTy" to this thread: Undefined reference to 'boost::system::generic_category()'?
according to that answer, try to add these lines to your cmake file:
find_package(Boost 1.55.0 REQUIRED COMPONENTS system filesystem)
include_directories(... ${Boost_INCLUDE_DIRS})
link_directories(... ${Boost_LIBRARY_DIRS})
target_link_libraries(... ${Boost_LIBRARIES})
Suppose you dataframe looks like :
Now you want to check if filename "80900026941984" is present in the dataframe or not.
You can simply write :
if sum(df["filename"].astype("str").str.contains("80900026941984")) > 0:
print("found")
Use PHP's strip_tags() function.
For example:
$businessDesc = strip_tags($row_get_Business['business_description']);
$businessDesc = substr($businessDesc, 0, 110);
print($businessDesc);
Here is the simple trick. Just copy and paste it.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Change Image on Hover in CSS</title>
<style type="text/css">
.card {
width: 130px;
height: 195px;
background: url("../images/card-back.jpg") no-repeat;
margin: 50px;
}
.card:hover {
background: url("../images/card-front.jpg") no-repeat;
}
</style>
</head>
<body>
<div class="card"></div>
</body>
</html>
I would just press A (append to end of line, puts you into insert mode) on the line where you want to remove the newline and then press delete.
Cursor might used for retrieving data row by row basis.its act like a looping statement(ie while or for loop). To use cursors in SQL procedures, you need to do the following: 1.Declare a cursor that defines a result set. 2.Open the cursor to establish the result set. 3.Fetch the data into local variables as needed from the cursor, one row at a time. 4.Close the cursor when done.
for ex:
declare @tab table
(
Game varchar(15),
Rollno varchar(15)
)
insert into @tab values('Cricket','R11')
insert into @tab values('VollyBall','R12')
declare @game varchar(20)
declare @Rollno varchar(20)
declare cur2 cursor for select game,rollno from @tab
open cur2
fetch next from cur2 into @game,@rollno
WHILE @@FETCH_STATUS = 0
begin
print @game
print @rollno
FETCH NEXT FROM cur2 into @game,@rollno
end
close cur2
deallocate cur2
You can try this,
$info = pathinfo($_FILES['userFile']['name']);
$ext = $info['extension']; // get the extension of the file
$newname = "newname.".$ext;
$target = 'images/'.$newname;
move_uploaded_file( $_FILES['userFile']['tmp_name'], $target);
You could try updating the table to get rid of these characters:
UPDATE dbo.[audit]
SET UserID = REPLACE(UserID, CHAR(0), '')
WHERE CHARINDEX(CHAR(0), UserID) > 0;
But then you'll also need to fix whatever is putting this bad data into the table in the first place. In the meantime perhaps try:
SELECT CONVERT(INT, REPLACE(UserID, CHAR(0), ''))
FROM dbo.[audit];
But that is not a long term solution. Fix the data (and the data type while you're at it). If you can't fix the data type immediately, then you can quickly find the culprit by adding a check constraint:
ALTER TABLE dbo.[audit]
ADD CONSTRAINT do_not_allow_stupid_data
CHECK (CHARINDEX(CHAR(0), UserID) = 0);
EDIT
Ok, so that is definitely a 4-digit integer followed by six instances of CHAR(0). And the workaround I posted definitely works for me:
DECLARE @foo TABLE(UserID VARCHAR(32));
INSERT @foo SELECT 0x31353831000000000000;
-- this succeeds:
SELECT CONVERT(INT, REPLACE(UserID, CHAR(0), '')) FROM @foo;
-- this fails:
SELECT CONVERT(INT, UserID) FROM @foo;
Please confirm that this code on its own (well, the first SELECT
, anyway) works for you. If it does then the error you are getting is from a different non-numeric character in a different row (and if it doesn't then perhaps you have a build where a particular bug hasn't been fixed). To try and narrow it down you can take random values from the following query and then loop through the characters:
SELECT UserID, CONVERT(VARBINARY(32), UserID)
FROM dbo.[audit]
WHERE UserID LIKE '%[^0-9]%';
So take a random row, and then paste the output into a query like this:
DECLARE @x VARCHAR(32), @i INT;
SET @x = CONVERT(VARCHAR(32), 0x...); -- paste the value here
SET @i = 1;
WHILE @i <= LEN(@x)
BEGIN
PRINT RTRIM(@i) + ' = ' + RTRIM(ASCII(SUBSTRING(@x, @i, 1)))
SET @i = @i + 1;
END
This may take some trial and error before you encounter a row that fails for some other reason than CHAR(0)
- since you can't really filter out the rows that contain CHAR(0)
because they could contain CHAR(0)
and CHAR(something else)
. For all we know you have values in the table like:
SELECT '15' + CHAR(9) + '23' + CHAR(0);
...which also can't be converted to an integer, whether you've replaced CHAR(0)
or not.
I know you don't want to hear it, but I am really glad this is painful for people, because now they have more war stories to push back when people make very poor decisions about data types.
Here is OpenSSL example of calculating sha-1 digest using BIO:
#include <openssl/bio.h>
#include <openssl/evp.h>
std::string sha1(const std::string &input)
{
BIO * p_bio_md = nullptr;
BIO * p_bio_mem = nullptr;
try
{
// make chain: p_bio_md <-> p_bio_mem
p_bio_md = BIO_new(BIO_f_md());
if (!p_bio_md) throw std::bad_alloc();
BIO_set_md(p_bio_md, EVP_sha1());
p_bio_mem = BIO_new_mem_buf((void*)input.c_str(), input.length());
if (!p_bio_mem) throw std::bad_alloc();
BIO_push(p_bio_md, p_bio_mem);
// read through p_bio_md
// read sequence: buf <<-- p_bio_md <<-- p_bio_mem
std::vector<char> buf(input.size());
for (;;)
{
auto nread = BIO_read(p_bio_md, buf.data(), buf.size());
if (nread < 0) { throw std::runtime_error("BIO_read failed"); }
if (nread == 0) { break; } // eof
}
// get result
char md_buf[EVP_MAX_MD_SIZE];
auto md_len = BIO_gets(p_bio_md, md_buf, sizeof(md_buf));
if (md_len <= 0) { throw std::runtime_error("BIO_gets failed"); }
std::string result(md_buf, md_len);
// clean
BIO_free_all(p_bio_md);
return result;
}
catch (...)
{
if (p_bio_md) { BIO_free_all(p_bio_md); }
throw;
}
}
Though it's longer than just calling SHA1
function from OpenSSL, but it's more universal and can be reworked for using with file streams (thus processing data of any length).
You can't just change the delimiters from ---- BEGIN SSH2 PUBLIC KEY ----
to -----BEGIN RSA PUBLIC KEY-----
and expect that it will be sufficient to convert from one format to another (which is what you've done in your example).
This article has a good explanation about both formats.
What you get in an RSA PUBLIC KEY
is closer to the content of a PUBLIC KEY
, but you need to offset the start of your ASN.1 structure to reflect the fact that PUBLIC KEY
also has an indicator saying which type of key it is (see RFC 3447). You can see this using openssl asn1parse
and -strparse 19
, as described in this answer.
EDIT: Following your edit, your can get the details of your RSA PUBLIC KEY
structure using grep -v -- ----- | tr -d '\n' | base64 -d | openssl asn1parse -inform DER
:
0:d=0 hl=4 l= 266 cons: SEQUENCE
4:d=1 hl=4 l= 257 prim: INTEGER :FB1199FF0733F6E805A4FD3B36CA68E94D7B974621162169C71538A539372E27F3F51DF3B08B2E111C2D6BBF9F5887F13A8DB4F1EB6DFE386C92256875212DDD00468785C18A9C96A292B067DDC71DA0D564000B8BFD80FB14C1B56744A3B5C652E8CA0EF0B6FDA64ABA47E3A4E89423C0212C07E39A5703FD467540F874987B209513429A90B09B049703D54D9A1CFE3E207E0E69785969CA5BF547A36BA34D7C6AEFE79F314E07D9F9F2DD27B72983AC14F1466754CD41262516E4A15AB1CFB622E651D3E83FA095DA630BD6D93E97B0C822A5EB4212D428300278CE6BA0CC7490B854581F0FFB4BA3D4236534DE09459942EF115FAA231B15153D67837A63
265:d=1 hl=2 l= 3 prim: INTEGER :010001
To decode the SSH key format, you need to use the data format specification in RFC 4251 too, in conjunction with RFC 4253:
The "ssh-rsa" key format has the following specific encoding: string "ssh-rsa" mpint e mpint n
For example, at the beginning, you get 00 00 00 07 73 73 68 2d 72 73 61
. The first four bytes (00 00 00 07
) give you the length. The rest is the string itself: 73=s, 68=h, ... -> 73 73 68 2d 72 73 61
=ssh-rsa
, followed by the exponent of length 1 (00 00 00 01 25
) and the modulus of length 256 (00 00 01 00 7f ...
).
Try using an X-Y Scatter graph with datetime formatted as YYYY-MM-DD HH:MM.
This provides a reasonable graph for me (using Excel 2010).
Another alternative is to use a lambda:
ent.bind("<Return>", (lambda event: name_of_function()))
Full code:
from tkinter import *
from tkinter.messagebox import showinfo
def reply(name):
showinfo(title="Reply", message = "Hello %s!" % name)
top = Tk()
top.title("Echo")
top.iconbitmap("Iconshock-Folder-Gallery.ico")
Label(top, text="Enter your name:").pack(side=TOP)
ent = Entry(top)
ent.bind("<Return>", (lambda event: reply(ent.get())))
ent.pack(side=TOP)
btn = Button(top,text="Submit", command=(lambda: reply(ent.get())))
btn.pack(side=LEFT)
top.mainloop()
As you can see, creating a lambda function with an unused variable "event" solves the problem.
String can be as large as 2GB.
Source
From Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning
the following
Excessive GC Time and OutOfMemoryError
The concurrent collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.
The policy is the same as that in the parallel collector, except that time spent performing concurrent collections is not counted toward the 98% time limit. In other words, only collections performed while the application is stopped count toward excessive GC time. Such collections are typically due to a concurrent mode failure or an explicit collection request (e.g., a call to System.gc()).
in conjunction with a passage further down
One of the most commonly encountered uses of explicit garbage collection occurs with RMIs distributed garbage collection (DGC). Applications using RMI refer to objects in other virtual machines. Garbage cannot be collected in these distributed applications without occasionally collection the local heap, so RMI forces full collections periodically. The frequency of these collections can be controlled with properties. For example,
java -Dsun.rmi.dgc.client.gcInterval=3600000
-Dsun.rmi.dgc.server.gcInterval=3600000
specifies explicit collection once per hour instead of the default rate of once per minute. However, this may also cause some objects to take much longer to be reclaimed. These properties can be set as high as Long.MAX_VALUE to make the time between explicit collections effectively infinite, if there is no desire for an upper bound on the timeliness of DGC activity.
Seems to imply that the evaluation period for determining the 98% is one minute long, but it might be configurable on Sun's JVM with the correct define.
Of course, other interpretations are possible.
sed
is a stream editor. It works with streams of characters on a per-line basis. It has a primitive programming language that includes goto-style loops and simple conditionals (in addition to pattern matching and address matching). There are essentially only two "variables": pattern space and hold space. Readability of scripts can be difficult. Mathematical operations are extraordinarily awkward at best.
There are various versions of sed
with different levels of support for command line options and language features.
awk
is oriented toward delimited fields on a per-line basis. It has much more robust programming constructs including if
/else
, while
, do
/while
and for
(C-style and array iteration). There is complete support for variables and single-dimension associative arrays plus (IMO) kludgey multi-dimension arrays. Mathematical operations resemble those in C. It has printf
and functions. The "K" in "AWK" stands for "Kernighan" as in "Kernighan and Ritchie" of the book "C Programming Language" fame (not to forget Aho and Weinberger). One could conceivably write a detector of academic plagiarism using awk
.
GNU awk
(gawk
) has numerous extensions, including true multidimensional arrays in the latest version. There are other variations of awk
including mawk
and nawk
.
Both programs use regular expressions for selecting and processing text.
I would tend to use sed
where there are patterns in the text. For example, you could replace all the negative numbers in some text that are in the form "minus-sign followed by a sequence of digits" (e.g. "-231.45") with the "accountant's brackets" form (e.g. "(231.45)") using this (which has room for improvement):
sed 's/-\([0-9.]\+\)/(\1)/g' inputfile
I would use awk
when the text looks more like rows and columns or, as awk
refers to them "records" and "fields". If I was going to do a similar operation as above, but only on the third field in a simple comma delimited file I might do something like:
awk -F, 'BEGIN {OFS = ","} {gsub("-([0-9.]+)", "(" substr($3, 2) ")", $3); print}' inputfile
Of course those are just very simple examples that don't illustrate the full range of capabilities that each has to offer.
Put the following:
<script type="text/javascript">
if (location.href.indexOf("#") != -1) {
// Your code in here accessing the string like this
// location.href.substr(location.href.indexOf("#"))
}
</script>
<a [routerLink]="['../']" [queryParams]="{name: 'ferret'}" [fragment]="nose">Ferret Nose</a>
foo://example.com:8042/over/there?name=ferret#nose
\_/ \______________/\_________/ \_________/ \__/
| | | | |
scheme authority path query fragment
For more info - https://angular.io/guide/router#query-parameters-and-fragments
Best way to add custom drawable is:
<RadioButton
android:id="@+id/radiocar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="@android:color/transparent"
android:button="@drawable/yourbuttonbackground"
android:checked="true"
android:drawableRight="@mipmap/car"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:text="yourtexthere"/>
Shadow overlay by custom drawable is removed here.
If your grep -i does not work then try using tr command to convert the the output of your file to lower case and then pipe it into standard grep with whatever you are looking for. (it sounds complicated but the actual command which I have provided for you is not !).
Notice the tr command does not change the content of your original file, it just converts it just before it feeds it into grep.
1.here is how you can do this on a file
tr '[:upper:]' '[:lower:]' <your_file.txt|grep what_ever_you_are_searching_in_lower_case
2.or in your case if you are just echoing something
echo "ABC"|tr '[:upper:]' '[:lower:]' | grep abc
If you are looking an algorithm to rank search results based on relevance of multiple words here comes a quick and easy way of generating search results with PHP only.
Implementation of the vector space model in PHP
function get_corpus_index($corpus = array(), $separator=' ') {
$dictionary = array();
$doc_count = array();
foreach($corpus as $doc_id => $doc) {
$terms = explode($separator, $doc);
$doc_count[$doc_id] = count($terms);
// tf–idf, short for term frequency–inverse document frequency,
// according to wikipedia is a numerical statistic that is intended to reflect
// how important a word is to a document in a corpus
foreach($terms as $term) {
if(!isset($dictionary[$term])) {
$dictionary[$term] = array('document_frequency' => 0, 'postings' => array());
}
if(!isset($dictionary[$term]['postings'][$doc_id])) {
$dictionary[$term]['document_frequency']++;
$dictionary[$term]['postings'][$doc_id] = array('term_frequency' => 0);
}
$dictionary[$term]['postings'][$doc_id]['term_frequency']++;
}
//from http://phpir.com/simple-search-the-vector-space-model/
}
return array('doc_count' => $doc_count, 'dictionary' => $dictionary);
}
function get_similar_documents($query='', $corpus=array(), $separator=' '){
$similar_documents=array();
if($query!=''&&!empty($corpus)){
$words=explode($separator,$query);
$corpus=get_corpus_index($corpus);
$doc_count=count($corpus['doc_count']);
foreach($words as $word) {
$entry = $corpus['dictionary'][$word];
foreach($entry['postings'] as $doc_id => $posting) {
//get term frequency–inverse document frequency
$score=$posting['term_frequency'] * log($doc_count + 1 / $entry['document_frequency'] + 1, 2);
if(isset($similar_documents[$doc_id])){
$similar_documents[$doc_id]+=$score;
}
else{
$similar_documents[$doc_id]=$score;
}
}
}
// length normalise
foreach($similar_documents as $doc_id => $score) {
$similar_documents[$doc_id] = $score/$corpus['doc_count'][$doc_id];
}
// sort fro high to low
arsort($similar_documents);
}
return $similar_documents;
}
IN YOUR CASE
$query = 'world';
$corpus = array(
1 => 'hello world',
);
$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
print_r($match_results);
echo '</pre>';
RESULTS
Array
(
[1] => 0.79248125036058
)
MATCHING MULTIPLE WORDS AGAINST MULTIPLE PHRASES
$query = 'hello world';
$corpus = array(
1 => 'hello world how are you today?',
2 => 'how do you do world',
3 => 'hello, here you are! how are you? Are we done yet?'
);
$match_results=get_similar_documents($query,$corpus);
echo '<pre>';
print_r($match_results);
echo '</pre>';
RESULTS
Array
(
[1] => 0.74864218272161
[2] => 0.43398500028846
)
from How do I check if a string contains a specific word in PHP?
Try your code like this:
var app = express();
app.get('/test', function(req, res) {
res.sendFile('views/test.html', {root: __dirname })
});
Use res.sendFile instead of reading the file manually so express can handle setting the content-type properly for you.
You don't need the app.engine
line, as that is handled internally by express.
In Google Maps API v3 you can try changing marker icon. For example for green icon use:
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')
Or as part of marker init:
marker = new google.maps.Marker({
icon: 'http://...'
});
Other colors:
Etc.
I jumped here looking for the very same thing, but none worked for me.
There are instances where regardless what you do, and depending on the system (Oracle Designer: Oracle 11g - PL/SQL), divs will always go to the next line, in which case you should use the span tag instead.
This worked wonders for me.
<span float: left; white-space: nowrap; overflow: hidden; onmouseover="rollOverImageSectionFiveThreeOne(this)">
<input type="radio" id="radio4" name="p_verify_type" value="SomeValue" />
</span>
Just Your Text ||
<span id="headerFiveThreeOneHelpText" float: left; white-space: nowrap; overflow: hidden;></span>
Had the same problem with a zipcode field. Some folks sent me an excel file with zips, but they were formatted as #'s. Had to convert them to strings as well as prepend leading 0's to them if they were < 5 len ...
declare @int tinyint
set @int = 25
declare @len tinyint
set @len = 3
select right(replicate('0', @len) + cast(@int as varchar(255)), @len)
You just alter the @len to get what you want. As formatted, you'll get...
001
002
...
010
011
...
255
Ideally you'd "varchar(@len)", too, but that blows up the SQL compile. Have to toss an actual # into it instead of a var.
For a RollingLogFileAppender you also need these elements and values:
<rollingStyle value="Date" />
<staticLogFileName value="false" />
I use bootstrap 3.x as well and the following code fore responsive youtube video embedding works like charm for me:
.videoWrapperOuter {
max-width:640px;
margin-left:auto;
margin-right:auto;
}
.videoWrapperInner {
float: none;
clear: both;
width: 100%;
position: relative;
padding-bottom: 50%;
padding-top: 25px;
height: 0;
}
.videoWrapperInner iframe {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
}
<div class="videoWrapperOuter">
<div class="videoWrapperInner">
<iframe src="//www.youtube.com/embed/C6-TWRn0k4I"
frameborder="0" allowfullscreen></iframe>
</div>
</div>
I gave a similiar answer on another thread (Shrink a YouTube video to responsive width), but I guess my answers can help here as well.
you're using jQuery UI dialog, you could just style the modal to appear with the position fixed in the window so it doesn't pop-up out of view, negating the need to scroll. Other
Async version of @SharpCoder's answer using fs.promises:
const fs = require('fs');
const afs = fs.promises;
const deleteFolderRecursive = async path => {
if (fs.existsSync(path)) {
for (let entry of await afs.readdir(path)) {
const curPath = path + "/" + entry;
if ((await afs.lstat(curPath)).isDirectory())
await deleteFolderRecursive(curPath);
else await afs.unlink(curPath);
}
await afs.rmdir(path);
}
};
OK, I got the icons because I wrote in menu.xml android:showAsAction="ifRoom"
instead of app:showAsAction="ifRoom"
since i am using v7 library.
However the title is coming at center of extended toolbar. How to make it appear at the top?
You can use --python
option to npm like so:
npm install --python=python2.7
or set it to be used always:
npm config set python python2.7
Npm will in turn pass this option to node-gyp when needed.
(note: I'm the one who opened an issue on Github to have this included in the docs, as there were so many questions about it ;-) )
Check out this Sample Camera Preview code, CameraPreview
. This would help you in devloping video recording code for video preview, create MediaRecorder
object, and set video recording parameters.
I use the len
function. It's much faster than empty
. len(df.index)
is even faster.
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10000, 4), columns=list('ABCD'))
def empty(df):
return df.empty
def lenz(df):
return len(df) == 0
def lenzi(df):
return len(df.index) == 0
'''
%timeit empty(df)
%timeit lenz(df)
%timeit lenzi(df)
10000 loops, best of 3: 13.9 µs per loop
100000 loops, best of 3: 2.34 µs per loop
1000000 loops, best of 3: 695 ns per loop
len on index seems to be faster
'''
Sharing my solution here, based on Chris' answer. Hope it can help others.
I needed to dynamically append child elements into my JSX, but in a simpler way than conditional checks in my return statement. I want to show a loader in the case that the child elements aren't ready yet. Here it is:
export class Settings extends React.PureComponent {
render() {
const loading = (<div>I'm Loading</div>);
let content = [];
let pushMessages = null;
let emailMessages = null;
if (this.props.pushPreferences) {
pushMessages = (<div>Push Content Here</div>);
}
if (this.props.emailPreferences) {
emailMessages = (<div>Email Content Here</div>);
}
// Push the components in the order I want
if (emailMessages) content.push(emailMessages);
if (pushMessages) content.push(pushMessages);
return (
<div>
{content.length ? content : loading}
</div>
)
}
Now, I do realize I could also just put {pushMessages}
and {emailMessages}
directly in my return()
below, but assuming I had even more conditional content, my return()
would just look cluttered.
The code can be
<div class="text-class"><span>hello</span><span>How are you</span></div>
CSS would be
.text-class {
display: flex;
justify-content: flex-start;
flex-direction: column;
align-items: center;
}
An interface defines behavior. For example, a Vehicle
interface might define the move()
method.
A Car is a Vehicle, but has additional behavior. For example, the Car
interface might define the startEngine()
method. Since a Car is also a Vehicle, the Car
interface extends the Vehicle
interface, and thus defines two methods: move()
(inherited) and startEngine()
.
The Car interface doesn't have any method implementation. If you create a class (Volkswagen) that implements Car, it will have to provide implementations for all the methods of its interface: move()
and startEngine()
.
An interface may not implement any other interface. It can only extend it.
From Apple's docs:
Symbolicating Crash Reports With Xcode Xcode will automatically attempt to symbolicate all crash reports that it encounters. All you need to do for symbolication is to add the crash report to the Xcode Organizer.
Xcode will automatically symbolicate the crash report and display the results To symbolicate a crash report, Xcode needs to be able to locate the following:
The crashing application's binary and dSYM file.
The binaries and dSYM files for all custom frameworks that the application links against. For frameworks that were built from source with the application, their dSYM files are copied into the archive alongside the application's dSYM file. For frameworks that were built by a third-party, you will need to ask the author for the dSYM file.
Symbols for the OS that the that application was running on when it crashed. These symbols contain debug information for the frameworks included in a specific OS release (e.g, iOS 9.3.3). OS symbols are architecture specific - a release of iOS for 64-bit devices won't include armv7 symbols. Xcode will automatically copy OS symbols from each device that you connect to your Mac.
If any of these are missing Xcode may not be able to symbolicate the crash report, or may only partially symbolicate the crash report.
well i found out the mistake i was committing i was adding a group to the project instead of adding real directory for more instructions
You can get them like this
$('#save_value').click(function() {
$('.ads_Checkbox:checked').each(function() {
alert($(this).val());
});
});
In some systems like your office system, there is sometimes a firewall/security client that is installed for security purpose. Try uninstalling that and then run the command again, it should start the download.
My system had Netskope Client installed and was blocking the ssl communication.
Search in finder -> uninstall netskope, run it, and try installing homebrew:
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)"
PS: consider installing the security client.
cat | git log --author="authorName" > author_commits_details.txt
This gives your commits in text format.
While doing my own server side JS experimentation I ended up using teajs. It conforms to common.js, is based on V8 AND is the only project that I know of that provides 'mod_teajs' apache server module.
In my opinion Node.js server is not production ready and lacks too many features - Apache is battle tested and the right way to do SSJS.
This is the quickest way to solve the problem but it's not recommended because its applicable only for your local system.
Download the jar, comment your previous entry for ojdbc6
, and give a new local entry like so:
Previous Entry:
<!-- OJDBC6 Dependency -->
<!-- <dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>1.0</version>
<scope>runtime</scope>
</dependency> -->
New Entry:
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
<version>1.0</version>
<scope>system</scope>
<systemPath>${project.basedir}/lib/ojdbc6/ojdbc6.jar</systemPath>
</dependency>
Edit: Since this turned out to be a popular answer, I'm adding the disclaimer that @crush mentioned in a comment below. If you use this work around, be aware that you're opening yourself up for an XSS vulnerability. Only use this solution if you know what you're doing and can be certain of the HTML content in the attribute.
The easiest way to do this is to supply a function to the content
option that overrides the default behavior:
$(function () {
$(document).tooltip({
content: function () {
return $(this).prop('title');
}
});
});
Example: http://jsfiddle.net/Aa5nK/12/
Another option would be to override the tooltip widget with your own that changes the content
option:
$.widget("ui.tooltip", $.ui.tooltip, {
options: {
content: function () {
return $(this).prop('title');
}
}
});
Now, every time you call .tooltip
, HTML content will be returned.
Example: http://jsfiddle.net/Aa5nK/14/
You need to install Cmake.
dlib is an c++ libary with python bindings. It needs to be builded first. My guess is this will happen automatically once you have installed Cmake
I wanted to check if a port is open on one of our linux test servers. I was able to do that by trying to connect with telnet from my dev machine to the test server. On you dev machine try to run:
$ telnet test2.host.com 8080
Trying 05.066.137.184...
Connected to test2.host.com
In this example I want to check if port 8080 is open on host test2.host.com
In the Code::Blocks IDE, navigate Settings -> Debugger
In the tree control at the right, select Common -> GDB/CDB debugger -> Common.
Then in the dialog at the left you can enter Executable path and choose Debugger type = GDB or CDB, as well as configuring various other options.
Using Visual Studio's Productivity Power Tools (free) extension helps a bit. Specifically, the Solution Error Visualizer
feature. With it, compilation errors marked visually in the solution explorer (in the source file where the error was found). For some reason, however, this feature does not work as with other errors anywhere else in the code.
With MVC views, any compile-time errors will still be underlined in red in their respective .cs files, but signaling these errors is not propagated upwards in the Solution Explorer (in no way, even not in the containing source file).
Thanks for BlueClouds
for correcting my previous statement.
I have just reported this as an issue on the extension's github project.
Use wildcard, e.g. replace 2008
with *
:
df = sqlContext.read
.format("com.databricks.spark.csv")
.option("header", "true")
.load("../Downloads/*.csv") // <-- note the star (*)
// these lines are equivalent in Spark 2.0
spark.read.format("csv").option("header", "true").load("../Downloads/*.csv")
spark.read.option("header", "true").csv("../Downloads/*.csv")
Notes:
Replace format("com.databricks.spark.csv")
by using format("csv")
or csv
method instead. com.databricks.spark.csv
format has been integrated to 2.0.
Use spark
not sqlContext
VBScript has no notion of throwing or catching exceptions, but the runtime provides a global Err object that contains the results of the last operation performed. You have to explicitly check whether the Err.Number property is non-zero after each operation.
On Error Resume Next
DoStep1
If Err.Number <> 0 Then
WScript.Echo "Error in DoStep1: " & Err.Description
Err.Clear
End If
DoStep2
If Err.Number <> 0 Then
WScript.Echo "Error in DoStop2:" & Err.Description
Err.Clear
End If
'If you no longer want to continue following an error after that block's completed,
'call this.
On Error Goto 0
The "On Error Goto [label]" syntax is supported by Visual Basic and Visual Basic for Applications (VBA), but VBScript doesn't support this language feature so you have to use On Error Resume Next as described above.
I resolved the conflict and then do a commit with -a option. It worked for me.
On Windows XP -
rundll32.exe syssetup,SetupOobeBnk
This will reset the 30 day timer for activation back to 30 days so you can enter in the key normally.
I would like to attract attention to the following specifics of the as operator:
https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/as
Note that the as operator performs only reference conversions, nullable conversions, and boxing conversions. The as operator can't perform other conversions, such as user-defined conversions, which should instead be performed by using cast expressions.
If the server's certificate is self-signed, then this is working as designed and you will have to import the server's certificate into your keystore.
Assuming the server certificate is signed by a well-known CA, this is happening because the set of CA certificates available to a modern browser is much larger than the limited set that is shipped with the JDK/JRE.
The EasySSL solution given in one of the posts you mention just buries the error, and you won't know if the server has a valid certificate.
You must import the proper Root CA into your keystore to validate the certificate. There's a reason you can't get around this with the stock SSL code, and that's to prevent you from writing programs that behave as if they are secure but are not.
You can increase that in php.ini
; Maximum allowed size for uploaded files.
upload_max_filesize = 2M
Just to add on Jacek's perfect solution. If you're trying to do this in Kotlin, it wont work immediately. Instead, you'll want to use this:
@Throws(IOException::class)
fun getSplashVideo(context: Context): File {
val cacheFile = File(context.cacheDir, "splash_video")
try {
val inputStream = context.assets.open("splash_video")
val outputStream = FileOutputStream(cacheFile)
try {
inputStream.copyTo(outputStream)
} finally {
inputStream.close()
outputStream.close()
}
} catch (e: IOException) {
throw IOException("Could not open splash_video", e)
}
return cacheFile
}
Well I found the answer set "aaSorting" to an empty array:
$(document).ready( function() {
$('#example').dataTable({
/* Disable initial sort */
"aaSorting": []
});
})
For newer versions of Datatables (>= 1.10) use order option:
$(document).ready( function() {
$('#example').dataTable({
/* No ordering applied by DataTables during initialisation */
"order": []
});
})
Split it by space
and take first part like below. Hope this will help you.
var d = '12/12/1955 12:00:00 AM';
d = d.split(' ')[0];
console.log(d);
You can use TypeScript's native string interpolation in case if your only goal to eliminate ugly string concatenations and boring string conversions:
var yourMessage = `Your text ${yourVariable} your text continued ${yourExpression} and so on.`
NOTE:
At the right side of the assignment statement the delimiters are neither single or double quotes, instead a special char called backtick or grave accent.
The TypeScript compiler will translate your right side special literal to a string concatenation expression. With other words this syntax is not relies the ECMAScript 6 feature instead a native TypeScript feature. Your generated javascript code remains compatible.