I did something similar with this construct
$('li').each(function(){
if(this.id){
this.id = this.id+"something";
}
});
QFile file("test.txt");
/*
*If file does not exist, it will be created
*/
if (!file.open(QIODevice::ReadOnly | QIODevice::Text | QIODevice::ReadWrite))
{
qDebug() << "FAILED TO CREATE FILE / FILE DOES NOT EXIST";
}
/*for Reading line by line from text file*/
while (!file.atEnd()) {
QByteArray line = file.readLine();
qDebug() << "read output - " << line;
}
/*for writing line by line to text file */
if (file.open(QIODevice::ReadWrite))
{
QTextStream stream(&file);
stream << "1_XYZ"<<endl;
stream << "2_XYZ"<<endl;
}
Here is a snippet that gets the default newline character for the current platform.
Use
System.getProperty("os.name")
and
System.getProperty("os.version").
Example:
public static String getSystemNewline(){
String eol = null;
String os = System.getProperty("os.name").toLowerCase();
if(os.contains("mac"){
int v = Integer.parseInt(System.getProperty("os.version"));
eol = (v <= 9 ? "\r" : "\n");
}
if(os.contains("nix"))
eol = "\n";
if(os.contains("win"))
eol = "\r\n";
return eol;
}
Where eol is the newline
The following should help
realpath
— Returns canonicalized absolute pathnameis_writable
— Tells whether the filename is writableunlink
— Deletes a fileRun your filepath through realpath, then check if the returned path is writable and if so, unlink it.
The best way to find out is looking at the Execution Plan.
I tried it with Oracle, and it was exactly the same.
CREATE TABLE performance_test AS ( SELECT * FROM dba_objects );
SELECT * FROM performance_test
WHERE object_name IN ('DBMS_STANDARD', 'DBMS_REGISTRY', 'DBMS_LOB' );
Even though the query uses IN
, the Execution Plan says that it uses OR
:
--------------------------------------------------------------------------------------
| Id | Operation | Name | Rows | Bytes | Cost (%CPU)| Time |
--------------------------------------------------------------------------------------
| 0 | SELECT STATEMENT | | 8 | 1416 | 163 (2)| 00:00:02 |
|* 1 | TABLE ACCESS FULL| PERFORMANCE_TEST | 8 | 1416 | 163 (2)| 00:00:02 |
--------------------------------------------------------------------------------------
Predicate Information (identified by operation id):
---------------------------------------------------
1 - filter("OBJECT_NAME"='DBMS_LOB' OR "OBJECT_NAME"='DBMS_REGISTRY' OR
"OBJECT_NAME"='DBMS_STANDARD')
By default, the created subprocess does not have its own terminal or console. All its standard I/O (i.e. stdin, stdout, stderr) operations will be redirected to the parent process, where they can be accessed via the streams obtained using the methods getOutputStream(), getInputStream(), and getErrorStream(). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, or even deadlock.
This code work in my mysql db:
ALTER TABLE `goods`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT,
ADD PRIMARY KEY (`id`);
span { display: table-cell; height: (your-height + px); vertical-align: middle; }
For spans to work like a table-cell (or any other element, for that matter), height must be specified. I've given spans a height, and they work just fine--but you must add height to get them to do what you want.
String exePath = System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0].FullyQualifiedName;
string dir = Path.GetDirectoryName(exePath);
Try this!
A little more elaborate example.
Setup: You have a website at example.com
and you have a web app at example.com/webapp
...
server {
listen 443 ssl;
server_name example.com;
root /usr/share/nginx/html/website_dir;
index index.html index.htm;
try_files $uri $uri/ /index.html;
location /webapp/ {
alias /usr/share/nginx/html/webapp_dir/;
index index.html index.htm;
try_files $uri $uri/ /webapp/index.html;
}
}
...
I've named webapp_dir
and website_dir
on purpose. If you have matching names and folders you can use the root
directive.
This setup works and is tested with Docker.
NB!!! Be careful with the slashes. Put them exactly as in the example.
This is more or less a summary of three answers (by Sara Inés Calderón, klaxon and Gothburz), but as they all added something important, I consider it worth joining the solutions and adding some more explanation.
Considering your example, you can do calculations in your template using:
{{ 100 * (count/total) }}
However, this may result in a whole lot of decimal places, so using filters is a good way to go:
{{ 100 * (count/total) | number }}
By default, the number filter will leave up to three fractional digits, this is where the fractionSize argument comes in quite handy
({{ 100 * (count/total) | number:fractionSize }}
), which in your case would be:
{{ 100 * (count/total) | number:0 }}
This will also round the result already:
angular.module('numberFilterExample', [])_x000D_
.controller('ExampleController', ['$scope',_x000D_
function($scope) {_x000D_
$scope.val = 1234.56789;_x000D_
}_x000D_
]);
_x000D_
<!doctype html>_x000D_
<html lang="en">_x000D_
<head> _x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
</head>_x000D_
<body ng-app="numberFilterExample">_x000D_
<table ng-controller="ExampleController">_x000D_
<tr>_x000D_
<td>No formatting:</td>_x000D_
<td>_x000D_
<span>{{ val }}</span>_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>3 Decimal places:</td>_x000D_
<td>_x000D_
<span>{{ val | number }}</span> (default)_x000D_
</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>2 Decimal places:</td>_x000D_
<td><span>{{ val | number:2 }}</span></td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>No fractions: </td>_x000D_
<td><span>{{ val | number:0 }}</span> (rounded)</td>_x000D_
</tr>_x000D_
</table>_x000D_
</body>_x000D_
</html>
_x000D_
Last thing to mention, if you rely on an external data source, it probably is good practise to provide a proper fallback value (otherwise you may see NaN or nothing on your site):
{{ (100 * (count/total) | number:0) || 0 }}
Sidenote: Depending on your specifications, you may even be able to be more precise with your fallbacks/define fallbacks on lower levels already (e.g. {{(100 * (count || 10)/ (total || 100) | number:2)}}
). Though, this may not not always make sense..
The map
method takes an enumerable object and a block, and runs the block for each element, outputting each returned value from the block (the original object is unchanged unless you use map!)
:
[1, 2, 3].map { |n| n * n } #=> [1, 4, 9]
Array
and Range
are enumerable types. map
with a block returns an Array. map!
mutates the original array.
Where is this helpful, and what is the difference between map!
and each
? Here is an example:
names = ['danil', 'edmund']
# here we map one array to another, convert each element by some rule
names.map! {|name| name.capitalize } # now names contains ['Danil', 'Edmund']
names.each { |name| puts name + ' is a programmer' } # here we just do something with each element
The output:
Danil is a programmer
Edmund is a programmer
The function below will return the x86 Program Files
directory in all of these three Windows configurations:
static string ProgramFilesx86()
{
if( 8 == IntPtr.Size
|| (!String.IsNullOrEmpty(Environment.GetEnvironmentVariable("PROCESSOR_ARCHITEW6432"))))
{
return Environment.GetEnvironmentVariable("ProgramFiles(x86)");
}
return Environment.GetEnvironmentVariable("ProgramFiles");
}
400 Bad request Error will be thrown due to incorrect authentication entries.
Note: Mostly due to Incorrect authentication entries due to spell changes will occur 400 Bad request.
On PostgreSQL (and many other RDBMS), you can do it with regular ALTER TABLE
statement:
=> SELECT * FROM Test1;
id | foo | bar
----+-----+-----
2 | 1 | 2
=> ALTER TABLE Test1 RENAME COLUMN foo TO baz;
ALTER TABLE
=> SELECT * FROM Test1;
id | baz | bar
----+-----+-----
2 | 1 | 2
OK - what you're missing is that its designed to be more industrial and serve many sites, so the config you want is probably:
/etc/apache2/sites-available/default
which on my system is linked to from /etc/apache2/sites-enabled/
if you want to have different sites with different options, copy the file and then change those...
Here's some code I use to add dynamic favicon support to Opera, Firefox and Chrome. I couldn't get IE or Safari working though. Basically Chrome allows dynamic favicons, but it only updates them when the page's location (or an iframe
etc in it) changes as far as I can tell:
var IE = navigator.userAgent.indexOf("MSIE")!=-1
var favicon = {
change: function(iconURL) {
if (arguments.length == 2) {
document.title = optionalDocTitle}
this.addLink(iconURL, "icon")
this.addLink(iconURL, "shortcut icon")
// Google Chrome HACK - whenever an IFrame changes location
// (even to about:blank), it updates the favicon for some reason
// It doesn't work on Safari at all though :-(
if (!IE) { // Disable the IE "click" sound
if (!window.__IFrame) {
__IFrame = document.createElement('iframe')
var s = __IFrame.style
s.height = s.width = s.left = s.top = s.border = 0
s.position = 'absolute'
s.visibility = 'hidden'
document.body.appendChild(__IFrame)}
__IFrame.src = 'about:blank'}},
addLink: function(iconURL, relValue) {
var link = document.createElement("link")
link.type = "image/x-icon"
link.rel = relValue
link.href = iconURL
this.removeLinkIfExists(relValue)
this.docHead.appendChild(link)},
removeLinkIfExists: function(relValue) {
var links = this.docHead.getElementsByTagName("link");
for (var i=0; i<links.length; i++) {
var link = links[i]
if (link.type == "image/x-icon" && link.rel == relValue) {
this.docHead.removeChild(link)
return}}}, // Assuming only one match at most.
docHead: document.getElementsByTagName("head")[0]}
To change favicons, just go favicon.change("ICON URL")
using the above.
(credits to http://softwareas.com/dynamic-favicons for the code I based this on.)
Other answers cover why parameters are important, but there is a downside! In .net, there are several methods for creating parameters (Add, AddWithValue), but they all require you to worry, needlessly, about the parameter name, and they all reduce the readability of the SQL in the code. Right when you're trying to meditate on the SQL, you need to hunt around above or below to see what value has been used in the parameter.
I humbly claim my little SqlBuilder class is the most elegant way to write parameterized queries. Your code will look like this...
C#
var bldr = new SqlBuilder( myCommand );
bldr.Append("SELECT * FROM CUSTOMERS WHERE ID = ").Value(myId);
//or
bldr.Append("SELECT * FROM CUSTOMERS WHERE NAME LIKE ").FuzzyValue(myName);
myCommand.CommandText = bldr.ToString();
Your code will be shorter and much more readable. You don't even need extra lines, and, when you're reading back, you don't need to hunt around for the value of parameters. The class you need is here...
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
public class SqlBuilder
{
private StringBuilder _rq;
private SqlCommand _cmd;
private int _seq;
public SqlBuilder(SqlCommand cmd)
{
_rq = new StringBuilder();
_cmd = cmd;
_seq = 0;
}
public SqlBuilder Append(String str)
{
_rq.Append(str);
return this;
}
public SqlBuilder Value(Object value)
{
string paramName = "@SqlBuilderParam" + _seq++;
_rq.Append(paramName);
_cmd.Parameters.AddWithValue(paramName, value);
return this;
}
public SqlBuilder FuzzyValue(Object value)
{
string paramName = "@SqlBuilderParam" + _seq++;
_rq.Append("'%' + " + paramName + " + '%'");
_cmd.Parameters.AddWithValue(paramName, value);
return this;
}
public override string ToString()
{
return _rq.ToString();
}
}
The answer by Chinmay Kanchi is excellent but I wanted an example of a function which passes and returns a variables/arrays to a C++ code. I though I'd include it here in case it is useful to others.
Passing and returning an integer
The C++ code for a function which takes an integer and adds one to the returned value,
extern "C" int add_one(int i)
{
return i+1;
}
Saved as file test.cpp
, note the required extern "C" (this can be removed for C code).
This is compiled using g++, with arguments similar to Chinmay Kanchi answer,
g++ -shared -o testlib.so -fPIC test.cpp
The Python code uses load_library
from the numpy.ctypeslib
assuming the path to the shared library in the same directory as the Python script,
import numpy.ctypeslib as ctl
import ctypes
libname = 'testlib.so'
libdir = './'
lib=ctl.load_library(libname, libdir)
py_add_one = lib.add_one
py_add_one.argtypes = [ctypes.c_int]
value = 5
results = py_add_one(value)
print(results)
This prints 6 as expected.
Passing and printing an array
You can also pass arrays as follows, for a C code to print the element of an array,
extern "C" void print_array(double* array, int N)
{
for (int i=0; i<N; i++)
cout << i << " " << array[i] << endl;
}
which is compiled as before and the imported in the same way. The extra Python code to use this function would then be,
import numpy as np
py_print_array = lib.print_array
py_print_array.argtypes = [ctl.ndpointer(np.float64,
flags='aligned, c_contiguous'),
ctypes.c_int]
A = np.array([1.4,2.6,3.0], dtype=np.float64)
py_print_array(A, 3)
where we specify the array, the first argument to print_array
, as a pointer to a Numpy array of aligned, c_contiguous 64 bit floats and the second argument as an integer which tells the C code the number of elements in the Numpy array. This then printed by the C code as follows,
1.4
2.6
3.0
Here's an approach using generators:
function* square(n) {
for (var i = 0; i < n; i++ ) yield i*i;
}
Then you can write
console.log(...square(7));
Another idea is:
[...Array(5)].map((_, i) => i*i)
Array(5)
creates an unfilled five-element array. That's how Array
works when given a single argument. We use the spread operator to create an array with five undefined elements. That we can then map. See http://ariya.ofilabs.com/2013/07/sequences-using-javascript-array.html.
Alternatively, we could write
Array.from(Array(5)).map((_, i) => i*i)
or, we could take advantage of the second argument to Array#from
to skip the map
and write
Array.from(Array(5), (_, i) => i*i)
A horrible hack which I saw recently, which I do not recommend you use, is
[...1e4+''].map((_, i) => i*i)
Since phone numbers must conform to a pattern, you can use regular expressions to match the entered phone number against the pattern you define in regexp.
php has both ereg and preg_match() functions. I'd suggest using preg_match() as there's more documentation for this style of regex.
An example
$phone = '000-0000-0000';
if(preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $phone)) {
// $phone is valid
}
Sure: svn rm
the unwanted folder, and commit.
To avoid this situation in the future, I would follow the recommended layout for SVN projects:
/someproject/trunk
folder (or just
/trunk
if you want to put only one
project in the repository)/someproject/branches/somebranch
/someproject/tags
Now when you check out a working copy, be sure to check out only trunk
or some individual branch. Don't check everything out in one huge working copy containing all branches.1
1Unless you know what you're doing, in which case you know how to create shallow working copies.
if you got two version of python, maybe my situation could help you
this is my situation
1-> mac osx
2-> i have two version python , (1) system default version 2.7 (2) manually installed version 3.6
3-> i have install the beautifulsoup4 with sudo pip install beautifulsoup4
4-> i run the python file with python3 /XXX/XX/XX.py
so this situation 3 and 4 are the key part, i have install beautifulsoup4 with "pip" but this module was installed for python verison 2.7, and i run the python file with "python3". so you should install beautifulsoup4 for the python 3.6;
with the sudo pip3 install beautifulsoup4
you can install the module for the python 3.6
I had the same issue.
Solution was to change the platform of my current solution to x64.
To do that in Visual Studio, right click solution > Configuration Manager > Active Solution Platform.
You should also use the style 'color' and not 'font-color'
<?php
foreach($months as $key => $month){
if(strpos($filename,$month)!==false){
echo "<style = 'color: #ff0000;'> Movie List for {$key} 2013 </style>";
}
}
?>
In general, the comments on double and single quotes are correct in other suggestions. $Variables only execute in double quotes.
For PHP version 4 or later versions:
<?PHP
$input = 4;
if(is_numeric($input)){ // return **TRUE** if it is numeric
echo "The input is numeric";
}else{
echo "The input is not numeric";
}
?>
Version 1.3.0 has flaw IMO.
Downgrade to version 1.2.3 fixes my problem.
I'm on
Check if the jQuery object contains any element before you try to get its offset:
var nav = $('.content-nav');
if (nav.length) {
var contentNav = nav.offset().top;
...continue to set up the menu
}
Do you want to find elements that contain "match", or that equal "match"?
This will find elements that have text nodes that equal 'match' (matches none of the elements because of leading and trailing whitespace in random2
):
//*[text()='match']
This will find all elements that have text nodes that equal "match", after removing leading and trailing whitespace(matches random2
):
//*[normalize-space(text())='match']
This will find all elements that contain 'match' in the text node value (matches random2
and random3
):
//*[contains(text(),'match')]
This XPATH 2.0 solution uses the matches()
function and a regex pattern that looks for text nodes that contain 'match' and begin at the start of the string(i.e. ^
) or a word boundary (i.e. \W
) and terminated by the end of the string (i.e. $
) or a word boundary. The third parameter i
evaluates the regex pattern case-insensitive. (matches random2
)
//*[matches(text(),'(^|\W)match($|\W)','i')]
logging.basicConfig()
can take a keyword argument handlers
since Python 3.3, which simplifies logging setup a lot, especially when setting up multiple handlers with the same formatter:
handlers
– If specified, this should be an iterable of already created handlers to add to the root logger. Any handlers which don’t already have a formatter set will be assigned the default formatter created in this function.
The whole setup can therefore be done with a single call like this:
import logging
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(message)s",
handlers=[
logging.FileHandler("debug.log"),
logging.StreamHandler()
]
)
(Or with import sys
+ StreamHandler(sys.stdout)
per original question's requirements – the default for StreamHandler is to write to stderr. Look at LogRecord attributes if you want to customize the log format and add things like filename/line, thread info etc.)
The setup above needs to be done only once near the beginning of the script. You can use the logging from all other places in the codebase later like this:
logging.info('Useful message')
logging.error('Something bad happened')
...
Note: If it doesn't work, someone else has probably already initialized the logging system differently. Comments suggest doing logging.root.handlers = []
before the call to basicConfig()
.
SELECT User FROM mysql.user;
use above query to get Mysql Users
Search for the Gemfile file in your project, go to that directory and then run "bundle install". prior to running this command make sure you have installed the gem "sudo gem install bundler"
Not a lot to go on there, but I think what you're looking for is to flip the width
and max-width
values:
#container2 {
width: 90%;
max-width: 960px;
/* etc, etc... */
}
That'll give you a container that's 90% of the width of the available space, up to a maximum of 960px, but that's dependent on its container being resizable itself. Responsive design is a whole big ball of wax though, so this doesn't even scratch the surface.
CSS tricks have a good solution to target IE 11:
http://css-tricks.com/ie-10-specific-styles/
The .NET and Trident/7.0 are unique to IE so can be used to detect IE version 11.
The code then adds the User Agent string to the html tag with the attribute 'data-useragent', so IE 11 can be targeted specifically...
Call System.Reflection.MethodBase.GetCurrentMethod().Name
from within the method.
NSString *folderName=[NSString stringWithFormat:@"/documents/%@",[tempDictLitrature objectForKey:@"folder"]];
NSString *fileName=[tempDictLitrature objectForKey:@"name"];
[self.navigationItem setTitle:fileName];
NSString *type=[tempDictLitrature objectForKey:@"type"];
NSString *path=[[NSBundle mainBundle]pathForResource:fileName ofType:type inDirectory:folderName];
NSURL *targetURL = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
webView=[[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 1024, 730)];
[webView setBackgroundColor:[UIColor lightGrayColor]];
webView.scalesPageToFit = YES;
[[webView scrollView] setContentOffset:CGPointZero animated:YES];
[webView stringByEvaluatingJavaScriptFromString:[NSString stringWithFormat:@"window.scrollTo(0.0, 50.0)"]];
[webView loadRequest:request];
[self.view addSubview:webView];
If you absolutely have to add the property to the object, I believe you could cast it as an array, add your property (as a new array key), then cast it back as an object. The only time you run into stdClass
objects (I believe) is when you cast an array as an object or when you create a new stdClass
object from scratch (and of course when you json_decode()
something - silly me for forgetting!).
Instead of:
$foo = new StdClass();
$foo->bar = '1234';
You'd do:
$foo = array('bar' => '1234');
$foo = (object)$foo;
Or if you already had an existing stdClass object:
$foo = (array)$foo;
$foo['bar'] = '1234';
$foo = (object)$foo;
Also as a 1 liner:
$foo = (object) array_merge( (array)$foo, array( 'bar' => '1234' ) );
@Clovis Six thank for your answer. It prove very usefull to me. A pity I cannot thanks you more than just a vote up.
Note: I have to change the "$J(" for "$(" for it to work on my config.
evendo, this out of the scope of this question and not in the use of SO, I extended your code to make it work for multi-line box with max-height.
/**
* Adjust the font-size of the text so it fits the container
*
* support multi-line, based on css 'max-height'.
*
* @param minSize Minimum font size?
* @param maxSize Maximum font size?
*/
$.fn.autoTextSize_UseMaxHeight = function(minSize, maxSize) {
var _self = this,
_width = _self.innerWidth(),
_boxHeight = parseInt(_self.css('max-height')),
_textHeight = parseInt(_self.getTextHeight(_width)),
_fontSize = parseInt(_self.css('font-size'));
while (_boxHeight < _textHeight || (maxSize && _fontSize > parseInt(maxSize))) {
if (minSize && _fontSize <= parseInt(minSize)) break;
_fontSize--;
_self.css('font-size', _fontSize + 'px');
_textHeight = parseInt(_self.getTextHeight(_width));
}
};
PS: I know this should be a comment, but comments don't let me post code properly.
You could use import * as
syntax. Although not a class, they are real const
variables.
Constants.js
export const factor = 3;
export const pi = 3.141592;
index.js
import * as Constants from 'Constants.js'
console.log( Constants.factor );
I have been trying to find a way to refresh the tableView(ScalaFx) for 3-4 hours. Finally I got a answer. I just want to publish my solution because of i wasted already hours.
-To retrieve the rows from database, i used to declare a method which returns ObservableBuffer.
My JDBC CLASS
//To get all customer details
def getCustomerDetails : ObservableBuffer[Customer] = {
val customerDetails = new ObservableBuffer[Customer]()
try {
val resultSet = statement.executeQuery("SELECT * FROM MusteriBilgileri")
while (resultSet.next()) {
val musteriId = resultSet.getString("MusteriId")
val musteriIsmi = resultSet.getString("MusteriIsmi")
val urununTakildigiTarih = resultSet.getDate("UrununTakildigiTarih").toString
val bakimTarihi = resultSet.getDate("BakimTarihi").toString
val urununIsmi = resultSet.getString("UrununIsmi")
val telNo = resultSet.getString("TelNo")
val aciklama = resultSet.getString("Aciklama")
customerDetails += new Customer(musteriId,musteriIsmi,urununTakildigiTarih,bakimTarihi,urununIsmi,telNo,aciklama)
}
} catch {
case e => e.printStackTrace
}
customerDetails
}
-And I have created a TableView object.
var table = new TableView[Customer](model.getCustomerDetails)
table.columns += (customerIdColumn,customerNameColumn,productInstallColumn,serviceDateColumn,
productNameColumn,phoneNoColumn,detailColumn)
-And Finally i got solution. In the refresh button, i have inserted this code;
table.setItems(FXCollections.observableArrayList(model.getCustomerDetails.delegate))
model is the reference of my jdbc connection class
val model = new ScalaJdbcConnectSelect
This is the scalafx codes but it gives some idea to javafx
var currentdate = new Date();
var datetime = "Last Sync: " + currentdate.getDate() + "/"+(currentdate.getMonth()+1)
+ "/" + currentdate.getFullYear() + " @ "
+ currentdate.getHours() + ":"
+ currentdate.getMinutes() + ":" + currentdate.getSeconds();
Change .getDay()
method to .GetDate()
and add one to month, because it counts months from 0.
This link goes to the best comparison chart around, directly from the Microsoft. It compares ALL aspects of all MS SQL server editions. To compare three editions you are asking about, just focus on the last three columns of every table in there.
Summary compiled from the above document:
* = contains the feature SQLEXPR SQLEXPRWT SQLEXPRADV ---------------------------------------------------------------------------- > SQL Server Core * * * > SQL Server Management Studio - * * > Distributed Replay – Admin Tool - * * > LocalDB - * * > SQL Server Data Tools (SSDT) - - * > Full-text and semantic search - - * > Specification of language in query - - * > some of Reporting services features - - *
I had the same problem of "gpg: keyserver timed out" with a couple of different servers. Finally, it turned out that I didn't need to do that manually at all. On a Debian system, the simple solution which fixed it was just (as root or precede with sudo):
aptitude install debian-archive-keyring
In case it is some other keyring you need, check out
apt-cache search keyring | grep debian
My squeeze system shows all these:
debian-archive-keyring - GnuPG archive keys of the Debian archive
debian-edu-archive-keyring - GnuPG archive keys of the Debian Edu archive
debian-keyring - GnuPG keys of Debian Developers
debian-ports-archive-keyring - GnuPG archive keys of the debian-ports archive
emdebian-archive-keyring - GnuPG archive keys for the emdebian repository
Here an alternative to the one liner from jim, this time in a script
ARGV[0..-3].each{|f| File.write(f, File.read(f).gsub(ARGV[-2],ARGV[-1]))}
Save it in a script, eg replace.rb
You start in on the command line with
replace.rb *.txt <string_to_replace> <replacement>
*.txt can be replaced with another selection or with some filenames or paths
broken down so that I can explain what's happening but still executable
# ARGV is an array of the arguments passed to the script.
ARGV[0..-3].each do |f| # enumerate the arguments of this script from the first to the last (-1) minus 2
File.write(f, # open the argument (= filename) for writing
File.read(f) # open the argument (= filename) for reading
.gsub(ARGV[-2],ARGV[-1])) # and replace all occurances of the beforelast with the last argument (string)
end
EDIT: if you want to use a regular expression use this instead Obviously, this is only for handling relatively small text files, no Gigabyte monsters
ARGV[0..-3].each{|f| File.write(f, File.read(f).gsub(/#{ARGV[-2]}/,ARGV[-1]))}
1 & 2
myVar = 8; //not dynamically allocated. Can't call delete on it.
myPointer = new int; //dynamically allocated, can call delete on it.
The first variable was allocated on the stack. You can call delete only on memory you allocated dynamically (on the heap) using the new
operator.
3.
myPointer = NULL;
delete myPointer;
The above did nothing at all. You didn't free anything, as the pointer pointed at NULL.
The following shouldn't be done:
myPointer = new int;
myPointer = NULL; //leaked memory, no pointer to above int
delete myPointer; //no point at all
You pointed it at NULL, leaving behind leaked memory (the new int you allocated).
You should free the memory you were pointing at. There is no way to access that allocated new int
anymore, hence memory leak.
The correct way:
myPointer = new int;
delete myPointer; //freed memory
myPointer = NULL; //pointed dangling ptr to NULL
The better way:
If you're using C++, do not use raw pointers. Use smart pointers instead which can handle these things for you with little overhead. C++11 comes with several.
HashMap
is unordered per the second line of the documentation:
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
Perhaps you can do as aix suggests and use a LinkedHashMap
, or another ordered collection. This link can help you find the most appropriate collection to use.
1. Installing OpenCV 2.4.3
First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\
.
Wait until all files get extracted. It will create a new directory C:\opencv
which
contains OpenCV header files, libraries, code samples, etc.
Now you need to add the directory C:\opencv\build\x86\vc10\bin
to your system PATH. This directory contains OpenCV DLLs required for running your code.
Open Control Panel → System → Advanced system settings → Advanced Tab → Environment variables...
On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin;
(3), then click Ok.
On some computers, you may need to restart your computer for the system to recognize the environment path variables.
This will completes the OpenCV 2.4.3 installation on your computer.
2. Create a new project and set up Visual C++
Open Visual C++ and select File → New → Project... → Visual C++ → Empty Project. Give a name for your project (e.g: cvtest
) and set the project location (e.g: c:\projects
).
Click Ok. Visual C++ will create an empty project.
Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest
and select Properties → VC++ Directories.
Select Include Directories to add a new entry and type C:\opencv\build\include
.
Click Ok to close the dialog.
Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib
.
Click Ok to close the dialog.
Back to the property dialog, select Linker → Input → Additional Dependencies to add new entries. On the popup dialog, type the files below:
opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib
Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).
Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.
NOTE:
These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:
opencv_core243.lib
opencv_imgproc243.lib
...
instead of:
opencv_core243d.lib
opencv_imgproc243d.lib
...
You've done setting up Visual C++, now is the time to write the real code. Right click your project and select Add → New Item... → Visual C++ → C++ File.
Name your file (e.g: loadimg.cpp
) and click Ok. Type the code below in the editor:
#include <opencv2/highgui/highgui.hpp>
#include <iostream>
using namespace cv;
using namespace std;
int main()
{
Mat im = imread("c:/full/path/to/lena.jpg");
if (im.empty())
{
cout << "Cannot load image!" << endl;
return -1;
}
imshow("Image", im);
waitKey(0);
}
The code above will load c:\full\path\to\lena.jpg
and display the image. You can
use any image you like, just make sure the path to the image is correct.
Type F5 to compile the code, and it will display the image in a nice window.
And that is your first OpenCV program!
3. Where to go from here?
Now that your OpenCV environment is ready, what's next?
c:\opencv\samples\cpp
.I had this issue as well, and the text-shadow
wasn't an option because the corners would look bad (unless I had many many shadows), and I didn't want any blur, therefore my only other option was to do the following: Have 2 divs, and for the background div, put a -webkit-text-stroke
on it, which then allows for as big of an outline as you like.
div {_x000D_
font-size: 200px;_x000D_
position: absolute;_x000D_
white-space: nowrap;_x000D_
}_x000D_
_x000D_
.front {_x000D_
color: blue;_x000D_
}_x000D_
_x000D_
.outline {_x000D_
-webkit-text-stroke: 30px red;_x000D_
user-select: none;_x000D_
}
_x000D_
<div class="outline">_x000D_
outline text_x000D_
</div>_x000D_
_x000D_
<div class="front">_x000D_
outline text_x000D_
</div>
_x000D_
Using this, I was able to achieve an outline, because the stroke-width
method was not an option if you want your text to remain legible with a very large outline (because with stroke-width
the outline will start inside the lettering which makes it not legible when the width gets larger than the letters.
Note: the reason I needed such a fat outline was I was emulating the street labels in "google maps" and I wanted a fat white halo around the text. This solution worked perfectly for me.
The lack of a Linux-like backtick/backquote facility is a major annoyance of the pre-PowerShell world. Using backquotes via for-loops is not at all cosy. So we need kinda of setvar myvar cmd-line
command.
In my %path%
I have a dir with a number of bins and batches to cope with those Win shortcomings.
One batch I wrote is:
:: setvar varname cmd
:: Set VARNAME to the output of CMD
:: Triple escape pipes, eg:
:: setvar x dir c:\ ^^^| sort
:: -----------------------------
@echo off
SETLOCAL
:: Get command from argument
for /F "tokens=1,*" %%a in ("%*") do set cmd=%%b
:: Get output and set var
for /F "usebackq delims=" %%a in (`%cmd%`) do (
ENDLOCAL
set %1=%%a
)
:: Show results
SETLOCAL EnableDelayedExpansion
echo %1=!%1!
So in your case, you would type:
> setvar text echo Hello
text=Hello
The script informs you of the results, which means you can:
> echo text var is now %text%
text var is now Hello
You can use whatever command:
> setvar text FIND "Jones" names.txt
What if the command you want to pipe to some variable contains itself a pipe?
Triple escape it, ^^^|
:
> setvar text dir c:\ ^^^| find "Win"
In a node.js server console.log
outputs to the terminal window, not to the browser's console window.
How are you running your server? You should see the output directly after you start it.
Constructors don't return a type , just remove the return type which is void in your case. It would run fine then.
String characters are runes, so to print them, you have to turn them back into String.
fmt.Print(string("HELLO"[1]))
$().live(function(){}); and jQuery.browser is undefined in jquery 1.9.0 - $.browser was deprecated in jquery update
sounds like you are using a different version of jquery 1.9 in godaddy so either change your code or include the migrate plugin http://code.jquery.com/jquery-migrate-1.0.0.js
You can try this,
UPDATE *tableName* SET *field1* = *your_data*, *field2* = *your_data* ... WHERE 1 = 1;
Well in your case if you want to update your online_status to some value, you can try this,
UPDATE thisTable SET online_status = 'Online' WHERE 1 = 1;
Hope it helps. :D
In your controller you'd return an HttpStatusCodeResult like this...
[HttpPost]
public ActionResult SomeMethod(...your method parameters go here...)
{
// todo: put your processing code here
//If not using MVC5
return new HttpStatusCodeResult(200);
//If using MVC5
return new HttpStatusCodeResult(HttpStatusCode.OK); // OK = 200
}
Have you considered using span
instead of div
? It is the in-line version of div
.
To populate the column during insert, use a DEFAULT
value:
CREATE TABLE users (
id serial not null,
firstname varchar(100),
middlename varchar(100),
lastname varchar(100),
email varchar(200),
timestamp timestamp default current_timestamp
)
Note that the value for that column can explicitly be overwritten by supplying a value in the INSERT
statement. If you want to prevent that you do need a trigger.
You also need a trigger if you need to update that column whenever the row is updated (as mentioned by E.J. Brennan)
Note that using reserved words for column names is usually not a good idea. You should find a different name than timestamp
If the frames are going to be the same size, why not create the frame and pass the frame then as a reference to it instead.
When you have passed the frame you can then decide how to populate it. It would be like having a method for calculating the average of a set of figures. Would you create the method over and over again?
It can be opened using Visual Studio 2012.Follow the below path in VS after opening the project. View->Server Explorer->
(int) add: (int) numberOne plus: (int) numberTwo ;
(returnType) functionPrimaryName : (returnTypeOfArgumentOne) argumentName functionSecondaryNa
me:
(returnTypeOfSecontArgument) secondArgumentName ;
as in other languages we use following syntax
void add(int one, int second)
but way of assigning arguments in OBJ_c
is different as described above
cv:Mat mat;
int rows = mat.rows;
int cols = mat.cols;
cv::Size s = mat.size();
rows = s.height;
cols = s.width;
Also note that stride >= cols; this means that actual size of the row can be greater than element size x cols. This is different from the issue of continuous Mat and is related to data alignment.
As you keep getting pages of results I'm assuming you started the session in SQL*Plus. If so, the easy thing to do is to bash ctrl + break many, many times until it stops.
The more complicated and the more generic way(s) I detail below in order of increasing ferocity / evil. The first one will probably work for you but if it doesn't you can keep moving down the list.
Most of these are not recommended and can have unintended consequences.
As per ObiWanKenobi's answer and the ALTER SESSION documentation
alter system kill session 'sid,serial#';
To find the sid
, session id, and the serial#
, serial number, run the following query - summarised from OracleBase - and find your session:
select s.sid, s.serial#, p.spid, s.username, s.schemaname
, s.program, s.terminal, s.osuser
from v$session s
join v$process p
on s.paddr = p.addr
where s.type != 'BACKGROUND'
If you're running a RAC then you need to change this slightly to take into account the multiple instances, inst_id
is what identifies them:
select s.inst_id, s.sid, s.serial#, p.spid, s.username
, s.schemaname, s.program, s.terminal, s.osuser
from Gv$session s
join Gv$process p
on s.paddr = p.addr
and s.inst_id = p.inst_id
where s.type != 'BACKGROUND'
This query would also work if you're not running a RAC.
If you're using a tool like PL/SQL Developer then the sessions window will also help you find it.
For a slightly stronger "kill" you can specify the IMMEDIATE keyword, which instructs the database to not wait for the transaction to complete:
alter system kill session 'sid,serial#' immediate;
kill pid
This assumes you're using Linux or another *nix variant. A SIGTERM is a terminate signal from the operating system to the specific process asking it to stop running. It tries to let the process terminate gracefully.
Getting this wrong could result in you terminating essential OS processes so be careful when typing.
You can find the pid
, process id, by running the following query, which'll also tell you useful information like the terminal the process is running from and the username that's running it so you can ensure you pick the correct one.
select p.*
from v$process p
left outer join v$session s
on p.addr = s.paddr
where s.sid = ?
and s.serial# = ?
Once again, if you're running a RAC you need to change this slightly to:
select p.*
from Gv$process p
left outer join Gv$session s
on p.addr = s.paddr
where s.sid = ?
and s.serial# = ?
Changing the where
clause to where s.status = 'KILLED'
will help you find already killed process that are still "running".
kill -9 pid
Using the same pid
you picked up in 2, a SIGKILL is a signal from the operating system to a specific process that causes the process to terminate immediately. Once again be careful when typing.
This should rarely be necessary. If you were doing DML or DDL it will stop any rollback being processed and may make it difficult to recover the database to a consistent state in the event of failure.
All the remaining options will kill all sessions and result in your database - and in the case of 6 and 7 server as well - becoming unavailable. They should only be used if absolutely necessary...
shutdown immediate
This is actually politer than a SIGKILL, though obviously it acts on all processes in the database rather than your specific process. It's always good to be polite to your database.
Shutting down the database should only be done with the consent of your DBA, if you have one. It's nice to tell the people who use the database as well.
It closes the database, terminating all sessions and does a rollback
on all uncommitted transactions. It can take a while if you have large uncommitted transactions that need to be rolled back.
shutdown abort
This is approximately the same as a SIGKILL, though once again on all processes in the database. It's a signal to the database to stop everything immediately and die - a hard crash. It terminates all sessions and does no rollback; because of this it can mean that the database takes longer to startup
again. Despite the incendiary language a shutdown abort
isn't pure evil and can normally be used safely.
As before inform people the relevant people first.
reboot
Obviously, this not only stops the database but the server as well so use with caution and with the consent of your sysadmins in addition to the DBAs, developers, clients and users.
I've had reboot not work... Once you've reached this stage you better hope you're using a VM. We ended up deleting it...
Where the usage of a regex can be helpful to determine if the character sequence of a date is correct, it cannot be used easily to determine if the date is valid. The following examples will pass the regular expression, but are all invalid dates: 20180231, 20190229, 20190431
So if you want to validate if your date string (let's call it datestr
) is in the correct format, it is best to parse it with date
and ask date
to convert the string to the correct format. If both strings are identical, you have a valid format and valid date.
if [[ "$datestr" == $(date -d "$datestr" "+%Y%m%d" 2>/dev/null) ]]; then
echo "Valid date"
else
echo "Invalid date"
fi
To check with current branch:
git diff -- projects/components/some.component.ts ... origin
git diff -- projects/components/some.component.html ... origin
To check with some other branch say staging:
git diff -- projects/components/some.component.ts ... origin/staging
git diff -- projects/components/some.component.html ... origin/staging
I will share my solution which worked for me in a create-react-app project:
in the same images folder include a js file which exports all the images, and in components where you need the image import that image and use it :), Yaaah thats it, lets see in detail
// js file in images folder
export const missing = require('./missingposters.png');
export const poster1 = require('./poster1.jpg');
export const poster2 = require('./poster2.jpg');
export const poster3 = require('./poster3.jpg');
export const poster4 = require('./poster4.jpg');
you can import in you component: import {missing , poster1, poster2, poster3, poster4} from '../../assets/indexImages';
you can now use this as src to image tag.
Happy coding!
You'll have to configure the server to interpret .html
files as .php
files. This configuration is different depending on the server software. This will also add an extra step to the server and will slow down response on all your pages and is probably not ideal.
It's used to load modules. Let's use a simple example.
In file circle_object.js
:
var Circle = function (radius) {
this.radius = radius
}
Circle.PI = 3.14
Circle.prototype = {
area: function () {
return Circle.PI * this.radius * this.radius;
}
}
We can use this via require
, like:
node> require('circle_object')
{}
node> Circle
{ [Function] PI: 3.14 }
node> var c = new Circle(3)
{ radius: 3 }
node> c.area()
The require()
method is used to load and cache JavaScript modules. So, if you want to load a local, relative JavaScript module into a Node.js application, you can simply use the require()
method.
Example:
var yourModule = require( "your_module_name" ); //.js file extension is optional
As I understand it, you want the server be able to send messages through from client 1 to client 2. You cannot directly connect two clients because one of the two ends of a WebSocket connection needs to be a server.
This is some pseudocodish JavaScript:
Client:
var websocket = new WebSocket("server address");
websocket.onmessage = function(str) {
console.log("Someone sent: ", str);
};
// Tell the server this is client 1 (swap for client 2 of course)
websocket.send(JSON.stringify({
id: "client1"
}));
// Tell the server we want to send something to the other client
websocket.send(JSON.stringify({
to: "client2",
data: "foo"
}));
Server:
var clients = {};
server.on("data", function(client, str) {
var obj = JSON.parse(str);
if("id" in obj) {
// New client, add it to the id/client object
clients[obj.id] = client;
} else {
// Send data to the client requested
clients[obj.to].send(obj.data);
}
});
Note that Git 1.9/2.0 (Q1 2014) has removed that limitation.
See commit 82fba2b, from Nguy?n Thái Ng?c Duy (pclouds
):
Now that git supports data transfer from or to a shallow clone, these limitations are not true anymore.
--depth <depth>::
Create a 'shallow' clone with a history truncated to the specified number of revisions.
That stems from commits like 0d7d285, f2c681c, and c29a7b8 which support clone, send-pack /receive-pack with/from shallow clones.
smart-http now supports shallow fetch/clone too.
All the details are in "shallow.c
: the 8 steps to select new commits for .git/shallow
".
Update June 2015: Git 2.5 will even allow for fetching a single commit!
(Ultimate shallow case)
Update January 2016: Git 2.8 (Mach 2016) now documents officially the practice of getting a minimal history.
See commit 99487cf, commit 9cfde9e (30 Dec 2015), commit 9cfde9e (30 Dec 2015), commit bac5874 (29 Dec 2015), and commit 1de2e44 (28 Dec 2015) by Stephen P. Smith (``).
(Merged by Junio C Hamano -- gitster
-- in commit 7e3e80a, 20 Jan 2016)
This is "Documentation/user-manual.txt
"
A
<<def_shallow_clone,shallow clone>>
is created by specifying thegit-clone --depth
switch.
The depth can later be changed with thegit-fetch --depth
switch, or full history restored with--unshallow
.Merging inside a
<<def_shallow_clone,shallow clone>>
will work as long as a merge base is in the recent history.
Otherwise, it will be like merging unrelated histories and may have to result in huge conflicts.
This limitation may make such a repository unsuitable to be used in merge based workflows.
Update 2020:
git fetch --shallow-exclude=
to prevent fetching all historygit fetch --shallow-since=
to prevent fetching old commits.For more on the shallow clone update process, see "How to update a git shallow clone?".
As commented by Richard Michael:
to backfill history:
git pull --unshallow
And Olle Härstedt adds in the comments:
To backfill part of the history:
git fetch --depth=100
.
I ran into this problem today and none of the solutions posted here worked. However, the code posted here worked for a POST request:
// HTTP POST request
private void sendPost() throws Exception {
String url = "https://selfsolve.apple.com/wcResults.do";
URL obj = new URL(url);
HttpsURLConnection con = (HttpsURLConnection) obj.openConnection();
//add reuqest header
con.setRequestMethod("POST");
con.setRequestProperty("User-Agent", USER_AGENT);
con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
String urlParameters = "sn=C02G8416DRJM&cn=&locale=&caller=&num=12345";
// Send post request
con.setDoOutput(true);
DataOutputStream wr = new DataOutputStream(con.getOutputStream());
wr.writeBytes(urlParameters);
wr.flush();
wr.close();
int responseCode = con.getResponseCode();
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + urlParameters);
System.out.println("Response Code : " + responseCode);
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
in.close();
//print result
System.out.println(response.toString());
}
It turns out that it's not the authorization that's the problem. In my case, it was an encoding problem. The content-type I needed was application/json but from the Java documentation:
static String encode(String s, String enc)
Translates a string into application/x-www-form-urlencoded format using a specific encoding scheme.
The encode function translates the string into application/x-www-form-urlencoded.
Now if you don't set a Content-Type, you may get a 415 Unsupported Media Type error. If you set it to application/json or anything that's not application/x-www-form-urlencoded, you get an IOException. To solve this, simply avoid the encode method.
For this particular scenario, the following should work:
String data = "product[title]=" + title +
"&product[content]=" + content +
"&product[price]=" + price.toString() +
"&tags=" + tags;
Another small piece of information that might be helpful as to why the code breaks when creating the buffered reader is because the POST request actually only gets executed when conn.getInputStream() is called.
Try this:
Sub GetColumns()
Dim lnRow As Long, lnCol As Long
lnRow = 3 'For testing
lnCol = Sheet1.Cells(lnRow, 1).EntireRow.Find(What:="sds", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column
End Sub
Probably best not to use colIndex and rowIndex as variable names as they are already mentioned in the Excel Object Library.
You can try just putting the image in the source directory. You'd link it by replacing the file path with src="../imagenamehere.fileextension
In your case, j3evn.jpg.
If you don't want to actually navigate to a new page you can also have your anchor somewhere on the page like this.
<a id="the_anchor" href="">
And then to assign your string of JavaScript to the the onclick of the anchor, put this somewhere else (i.e. the header, later in the body, whatever):
<script>
var js = "alert('I am your string of JavaScript');"; // js is your string of script
document.getElementById('the_anchor').href = 'javascript:' + js;
</script>
If you have all of this info on the server before sending out the page, then you could also simply place the JavaScript directly in the href
attribute of the anchor like so:
<a href="javascript:alert('I am your script.'); alert('So am I.');">Click me</a>
This problem was solved for me by repairing vmware
with the run installer which fixed the services correctly.
You can use outline with outline offset
<div class="double-border"></div>
.double-border{
background-color:#ccc;
outline: 1px solid #f00;
outline-offset: 3px;
}
Click on View/Show Symbol/Show All Character - to show the [SOH] characters in the file Click on the [SOH] symbol in the file CTRL=H to bring up the replace Leave the 'Find What:' as is Change the 'Replace with:' to the character of your choosing (comma,semicolon, other...) Click 'Replace All' Done and done!
@Espo: I just have to say that regex is incredible. I'd hate to have to write the code that did something useful with the matches, such as if you wanted to actually find out what date and time the user typed.
It seems like Tom's solution would be more tenable, as it is about a zillion times simpler and with the addition of some parentheses you can easily get at the values the user typed:
(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})
If you're using perl, then you can get the values out with something like this:
$year = $1;
$month = $2;
$day = $3;
$hour = $4;
$minute = $5;
$second = $6;
Other languages will have a similar capability. Note that you will need to make some minor mods to the regex if you want to accept values such as single-digit months.
One equivalent of lsof could be combined output from Sysinternals' handle and listdlls, i.e.:
c:\SysInternals>handle
[...]
------------------------------------------------------------------------------
gvim.exe pid: 5380 FOO\alois.mahdal
10: File (RW-) C:\Windows
1C: File (RW-) D:\some\locked\path\OpenFile.txt
[...]
c:\SysInternals>listdlls
[...]
------------------------------------------------------------------------------
Listdlls.exe pid: 6840
Command line: listdlls
Base Size Version Path
0x00400000 0x29000 2.25.0000.0000 D:\opt\SysinternalsSuite\Listdlls.exe
0x76ed0000 0x180000 6.01.7601.17725 C:\Windows\SysWOW64\ntdll.dll
[...]
c:\SysInternals>listdlls
Unfortunately, you have to "run as Administrator" to be able to use them.
Also listdlls and handle do not produce continuous table-like form so filtering filename would hide PID. findstr /c:pid: /c:<filename>
should get you very close with both utilities, though
c:\SysinternalsSuite>handle | findstr /c:pid: /c:Driver.pm
System pid: 4 \<unable to open process>
smss.exe pid: 308 NT AUTHORITY\SYSTEM
avgrsa.exe pid: 384 NT AUTHORITY\SYSTEM
[...]
cmd.exe pid: 7140 FOO\alois.mahdal
conhost.exe pid: 1212 FOO\alois.mahdal
gvim.exe pid: 3408 FOO\alois.mahdal
188: File (RW-) D:\some\locked\path\OpenFile.txt
taskmgr.exe pid: 6016 FOO\alois.mahdal
[...]
Here we can see that gvim.exe is the one having this file open.
If you are using a newer version (over 1.3.x) you should learn more about the function parseJSON! I experienced the same problem. Use an old version or change your code
success=function(data){
//something like this
jQuery.parseJSON(data)
}
My answer addresses the specific (and somewhat common) case where you don't really need to convert the entire xml to json, but what you need is to traverse/access specific parts of the xml, and you need it to be fast, and simple (using json/dict-like operations).
For this, it is important to note that parsing an xml to etree using lxml
is super fast. The slow part in most of the other answers is the second pass: traversing the etree structure (usually in python-land), converting it to json.
Which leads me to the approach I found best for this case: parsing the xml using lxml
, and then wrapping the etree nodes (lazily), providing them with a dict-like interface.
Here's the code:
from collections import Mapping
import lxml.etree
class ETreeDictWrapper(Mapping):
def __init__(self, elem, attr_prefix = '@', list_tags = ()):
self.elem = elem
self.attr_prefix = attr_prefix
self.list_tags = list_tags
def _wrap(self, e):
if isinstance(e, basestring):
return e
if len(e) == 0 and len(e.attrib) == 0:
return e.text
return type(self)(
e,
attr_prefix = self.attr_prefix,
list_tags = self.list_tags,
)
def __getitem__(self, key):
if key.startswith(self.attr_prefix):
return self.elem.attrib[key[len(self.attr_prefix):]]
else:
subelems = [ e for e in self.elem.iterchildren() if e.tag == key ]
if len(subelems) > 1 or key in self.list_tags:
return [ self._wrap(x) for x in subelems ]
elif len(subelems) == 1:
return self._wrap(subelems[0])
else:
raise KeyError(key)
def __iter__(self):
return iter(set( k.tag for k in self.elem) |
set( self.attr_prefix + k for k in self.elem.attrib ))
def __len__(self):
return len(self.elem) + len(self.elem.attrib)
# defining __contains__ is not necessary, but improves speed
def __contains__(self, key):
if key.startswith(self.attr_prefix):
return key[len(self.attr_prefix):] in self.elem.attrib
else:
return any( e.tag == key for e in self.elem.iterchildren() )
def xml_to_dictlike(xmlstr, attr_prefix = '@', list_tags = ()):
t = lxml.etree.fromstring(xmlstr)
return ETreeDictWrapper(
t,
attr_prefix = '@',
list_tags = set(list_tags),
)
This implementation is not complete, e.g., it doesn't cleanly support cases where an element has both text and attributes, or both text and children (only because I didn't need it when I wrote it...) It should be easy to improve it, though.
In my specific use case, where I needed to only process specific elements of the xml, this approach gave a suprising and striking speedup by a factor of 70 (!) compared to using @Martin Blech's xmltodict and then traversing the dict directly.
As a bonus, since our structure is already dict-like, we get another alternative implementation of xml2json
for free. We just need to pass our dict-like structure to json.dumps
. Something like:
def xml_to_json(xmlstr, **kwargs):
x = xml_to_dictlike(xmlstr, **kwargs)
return json.dumps(x)
If your xml includes attributes, you'd need to use some alphanumeric attr_prefix
(e.g. "ATTR_"), to ensure the keys are valid json keys.
I haven't benchmarked this part.
After a few hours of messing around I eventually got something that works, partially answered in a similar issue here: How do I include a JavaScript file in another JavaScript file?
BUT there was an import that was screwing the rest of it up:
.vue
files<script>
var mylib = require('./mylib');
export default {
....
mylib
exports.myfunc = () => {....}
import
The actual issue in my case (which I didn't think was relevant!) was that mylib.js
was itself using other dependencies. The resulting error seems to have nothing to do with this, and there was no transpiling error from webpack
but anyway I had:
import models from './model/models'
import axios from 'axios'
This works so long as I'm not using mylib
in a .vue
component. However as soon as I use mylib
there, the error described in this issue arises.
I changed to:
let models = require('./model/models');
let axios = require('axios');
And all works as expected.
Workaround:
template<class T, size_t N>
struct simple_array { // like std::array in C++0x
T arr[N];
};
class C : private simple_array<int, 3>
{
static simple_array<int, 3> myarr() {
simple_array<int, 3> arr = {1,2,3};
return arr;
}
public:
C() : simple_array<int, 3>(myarr()) {}
};
Answer to your first question is : both are similar,
Answer to your second question is: one-to-many --> a MAN(MAN table) may have more than one wife(WOMEN table) many-to-one --> more than one women have married one MAN.
Now if you want to relate this relation with two tables MAN and WOMEN, one MAN table row may have many relations with rows in the WOMEN table. hope it clear.
I'm going to agree with shodanex, it looks like you're prematurely trying to optimize something that isn't yet problematic. Unless you know sockets are going to be a bottleneck, I'd just use them.
A lot of people who swear by named pipes find a little savings (depending on how well everything else is written), but end up with code that spends more time blocking for an IPC reply than it does doing useful work. Sure, non-blocking schemes help this, but those can be tricky. Spending years bringing old code into the modern age, I can say, the speedup is almost nil in the majority of cases I've seen.
If you really think that sockets are going to slow you down, then go out of the gate using shared memory with careful attention to how you use locks. Again, in all actuality, you might find a small speedup, but notice that you're wasting a portion of it waiting on mutual exclusion locks. I'm not going to advocate a trip to futex hell (well, not quite hell anymore in 2015, depending upon your experience).
Pound for pound, sockets are (almost) always the best way to go for user space IPC under a monolithic kernel .. and (usually) the easiest to debug and maintain.
For general information: by default to ssh-connect you may simply use
user: vagrant
password: vagrant
https://www.vagrantup.com/docs/boxes/base.html#quot-vagrant-quot-user
First, try: to see what vagrant insecure_private_key
is in your machine config
$ vagrant ssh-config
Example:
$ vagrant ssh-config
Host default
HostName 127.0.0.1
User vagrant
Port 2222
UserKnownHostsFile /dev/null
StrictHostKeyChecking no
PasswordAuthentication no
IdentityFile C:/Users/konst/.vagrant.d/insecure_private_key
IdentitiesOnly yes
LogLevel FATAL
http://docs.vagrantup.com/v2/cli/ssh_config.html
Second, do:
Change the contents of file insecure_private_key
with the contents of your personal system private key
Or use: Add it to the Vagrantfile:
Vagrant.configure("2") do |config|
config.ssh.private_key_path = "~/.ssh/id_rsa"
config.ssh.forward_agent = true
end
config.ssh.private_key_path
is your local private keyssh-add -L
. If it's not listed, add it with ssh-add ~/.ssh/id_rsa
~/.ssh/authorized_keys
on the Vagrant VM. You can do it by copy-and-pasting or using a tool like ssh-copy-id (user: root
password: vagrant
port: 2222) ssh-copy-id '-p 2222 [email protected]'
If still does not work try this:
Remove insecure_private_key
file from c:\Users\USERNAME\.vagrant.d\insecure_private_key
Run vagrant up
(vagrant will be generate a new insecure_private_key
file)
In other cases, it is helpful to just set forward_agent in Vagrantfile
:
Vagrant::Config.run do |config|
config.ssh.forward_agent = true
end
Useful:
Configurating git may be with git-scm.com
After setup this program and creating personal system private key will be in yours profile path: c:\users\USERNAME\.ssh\id_rsa.pub
PS: Finally - suggest you look at Ubuntu on Windows 10
Use the Controller's Redirect() method.
public ActionResult YourAction()
{
// ...
return Redirect("http://www.example.com");
}
Update
You can't directly perform a server side redirect from an ajax response. You could, however, return a JsonResult with the new url and perform the redirect with javascript.
public ActionResult YourAction()
{
// ...
return Json(new {url = "http://www.example.com"});
}
$.post("@Url.Action("YourAction")", function(data) {
window.location = data.url;
});
https://www.w3schools.com/tags/av_event_timeupdate.asp
// Get the <video> element with id="myVideo"
var vid = document.getElementById("myVideo");
// Assign an ontimeupdate event to the <video> element, and execute a function if the current playback position has changed
vid.ontimeupdate = function() {myFunction()};
function myFunction() {
// Display the current position of the video in a <p> element with id="demo"
document.getElementById("demo").innerHTML = vid.currentTime;
}
Not the right function name I think
$(document).ready(function() {
$('.datepicker').datetimepicker({
format: 'dd/mm/yyyy'
});
});
var input = document.createElement("input");
input.setAttribute("type", "hidden");
input.setAttribute("name", "name_you_want");
input.setAttribute("value", "value_you_want");
//append to form element that you want .
document.getElementById("chells").appendChild(input);
This regex extracts an element from a comma separated list, regardless of contents:
(.+?)(?:,|$)
If you just replace the comma with something else, it should work for any delimiter.
Can't comment the last answer but the fix is relatively easy. Just set the background color of your opaque canvas:
#canvas1 { background-color: black; } //opaque canvas
#canvas2 { ... } //transparent canvas
I'm not sure but it looks like that the background-color is inherited as transparent from the body.
First I would like to thank Rose who was willing to help us, but your answer could solve the problem on a computer, but in others there was what was done could not always connect gets error 720. After much searching and contact the Microsoft support we can solve. In Device Manager, on the View menu, select to show hidden devices. Made it look for a remote Miniport IP or network monitor that is with warning of problems with the driver icon. In its properties in the details tab check the Key property of the driver. Look for this key in Regedit on Local Machine, make a backup of that key and delete it. Restart your windows. Reopen your device manager and select the miniport that had deleted the record. Activate the option to update the driver and look for the option driver on the computer manually and then use the option to locate the driver from the list available on the computer on the next screen uncheck show compatible hardware. Then you must select the Microsoft Vendor and the driver WAN Miniport the type that is changing, IP or IPV6 L2TP Network Monitor. After upgrading restart the computer.
I know it's a bit laborious but that was the only way that worked on all computers.
if setting height to 100% doesn't work, try min-height=100% for div. You still have to set the html tag.
html {
height: 100%;
margin: 0px;
padding: 0px;
position: relative;
}
#fullHeight{
width: 450px;
**min-height: 100%;**
background-color: blue;
}
I was facing the same issue, the funny thing was I had two projects opened on simultaneously, I have changed the wrong app.modules.ts files.
First, check that.
After that change add the following code to the app.module.ts file
import { HttpClientModule } from '@angular/common/http';
After that add the following to the imports array in the app.module.ts file
imports: [
HttpClientModule,....
],
Now you should be ok!
My understanding is that if you use a View
object (as supposed to eg. android:windowBackground
) Android will automatically scale your image to the correct size. The problem is that too much scaling can result in artifacts (both during up and down scaling) and blurring. Due to various resolutions and aspects ratios on the market, it's impossible to create "perfect" fits for every screen, but you can do your best to make sure only a little bit of scaling has to be done, and thus mitigate the unwanted side effects. So what I would do is:
getDisplayMetrics().density
returns 4 (xxxhdpi), so perhaps this info is outdated.Then look at the new phone models on the market, and find the representative ones. Assumming the new google pixel is a good representation of an android phone: It has a 1080 x 1920 resolution at 441 dpi, and a screen size of 4.4 x 2.5 inches. Then from the the android developer docs:
- ldpi (low) ~120dpi
- mdpi (medium) ~160dpi
- hdpi (high) ~240dpi
- xhdpi (extra-high) ~320dpi
- xxhdpi (extra-extra-high) ~480dpi
- xxxhdpi (extra-extra-extra-high) ~640dpi
This corresponds to an xxhdpi
screen. From here I could scale these 1080 x 1920 down by the (3:4:6:8:12) ratios above.
sw
, long
, large
, etc.<item name="android:windowBackground">@null</item>
Your data class doesn't match the JSON object. Use this instead:
[DataContract]
public class GoogleSearchResults
{
[DataMember]
public ResponseData responseData { get; set; }
}
[DataContract]
public class ResponseData
{
[DataMember]
public IEnumerable<Results> results { get; set; }
}
[DataContract]
public class Results
{
[DataMember]
public string unescapedUrl { get; set; }
[DataMember]
public string url { get; set; }
[DataMember]
public string visibleUrl { get; set; }
[DataMember]
public string cacheUrl { get; set; }
[DataMember]
public string title { get; set; }
[DataMember]
public string titleNoFormatting { get; set; }
[DataMember]
public string content { get; set; }
}
Also, you don't have to instantiate the class to get its type for deserialization:
public static T Deserialise<T>(string json)
{
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(json)))
{
var serialiser = new DataContractJsonSerializer(typeof(T));
return (T)serialiser.ReadObject(ms);
}
}
Google Drive folders can be embedded and displayed in list
and grid
views:
<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID#list" style="width:100%; height:600px; border:0;"></iframe>
<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID#grid" style="width:100%; height:600px; border:0;"></iframe>
Q: What is a folder ID (FOLDER-ID) and how can I get it?
A: Go to Google Drive >> open the folder >> look at its URL in the address bar of your browser. For example:
Folder URL: https://drive.google.com/drive/folders/0B1iqp0kGPjWsNDg5NWFlZjEtN2IwZC00NmZiLWE3MjktYTE2ZjZjNTZiMDY2
Folder ID:
0B1iqp0kGPjWsNDg5NWFlZjEtN2IwZC00NmZiLWE3MjktYTE2ZjZjNTZiMDY2
This technique works best for folders with public access. Folders that are shared only with certain Google accounts will cause trouble when you embed them this way. At the time of this edit, a message "You need permission" appears, with some buttons to help you "Request access" or "Switch accounts" (or possibly sign-in to a Google account). The Javascript in these buttons doesn't work properly inside an IFRAME
in Chrome.
Read more at https://productforums.google.com/forum/#!msg/drive/GpVgCobPL2Y/_Xt7sMc1WzoJ
FOR MYSQL:
ALTER TABLE `table_name` CHANGE `old_name` `new_name` VARCHAR(255) NOT NULL;
FOR ORACLE:
ALTER TABLE `table_name` RENAME COLUMN `old_name` TO `new_name`;
Apparently, it is possible. From the manual:
You can specify multiple tables in a DELETE statement to delete rows from one or more tables depending on the particular condition in the WHERE clause. However, you cannot use ORDER BY or LIMIT in a multiple-table DELETE. The table_references clause lists the tables involved in the join. Its syntax is described in Section 12.2.8.1, “JOIN Syntax”.
The example in the manual is:
DELETE t1, t2 FROM t1 INNER JOIN t2 INNER JOIN t3
WHERE t1.id=t2.id AND t2.id=t3.id;
should be applicable 1:1.
Does anyone else else think it's a waste to convert these strings to date/time objects for what is, in the end, a simple text transformation? If you're certain the incoming dates will be valid, you can just use:
>>> ddmmyyyy = "21/12/2008"
>>> yyyymmdd = ddmmyyyy[6:] + "-" + ddmmyyyy[3:5] + "-" + ddmmyyyy[:2]
>>> yyyymmdd
'2008-12-21'
This will almost certainly be faster than the conversion to and from a date.
I had the same problem extending a TextEdit. For me the mistake was I did non add "public" to the constructor. In my case it works even if I define only one constructor, the one with arguments Context
and AttributeSet
. The wired thing is that the bug reveals itself only when I build an APK (singed or not) and I transfer it to the devices. When the application is run via AndroidStudio -> RunApp on a USB connected device the app works.
Depending on what you want to accomplish, you might replace INSERT with INSERT IGNORE in your file. This will avoid generating an error for the rows that you are trying to insert and already exist.
Not an exact answer because you're using xml data and there is currently no pd.read_xml()
function (as of v0.23.4), but pandas (starting with v0.21.0) can uncompress the file for you! Thanks Wes!
import pandas as pd
import os
fn = '../data/file_to_load.json.gz'
print(os.path.isfile(fn))
df = pd.read_json(fn, lines=True, compression='gzip')
df.tail()
Yes, I think performance-wise you might find a difference as bitwise left and right shift operations can be performed with a complexity of o(1) with a huge data set.
For example, calculating the power of 2 ^ n:
int value = 1;
while (exponent<n)
{
// Print out current power of 2
value = value *2; // Equivalent machine level left shift bit wise operation
exponent++;
}
}
Similar code with a bitwise left shift operation would be like:
value = 1 << n;
Moreover, performing a bit-wise operation is like exacting a replica of user level mathematical operations (which is the final machine level instructions processed by the microcontroller and processor).
/*You might be looking something like this?
grep -vn "gloom" `grep -l "loom" ~/projects/**/trunk/src/**/*.@(h|cpp)`
The BACKQUOTES are used like brackets for commands, so in this case with -l
enabled,
the code in the BACKQUOTES will return you the file names, then with -vn to do what you wanted: have filenames, linenumbers, and also the actual lines.
UPDATE Or with xargs
grep -l "loom" ~/projects/**/trunk/src/**/*.@(h|cpp) | xargs grep -vn "gloom"
Hope that helps.*/
Please ignore what I've written above, it's rubbish.
grep -n "loom" `grep -l "loom" tt4.txt` | grep -v "gloom"
#this part gets the filenames with "loom"
#this part gets the lines with "loom"
#this part gets the linenumber,
#filename and actual line
i created a custom View DistributeLayout to do this.
This seems to be the best solution I’ve found to this problem, as long as your browser supports the ::before
pseudo element: CSS-Tricks: Centering in the Unknown.
It doesn’t require any extra markup and seems to work extremely well. I couldn’t use the display: table
method because table
elements don’t obey the max-height
property.
.block {_x000D_
height: 300px;_x000D_
text-align: center;_x000D_
background: #c0c0c0;_x000D_
border: #a0a0a0 solid 1px;_x000D_
margin: 20px;_x000D_
}_x000D_
_x000D_
.block::before {_x000D_
content: '';_x000D_
display: inline-block;_x000D_
height: 100%; _x000D_
vertical-align: middle;_x000D_
margin-right: -0.25em; /* Adjusts for spacing */_x000D_
_x000D_
/* For visualization _x000D_
background: #808080; width: 5px;_x000D_
*/_x000D_
}_x000D_
_x000D_
.centered {_x000D_
display: inline-block;_x000D_
vertical-align: middle;_x000D_
width: 300px;_x000D_
padding: 10px 15px;_x000D_
border: #a0a0a0 solid 1px;_x000D_
background: #f5f5f5;_x000D_
}
_x000D_
<div class="block">_x000D_
<div class="centered">_x000D_
<h1>Some text</h1>_x000D_
<p>But he stole up to us again, and suddenly clapping his hand on my_x000D_
shoulder, said—"Did ye see anything looking like men going_x000D_
towards that ship a while ago?"</p>_x000D_
</div>_x000D_
</div>
_x000D_
As per late 2020 this as easy as follows.
For the geometry
key to be presented on a place selected from the places dropdown, the field geometry
should be set on Autocomplete
object instance with setFields()
method.
The code should look like this.
Load the API library:
<script src="https://maps.googleapis.com/maps/api/js?key=API_KEY&libraries=places&callback=initAutocomplete"
Init the autocomplete and process the selected place data generally same as all answers above. But use autocomplete.setFields(['geometry'])
to get coordinates back;
const autocomplete;
// Init the autocomplete object
function initAutocomplete() {
autocomplete = new window.google.maps.places.Autocomplete(
document.getElementById('current_location'), { types: ["geocode"] }
);
// !!! This is where you set `geometry` field to be returned with the place.
autocomplete.setFields(['address_component', 'geometry']); // <--
autocomplete.addListener("place_changed", fillInAddress);
}
// Process the address selected by user
function fillInAddress() {
const place = autocomplete.getPlace();
// Here you can get your coordinates like this
console.log(place.geometry.location.lat());
console.log(place.geometry.location.lng());
}
See the Google API docs on Autocomplete.setFields
and geometry
option.
The vimrc file in Ubuntu (12.04 (Precise Pangolin)): I tried :scriptnames
in Vim, and it shows both /usr/share/vim/vimrc
and ~/.vimrc
.
But I had manually created ~/.vimrc
.
your panel class don't have a constructor that accepts a string
try change
RLS_strid_panel p = new RLS_strid_panel(namn1);
to
RLS_strid_panel p = new RLS_strid_panel();
p.setName1(name1);
For StaggeredGridLayoutManager
do this:
RecyclerView rv = findViewById(...);
StaggeredGridLayoutManager lm = new StaggeredGridLayoutManager(...);
rv.setLayoutManager(lm);
And to get visible item views:
int[] viewsIds = lm.findFirstCompletelyVisibleItemPositions(null);
ViewHolder firstViewHolder = rvPlantios.findViewHolderForLayoutPosition(viewsIds[0]);
View itemView = viewHolder.itemView;
Remember to check if it is empty.
step 1 : make a web service on your server
step 2 : make your application make a call to the web service and receive result sets
The best solution for me was to both
man python
mentions modifying the path in shell at $PYTHONPATH
or in python with sys.path
Other answers mention ideas for doing this using the shell. From python, adding the following lines to my script allows me to successfully run it directly from cron.
import sys
sys.path.insert(0,'/path/to/venv/lib/python3.3/site-packages');
Here's how it looks in an interactive session --
Python 3.3.2+ (default, Feb 28 2014, 00:52:16)
[GCC 4.8.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.path
['', '/usr/lib/python3.3', '/usr/lib/python3.3/plat-x86_64-linux-gnu', '/usr/lib/python3.3/lib-dynload']
>>> import requests
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'requests'
>>> sys.path.insert(0,'/path/to/venv/modules/');
>>> import requests
>>>
Ended up just using the built-in angular attribute ng-checked="model"
Very simple:
git checkout from-branch-name -- path/to/the/file/you/want
This will not checkout the from-branch-name
branch. You will stay on whatever branch you are on, and only that single file will be checked out from the specified branch.
Here's the relevant part of the manpage for git-checkout
git checkout [-p|--patch] [<tree-ish>] [--] <pathspec>...
When <paths> or --patch are given, git checkout does not switch
branches. It updates the named paths in the working tree from the
index file or from a named <tree-ish> (most often a commit). In
this case, the -b and --track options are meaningless and giving
either of them results in an error. The <tree-ish> argument can be
used to specify a specific tree-ish (i.e. commit, tag or tree) to
update the index for the given paths before updating the working
tree.
Hat tip to Ariejan de Vroom who taught me this from this blog post.
The answer by Daniel A.A. Pelsmaeker and Yesh analogy is excellent. I would like to add a bit more from hackerrank tutorial. Hope it helps a bit too.
I'm using the one used by Django and it seems to work pretty well:
def is_valid_url(url):
import re
regex = re.compile(
r'^https?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+[A-Z]{2,6}\.?|' # domain...
r'localhost|' # localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
return url is not None and regex.search(url)
You can always check the latest version here: https://github.com/django/django/blob/master/django/core/validators.py#L74
I would suggest you using my method to get a resource ID. It's Much more efficient, than using getIdentidier() method, which is slow.
Here's the code:
/**
* @author Lonkly
* @param variableName - name of drawable, e.g R.drawable.<b>image</b>
* @param ? - class of resource, e.g R.drawable.class or R.raw.class
* @return integer id of resource
*/
public static int getResId(String variableName, Class<?> ?) {
Field field = null;
int resId = 0;
try {
field = ?.getField(variableName);
try {
resId = field.getInt(null);
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
return resId;
}
if you only want the first line of the messages (the subject):
git log --pretty=format:"%s"
and if you want all the messages on this branch going back to master:
git log --pretty=format:"%s" master..HEAD
Last but not least, if you want to add little bullets for quick markdown release notes:
git log --pretty=format:"- %s" master..HEAD
This is all generally covered by Section 23.3.2 of SystemVerilog IEEE Std 1800-2012.
The simplest way is to instantiate in the main section of top, creating a named instance and wiring the ports up in order:
module top(
input clk,
input rst_n,
input enable,
input [9:0] data_rx_1,
input [9:0] data_rx_2,
output [9:0] data_tx_2
);
subcomponent subcomponent_instance_name (
clk, rst_n, data_rx_1, data_tx );
endmodule
This is described in Section 23.3.2.1 of SystemVerilog IEEE Std 1800-2012.
This has a few draw backs especially regarding the port order of the subcomponent code. simple refactoring here can break connectivity or change behaviour. for example if some one else fixs a bug and reorders the ports for some reason, switching the clk and reset order. There will be no connectivity issue from your compiler but will not work as intended.
module subcomponent(
input rst_n,
input clk,
...
It is therefore recommended to connect using named ports, this also helps tracing connectivity of wires in the code.
module top(
input clk,
input rst_n,
input enable,
input [9:0] data_rx_1,
input [9:0] data_rx_2,
output [9:0] data_tx_2
);
subcomponent subcomponent_instance_name (
.clk(clk), .rst_n(rst_n), .data_rx(data_rx_1), .data_tx(data_tx) );
endmodule
This is described in Section 23.3.2.2 of SystemVerilog IEEE Std 1800-2012.
Giving each port its own line and indenting correctly adds to the readability and code quality.
subcomponent subcomponent_instance_name (
.clk ( clk ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
So far all the connections that have been made have reused inputs and output to the sub module and no connectivity wires have been created. What happens if we are to take outputs from one component to another:
clk_gen(
.clk ( clk_sub ), // output
.en ( enable ) // input
subcomponent subcomponent_instance_name (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
This nominally works as a wire for clk_sub is automatically created, there is a danger to relying on this. it will only ever create a 1 bit wire by default. An example where this is a problem would be for the data:
Note that the instance name for the second component has been changed
subcomponent subcomponent_instance_name (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_temp ) // output [9:0]
);
subcomponent subcomponent_instance_name2 (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_temp ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
The issue with the above code is that data_temp is only 1 bit wide, there would be a compile warning about port width mismatch. The connectivity wire needs to be created and a width specified. I would recommend that all connectivity wires be explicitly written out.
wire [9:0] data_temp
subcomponent subcomponent_instance_name (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_temp ) // output [9:0]
);
subcomponent subcomponent_instance_name2 (
.clk ( clk_sub ), // input
.rst_n ( rst_n ), // input
.data_rx ( data_temp ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
Moving to SystemVerilog there are a few tricks available that save typing a handful of characters. I believe that they hinder the code readability and can make it harder to find bugs.
Use .port
with no brackets to connect to a wire/reg of the same name. This can look neat especially with lots of clk and resets but at some levels you may generate different clocks or resets or you actually do not want to connect to the signal of the same name but a modified one and this can lead to wiring bugs that are not obvious to the eye.
module top(
input clk,
input rst_n,
input enable,
input [9:0] data_rx_1,
input [9:0] data_rx_2,
output [9:0] data_tx_2
);
subcomponent subcomponent_instance_name (
.clk, // input **Auto connect**
.rst_n, // input **Auto connect**
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
endmodule
This is described in Section 23.3.2.3 of SystemVerilog IEEE Std 1800-2012.
Another trick that I think is even worse than the one above is .*
which connects unmentioned ports to signals of the same wire. I consider this to be quite dangerous in production code. It is not obvious when new ports have been added and are missing or that they might accidentally get connected if the new port name had a counter part in the instancing level, they get auto connected and no warning would be generated.
subcomponent subcomponent_instance_name (
.*, // **Auto connect**
.data_rx ( data_rx_1 ), // input [9:0]
.data_tx ( data_tx ) // output [9:0]
);
This is described in Section 23.3.2.4 of SystemVerilog IEEE Std 1800-2012.
Sometimes all you have to do to make sure the cursor is inside the text box is: click on the text box and when a menu is displayed, click on "Format text box" then click on the "text box" tab and finally modify all four margins (left, right, upper and bottom) by arrowing down until "0" appear on each margin.
if( ($_POST) && (!empty($_POST['cover_image'])) ) //verifies if post exists and cover_image is not empty
{
//execute whatever code you want
}
Before reconfiguring the global excludes file, you might want to check what it's currently configured to, using this command:
git config --get core.excludesfile
In my case, when I ran it I saw my global excludes file was configured to
~/.gitignore_globaland there were already a couple things listed there. So in the case of the given question, it might make sense to first check for an existing excludes file, and add the new file mask to it.
No need for jQuery
var type = window.location.hash.substr(1);
just get rid of those speech marks
Sub test()
Dim thesentence As String
thesentence = InputBox("Type the filename with full extension", "Raw Data File")
Range("A1").Value = thesentence
If Dir(thesentence) <> "" Then
MsgBox "File exists."
Else
MsgBox "File doesn't exist."
End If
End Sub
This is the one I like:
Option Explicit
Enum IsFileOpenStatus
ExistsAndClosedOrReadOnly = 0
ExistsAndOpenSoBlocked = 1
NotExists = 2
End Enum
Function IsFileReadOnlyOpen(FileName As String) As IsFileOpenStatus
With New FileSystemObject
If Not .FileExists(FileName) Then
IsFileReadOnlyOpen = 2 ' NotExists = 2
Exit Function 'Or not - I don't know if you want to create the file or exit in that case.
End If
End With
Dim iFilenum As Long
Dim iErr As Long
On Error Resume Next
iFilenum = FreeFile()
Open FileName For Input Lock Read As #iFilenum
Close iFilenum
iErr = Err
On Error GoTo 0
Select Case iErr
Case 0: IsFileReadOnlyOpen = 0 'ExistsAndClosedOrReadOnly = 0
Case 70: IsFileReadOnlyOpen = 1 'ExistsAndOpenSoBlocked = 1
Case Else: IsFileReadOnlyOpen = 1 'Error iErr
End Select
End Function 'IsFileReadOnlyOpen
You could use this:
string path = @"c:\projects\roott\wsdlproj\devlop\beta2\text";
string lastDirectory = path.Split(new char[] { System.IO.Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries).Last();
How about this one?
import signal
signal.pause()
This will let your program sleep until it receives a signal from some other process (or itself, in another thread), letting it know it is time to do something.
This will never work, at least not under Windows Vista or later. The key problem is that you're trying to execute this from within a Windows Service, rather than a standard Windows application. The code you've shown will work perfectly in a Windows Forms, WPF, or Console application, but it won't work at all in a Windows Service.
Windows Services cannot start additional applications because they are not running in the context of any particular user. Unlike regular Windows applications, services are now run in an isolated session and are prohibited from interacting with a user or the desktop. This leaves no place for the application to be run.
More information is available in the answers to these related questions:
The best solution to your problem, as you've probably figured out by now, is to create a standard Windows application instead of a service. These are designed to be run by a particular user and are associated with that user's desktop. This way, you can run additional applications whenever you want, using the code that you've already shown.
Another possible solution, assuming that your Console application does not require an interface or output of any sort, is to instruct the process not to create a window. This will prevent Windows from blocking the creation of your process, because it will no longer request that a Console window be created. You can find the relevant code in this answer to a related question.
Given a data URL, you can create an image (either on the page or purely in JS) by setting the src
of the image to your data URL. For example:
var img = new Image;
img.src = strDataURI;
The drawImage()
method of HTML5 Canvas Context lets you copy all or a portion of an image (or canvas, or video) onto a canvas.
You might use it like so:
var myCanvas = document.getElementById('my_canvas_id');
var ctx = myCanvas.getContext('2d');
var img = new Image;
img.onload = function(){
ctx.drawImage(img,0,0); // Or at whatever offset you like
};
img.src = strDataURI;
Edit: I previously suggested in this space that it might not be necessary to use the onload
handler when a data URI is involved. Based on experimental tests from this question, it is not safe to do so. The above sequence—create the image, set the onload
to use the new image, and then set the src
—is necessary for some browsers to surely use the results.
In the accepted answer's update you don't see the example for the to_date
function, so another solution using it would be:
from pyspark.sql import functions as F
df = df.withColumn(
'new_date',
F.to_date(
F.unix_timestamp('STRINGCOLUMN', 'MM-dd-yyyy').cast('timestamp')))
Refer https://docs.python.org/2/tutorial/controlflow.html#unpacking-argument-lists
dt = datetime.datetime(*t[:7])
The typeof operator...
typeof(T)
... won't work with the c# switch statement. But how about this? The following post contains a static class...
Is there a better alternative than this to 'switch on type'?
...that will let you write code like this:
TypeSwitch.Do(
sender,
TypeSwitch.Case<Button>(() => textBox1.Text = "Hit a Button"),
TypeSwitch.Case<CheckBox>(x => textBox1.Text = "Checkbox is " + x.Checked),
TypeSwitch.Default(() => textBox1.Text = "Not sure what is hovered over"));
#An example for counting matched groups
import re
pattern = re.compile(r'(\w+).(\d+).(\w+).(\w+)', re.IGNORECASE)
search_str = "My 11 Char String"
res = re.match(pattern, search_str)
print(len(res.groups())) # len = 4
print (res.group(1) ) #My
print (res.group(2) ) #11
print (res.group(3) ) #Char
print (res.group(4) ) #String
This script works!
#/bin/bash
if [[ ( "$#" < 1 ) || ( !( "$1" == 1 ) && !( "$1" == 0 ) ) ]] ; then
echo this script requires a 1 or 0 as first parameter.
else
echo "first parameter is $1"
xinput set-prop 12 "Device Enabled" $0
fi
But this also works, and in addition keeps the logic of the OP, since the question is about calculations. Here it is with only arithmetic expressions:
#/bin/bash
if (( $# )) && (( $1 == 0 || $1 == 1 )); then
echo "first parameter is $1"
xinput set-prop 12 "Device Enabled" $0
else
echo this script requires a 1 or 0 as first parameter.
fi
The output is the same1:
$ ./tmp.sh
this script requires a 1 or 0 as first parameter.
$ ./tmp.sh 0
first parameter is 0
$ ./tmp.sh 1
first parameter is 1
$ ./tmp.sh 2
this script requires a 1 or 0 as first parameter.
[1] the second fails if the first argument is a string
or you can simply try this in inline css
<textarea style="::placeholder{color:white}"/>
In almost any language this should work instead:
a = true && 5 || 10
a = false && 5 || 10
Try to use jquery-transport-xdr jQuery plugin for CORS requests in IE8/9.
Add the active: false
option (documentation)..
$("#accordion").accordion({ header: "h3", collapsible: true, active: false });
No doubt, most of the answers here are correct, but you can also do this:
document.addEventListener('DOMContentLoaded', function what() {
document.getElementById('hello').innerHTML = 'hi';
});
Remove your key listener or return true
when you have KEY_BACK
.
You just need the following to catch the back key (Make sure not to call super in onBackPressed()
).
Also, if you plan on having a service run in the background, make sure to look at startForeground()
and make sure to have an ongoing notification or else Android will kill your service if it needs to free memory.
@Override
public void onBackPressed() {
Log.d("CDA", "onBackPressed Called");
Intent setIntent = new Intent(Intent.ACTION_MAIN);
setIntent.addCategory(Intent.CATEGORY_HOME);
setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(setIntent);
}
Assuming you have two log-files in:
cd to C: and use:
grep -r somethingtosearch temp/*.log
It will give you a list like:
temp/my.log:somethingtosearch
temp/alsoMy.log:somethingtosearch1
temp/alsoMy.log:somethingtosearch2
If you are reading from a file then you should hear the advice given and just put it into a double.
On the other hand, if you do have, say, a string you could use boost's lexical_cast.
Here is a (very simple) example:
int Foo(std::string anInt)
{
return lexical_cast<int>(anInt);
}
if let
/if var
optional binding only works when the result of the right side of the expression is an optional. If the result of the right side is not an optional, you can not use this optional binding. The point of this optional binding is to check for nil
and only use the variable if it's non-nil
.
In your case, the tableView
parameter is declared as the non-optional type UITableView
. It is guaranteed to never be nil
. So optional binding here is unnecessary.
func tableView(tableView: UITableView, commitEditingStyle editingStyle:UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
myData.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
All we have to do is get rid of the if let
and change any occurrences of tv
within it to just tableView
.
There is a nice CLI based tool for accessing MSSQL databases now.
It's called mssql-cli
and it's a bit similar to postgres' psql
.
Install for example via pip
(global installation, for a local one omit the sudo
part):
sudo pip install mssql-cli
Use accept attribute with the MIME_type as values
<input type="file" accept="image/gif, image/jpeg" />
Since the large post above covers many different SQL approaches for Postgres versions (not only non-9.5 as in the question), I would like to add how to do it in SQLAlchemy if you are using Postgres 9.5. Instead of implementing your own upsert, you can also use SQLAlchemy's functions (which were added in SQLAlchemy 1.1). Personally, I would recommend using these, if possible. Not only because of convenience, but also because it lets PostgreSQL handle any race conditions that might occur.
Cross-posting from another answer I gave yesterday (https://stackoverflow.com/a/44395983/2156909)
SQLAlchemy supports ON CONFLICT
now with two methods on_conflict_do_update()
and on_conflict_do_nothing()
:
Copying from the documentation:
from sqlalchemy.dialects.postgresql import insert
stmt = insert(my_table).values(user_email='[email protected]', data='inserted data')
stmt = stmt.on_conflict_do_update(
index_elements=[my_table.c.user_email],
index_where=my_table.c.user_email.like('%@gmail.com'),
set_=dict(data=stmt.excluded.data)
)
conn.execute(stmt)
A plain list of the current directory, it'd be:
ls -1d */
If you want it sorted and clean:
ls -1d */ | cut -c 1- | rev | cut -c 2- | rev | sort
Remember: capitalized characters have different behavior in the sort
It took me a while to find out what is going on, but here is the summary. I hope this save people a lot of time.
Apple are not playing nice with Wi-Fi Direct, not in the same way that Android is. The Multipeer Connectivity Framework that Apple provides combines both BLE and WiFi Direct together and will only work with Apple devices and not any device that is using Wi-Fi Direct.
It states the following in this documentation - "The Multipeer Connectivity framework provides support for discovering services provided by nearby iOS devices using infrastructure Wi-Fi networks, peer-to-peer Wi-Fi, and Bluetooth personal area networks and subsequently communicating with those services by sending message-based data, streaming data, and resources (such as files)."
Additionally, Wi-Fi direct in this mode between i-Devices will need iPhone 5 and above.
There are apps that use a form of Wi-Fi Direct on the App Store, but these are using their own libraries.
If someone doesn't want to override default Control Template then here is the solution.
You can create DataTemplate for button which can have TextBlock and then you can write Property trigger on IsMouseOver property to disable mouse over effect. Height of TextBlock and Button should be same.
<Button Background="Black" Margin="0" Padding="0" BorderThickness="0" Cursor="Hand" Height="20">
<Button.ContentTemplate>
<DataTemplate>
<TextBlock Text="GO" Foreground="White" HorizontalAlignment="Center" VerticalAlignment="Center" TextDecorations="Underline" Margin="0" Padding="0" Height="20">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<Trigger Property ="IsMouseOver" Value="True">
<Setter Property= "Background" Value="Black"/>
</Trigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</DataTemplate>
</Button.ContentTemplate>
</Button>
There is another way to do this. In case you need to set only one parameter, for example 'height':
TextView textView = (TextView)findViewById(R.id.text_view);
ViewGroup.LayoutParams params = textView.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
textView.setLayoutParams(params);
A better solution is to use -webkit-columns:2;
http://jsfiddle.net/YMN7U/889/
ul { margin:0.5em auto;
-webkit-columns:2;
}
The string you give split
is the string form of a regular expression, so:
private void getId(String pdfName){
String[]tokens = pdfName.split("[\\-.]");
}
That means to split on any character in the []
(we have to escape -
with a backslash because it's special inside []
; and of course we have to escape the backslash because this is a string). (Conversely, .
is normally special but isn't special inside []
.)
20190907
OS: Win 10
I'm making an exe in c++, for some reason usting START make my program fail.
So, just use quotes:
"c:\folder\program.exe"
Use the following method.
self.imageView_VedioContainer
is the container view of your AVPlayer
.
- (void)playMedia:(UITapGestureRecognizer *)tapGesture
{
playerViewController = [[AVPlayerViewController alloc] init];
playerViewController.player = [AVPlayer playerWithURL:[[NSBundle mainBundle]
URLForResource:@"VID"
withExtension:@"3gp"]];
[playerViewController.player play];
playerViewController.showsPlaybackControls =YES;
playerViewController.view.frame=self.imageView_VedioContainer.bounds;
[playerViewController.view setAutoresizingMask:UIViewAutoresizingNone];// you can comment this line
[self.imageView_VedioContainer addSubview: playerViewController.view];
}
If the problem is happening on a specific computer,then please try the following fix provided you have Internet Explorer 11.
Please open regedit.exe as an Administrator. Navigate to the following path/paths:
For 32 bit machine:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION
For 64 bit machine:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION &
HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION
And delete the REG_DWORD
value iexplore.exe
.
Please close and relaunch the website using Internet Explorer 11, it will default to Edge as Document Mode.
CASCADE will also delete the corresponding field connected with it.
You could use this pretty simple solution:
Array.from(document.querySelectorAll('div'))
.find(el => el.textContent === 'SomeText, text continues.');
The Array.from
will convert the NodeList to an array (there are multiple methods to do this like the spread operator or slice)
The result now being an array allows for using the Array.find
method, you can then put in any predicate. You could also check the textContent with a regex or whatever you like.
Note that Array.from
and Array.find
are ES2015 features. Te be compatible with older browsers like IE10 without a transpiler:
Array.prototype.slice.call(document.querySelectorAll('div'))
.filter(function (el) {
return el.textContent === 'SomeText, text continues.'
})[0];
A good option to ping the site on a schedule is to use Microsoft Flow, which is free for up to 750 "runs" per month. It is very easy to create a Flow that hits your site every hour to keep it warm. You can even work around their limit of 750 by creating a single flow with delays separating multiple hits of your site.
I also had this problem, however, right-clicking on the model.tt file and running "Custom tool" didn't make any difference for me somehow, but a comment on the page Ghlouw linked to mentioned to use the menu item "BUILD > Transform All T4 Templates." which did it for me
Chrome can run as root (remember to use gksu
when doing so) so long as you provide it with a profile directory.
Rather than type in the profile directory every time you want to run it, create a new bash file (I'd name it something like start-chrome.sh
)
#/bin/bash
google-chrome --user-data-dir="/root/chrome-profile/"
Rember to call that script with root privelages!
$ gksu /root/start-chrome.sh
Don't set height AND width. Use one or the other and the correct aspect ratio will be maintained.
.widthSet {_x000D_
max-width: 64px;_x000D_
}_x000D_
_x000D_
.heightSet {_x000D_
max-height: 64px;_x000D_
}
_x000D_
<img src="http://placehold.it/200x250" />_x000D_
_x000D_
<img src="http://placehold.it/200x250" width="64" />_x000D_
_x000D_
<img src="http://placehold.it/200x250" height="64" />_x000D_
_x000D_
<img src="http://placehold.it/200x250" class="widthSet" />_x000D_
_x000D_
<img src="http://placehold.it/200x250" class="heightSet" />
_x000D_
If you use Windows (note, we are using printf(), not cout):
//Save As UTF8 without signature
#include <stdio.h>
#include<windows.h>
int main (){
SetConsoleOutputCP(65001);
printf("?\n");
}
Not Unicode but working - 1251 instead of UTF8:
//Save As Windows 1251
#include <iostream>
#include<windows.h>
using namespace std;
int main (){
SetConsoleOutputCP(1251);
cout << "?" << endl;
}
Remember this if all your Strings in the column do not have an underscore (...or else if null value will be the output):
SELECT COALESCE
(SUBSTR("STRING_COLUMN" , 0, INSTR("STRING_COLUMN", '_')-1),
"STRING_COLUMN")
AS OUTPUT FROM DUAL
The shortest way, I think, is the following:
import struct
val = 0x11223344
val = struct.unpack("<I", struct.pack(">I", val))[0]
print "%08x" % val
This converts an integer to a byte-swapped integer.
Please bear in mind that the formatting of the date is independent of the storage. If it's essential to you that the date is stored in that format you will need to either define a custom data type or store it as a string. Then you can use a combination of extract, typecasting and concatenation to get that format.
However, I suspect that you want to store a date and get the format on output. So, something like this will do the trick for you:
CREATE TABLE my_table
(
id serial PRIMARY KEY not null,
my_date date not null default CURRENT_DATE
);
(CURRENT_DATE is basically a synonym for now() and a cast to date).
(Edited to use to_char).
Then you can get your output like:
SELECT id, to_char(my_date, 'yyyymm') FROM my_table;
Now, if you did really need to store that field as a string and ensure the format you could always do:
CREATE TABLE my_other_table
(
id serial PRIMARY KEY not null,
my_date varchar(6) default to_char(CURRENT_DATE, 'yyyymm')
);
Editor's note: disabling SSL verification has security implications. Without verification of the authenticity of SSL/HTTPS connections, a malicious attacker can impersonate a trusted endpoint such as Gmail, and you'll be vulnerable to a Man-in-the-Middle Attack.
Be sure you fully understand the security issues before using this as a solution.
You can add below code in /config/mail.php ( tested and worked on laravel 5.1, 5.2, 5.4 )
'stream' => [
'ssl' => [
'allow_self_signed' => true,
'verify_peer' => false,
'verify_peer_name' => false,
],
],
A convinient way is using the package python-dotenv
:
It reads out a .flaskenv
file where you can store environment variables for flask.
pip install python-dotenv
.flaskenv
in the root directory of your appInside the file you specify:
FLASK_APP=application.py
FLASK_RUN_HOST=localhost
FLASK_RUN_PORT=80
After that you just have to run your app with flask run
and can access your app at that port.
Please note that FLASK_RUN_HOST
defaults to 127.0.0.1
and FLASK_RUN_PORT
defaults to 5000
.
as.vector(unlist(aframe['a2']))
A way to write a common subset of HTML and XHTML
In the hope of greater portability.
In HTML, <script>
is magic escapes everything until </script>
appears.
So you can write:
<script>x = '<br/>';
and <br/>
won't be considered a tag.
This is why strings such as:
x = '</scripts>'
must be escaped like:
x = '</scri' + 'pts>'
See: Why split the <script> tag when writing it with document.write()?
But XML (and thus XHTML, which is a "subset" of XML, unlike HTML), doesn't have that magic: <br/>
would be seen as a tag.
<![CDATA[
is the XHTML way to say:
don't parse any tags until the next
]]>
, consider it all a string
The //
is added to make the CDATA work well in HTML as well.
In HTML <![CDATA[
is not magic, so it would be run by JavaScript. So //
is used to comment it out.
The XHTML also sees the //
, but will observe it as an empty comment line which is not a problem:
//
That said:
<!DOCTYPE html>
vs <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
script
syntaxBut that violates the golden rule of the Internet:
don't trust third parties, or your product will break
Pass multiple -v
arguments.
For instance:
docker -v /on/my/host/1:/on/the/container/1 \
-v /on/my/host/2:/on/the/container/2 \
...
http://jsbin.com/qamuyajipo/3/edit?html,output
.circle {
border: 1px solid red;
background-color: #FFFFFF;
height: 100px;
-moz-border-radius:75px;
-webkit-border-radius: 75px;
width: 100px;
}
References are "hidden pointers" (non-null) to things which can change (lvalues). You cannot define them to a constant. It should be a "variable" thing.
EDIT::
I am thinking of
int &x = y;
as almost equivalent of
int* __px = &y;
#define x (*__px)
where __px
is a fresh name, and the #define x
works only inside the block containing the declaration of x
reference.
This can also be done with looping over ls instead of find
for f in */; do echo "$f -> $(ls $f | wc -l)"; done
Explanation:
for f in */;
- loop over all directories
do echo "$f ->
- print out each directory name
$(ls $f | wc -l)
- call ls for this directory and count lines
Let suppose we have a primary color in values=>colors.xml
as:
<resources>
<color name="primary">#FDD835</color>
</resources>
so if we want to use our custom color into setBackgroundColor(@ColorInt int Color)
then we just need an annotation @SuppressLint("ResourceAsColor")
with constructor/method which will be used as:
@SuppressLint("ResourceAsColor")
public _LinearLayout(Context context) {
super(context);
// Formatting our layout : )
super.setBackgroundColor(R.color.primary);
....
}
Its a good programming practice to avoid having null
values in a Map.
If you have an entry with null
value, then it is not possible to tell whether an entry is present in the map or has a null
value associated with it.
You can either define a constant for such cases (Example: String NOT_VALID = "#NA"
), or you can have another collection storing keys which have null
values.
Please check this link for more details.
Most of the issues I've seen with developers complaining that Get Latest doesn't do what they expect stem from the fact that they're performing a Get Latest from Solution Explorer rather than from Source Control Explorer. Solution Explorer only gets the files that are part of the solution and ignores anything that may be required by files within the solution, and therefore part of source control, whereas Source Control explorer compares your local workspace against the repository on the server to determine which files are needed.
This is something I wrote a few minutes ago just messing around. Hope it helps!
public class Main {
public static void main(String[] args) {
ArrayList<Integer> powers = new ArrayList<Integer>();
ArrayList<Integer> binaryStore = new ArrayList<Integer>();
powers.add(128);
powers.add(64);
powers.add(32);
powers.add(16);
powers.add(8);
powers.add(4);
powers.add(2);
powers.add(1);
Scanner sc = new Scanner(System.in);
System.out.println("Welcome to Paden9000 binary converter. Please enter an integer you wish to convert: ");
int input = sc.nextInt();
int printableInput = input;
for (int i : powers) {
if (input < i) {
binaryStore.add(0);
} else {
input = input - i;
binaryStore.add(1);
}
}
String newString= binaryStore.toString();
String finalOutput = newString.replace("[", "")
.replace(" ", "")
.replace("]", "")
.replace(",", "");
System.out.println("Integer value: " + printableInput + "\nBinary value: " + finalOutput);
sc.close();
}
}
I found this related question: Directory Listing in S3 Static Website
As it turns out, if you enable public read for the whole bucket, S3 can serve directory listings. Problem is they are in XML instead of HTML, so not very user-friendly.
There are three ways you could go for generating listings:
Generate index.html files for each directory on your own computer, upload them to s3, and update them whenever you add new files to a directory. Very low-tech. Since you're saying you're uploading build files straight from Travis, this may not be that practical since it would require doing extra work there.
Use a client-side S3 browser tool.
Use a server-side browser tool.
The message usually comes when you put the wrong image name. Please check your image if it exists on the Docker repository with the correct tag. It helped me.
docker run -d -p 80:80 --name ngnix ngnix:latest
Unable to find image 'ngnix:latest' locally
docker: Error response from daemon: pull access denied for ngnix, repository does not exist or may require 'docker login': denied: requested access to the resource is denied.
See 'docker run --help'.
$ docker run -d -p 80:80 --name nginx nginx:latest
Unable to find image 'nginx:latest' locally
latest: Pulling from library/nginx
When using SQLFiddle, make sure that the separator is set to GO. Also the schema build script is executed in a different connection from the run script, so a temp table created in the one is not visible in the other. This fiddle shows that your code is valid and working in SQL 2012:
MS SQL Server 2012 Schema Setup:
Query 1:
CREATE TABLE #Names
(
Name1 VARCHAR(100),
Name2 VARCHAR(100)
)
INSERT INTO #Names
(Name1, Name2)
VALUES
('Matt', 'Matthew'),
('Matt', 'Marshal'),
('Matt', 'Mattison')
SELECT * FROM #NAMES
| NAME1 | NAME2 |
--------------------
| Matt | Matthew |
| Matt | Marshal |
| Matt | Mattison |
Here a SSMS 2012 screenshot:
I had this problem aswell (The error occurred both on VS 15 and 17). However on VS15 it returned a CONNECTION_REFUSED
error and on VS17 it returned ASP.NET Core 1.0 on IIS error 502.5
.
FIX
Navigate to your project directory and locate the hidden folder .vs
(it's located in the projects folder dir). (Remember to show hidden files/folders)
Close VS
For linux users, and to sum up and add to what others have said here, you should know the following:
Global variables are not evil. $CLASSPATH is specifically what Java uses to look through multiple directories to find all the different classes it needs for your script (unless you explicitly tell it otherwise with the -cp override).
The colon (":") character separates the different directories. There is only one $CLASSPATH and it has all the directories in it. So, when you run "export CLASSPATH=...." you want to include the current value "$CLASSPATH" in order to append to it. For example:
export CLASSPATH=.
export CLASSPATH=$CLASSPATH:/usr/share/java/mysql-connector-java-5.1.12.jar
In the first line above, you start CLASSPATH out with just a simple 'dot' which is the path to your current working directory. With that, whenever you run java it will look in the current working directory (the one you're in) for classes. In the second line above, $CLASSPATH grabs the value that you previously entered (.) and appends the path to a mysql dirver. Now, java will look for the driver AND for your classes.
echo $CLASSPATH
is super handy, and what it returns should read like a colon-separated list of all the directories you want java looking in for what it needs to run your script.
Tomcat does not use CLASSPATH. Read what to do about that here: https://tomcat.apache.org/tomcat-8.0-doc/class-loader-howto.html
The nearest equivalents would be icode and bcode as used by scalac, view Miguel Garcia's site on the Scalac optimiser for more information, here: http://magarciaepfl.github.io/scala/
You might also consider Java bytecode itself to be your intermediate representation, given that bytecode is the ultimate output of scalac.
Or perhaps the true intermediate is something that the JIT produces before it finally outputs native instructions?
Ultimately though... There's no single place that you can point at an claim "there's the intermediate!". Scalac works in phases that successively change the abstract syntax tree, every single phase produces a new intermediate. The whole thing is like an onion, and it's very hard to try and pick out one layer as somehow being more significant than any other.
import java.util.Scanner;
public class camelCase {
public static void main(String[] args)
{
Scanner user_input=new Scanner(System.in);
String Line1;
Line1 = user_input.nextLine();
int j=1;
//Now Read each word from the Line and convert it to Camel Case
String result = "", result1 = "";
for (int i = 0; i < Line1.length(); i++) {
String next = Line1.substring(i, i + 1);
System.out.println(next + " i Value:" + i + " j Value:" + j);
if (i == 0 | j == 1 )
{
result += next.toUpperCase();
} else {
result += next.toLowerCase();
}
if (Character.isWhitespace(Line1.charAt(i)) == true)
{
j=1;
}
else
{
j=0;
}
}
System.out.println(result);
not so elegant but you dont need to declare any variable:
for k in (select max(1) from table where 1 = 1) loop
update x where column = value;
end loop;
I have stumbled across this question and I will submit my answer that I used and worked pretty well. I had a search box that filtered and array of objects and on my search box I used the (ngModelChange)="onChange($event)"
in my .html
<input type="text" [(ngModel)]="searchText" (ngModelChange)="reSearch(newValue)" placeholder="Search">
then in my component.ts
reSearch(newValue: string) {
//this.searchText would equal the new value
//handle my filtering with the new value
}
This solution is for windows:
You should check for ''
(empty string) before pushing into your array. Your array has elements that are empty strings. Then your album_text.length === 0
will work just fine.
this solution worked for me:
var oldURL = "";
var currentURL = window.location.href;
function checkURLchange(currentURL){
if(currentURL != oldURL){
alert("url changed!");
oldURL = currentURL;
}
oldURL = window.location.href;
setTimeout(function() {
checkURLchange(window.location.href);
}, 1000);
}
checkURLchange();
A lot of SVN repos are "simply" HTTP sites, so you might consider looking at some off the shelf "web crawling" search app that you can point at the SVN root and it will give you basic functionality. Updating it will probably be a bit of a trick, perhaps some SVN check in hackery can tickle the index to discard or reindex changes as you go.
Just thinking out loud.
[What you need for interviews] A Node class is the sufficient data structure to represent a binary tree.
(While other answers are mostly correct, they are not required for a binary tree: no need to extend object class, no need to be a BST, no need to import deque).
class Node:
def __init__(self, value = None):
self.left = None
self.right = None
self.value = value
Here is an example of a tree:
n1 = Node(1)
n2 = Node(2)
n3 = Node(3)
n1.left = n2
n1.right = n3
In this example n1 is the root of the tree having n2, n3 as its children.
Now the class is this
<img src="img/img5.jpg" width="200px" class="rounded-circle float-right">
_x000D_
char[] chars = new char[10];
Arrays.fill(chars, '*');
String text = new String(chars);
First of all, Relax.
"Nothing is under our control. Our control is mere illusion.", "To err is human"
I get that you've unintentionally pushed your code to remote-master
. THIS is going to be alright.
1. At first, get the SHA-1
value of the commit you are trying to return, e.g. commit to master branch. run this:
git log
you'll see bunch of 'f650a9e398ad9ca606b25513bd4af9fe...' like strings along with each of the commits. copy that number from the commit that you want to return back.
2. Now, type in below command:
git reset --hard your_that_copied_string_but_without_quote_mark
you should see message like "HEAD is now at ". you are on clear. What it just have done is to reflect that change locally.
3. Now, type in below command:
git push -f
you should see like
"warning: push.default is unset; its implicit value has changed in..... ... Total 0 (delta 0), reused 0 (delta 0) ... ...your_branch_name -> master (forced update)."
Now, you are all clear. Check the master with "git log" again, your fixed_destination_commit should be on top of the list.
You are welcome (in advance ;))
UPDATE:
Now, the changes you had made before all these began, are now gone. If you want to bring those hard-works back again, it's possible. Thanks to git reflog, and git cherry-pick commands.
For that, i would suggest to please follow this blog or this post.
You can use format like here,
public static double getDoubleValue(String value,int digit){
if(value==null){
value="0";
}
double i=0;
try {
DecimalFormat digitformat = new DecimalFormat("#.##");
digitformat.setMaximumFractionDigits(digit);
return Double.valueOf(digitformat.format(Double.parseDouble(value)));
} catch (NumberFormatException numberFormatExp) {
return i;
}
}
Sample DF:
In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))
In [80]: df
Out[80]:
a b c
0 6 11 11
1 14 7 8
2 13 5 11
3 13 7 11
4 13 5 9
5 5 11 9
6 9 8 6
7 5 11 10
8 8 10 14
9 7 14 13
present only those rows where b > 10
In [81]: df[df.b > 10]
Out[81]:
a b c
0 6 11 11
5 5 11 9
7 5 11 10
9 7 14 13
Minimums (for all columns) for the rows satisfying b > 10
condition
In [82]: df[df.b > 10].min()
Out[82]:
a 5
b 11
c 9
dtype: int32
Minimum (for the b
column) for the rows satisfying b > 10
condition
In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11
UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.