Generally, using Promise.all()
runs requests "async" in parallel. Using await
can run in parallel OR be "sync" blocking.
test1 and test2 functions below show how await
can run async or sync.
test3 shows Promise.all()
that is async.
jsfiddle with timed results - open browser console to see test results
Sync behavior. Does NOT run in parallel, takes ~1800ms:
const test1 = async () => {
const delay1 = await Promise.delay(600); //runs 1st
const delay2 = await Promise.delay(600); //waits 600 for delay1 to run
const delay3 = await Promise.delay(600); //waits 600 more for delay2 to run
};
Async behavior. Runs in paralel, takes ~600ms:
const test2 = async () => {
const delay1 = Promise.delay(600);
const delay2 = Promise.delay(600);
const delay3 = Promise.delay(600);
const data1 = await delay1;
const data2 = await delay2;
const data3 = await delay3; //runs all delays simultaneously
}
Async behavior. Runs in parallel, takes ~600ms:
const test3 = async () => {
await Promise.all([
Promise.delay(600),
Promise.delay(600),
Promise.delay(600)]); //runs all delays simultaneously
};
TLDR; If you are using Promise.all()
it will also "fast-fail" - stop running at the time of the first failure of any of the included functions.
Another option:
string strVal = "32.11"; // will return 33
// string strVal = "32.00" // returns 32
// string strVal = "32.98" // returns 33
string[] valStr = strVal.Split('.');
int32 leftSide = Convert.ToInt32(valStr[0]);
int32 rightSide = Convert.ToInt32(valStr[1]);
if (rightSide > 0)
leftSide = leftSide + 1;
return (leftSide);
Just for those who have already created the table with the header. Here is the alter command for the same. This is useful in case you already have the table and want the first row to be ignored without dropping and recreating. It also helps with people to familiarize with ALTER as a option with TBLPROPERTIES.
ALTER TABLE tablename SET TBLPROPERTIES ("skip.header.line.count"="1");
Like others have already said, it's not immediately obvious what you're asking. I'm going to assume that you want to start a process and then perform another action when the process "is ready".
Of course, the "is ready" is the tricky bit. Depending on what you're needs are, you may find that simply waiting is sufficient. However, if you need a more robust solution, you can consider using a named Mutex to control the control flow between your two processes.
For example, in your main process, you might create a named mutex and start a thread or task which will wait. Then, you can start the 2nd process. When that process decides that "it is ready", it can open the named mutex (you have to use the same name, of course) and signal to the first process.
See: http://docs.oracle.com/javase/tutorial/essential/io/pathOps.html
Using java.nio.file.Path
and java.nio.file.Paths
, you can do the following to show what Java thinks is your current path. This for 7 and on, and uses NIO.
Path currentRelativePath = Paths.get("");
String s = currentRelativePath.toAbsolutePath().toString();
System.out.println("Current relative path is: " + s);
This outputs Current relative path is: /Users/george/NetBeansProjects/Tutorials
that in my case is where I ran the class from. Constructing paths in a relative way, by not using a leading separator to indicate you are constructing an absolute path, will use this relative path as the starting point.
This would truncate the file:
$fh = fopen( 'filelist.txt', 'w' );
fclose($fh);
In clear.php, redirect to the caller page by making use of $_SERVER['HTTP_REFERER']
value.
Here's an example using Guzzle:
/**
* @param string $accessToken JSON-encoded access token as returned by \Google_Client->getAccessToken() or raw access token
* @return array|false False if token is invalid or array in the form
*
* array (
* 'issued_to' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
* 'audience' => 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
* 'scope' => 'https://www.googleapis.com/auth/calendar',
* 'expires_in' => 3350,
* 'access_type' => 'offline',
* )
*/
public static function tokenInfo($accessToken) {
if(!strlen($accessToken)) {
return false;
}
if($accessToken[0] === '{') {
$accessToken = json_decode($accessToken)->access_token;
}
$guzzle = new \GuzzleHttp\Client();
try {
$resp = $guzzle->get('https://www.googleapis.com/oauth2/v1/tokeninfo', [
'query' => ['access_token' => $accessToken],
]);
} catch(ClientException $ex) {
return false;
}
return $resp->json();
}
You could make use of the Javascript DOM API. In particular, look at the createElement() method.
You could create a re-usable function that will create an image like so...
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
// This next line will just add it to the <body> tag
document.body.appendChild(img);
}
Then you could use it like this...
<button onclick=
"show_image('http://google.com/images/logo.gif',
276,
110,
'Google Logo');">Add Google Logo</button>
I would prefer to do this by return. Put the looping part in private function and return when you want to break the loop.
just to save my own deductions from all this is (for saving DBMS_OUTPUT output on the client, using sqlplus):
I think the full validate function should look like this:
from datetime import datetime
def validate(date_text):
try:
if date_text != datetime.strptime(date_text, "%Y-%m-%d").strftime('%Y-%m-%d'):
raise ValueError
return True
except ValueError:
return False
Executing just
datetime.strptime(date_text, "%Y-%m-%d")
is not enough because strptime method doesn't check that month and day of the month are zero-padded decimal numbers. For example
datetime.strptime("2016-5-3", '%Y-%m-%d')
will be executed without errors.
Assuming you use VS Express and C#. The icon is set in the project properties page. To open it right click on the project name in the solution explorer. in the page that opens, there is an Application tab, in this tab you can set the icon.
Well, what I do on every project is a mix of the options above.
First, add the jsr310 dependency:
<dependency>
<groupId>com.fasterxml.jackson.datatype</groupId>
<artifactId>jackson-datatype-jsr310</artifactId>
</dependency>
Important detail: put this dependency on the top of your depedencies list. I already see a project where the Localdate error persists even with this dependency on the pom.xml. But changing the order of the depedency the error was gone.
On your /src/main/resources/application.yml
file, setup the write-dates-as-timestamps
property:
spring:
jackson:
serialization:
write-dates-as-timestamps: false
And create a ObjectMapper
bean as this:
@Configuration
public class WebConfigurer {
@Bean
@Primary
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {
ObjectMapper objectMapper = builder.build();
objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
return objectMapper;
}
}
Following this configuration, the conversion always work on Spring Boot 1.5.x without any error.
Working with Spring AMQP, pay attention if you have a new instance of Jackson2JsonMessageConverter
(common thing when creating a SimpleRabbitListenerContainerFactory
). You need to pass the ObjectMapper
bean to it, like:
Jackson2JsonMessageConverter converter = new Jackson2JsonMessageConverter(objectMapper);
Otherwise, you will receive the same error.
In plain english a callback is a promise. Joe, Jane, David and Samantha share a carpool to work. Joe is driving today. Jane, David and Samantha have a couple of options:
Option 1: This is more like a polling example where Jane would be stuck in a "loop" checking if Joe is outside. Jane can't do anything else in the mean time.
Option 2: This is the callback example. Jane tells Joe to ring her doorbell when he's outside. She gives him a "function" to ring the door bell. Joe does not need to know how the door bell works or where it is, he just needs to call that function i.e. ring the door bell when he's there.
Callbacks are driven by "events". In this example the "event" is Joe's arrival. In Ajax for example events can be "success" or "failure" of the asynchronous request and each can have the same or different callbacks.
In terms of JavaScript applications and callbacks. We also need to understand "closures" and application context. What "this" refers to can easily confuse JavaScript developers. In this example within each person's "ring_the_door_bell()" method/callback there might be some other methods that each person need to do based on their morning routine ex. "turn_off_the_tv()". We would want "this" to refer to the "Jane" object or the "David" object so that each can setup whatever else they need done before Joe picks them up. This is where setting up the callback with Joe requires parodying the method so that "this" refers to the right object.
Hope that helps!
Since this is about REST, just getting the request method from the server is not enough. You also need to receive RESTful route parameters. The reason for separating RESTful parameters and GET/POST/PUT parameters is that a resource needs to have its own unique URL for identification.
Here's one way of implementing RESTful routes in PHP using Slim:
https://github.com/codeguy/Slim
$app = new \Slim\Slim();
$app->get('/hello/:name', function ($name) {
echo "Hello, $name";
});
$app->run();
And configure the server accordingly.
Here's another example using AltoRouter:
https://github.com/dannyvankooten/AltoRouter
$router = new AltoRouter();
$router->setBasePath('/AltoRouter'); // (optional) the subdir AltoRouter lives in
// mapping routes
$router->map('GET|POST','/', 'home#index', 'home');
$router->map('GET','/users', array('c' => 'UserController', 'a' => 'ListAction'));
$router->map('GET','/users/[i:id]', 'users#show', 'users_show');
$router->map('POST','/users/[i:id]/[delete|update:action]', 'usersController#doAction', 'users_do');
I was in your shoes for a while and finally ended up using node.js, because it can do hybrid solutions like having web and socket server in one. So php backend can submit requests thru http to node web server and then broadcast it with websocket. Very efficiant way to go.
There 3 functions you want to look at here:
I ran a sample in Excel with your OPS values in Column B and Players in Column C, see below:
=LARGE($B$2:$B$11, A13)
=INDEX($C$2:$C$11,MATCH(B13,$B$2:$B$11,0))
Well first of all I think rolling out your own solution for this all you need is urllib2 or httplib2 . Anyways in case you do require a generic REST client check this out .
https://github.com/scastillo/siesta
However i think the feature set of the library will not work for most web services because they shall probably using oauth etc .. . Also I don't like the fact that it is written over httplib which is a pain as compared to httplib2 still should work for you if you don't have to handle a lot of redirections etc ..
Do not invoke the method when assigning the new onclick
handler.
Simply remove the parenthesis:
document.getElementById("a").onclick = Foo;
UPDATE (due to new information):
document.getElementById("a").onclick = function () { Foo(param); };
Also, Jackson 1.6 has support for handling bi-directional references... which seems like what you are looking for (this blog entry also mentions the feature)
And as of July 2011, there is also "jackson-module-hibernate" which might help in some aspects of dealing with Hibernate objects, although not necessarily this particular one (which does require annotations).
This is how to set an image into ImageView
using the setImageResource() method:
ImageView myImageView = (ImageView)v.findViewById(R.id.img_play);
// supossing to have an image called ic_play inside my drawables.
myImageView.setImageResource(R.drawable.ic_play);
the delete query only allows for modifiers after the DELETE 'command' to tell the database what/how do handle things.
see this page
FIRST, if you want to be able to access man1.py from man1test.py AND manModules.py from man1.py, you need to properly setup your files as packages and modules.
Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name
A.B
designates a submodule namedB
in a package namedA
....
When importing the package, Python searches through the directories on
sys.path
looking for the package subdirectory.The
__init__.py
files are required to make Python treat the directories as containing packages; this is done to prevent directories with a common name, such asstring
, from unintentionally hiding valid modules that occur later on the module search path.
You need to set it up to something like this:
man
|- __init__.py
|- Mans
|- __init__.py
|- man1.py
|- MansTest
|- __init.__.py
|- SoftLib
|- Soft
|- __init__.py
|- SoftWork
|- __init__.py
|- manModules.py
|- Unittests
|- __init__.py
|- man1test.py
SECOND, for the "ModuleNotFoundError: No module named 'Soft'
" error caused by from ...Mans import man1
in man1test.py, the documented solution to that is to add man1.py to sys.path
since Mans is outside the MansTest package. See The Module Search Path from the Python documentation. But if you don't want to modify sys.path
directly, you can also modify PYTHONPATH
:
sys.path
is initialized from these locations:
- The directory containing the input script (or the current directory when no file is specified).
PYTHONPATH
(a list of directory names, with the same syntax as the shell variablePATH
).- The installation-dependent default.
THIRD, for from ...MansTest.SoftLib import Soft
which you said "was to facilitate the aforementioned import statement in man1.py", that's now how imports work. If you want to import Soft.SoftLib in man1.py, you have to setup man1.py to find Soft.SoftLib and import it there directly.
With that said, here's how I got it to work.
man1.py:
from Soft.SoftWork.manModules import *
# no change to import statement but need to add Soft to PYTHONPATH
def foo():
print("called foo in man1.py")
print("foo call module1 from manModules: " + module1())
man1test.py
# no need for "from ...MansTest.SoftLib import Soft" to facilitate importing..
from ...Mans import man1
man1.foo()
manModules.py
def module1():
return "module1 in manModules"
Terminal output:
$ python3 -m man.MansTest.Unittests.man1test
Traceback (most recent call last):
...
from ...Mans import man1
File "/temp/man/Mans/man1.py", line 2, in <module>
from Soft.SoftWork.manModules import *
ModuleNotFoundError: No module named 'Soft'
$ PYTHONPATH=$PYTHONPATH:/temp/man/MansTest/SoftLib
$ export PYTHONPATH
$ echo $PYTHONPATH
:/temp/man/MansTest/SoftLib
$ python3 -m man.MansTest.Unittests.man1test
called foo in man1.py
foo called module1 from manModules: module1 in manModules
As a suggestion, maybe re-think the purpose of those SoftLib files. Is it some sort of "bridge" between man1.py and man1test.py? The way your files are setup right now, I don't think it's going to work as you expect it to be. Also, it's a bit confusing for the code-under-test (man1.py) to be importing stuff from under the test folder (MansTest).
It can be done without find
as well by using grep's "--include"
option.
grep man page says:
--include=GLOB
Search only files whose base name matches GLOB (using wildcard matching as described under --exclude).
So to do a recursive search for a string in a file matching a specific pattern, it will look something like this:
grep -r --include=<pattern> <string> <directory>
For example, to recursively search for string "mytarget" in all Makefiles:
grep -r --include="Makefile" "mytarget" ./
Or to search in all files starting with "Make" in filename:
grep -r --include="Make*" "mytarget" ./
You can also use Windows PowerShell with the following command:
if ([System.Diagnostics.EventLog]::SourceExists($source) -eq $false) {
[System.Diagnostics.EventLog]::CreateEventSource($source, "Application")
}
Make sure to check that the source does not exist before calling CreateEventSource, otherwise it will throw an exception.
For more info:
HH
used 24 hour format while hh
used for 12 format
This is late, but here is my python implementation of the flowingdata NBA heatmap.
updated:1/4/2014: thanks everyone
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# ------------------------------------------------------------------------
# Filename : heatmap.py
# Date : 2013-04-19
# Updated : 2014-01-04
# Author : @LotzJoe >> Joe Lotz
# Description: My attempt at reproducing the FlowingData graphic in Python
# Source : http://flowingdata.com/2010/01/21/how-to-make-a-heatmap-a-quick-and-easy-solution/
#
# Other Links:
# http://stackoverflow.com/questions/14391959/heatmap-in-matplotlib-with-pcolor
#
# ------------------------------------------------------------------------
import matplotlib.pyplot as plt
import pandas as pd
from urllib2 import urlopen
import numpy as np
%pylab inline
page = urlopen("http://datasets.flowingdata.com/ppg2008.csv")
nba = pd.read_csv(page, index_col=0)
# Normalize data columns
nba_norm = (nba - nba.mean()) / (nba.max() - nba.min())
# Sort data according to Points, lowest to highest
# This was just a design choice made by Yau
# inplace=False (default) ->thanks SO user d1337
nba_sort = nba_norm.sort('PTS', ascending=True)
nba_sort['PTS'].head(10)
# Plot it out
fig, ax = plt.subplots()
heatmap = ax.pcolor(nba_sort, cmap=plt.cm.Blues, alpha=0.8)
# Format
fig = plt.gcf()
fig.set_size_inches(8, 11)
# turn off the frame
ax.set_frame_on(False)
# put the major ticks at the middle of each cell
ax.set_yticks(np.arange(nba_sort.shape[0]) + 0.5, minor=False)
ax.set_xticks(np.arange(nba_sort.shape[1]) + 0.5, minor=False)
# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()
# Set the labels
# label source:https://en.wikipedia.org/wiki/Basketball_statistics
labels = [
'Games', 'Minutes', 'Points', 'Field goals made', 'Field goal attempts', 'Field goal percentage', 'Free throws made', 'Free throws attempts', 'Free throws percentage',
'Three-pointers made', 'Three-point attempt', 'Three-point percentage', 'Offensive rebounds', 'Defensive rebounds', 'Total rebounds', 'Assists', 'Steals', 'Blocks', 'Turnover', 'Personal foul']
# note I could have used nba_sort.columns but made "labels" instead
ax.set_xticklabels(labels, minor=False)
ax.set_yticklabels(nba_sort.index, minor=False)
# rotate the
plt.xticks(rotation=90)
ax.grid(False)
# Turn off all the ticks
ax = plt.gca()
for t in ax.xaxis.get_major_ticks():
t.tick1On = False
t.tick2On = False
for t in ax.yaxis.get_major_ticks():
t.tick1On = False
t.tick2On = False
The output looks like this:
There's an ipython notebook with all this code here. I've learned a lot from 'overflow so hopefully someone will find this useful.
If you use Unix system, you can solve your problem in two commands. Where the first initialize configs and the second alters file with a file to ignore.
$ git config --global core.excludesfile ~/.gitignore
$ echo '.idea' >> ~/.gitignore
I use three flags to resolve the problem:
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP|
Intent.FLAG_ACTIVITY_CLEAR_TASK |
Intent.FLAG_ACTIVITY_NEW_TASK);
being overwhelmed by being VERY NEW to python i missed some very simple and useful commands given here: Print in terminal with colors using Python? -
eventually decided to use CLINT as an answer that was given there by great and smart people
Just for the sake of completeness, appending values to a vector in a for loop is not really the philosophy in R. R works better by operating on vectors as a whole, as @BrodieG pointed out. See if your code can't be rewritten as:
ouput <- sapply(values, function(v) return(2*v))
Output will be a vector of return values. You can also use lapply
if values is a list instead of a vector.
import numpy as np
import PIL
def convert_image(image_file):
image = Image.open(image_file) # this could be a 4D array PNG (RGBA)
original_width, original_height = image.size
np_image = np.array(image)
new_image = np.zeros((np_image.shape[0], np_image.shape[1], 3))
# create 3D array
for each_channel in range(3):
new_image[:,:,each_channel] = np_image[:,:,each_channel]
# only copy first 3 channels.
# flushing
np_image = []
return new_image
This might not directly answer your question but for the sake of those that come with states like the below
state = {
currentstate:[
{
id: 1 ,
firstname: 'zinani',
sex: 'male'
}
]
}
Solution
const new_value = {
id: 2 ,
firstname: 'san',
sex: 'male'
}
Replace the current state with the new value
this.setState({ currentState: [...this.state.currentState, new_array] })
For me it worked to add the phrase "explicit_defaults_for_timestamp = ON" without quotes into the config file my.ini
.
Make sure you add this phrase right underneath the [mysqld] statement in the config file.
You will find my.ini
under C:\ProgramData\MySQL\MySQL Server 5.7
if you had conducted the default installation of MySQL.
I know this is an old thread but PARTITION is the equiv of GROUP BY not ORDER BY. ORDER BY in this function is . . . ORDER BY. It's just a way to create uniqueness out of redundancy by adding a sequence number. Or you may eliminate the other redundant records by the WHERE clause when referencing the aliased column for the function. However, DISTINCT in the SELECT statement would probably accomplish the same thing in that regard.
Visit https://play.golang.org/p/dx6PTtuBXQW
package main
import (
"fmt"
"sort"
)
func main() {
mapEg := map[string]string{"c":"a","a":"c","b":"b"}
keys := make([]string, 0, len(mapEg))
for k := range mapEg {
keys = append(keys, k)
}
sort.Strings(keys)
fmt.Println(keys)
}
I would like to improve Evan Knowles answer: https://stackoverflow.com/a/30796829/2628125
In my case I had class with handlers for UI Component part. Initialization:
this.dataText.textProperty().addListener((observable, oldValue, newValue) -> this.numericSanitization(observable, oldValue, newValue));
And the numbericSanitization method:
private synchronized void numericSanitization(ObservableValue<? extends String> observable, String oldValue, String newValue) {
final String allowedPattern = "\\d*";
if (!newValue.matches(allowedPattern)) {
this.dataText.setText(oldValue);
}
}
Keyword synchronized is added to prevent possible render lock issue in javafx if setText will be called before old one is finished execution. It is easy to reproduce if you will start typing wrong chars really fast.
Another advantage is that you keep only one pattern to match and just do rollback. It is better because you can easily abstragate solution for different sanitization patterns.
In my case, while copying the text from other source it somehow included the space at the end of clipboard entry. That way the key password had a space at the end.
Put this in C2 and copy down
=IF(ISNA(VLOOKUP(A2,$B$2:$B$65535,1,FALSE)),"not in B","")
Then if the value in A isn't in B the cell in column C will say "not in B".
Using Node.js
sync mode:
var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")
async mode:
var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
var textByLine = text.split("\n")
});
UPDATE
As of at least Node 6, readFileSync
returns a Buffer
, so it must first be converted to a string in order for split
to work:
var text = fs.readFileSync("./mytext.txt").toString('utf-8');
Or
var text = fs.readFileSync("./mytext.txt", "utf-8");
The controller
function/object represents an abstraction model-view-controller (MVC). While there is nothing new to write about MVC, it is still the most significant advanatage of angular: split the concerns into smaller pieces. And that's it, nothing more, so if you need to react on Model
changes coming from View
the Controller
is the right person to do that job.
The story about link
function is different, it is coming from different perspective then MVC. And is really essential, once we want to cross the boundaries of a controller/model/view
(template).
Let' start with the parameters which are passed into the link
function:
function link(scope, element, attrs) {
To put the link
into the context, we should mention that all directives are going through this initialization process steps: Compile, Link. An Extract from Brad Green and Shyam Seshadri book Angular JS:
Compile phase (a sister of link, let's mention it here to get a clear picture):
In this phase, Angular walks the DOM to identify all the registered directives in the template. For each directive, it then transforms the DOM based on the directive’s rules (template, replace, transclude, and so on), and calls the compile function if it exists. The result is a compiled template function,
Link phase:
To make the view dynamic, Angular then runs a link function for each directive. The link functions typically creates listeners on the DOM or the model. These listeners keep the view and the model in sync at all times.
A nice example how to use the link
could be found here: Creating Custom Directives. See the example: Creating a Directive that Manipulates the DOM, which inserts a "date-time" into page, refreshed every second.
Just a very short snippet from that rich source above, showing the real manipulation with DOM. There is hooked function to $timeout service, and also it is cleared in its destructor call to avoid memory leaks
.directive('myCurrentTime', function($timeout, dateFilter) {
function link(scope, element, attrs) {
...
// the not MVC job must be done
function updateTime() {
element.text(dateFilter(new Date(), format)); // here we are manipulating the DOM
}
function scheduleUpdate() {
// save the timeoutId for canceling
timeoutId = $timeout(function() {
updateTime(); // update DOM
scheduleUpdate(); // schedule the next update
}, 1000);
}
element.on('$destroy', function() {
$timeout.cancel(timeoutId);
});
...
In case if you were to pass the image as part of JSON along with other attributes, you can use the below snippet.
client.py
import base64
import json
import requests
api = 'http://localhost:8080/test'
image_file = 'sample_image.png'
with open(image_file, "rb") as f:
im_bytes = f.read()
im_b64 = base64.b64encode(im_bytes).decode("utf8")
headers = {'Content-type': 'application/json', 'Accept': 'text/plain'}
payload = json.dumps({"image": im_b64, "other_key": "value"})
response = requests.post(api, data=payload, headers=headers)
try:
data = response.json()
print(data)
except requests.exceptions.RequestException:
print(response.text)
server.py
import io
import json
import base64
import logging
import numpy as np
from PIL import Image
from flask import Flask, request, jsonify, abort
app = Flask(__name__)
app.logger.setLevel(logging.DEBUG)
@app.route("/test", methods=['POST'])
def test_method():
# print(request.json)
if not request.json or 'image' not in request.json:
abort(400)
# get the base64 encoded string
im_b64 = request.json['image']
# convert it into bytes
img_bytes = base64.b64decode(im_b64.encode('utf-8'))
# convert bytes data to PIL Image object
img = Image.open(io.BytesIO(img_bytes))
# PIL image object to numpy array
img_arr = np.asarray(img)
print('img shape', img_arr.shape)
# process your img_arr here
# access other keys of json
# print(request.json['other_key'])
result_dict = {'output': 'output_key'}
return result_dict
def run_server_api():
app.run(host='0.0.0.0', port=8080)
if __name__ == "__main__":
run_server_api()
If you want to do it without cli, you can do it fully on Github website.
New pull request
.Create new pull request
.You can use this
var data = $("#myForm").serialize();
data += '&moreinfo='+JSON.stringify(wordlist);
The answer with the method count() above gave me line miscounts if a file didn't have a newline at the end of the file - it failed to count the last line in the file.
This method works better for me:
public int countLines(String filename) throws IOException {
LineNumberReader reader = new LineNumberReader(new FileReader(filename));
int cnt = 0;
String lineRead = "";
while ((lineRead = reader.readLine()) != null) {}
cnt = reader.getLineNumber();
reader.close();
return cnt;
}
next:
select * from foo where id = (select min(id) from foo where id > 4)
previous:
select * from foo where id = (select max(id) from foo where id < 4)
Mixins is a concept in Programming in which the class provides functionalities but it is not meant to be used for instantiation. Main purpose of Mixins is to provide functionalities which are standalone and it would be best if the mixins itself do not have inheritance with other mixins and also avoid state. In languages such as Ruby, there is some direct language support but for Python, there isn't. However, you could used multi-class inheritance to execute the functionality provided in Python.
I watched this video http://www.youtube.com/watch?v=v_uKI2NOLEM to understand the basics of mixins. It is quite useful for a beginner to understand the basics of mixins and how they work and the problems you might face in implementing them.
Wikipedia is still the best: http://en.wikipedia.org/wiki/Mixin
A simple solution:
<a href="https://www.google.com" target="_blank">
<button type="button">Open new tab</button>
</a>
Single line comments start with a hash symbol, everything to the right of the #
will be ignored:
# Comment Here
In PowerShell 2.0 and above multi-line block comments can be used:
<#
Multi
Line
#>
You could use block comments to embed comment text within a command:
Get-Content -Path <# configuration file #> C:\config.ini
Note: Because PowerShell supports Tab Completion you need to be careful about copying and pasting Space + TAB
before comments.
You must write onActivityResult()
in your FirstActivity.Java
as follows
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
So this will call your fragment's onActivityResult()
Edit: the solution is to replace getActivity().startActivityForResult(i, 1);
with startActivityForResult(i, 1);
This works for me in iOS 9.3.x with Swift:
override func didMoveToParentViewController(parent: UIViewController?) {
super.didMoveToParentViewController(parent)
if parent == self.navigationController?.parentViewController {
print("Back tapped")
}
}
Unlike other solutions here, this doesn't seem to trigger unexpectedly.
You can try this force-download script. Even if you don't use it, it'll probably point you in the right direction:
<?php
$filename = $_GET['file'];
// required for IE, otherwise Content-disposition is ignored
if(ini_get('zlib.output_compression'))
ini_set('zlib.output_compression', 'Off');
// addition by Jorg Weske
$file_extension = strtolower(substr(strrchr($filename,"."),1));
if( $filename == "" )
{
echo "<html><title>eLouai's Download Script</title><body>ERROR: download file NOT SPECIFIED. USE force-download.php?file=filepath</body></html>";
exit;
} elseif ( ! file_exists( $filename ) )
{
echo "<html><title>eLouai's Download Script</title><body>ERROR: File not found. USE force-download.php?file=filepath</body></html>";
exit;
};
switch( $file_extension )
{
case "pdf": $ctype="application/pdf"; break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "doc": $ctype="application/msword"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
default: $ctype="application/octet-stream";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain browsers
header("Content-Type: $ctype");
// change, added quotes to allow spaces in filenames, by Rajkumar Singh
header("Content-Disposition: attachment; filename=\"".basename($filename)."\";" );
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filename));
readfile("$filename");
exit();
I was using https redirection just before adding cors middleware and able to fix the issue by changing order of them
What i mean is:
change this:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseHttpsRedirection();
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
...
}
to this:
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
...
app.UseCors(x => x
.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader());
app.UseHttpsRedirection();
...
}
By the way, allowing requests from any origins and methods may not be a good idea for production stage, you should write your own cors policies at production.
If all above answers is not to your liking you can use autoIT to run your file (or what ever file) as a specific user with their credentials.
Sample of a script that will run a program using that users privelages.
installAdmin()
Func installAdmin()
; Change the username and password to the appropriate values for your system.
Local $sUserName = "xxxxx"
Local $sPassword = "xxx"
Local $sDirectory = "C:\ASD4VM\Download\"
Local $sFiletoRun = "Inst_with_Privileges.bat"
RunAsWait($sUserName, @ComputerName, $sPassword, 0, $sDirectory & $sFiletoRun)
EndFunc ;==>Example
AutoIT can be found here. -> It uses a .ua3 format that is compiled to a .exe file that can be run.
You check if it's null
in C# like this:
if(MyObject != null) {
//do something
}
If you want to check against default (tough to understand the question on the info given) check:
if(MyObject != default(MyObject)) {
//do something
}
Alternatively, you could cherry-pick the commit-id onto your branch.
<commit-id> made in detached head state
git checkout master
git cherry-pick <commit-id>
No temporary branches, no merging.
TL;DR
npm uninstall node-sass
npm install [email protected]
Or, if using yarn (default in newer CRA versions)
yarn remove node-sass
yarn add [email protected]
Edit2: sass-loader v10.0.5 fixes it. Problem is, you might not be using it as a project dependency, but more as a dependency of your dependencies. CRA uses a fixed version, angular-cli locks to node-sass v4 an so on.
The recommendation for now is: if you're installing just node-sass check below workaround (and the note). If you're working on a blank project and you can manage your webpack configuration (not using CRA or a CLI to scaffold your project) install latest sass-loader.
Edit: this error comes from sass-loader. There is a semver mismatch since node-sass @latest is v5.0.0 and sass-loader expects ^4.0.0.
There is an open issue on their repository with an associated fix that needs to be reviewed. Until then, refer to the solution below.
Workaround: don't install node-sass 5.0.0 yet (major version was just bumped).
Uninstall node-sass
npm uninstall node-sass
Then install the latest version (before 5.0)
npm install [email protected]
Note: LibSass (hence node-sass as well) is deprecated and dart-sass is the recommended implementation. You can use sass
instead, which is a node distribution of dart-sass compiled to pure JavaScript.
Be warned though:
Be careful using this approach. React-scripts uses sass-loader v8, which prefers node-sass to sass (which has some syntax not supported by node-sass). If both are installed and the user worked with sass, this could lead to errors on css compilation
Notice that that @InjectMocks
are about to be deprecated
deprecate @InjectMocks and schedule for removal in Mockito 3/4
and you can follow @avp answer and link on:
Why You Should Not Use InjectMocks Annotation to Autowire Fields
For completeness, if you wanted to use replaceFirst, try this:
public static String cap1stChar(String userIdea)
{
String betterIdea = userIdea;
if (userIdea.length() > 0)
{
String first = userIdea.substring(0,1);
betterIdea = userIdea.replaceFirst(first, first.toUpperCase());
}
return betterIdea;
}//end cap1stChar
On Linux, the symlink /proc/<pid>/exe
has the path of the executable. Use the command readlink -f /proc/<pid>/exe
to get the value.
On AIX, this file does not exist. You could compare cksum <actual path to binary>
and cksum /proc/<pid>/object/a.out
.
If you are accessing database directly then you can write following query:
OPTIMIZE TABLE table1,table2,table3,table4......;
This can also happen when you forget to make a first commit.
Check that you have database dependency at runtime group at build.gradle
runtime group: 'com.h2database', name: 'h2', version: '1.4.194'
or change scope from test to runtime if you use Maven
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.194</version>
<scope>runtime</scope>
</dependency>
Seems there's an easier way, at least in Kendo UI v2015.2.624:
$('#myDropDownSelector').data('kendoDropDownList').search('Text value to find');
If there's not a match in the dropdown, Kendo appears to set the dropdown to an unselected value, which makes sense.
I couldn't get @Gang's answer to work, but if you swap his value
with search
, as above, we're golden.
For the below line, Initially faced problem with out giving single code that 'currnetRowAppName'value is not taking space with string. So, after that giving single code '"+row.applicationName+"'
, its taking space also.
Example:
<button class='btn btn-primary btn-xs appDelete' type='button' currnetRowAppName='"+row.applicationName+"' id="+row.id+ >
var viewAppNAME = $(this).attr("currnetRowAppName");
alert(viewAppNAME)
This is working fine.
This one-liner works for me:
WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultNetworkCredentials;
CredentialCache.DefaultNetWorkCredentials
is the proxy settings set in Internet Explorer.
WebRequest.DefaultWebProxy.Credentials
is used for all internet connectivity in the application.
If you're using Laravel 5.2 and you installed the auth related functionality with php artisan make:auth
then your app/Http/routes.php
file will include all auth-related routes by simply calling Route::auth()
.
The auth() method can be found in vendor/laravel/framework/src/Illuminate/Routing/Router.php
. So if you want to do as some people suggest here and disable registration by removing unwanted routes (probably a good idea) then you have to copy the routes you still want from the auth() method and put them in app/Http/routes.php
(replacing the call to Route::auth()). So for instance:
<?php
// This is app/Http/routes.php
// Authentication Routes...
Route::get('login', 'Auth\AuthController@showLoginForm');
Route::post('login', 'Auth\AuthController@login');
Route::get('logout', 'Auth\AuthController@logout');
// Registration Routes... removed!
// Password Reset Routes...
Route::get('password/reset/{token?}', 'Auth\PasswordController@showResetForm');
Route::post('password/email', 'Auth\PasswordController@sendResetLinkEmail');
Route::post('password/reset', 'Auth\PasswordController@reset');
If you're using lower version than 5.2 then it's probably different, I remember things changed quite a bit since 5.0, at some point artisan make:auth
was even removed IIRC.
I ran into this problem because I had multiple wildcard entries for the same ports. You can easily check this by executing apache2ctl -S
:
# apache2ctl -S
[Wed Oct 22 18:02:18 2014] [warn] _default_ VirtualHost overlap on port 30000, the first has precedence
[Wed Oct 22 18:02:18 2014] [warn] _default_ VirtualHost overlap on port 20001, the first has precedence
VirtualHost configuration:
11.22.33.44:80 is a NameVirtualHost
default server xxx.com (/etc/apache2/sites-enabled/xxx.com.conf:1)
port 80 namevhost xxx.com (/etc/apache2/sites-enabled/xxx.com.conf:1)
[...]
11.22.33.44:443 is a NameVirtualHost
default server yyy.com (/etc/apache2/sites-enabled/yyy.com.conf:37)
port 443 namevhost yyy.com (/etc/apache2/sites-enabled/yyy.com.conf:37)
wildcard NameVirtualHosts and _default_ servers:
*:80 hostname.com (/etc/apache2/sites-enabled/000-default:1)
*:20001 hostname.com (/etc/apache2/sites-enabled/000-default:33)
*:30000 hostname.com (/etc/apache2/sites-enabled/000-default:57)
_default_:443 hostname.com (/etc/apache2/sites-enabled/default-ssl:2)
*:20001 hostname.com (/etc/apache2/sites-enabled/default-ssl:163)
*:30000 hostname.com (/etc/apache2/sites-enabled/default-ssl:178)
Syntax OK
Notice how at the beginning of the output are a couple of warning lines. These will indicate which ports are creating the problems (however you probably already knew that).
Next, look at the end of the output and you can see exactly which files and lines the virtualhosts are defined that are creating the problem. In the above example, port 20001 is assigned both in /etc/apache2/sites-enabled/000-default
on line 33 and /etc/apache2/sites-enabled/default-ssl
on line 163. Likewise *:30000
is listed in 2 places. The solution (in my case) was simply to delete one of the entries.
it because it apply flex. you can use this code
@media (min-width: 992px){
.navbar-expand-lg .navbar-collapse {
display: -ms-flexbox!important;
display: flex!important;
-ms-flex-preferred-size: auto;
flex-basis: auto;
justify-content: center;
}
in my case it workded correctly.
The default character set of the JVM is that of the system it's running on. There's no specific value for this and you shouldn't generally depend on the default encoding being any particular value.
It can be accessed at runtime via Charset.defaultCharset()
, if that's any use to you, though really you should make a point of always specifying encoding explicitly when you can do so.
DISCLAIMER: The below solution does not preserve trailing tabs.
If you know the exact number of lines in the text file, try the following method:
@ECHO OFF
SET origfile=original file
SET tempfile=temporary file
SET insertbefore=4
SET totallines=200
<%origfile% (FOR /L %%i IN (1,1,%totallines%) DO (
SETLOCAL EnableDelayedExpansion
SET /P L=
IF %%i==%insertbefore% ECHO(
ECHO(!L!
ENDLOCAL
)
) >%tempfile%
COPY /Y %tempfile% %origfile% >NUL
DEL %tempfile%
The loop reads lines from the original file one by one and outputs them. The output is redirected to a temporary file. When a certain line is reached, an empty line is output before it.
After finishing, the original file is deleted and the temporary one gets assigned the original name.
UPDATE
If the number of lines is unknown beforehand, you can use the following method to obtain it:
FOR /F %%C IN ('FIND /C /V "" ^<%origfile%') DO SET totallines=%%C
(This line simply replaces the SET totallines=200
line in the above script.)
The method has one tiny flaw: if the file ends with an empty line, the result will be the actual number of lines minus one. If you need a workaround (or just want to play safe), you can use the method described in this answer.
This depends on where you want the error message be stored.
You can do the following:
echo "Error!" > logfile.log
exit 125
Or the following:
echo "Error!" 1>&2
exit 64
When you raise an exception you stop the program's execution.
You can also use something like exit xxx
where xxx
is the error code you may want to return to the operating system (from 0 to 255). Here 125
and 64
are just random codes you can exit with. When you need to indicate to the OS that the program stopped abnormally (eg. an error occurred), you need to pass a non-zero exit code to exit
.
As @chepner pointed out, you can do exit 1
, which will mean an unspecified error.
A better one using explode()
function is as follows...
Don't forget to replace your URL variable in the hyperlink href
.
<?php
if($url != ''){
$b = '';
$links = explode('/',rtrim($url,'/'));
foreach($links as $l){
$b .= $l;
if($url == $b){
echo $l;
}else{
echo "<a href='URL?url=".$b."'>".$l."/</a>";
}
$b .= '/';
}
}
?>
com.apple.dt.SourceKitService
process. Then XCode would start to index again instead of stuck.As described elsewhere, perhaps the best solution is to use the logging module directly:
import logging
logging.basicConfig(level=logging.DEBUG, filename='mylog.log')
logging.info('this should to write to the log file')
However, there are some (rare) occasions where you really want to redirect stdout. I had this situation when I was extending django's runserver command which uses print: I didn't want to hack the django source but needed the print statements to go to a file.
This is a way of redirecting stdout and stderr away from the shell using the logging module:
import logging, sys
class LogFile(object):
"""File-like object to log text using the `logging` module."""
def __init__(self, name=None):
self.logger = logging.getLogger(name)
def write(self, msg, level=logging.INFO):
self.logger.log(level, msg)
def flush(self):
for handler in self.logger.handlers:
handler.flush()
logging.basicConfig(level=logging.DEBUG, filename='mylog.log')
# Redirect stdout and stderr
sys.stdout = LogFile('stdout')
sys.stderr = LogFile('stderr')
print 'this should to write to the log file'
You should only use this LogFile implementation if you really cannot use the logging module directly.
You could try using HTML5s sessionStorage it lasts for the duration on the page session. A page session lasts for as long as the browser is open and survives over page reloads and restores. Opening a page in a new tab or window will cause a new session to be initiated.
sessionStorage.setItem("username", "John");
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage#sessionStorage
Browser Compatibility https://code.google.com/p/sessionstorage/ compatible with every A-grade browser, included iPhone or Android. http://www.nczonline.net/blog/2009/07/21/introduction-to-sessionstorage/
I have been using the below script to upload images which happens to work fine.
<input id="file" type="file" name="file"/>
<div id="response"></div>
jQuery('document').ready(function(){
var input = document.getElementById("file");
var formdata = false;
if (window.FormData) {
formdata = new FormData();
}
input.addEventListener("change", function (evt) {
var i = 0, len = this.files.length, img, reader, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (!!file.type.match(/image.*/)) {
if ( window.FileReader ) {
reader = new FileReader();
reader.onloadend = function (e) {
//showUploadedItem(e.target.result, file.fileName);
};
reader.readAsDataURL(file);
}
if (formdata) {
formdata.append("image", file);
formdata.append("extra",'extra-data');
}
if (formdata) {
jQuery('div#response').html('<br /><img src="ajax-loader.gif"/>');
jQuery.ajax({
url: "upload.php",
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (res) {
jQuery('div#response').html("Successfully uploaded");
}
});
}
}
else
{
alert('Not a vaild image!');
}
}
}, false);
});
I use response div
to show the uploading animation and response after upload is done.
Best part is you can send extra data such as ids & etc with the file when you use this script. I have mention it extra-data
as in the script.
At the PHP level this will work as normal file upload. extra-data can be retrieved as $_POST
data.
Here you are not using a plugin and stuff. You can change the code as you want. You are not blindly coding here. This is the core functionality of any jQuery file upload. Actually Javascript.
This is not a system font. this font is not supported in other systems. you can use font-face, convert font from this Site or from this
Ctrl-v ................ start visual block selection
6j .................... go down 6 lines
I" .................... inserts " at the beginning
<Esc><Esc> ............ finishes start
2fdl. ................. second 'd' l (goes right) . (repeats insertion)
Seems to me like you want to create a property.
public int MyProperty
{
get { return _myProperty; }
set
{
_myProperty = value;
if (_myProperty == 1)
{
// DO SOMETHING HERE
}
}
}
private int _myProperty;
This allows you to run some code any time the property value changes. You could raise an event here, if you wanted.
Thanks to Amjad Masad that inspired me.
I've the following solution which seems to work in IE9, FF and Chrome and the code is quite short (without the complex closure and transverse child things) :
DIV.onmouseout=function(e){
// check and loop relatedTarget.parentNode
// ignore event triggered mouse overing any child element or leaving itself
var obj=e.relatedTarget;
while(obj!=null){
if(obj==this){
return;
}
obj=obj.parentNode;
}
// now perform the actual action you want to do only when mouse is leaving the DIV
}
Efficiency isn't going to matter for something like this in 99.999999% of situations. Do whatever is easier to read and or maintain.
In my apps I usually rely on classes to provide hiding and showing, for example .addClass('isHidden')/.removeClass('isHidden')
which would allow me to animate things with CSS3 if I wanted to. It provides more flexibility.
If a DLL is written in one of the .NET languages and if you only want to view what functions, there is a reference to this DLL in the project.
Then doubleclick the DLL in the references folder and then you will see what functions it has in the OBJECT EXPLORER window
If you would like to view the source code of that DLL file you can use a decompiler application such as .NET reflector. hope this helps you.
Your hostname is missing. JBoss uses this environment variable ($HOSTNAME) when it connects to the server.
[root@xyz ~]# echo $HOSTNAME
xyz
[root@xyz ~]# ping $HOSTNAME
ping: unknown host xyz
[root@xyz ~]# hostname -f
hostname: Unknown host
There are dozens of things that can cause this. Please comment if you discover a new reason.
For a hack until you can permanently resolve this issue on your server, you can add a line to the end of your /etc/hosts file:
127.0.0.1 xyz.xxx.xxx.edu xyz
I'm very late to the party but I'll put this up here if anyone else would like to know my solution:
I had a real struggle with this exact problem but I found a viable solution using iframes (I know, I know. It's terrible but it works for a simple problem that I had)
I had an html page that launched a separate php script that generated the file and then downloaded it. On the html page, i used the following jquery in the html header (you'll need to include a jquery library as well):
<script>
$(function(){
var iframe = $("<iframe>", {name: 'iframe', id: 'iframe',}).appendTo("body").hide();
$('#click').on('click', function(){
$('#iframe').attr('src', 'your_download_script.php');
});
$('iframe').load(function(){
$('#iframe').attr('src', 'your_download_script.php?download=yes'); <!--on first iframe load, run script again but download file instead-->
$('#iframe').unbind(); <!--unbinds the iframe. Helps prevent against infinite recursion if the script returns valid html (such as echoing out exceptions) -->
});
});
</script>
On your_download_script.php, have the following:
function downloadFile($file_path) {
if (file_exists($file_path)) {
header('Content-Description: File Transfer');
header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename=' . basename($file_path));
header('Expires: 0');
header('Cache-Control: must-revalidate');
header('Pragma: public');
header('Content-Length: ' . filesize($file_path));
ob_clean();
flush();
readfile($file_path);
exit();
}
}
$_SESSION['your_file'] = path_to_file; //this is just how I chose to store the filepath
if (isset($_REQUEST['download']) && $_REQUEST['download'] == 'yes') {
downloadFile($_SESSION['your_file']);
} else {
*execute logic to create the file*
}
To break this down, jquery first launches your php script in an iframe. The iframe is loaded once the file is generated. Then jquery launches the script again with a request variable telling the script to download the file.
The reason that you can't do the download and file generation all in one go is due to the php header() function. If you use header(), you're changing the script to something other than a web page and jquery will never recognize the download script as being 'loaded'. I know this may not necessarily be detecting when a browser receives a file but your issue sounded similar to mine.
If you are stuck with C++98 and don't want to use boost, here there is the solution I use when I need to initialize a static map:
typedef std::pair< int, char > elemPair_t;
elemPair_t elemPairs[] =
{
elemPair_t( 1, 'a'),
elemPair_t( 3, 'b' ),
elemPair_t( 5, 'c' ),
elemPair_t( 7, 'd' )
};
const std::map< int, char > myMap( &elemPairs[ 0 ], &elemPairs[ sizeof( elemPairs ) / sizeof( elemPairs[ 0 ] ) ] );
Try this: really quick + worked for me:
ps: excuse image below for different language :)
we are using below configuration to do something similar
var gulp = require('gulp'),
async = require("async"),
less = require('gulp-less'),
minifyCSS = require('gulp-minify-css'),
uglify = require('gulp-uglify'),
concat = require('gulp-concat'),
gulpDS = require("./gulpDS"),
del = require('del');
// CSS & Less
var jsarr = [gulpDS.jsbundle.mobile, gulpDS.jsbundle.desktop, gulpDS.jsbundle.common];
var cssarr = [gulpDS.cssbundle];
var generateJS = function() {
jsarr.forEach(function(gulpDSObject) {
async.map(Object.keys(gulpDSObject), function(key) {
var val = gulpDSObject[key]
execGulp(val, key);
});
})
}
var generateCSS = function() {
cssarr.forEach(function(gulpDSObject) {
async.map(Object.keys(gulpDSObject), function(key) {
var val = gulpDSObject[key];
execCSSGulp(val, key);
})
})
}
var execGulp = function(arrayOfItems, dest) {
var destSplit = dest.split("/");
var file = destSplit.pop();
del.sync([dest])
gulp.src(arrayOfItems)
.pipe(concat(file))
.pipe(uglify())
.pipe(gulp.dest(destSplit.join("/")));
}
var execCSSGulp = function(arrayOfItems, dest) {
var destSplit = dest.split("/");
var file = destSplit.pop();
del.sync([dest])
gulp.src(arrayOfItems)
.pipe(less())
.pipe(concat(file))
.pipe(minifyCSS())
.pipe(gulp.dest(destSplit.join("/")));
}
gulp.task('css', generateCSS);
gulp.task('js', generateJS);
gulp.task('default', ['css', 'js']);
sample GulpDS file is below:
{
jsbundle: {
"mobile": {
"public/javascripts/sample.min.js": ["public/javascripts/a.js", "public/javascripts/mobile/b.js"]
},
"desktop": {
'public/javascripts/sample1.js': ["public/javascripts/c.js", "public/javascripts/d.js"]},
"common": {
'public/javascripts/responsive/sample2.js': ['public/javascripts/n.js']
}
},
cssbundle: {
"public/stylesheets/a.css": "public/stylesheets/less/a.less",
}
}
Just add a div around the container
so it looks like:
<div style="background: red;">
<div class="container marketing">
<h2 style="padding-top: 60px;"></h2>
</div>
</div>
This Can be Done by Style Property.
<!DOCTYPE html>
<html>
<head>
<style>
#main {
display: flex;
}
#main div {
flex-grow: 0;
flex-shrink: 0;
flex-basis: 40px;
}
</style>
</head>
<body>
<div id="main">
<div style="background-color:coral;">Red DIV</div>
<div style="background-color:lightblue;" id="myBlueDiv">Blue DIV</div>
</div>
</body>
</html>
Its Result will be :
Enjoy... Please Note: This works in Higher version of CSS (>3.0).
The SSMS Tools PACK Add-In (Add-On) for Microsoft SQL Server Management Studio and Microsoft SQL Server Management Studio Express will do exactly what you need. On larger database it takes some time to search, but that is to be expected. It also includes a ton of cool features that should have be included with SQL Server Management Studio in the first place. Give it a try www.ssmstoolspack.com/
You do need to have SP2 for SQL Server Management Studio installed to run the tools.
The method signature for addMarker
is:
public final Marker addMarker (MarkerOptions options)
So when you add a marker to a GoogleMap
by specifying the options for the marker, you should save the Marker
object that is returned (instead of the MarkerOptions
object that you used to create it). This object allows you to change the marker state later on. When you are finished with the marker, you can call Marker.remove()
to remove it from the map.
As an aside, if you only want to hide it temporarily, you can toggle the visibility of the marker by calling Marker.setVisible(boolean)
.
Why stop at just the instance name? You can inventory your SQL Server environment with following:
SELECT
SERVERPROPERTY('ServerName') AS ServerName,
SERVERPROPERTY('MachineName') AS MachineName,
CASE
WHEN SERVERPROPERTY('InstanceName') IS NULL THEN ''
ELSE SERVERPROPERTY('InstanceName')
END AS InstanceName,
'' as Port, --need to update to strip from Servername. Note: Assumes Registered Server is named with Port
SUBSTRING ( (SELECT @@VERSION),1, CHARINDEX('-',(SELECT @@VERSION))-1 ) as ProductName,
SERVERPROPERTY('ProductVersion') AS ProductVersion,
SERVERPROPERTY('ProductLevel') AS ProductLevel,
SERVERPROPERTY('ProductMajorVersion') AS ProductMajorVersion,
SERVERPROPERTY('ProductMinorVersion') AS ProductMinorVersion,
SERVERPROPERTY('ProductBuild') AS ProductBuild,
SERVERPROPERTY('Edition') AS Edition,
CASE SERVERPROPERTY('EngineEdition')
WHEN 1 THEN 'PERSONAL'
WHEN 2 THEN 'STANDARD'
WHEN 3 THEN 'ENTERPRISE'
WHEN 4 THEN 'EXPRESS'
WHEN 5 THEN 'SQL DATABASE'
WHEN 6 THEN 'SQL DATAWAREHOUSE'
END AS EngineEdition,
CASE SERVERPROPERTY('IsHadrEnabled')
WHEN 0 THEN 'The Always On Availability Groups feature is disabled'
WHEN 1 THEN 'The Always On Availability Groups feature is enabled'
ELSE 'Not applicable'
END AS HadrEnabled,
CASE SERVERPROPERTY('HadrManagerStatus')
WHEN 0 THEN 'Not started, pending communication'
WHEN 1 THEN 'Started and running'
WHEN 2 THEN 'Not started and failed'
ELSE 'Not applicable'
END AS HadrManagerStatus,
CASE SERVERPROPERTY('IsSingleUser') WHEN 0 THEN 'No' ELSE 'Yes' END AS InSingleUserMode,
CASE SERVERPROPERTY('IsClustered')
WHEN 1 THEN 'Clustered'
WHEN 0 THEN 'Not Clustered'
ELSE 'Not applicable'
END AS IsClustered,
'' as ServerEnvironment,
'' as ServerStatus,
'' as Comments
There is a solution after reloading the page and keeping the expected tab as selected.
Suppose after saving data the redirected url is : my_url#tab_2
Now through the following script your expected tab will remain selected.
$(document).ready(function(){
var url = document.location.toString();
if (url.match('#')) {
$('.nav-tabs a[href="#' + url.split('#')[1] + '"]').tab('show');
$('.nav-tabs a').removeClass('active');
}
});
$date = new DateTime($bithdayDate);
$now = new DateTime();
$interval = $now->diff($date);
return $interval->y;
This works for me saving a numpy array plotted with imshow to file
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10,10))
plt.imshow(img) # your image here
plt.axis("off")
plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0,
hspace = 0, wspace = 0)
plt.savefig("example2.png", box_inches='tight', dpi=100)
plt.show()
There is a method in Guava Sets
which can help here:
public static <E> boolean equals(Set<? extends E> set1, Set<? extends E> set2){
return Sets.symmetricDifference(set1,set2).isEmpty();
}
Go to Window → Preferences → Java → Installed JREs. Select the JRE you're using, click Edit, and there will be a line for Default VM Arguments which will apply to every execution. For instance, I use this on OS X to hide the icon from the dock, increase max memory and turn on assertions:
-Xmx512m -ea -Djava.awt.headless=true
Set texts with different sizes and styles, and size and style for texts from cells ( with Range)
Sub EmailManuellAbsenden()
Dim ghApp As Object
Dim ghOldBody As String
Dim ghNewBody As String
Set ghApp = CreateObject("Outlook.Application")
With ghApp.CreateItem(0)
.To = Range("B2")
.CC = Range("B3")
.Subject = Range("B4")
.GetInspector.Display
ghOldBody = .htmlBody
ghNewBody = "<font style=""font-family: Calibri; font-size: 11pt;""/font>" & _
"<font style=""font-family: Arial; font-size: 14pt;"">Arial Text 14</font>" & _
Range("B5") & "<br>" & _
Range("B6") & "<br>" & _
"<font style=""font-family: Chiller; font-size: 21pt;"">Ciller 21</font>" &
Range("B5")
.htmlBody = ghNewBody & ghOldBody
End With
End Sub
'Fill B2 to B6 with some letters for testing
'"<font style=""font-family: Calibri; font-size: 15pt;""/font>" = works for all Range Objekts
It is called favicon.ico and you can generate it from this site.
for bootstrap4 vertical center of few items
d-flex for flex rules
flex-column for vertical direction on items
justify-content-center for centering
style='height: 300px;' must have for set points where center be calc or use h-100 class
<div class="d-flex flex-column justify-content-center bg-secondary" style="
height: 300px;
">
<div class="p-2 bg-primary">Flex item</div>
<div class="p-2 bg-primary">Flex item</div>
<div class="p-2 bg-primary">Flex item</div>
</div>
class A
{
public:
int x;
protected:
int y;
private:
int z;
};
class B : public A
{
// x is public
// y is protected
// z is not accessible from B
};
class C : protected A
{
// x is protected
// y is protected
// z is not accessible from C
};
class D : private A // 'private' is default for classes
{
// x is private
// y is private
// z is not accessible from D
};
IMPORTANT NOTE: Classes B, C and D all contain the variables x, y and z. It is just question of access.
About usage of protected and private inheritance you could read here.
You can install the JVisualVM plugin from here: https://plugins.jetbrains.com/plugin/3749?pr=
This will allow you to analyse the dump within the plugin.
$(".advanced ul li").live('click',function(e){
if(e.target != this) return;
//code
// this code will execute only when you click to li and not to a child
})
Below is working solution using NgModel
Add variable
public Phone:string;
In html add
<input class="input-width" [(ngModel)]="Phone" (keyup)="keyUpEvent($event)"
type="text" class="form-control" placeholder="Enter Mobile Number">
In Ts file
keyUpEvent(event: any) {
const pattern = /[0-9\+\-\ ]/;
let inputChar = String.fromCharCode(event.keyCode);
if (!pattern.test(inputChar)) {
// invalid character, prevent input
if(this.Phone.length>0)
{
this.Phone= this.Phone.substr(0,this.Phone.length-1);
}
}
}
I will throw my vote behind Raphael - the cross-browser support, clean API and consistent updates (so far) make it a joy to use. It plays very nicely with jQuery too. Processing is cool, but more useful as a demo for bleeding-edge stuff at the moment.
There are two possibilities, both from Quest Software, TOAD & SQL Navigator:
Here is the TOAD Freeware download: http://www.toadworld.com/Downloads/FreewareandTrials/ToadforOracleFreeware/tabid/558/Default.aspx
And the SQL Navigator (trial version): http://www.quest.com/sql-navigator/software-downloads.aspx
Don't loop through every file line. Use readfile instead, its faster. This is off the php site: http://php.net/manual/en/function.readfile.php
$file = $_GET["file"];
if (file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header("Content-Type: application/force-download");
header('Content-Disposition: attachment; filename=' . urlencode(basename($file)));
// header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
Make sure to sanitize your get variable as someone could download some php files...
The following code should work. It takes every filename in the current directory, if the filename contains the pattern CHEESE_CHEESE_
then it is renamed. If not nothing is done to the filename.
import os
for fileName in os.listdir("."):
os.rename(fileName, fileName.replace("CHEESE_CHEESE_", "CHEESE_"))
google-services.json file work like API keys means it store your project_id and api key with json format for all google services(Which enable by you at google console) so no need manage all at different places.
at application gradle you should add
apply plugin: 'com.google.gms.google-services'.
at top level gradle you should add below dependency
dependencies {
// Add this line
classpath 'com.google.gms:google-services:3.0.0'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
I had the same problem. I also had added CA certificates in the local store, but I did in the WRONG way.
Using mmc Console (Start -> Run -> mmc ) you should add Certificates snap-in as Service account (choosing the service account of IIS) or Computer account (it adds for every account on the machine)
Here an image of what I'm talking about
From here now, you can add certificates of CAs (Trusted Root CAs and Intermediate CAs), and everything will work fine
Edited
ES6 solution:
[...new Set(a)];
Alternative:
Array.from(new Set(a));
Old response. O(n^2) (do not use it with large arrays!)
var arrayUnique = function(a) {
return a.reduce(function(p, c) {
if (p.indexOf(c) < 0) p.push(c);
return p;
}, []);
};
You say that the matrices are the same dimensions, and yet you are trying to perform matrix multiplication on them. Multiplication of matrices with the same dimension is only possible if they are square. In your case, you get an assertion error, because the dimensions are not square. You have to be careful when multiplying matrices, as there are two possible meanings of multiply.
Matrix multiplication is where two matrices are multiplied directly. This operation multiplies matrix A of size [a x b] with matrix B of size [b x c] to produce matrix C of size [a x c]. In OpenCV it is achieved using the simple *
operator:
C = A * B
Element-wise multiplication is where each pixel in the output matrix is formed by multiplying that pixel in matrix A by its corresponding entry in matrix B. The input matrices should be the same size, and the output will be the same size as well. This is achieved using the mul()
function:
output = A.mul(B);
System.getProperties()
can be overridden by calls to System.setProperty(String key, String value)
or with command line parameters -Dfile.separator=/
File.separator
gets the separator for the default filesystem.
FileSystems.getDefault()
gets you the default filesystem.
FileSystem.getSeparator()
gets you the separator character for the filesystem. Note that as an instance method you can use this to pass different filesystems to your code other than the default, in cases where you need your code to operate on multiple filesystems in the one JVM.
Had same issue when I had to develop a fixed length field format.
Usually we do not use line separator for binary files but For some reason our customer wished to add a line break as separator between records. They set
< record_delimiter value="\n"/ >
but this didn't work as records got two additional characters:
< record1 > \n < record2 > \n.... and so on.
Did following change and it just worked.
< record_delimiter value="\n"/> => < record_delimiter value="
"/ >
After unmarshaling Java interprets as new line character.
For nested dicts, lists of dicts, and dicts of listed dicts, ... you can use
def get_all_values(d):
if isinstance(d, dict):
for v in d.values():
yield from get_all_values(v)
elif isinstance(d, list):
for v in d:
yield from get_all_values(v)
else:
yield d
An example:
d = {'a': 1, 'b': {'c': 2, 'd': [3, 4]}, 'e': [{'f': 5}, {'g': 6}]}
list(get_all_values(d)) # returns [1, 2, 3, 4, 5, 6]
PS: I love yield
. ;-)
any large single block of data stored in a database, such as a picture or sound file, which does not include record fields, and cannot be directly searched by the database's search engine.
Problem solved.
Just drop down status bar, touch Choose input method, then change to another input method, type the password again. And everything is OK.
So weird...
Solution from a Chinese BBS. Thanks for the answer's author and all above who try to provide a solution, thanks!
Updated answer for 2017
The following will parse an XML string into an XML document in all major browsers. Unless you need support for IE <= 8 or some obscure browser, you could use the following function:
function parseXml(xmlStr) {
return new window.DOMParser().parseFromString(xmlStr, "text/xml");
}
If you need to support IE <= 8, the following will do the job:
var parseXml;
if (typeof window.DOMParser != "undefined") {
parseXml = function(xmlStr) {
return new window.DOMParser().parseFromString(xmlStr, "text/xml");
};
} else if (typeof window.ActiveXObject != "undefined" &&
new window.ActiveXObject("Microsoft.XMLDOM")) {
parseXml = function(xmlStr) {
var xmlDoc = new window.ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async = "false";
xmlDoc.loadXML(xmlStr);
return xmlDoc;
};
} else {
throw new Error("No XML parser found");
}
Once you have a Document
obtained via parseXml
, you can use the usual DOM traversal methods/properties such as childNodes
and getElementsByTagName()
to get the nodes you want.
Example usage:
var xml = parseXml("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);
If you're using jQuery, from version 1.5 you can use its built-in parseXML()
method, which is functionally identical to the function above.
var xml = $.parseXML("<foo>Stuff</foo>");
alert(xml.documentElement.nodeName);
HTML:
<button onclick="render()">Render</button>
<canvas id="myCanvas" height="100" width="100" style="object-fit:contain;"></canvas>
CSS:
canvas {
width: 400px;
height: 200px;
border: 1px solid red;
display: block;
}
Javascript:
const myCanvas = document.getElementById("myCanvas");
const originalHeight = myCanvas.height;
const originalWidth = myCanvas.width;
render();
function render() {
let dimensions = getObjectFitSize(
true,
myCanvas.clientWidth,
myCanvas.clientHeight,
myCanvas.width,
myCanvas.height
);
myCanvas.width = dimensions.width;
myCanvas.height = dimensions.height;
let ctx = myCanvas.getContext("2d");
let ratio = Math.min(
myCanvas.clientWidth / originalWidth,
myCanvas.clientHeight / originalHeight
);
ctx.scale(ratio, ratio); //adjust this!
ctx.beginPath();
ctx.arc(50, 50, 50, 0, 2 * Math.PI);
ctx.stroke();
}
// adapted from: https://www.npmjs.com/package/intrinsic-scale
function getObjectFitSize(
contains /* true = contain, false = cover */,
containerWidth,
containerHeight,
width,
height
) {
var doRatio = width / height;
var cRatio = containerWidth / containerHeight;
var targetWidth = 0;
var targetHeight = 0;
var test = contains ? doRatio > cRatio : doRatio < cRatio;
if (test) {
targetWidth = containerWidth;
targetHeight = targetWidth / doRatio;
} else {
targetHeight = containerHeight;
targetWidth = targetHeight * doRatio;
}
return {
width: targetWidth,
height: targetHeight,
x: (containerWidth - targetWidth) / 2,
y: (containerHeight - targetHeight) / 2
};
}
Basically, canvas.height/width sets the size of the bitmap you are rendering to. The CSS height/width then scales the bitmap to fit the layout space (often warping it as it scales it). The context can then modify it's scale to draw, using vector operations, at different sizes.
With Spring 3.1 and Tomcat 7 I got next error:
org.springframework.web.servlet.DispatcherServlet noHandlerFound No mapping found for HTTP request with URI [/baremvc/] in DispatcherServlet with name 'appServlet'
And I needed to add to web.xml next configuration:
<welcome-file-list>
<welcome-file/>
</welcome-file-list>
And the application worked!
What about using the .click() function and the tag?
(Compressed version)
<a id="downloadtag" href="examplefolder/testfile.txt" hidden download></a>_x000D_
_x000D_
<button onclick="document.getElementById('downloadtag').click()">Download</button>
_x000D_
Now you can trigger it with js. It also doesn't open, as other examples, image and text files!
(js-function version)
function download(){_x000D_
document.getElementById('downloadtag').click();_x000D_
}
_x000D_
<!-- HTML -->_x000D_
<button onclick="download()">Download</button>_x000D_
<a id="downloadtag" href="coolimages/awsome.png" hidden download></a>
_x000D_
You are probably looking for System.Guid.NewGuid()
.
I've taken @gauravsapiens answer with my comments inside to give you a reasonable apprehension of what the parameters will effect.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Background color -->
<solid android:color="@color/white" />
<!-- Stroke around the background, width and color -->
<stroke android:width="4dp" android:color="@color/drop_shadow"/>
<!-- The corners of the shape -->
<corners android:radius="4dp"/>
<!-- Padding for the background, e.g the Text inside a TextView will be
located differently -->
<padding android:left="10dp" android:right="10dp"
android:bottom="10dp" android:top="10dp" />
</shape>
If you're just looking to create a shape that rounds the corners, removing the padding and the stroke will do. If you remove the solid as well you will, in effect, have created rounded corners on a transparent background.
For the sake of being lazy I have created a shape underneath, which is just a solid white background with rounded corners - enjoy! :)
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Background color -->
<solid android:color="@color/white" />
<!-- The corners of the shape -->
<corners android:radius="4dp"/>
</shape>
as @PhilHarvey said, you can use mysqld --verbose --help | grep datadir
One mistake what i did was not including "implements OnClickListener" in the main class declaration. This is a sample code to clearly illustrate the use of switch case during on click. The code changes background colour as per the button pressed. Hope this helps.
public class MainActivity extends Activity implements OnClickListener{
TextView displayText;
Button cred, cblack, cgreen, cyellow, cwhite;
LinearLayout buttonLayout;
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cred = (Button) findViewById(R.id.bred);
cblack = (Button) findViewById(R.id.bblack);
cgreen = (Button) findViewById(R.id.bgreen);
cyellow = (Button) findViewById(R.id.byellow);
cwhite = (Button) findViewById(R.id.bwhite);
displayText = (TextView) findViewById(R.id.tvdisplay);
buttonLayout = (LinearLayout) findViewById(R.id.llbuttons);
cred.setOnClickListener(this);
cblack.setOnClickListener(this);
cgreen.setOnClickListener(this);
cyellow.setOnClickListener(this);
cwhite.setOnClickListener(this);
}
@Override
protected void onClick(View V){
int id=V.getId();
switch(id){
case R.id.bred:
displayText.setBackgroundColor(Color.rgb(255, 0, 0));
vanishLayout();
break;
case R.id.bblack:
displayText.setBackgroundColor(Color.rgb(0, 0, 0));
vanishLayout();
break;
case R.id.byellow:
displayText.setBackgroundColor(Color.rgb(255, 255, 0));
vanishLayout();
break;
case R.id.bgreen:
displayText.setBackgroundColor(Color.rgb(0, 255, 0));
vanishLayout();
break;
case R.id.bwhite:
displayText.setBackgroundColor(Color.rgb(255, 255, 255));
vanishLayout();
break;
}
}
It should be this way:
h2.myClass
looks for h2 with class myClass
. But you actually want to apply style for h2 inside .myClass
so you can use descendant selector .myClass h2
.
h2 {
color: red;
}
.myClass {
color: green;
}
.myClass h2 {
color: blue;
}
This ref will give you some basic idea about the selectors and have a look at descendant selectors
If you are using EF version more than 6.x , then see if you have installed the entity framework nuget package in every project of your solution. You might have installed Ef but not in that particular project which you are working on.
There are two prerequisite requirements need to install MySql Workbench as follows.
When .Net Framework 4.0
does not exist your computer installation will be corrupted. But if Microsoft Visual C++ 2010
does not exist your computer then you will continue the installation but cannot open MySql Workbench program. Sometimes you will need Microsoft Visual C++ 2013
instead of Microsoft Visual C++ 2010
. So I recommend to install Microsoft Visual C++ 2013
.
itertools.combinations is your friend if you have Python 2.6 or greater. Otherwise, check the link for an implementation of an equivalent function.
import itertools
def findsubsets(S,m):
return set(itertools.combinations(S, m))
S: The set for which you want to find subsets
m: The number of elements in the subset
You are using improper syntax. If you read the docs mysqli_query() you will find that it needs two parameter.
mixed mysqli_query ( mysqli $link , string $query [, int $resultmode = MYSQLI_STORE_RESULT ] )
mysql $link
generally means, the resource object of the established mysqli connection to query the database.
So there are two ways of solving this problem
mysqli_query();
$myConnection= mysqli_connect("$db_host","$db_username","$db_pass", "mrmagicadam") or die ("could not connect to mysql");
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysqli_query($myConnection, $sqlCommand) or die(mysqli_error($myConnection));
Or, Using mysql_query()
(This is now obselete)
$myConnection= mysql_connect("$db_host","$db_username","$db_pass") or die ("could not connect to mysql");
mysql_select_db("mrmagicadam") or die ("no database");
$sqlCommand="SELECT id, linklabel FROM pages ORDER BY pageorder ASC";
$query=mysql_query($sqlCommand) or die(mysql_error());
As pointed out in the comments, be aware of using die to just get the error. It might inadvertently give the viewer some sensitive information .
All the answers given using LIKE
are totally valid, but as all of them noted will be slow. So if you have a lot of queries and not too many changes in the list of keywords, it pays to build a structure that allows for faster querying.
Here are some ideas:
If all you are looking for is the letters a-z and you don't care about uppercase/lowercase, you can add columns containsA .. containsZ and prefill those columns:
UPDATE table
SET containsA = 'X'
WHERE UPPER(your_field) Like '%A%';
(and so on for all the columns).
Then index the contains.. columns and your query would be
SELECT
FROM your_table
WHERE containsA = 'X'
AND containsB = 'X'
This may be normalized in an "index table" iTable with the columns your_table_key
, letter, index the letter-column and your query becomes something like
SELECT
FROM your_table
WHERE <key> in (select a.key
From iTable a join iTable b and a.key = b.key
Where a.letter = 'a'
AND b.letter = 'b');
All of these require some preprocessing (maybe in a trigger or so), but the queries should be a lot faster.
We can also use binary search tree for getting sorted array by using in-order traversal method. The code also has implementation of basic binary search tree below.
class Util {
public static void printInorder(Node node)
{
if (node == null) {
return;
}
/* traverse left child */
printInorder(node.left);
System.out.print(node.data + " ");
/* traverse right child */
printInorder(node.right);
}
public static void sort(ArrayList<Integer> al, Node node) {
if (node == null) {
return;
}
/* sort left child */
sort(al, node.left);
al.add(node.data);
/* sort right child */
sort(al, node.right);
}
}
class Node {
Node left;
Integer data;
Node right;
public Node(Integer data) {
this.data = data;
}
public void insert(Integer element) {
if(element.equals(data)) {
return;
}
// if element is less than current then we know we will insert element to left-sub-tree
if(element < data) {
// if this node does not have a sub tree then this is the place we insert the element.
if(this.left == null) {
this.left = new Node(element);
} else { // if it has left subtree then we should iterate again.
this.left.insert(element);
}
} else {
if(this.right == null) {
this.right = new Node(element);
} else {
this.right.insert(element);
}
}
}
}
class Tree {
Node root;
public void insert(Integer element) {
if(root == null) {
root = new Node(element);
} else {
root.insert(element);
}
}
public void print() {
Util.printInorder(root);
}
public ArrayList<Integer> sort() {
ArrayList<Integer> al = new ArrayList<Integer>();
Util.sort(al, root);
return al;
}
}
public class Test {
public static void main(String[] args) {
int [] array = new int[10];
array[0] = ((int)(Math.random()*100+1));
array[1] = ((int)(Math.random()*100+1));
array[2] = ((int)(Math.random()*100+1));
array[3] = ((int)(Math.random()*100+1));
array[4] = ((int)(Math.random()*100+1));
array[5] = ((int)(Math.random()*100+1));
array[6] = ((int)(Math.random()*100+1));
array[7] = ((int)(Math.random()*100+1));
array[8] = ((int)(Math.random()*100+1));
array[9] = ((int)(Math.random()*100+1));
Tree tree = new Tree();
for (int i = 0; i < array.length; i++) {
tree.insert(array[i]);
}
tree.print();
ArrayList<Integer> al = tree.sort();
System.out.println("sorted array : ");
al.forEach(item -> System.out.print(item + " "));
}
}
I usually pass the RowIndex via CommandArgument and use it to retrieve the DataKey value I want.
On the Button:
CommandArgument='<%# DataBinder.Eval(Container, "RowIndex") %>'
On the Server Event
int rowIndex = int.Parse(e.CommandArgument.ToString());
string val = (string)this.grid.DataKeys[rowIndex]["myKey"];
I use Goto
For x= 1 to 20
If something then goto continue
skip this code
Continue:
Next x
random_state number splits the test and training datasets with a random manner. In addition to what is explained here, it is important to remember that random_state value can have significant effect on the quality of your model (by quality I essentially mean accuracy to predict). For instance, If you take a certain dataset and train a regression model with it, without specifying the random_state value, there is the potential that everytime, you will get a different accuracy result for your trained model on the test data. So it is important to find the best random_state value to provide you with the most accurate model. And then, that number will be used to reproduce your model in another occasion such as another research experiment. To do so, it is possible to split and train the model in a for-loop by assigning random numbers to random_state parameter:
for j in range(1000):
X_train, X_test, y_train, y_test = train_test_split(X, y , random_state =j, test_size=0.35)
lr = LarsCV().fit(X_train, y_train)
tr_score.append(lr.score(X_train, y_train))
ts_score.append(lr.score(X_test, y_test))
J = ts_score.index(np.max(ts_score))
X_train, X_test, y_train, y_test = train_test_split(X, y , random_state =J, test_size=0.35)
M = LarsCV().fit(X_train, y_train)
y_pred = M.predict(X_test)`
If you are a java guy simple place your angular folder in web content folder of your web application and deploy to your tomcat server. Super easy !
echo `date +%s`/86400 | bc
Happens when you try to access a property of an object while there is no object.
A typical example for a non-object notice would be
$users = json_decode('[{"name": "hakre"}]');
echo $users->name; # Notice: Trying to get property of non-object
In this case, $users
is an array (so not an object) and it does not have any properties.
This is similar to accessing a non-existing index or key of an array (see Notice: Undefined Index).
This example is much simplified. Most often such a notice signals an unchecked return value, e.g. when a library returns NULL
if an object does not exists or just an unexpected non-object value (e.g. in an Xpath result, JSON structures with unexpected format, XML with unexpected format etc.) but the code does not check for such a condition.
As those non-objects are often processed further on, often a fatal-error happens next on calling an object method on a non-object (see: Fatal error: Call to a member function ... on a non-object) halting the script.
It can be easily prevented by checking for error conditions and/or that a variable matches an expectation. Here such a notice with a DOMXPath example:
$result = $xpath->query("//*[@id='detail-sections']/div[1]");
$divText = $result->item(0)->nodeValue; # Notice: Trying to get property of non-object
The problem is accessing the nodeValue
property (field) of the first item while it has not been checked if it exists or not in the $result
collection. Instead it pays to make the code more explicit by assigning variables to the objects the code operates on:
$result = $xpath->query("//*[@id='detail-sections']/div[1]");
$div = $result->item(0);
$divText = "-/-";
if (is_object($div)) {
$divText = $div->nodeValue;
}
echo $divText;
Related errors:
For anyone coming across this thread, here's a script called thatsNotYoChild.js that I just wrote that solves this problem automatically:
http://www.impressivewebs.com/fixing-parent-child-opacity/
Basically, it separates children from the parent element, but keeps the element in the same physical location on the page.
I used the content+wrapper
approach ... but I did something different than mentioned so far: I made sure that my wrapper's boundaries did NOT line up with the content's boundaries in the direction that I wanted to be visible.
Important NOTE: It was easy enough to get the content+wrapper, same-bounds
approach to work on one browser or another depending on various css combinations of position
, overflow-*
, etc ... but I never could use that approach to get them all correct (Edge, Chrome, Safari, ...).
But when I had something like:
<div id="hack_wrapper" // created solely for this purpose
style="position:absolute; width:100%; height:100%; overflow-x:hidden;">
<div id="content_wrapper"
style="position:absolute; width:100%; height:15%; overflow:visible;">
... content with too-much horizontal content ...
</div>
</div>
... all browsers were happy.
This came from standford's sna free tutorial and it states that ...
# Reachability can only be computed on one vertex at a time. To
# get graph-wide statistics, change the value of "vertex"
# manually or write a for loop. (Remember that, unlike R objects,
# igraph objects are numbered from 0.)
ok, so when ever using igraph, the first roll/column is 0 other than 1, but matrix starts at 1, thus for any calculation under igraph, you would need x-1, shown at
this_node_reach <- subcomponent(g, (i - 1), mode = m)
but for the alter calculation, there is a typo here
alter = this_node_reach[j] + 1
delete +1 and it will work alright
function make_call()
{
// do the request
setTimeout(function(){
make_call();
}, 5000);
}
$(document).ready(function() {
make_call();
});
The most simple way is to use Record type Record<number, productDetails >
interface productDetails {
productId : number ,
price : number ,
discount : number
};
const myVar : Record<number, productDetails> = {
1: {
productId : number ,
price : number ,
discount : number
}
}
The calloc()
function that is declared in the <stdlib.h>
header offers a couple of advantages over the malloc()
function.
console.log
logs debug information to the console on some browsers (Firefox with Firebug installed, Chrome, IE8, anything with Firebug Lite installed). On Firefox it is a very powerful tool, allowing you to inspect objects or examine the layout or other properties of HTML elements. It isn't related to jQuery, but there are two things that are commonly done when using it with jQuery:
install the FireQuery extension for Firebug. This, amongst other advantages, makes the logging of jQuery objects look nicer.
create a wrapper that is more in line with jQuery's chaining code conventions.
This means usually something like this:
$.fn.log = function() {
if (window.console && console.log) {
console.log(this);
}
return this;
}
which you can then invoke like
$('foo.bar').find(':baz').log().hide();
to easily check inside jQuery chains.
Oracle
's locking concept is quite different from that of the other systems.
When a row in Oracle
gets locked, the record itself is updated with the new value (if any) and, in addition, a lock (which is essentially a pointer to transaction lock that resides in the rollback segment) is placed right into the record.
This means that locking a record in Oracle
means updating the record's metadata and issuing a logical page write. For instance, you cannot do SELECT FOR UPDATE
on a read only tablespace.
More than that, the records themselves are not updated after commit: instead, the rollback segment is updated.
This means that each record holds some information about the transaction that last updated it, even if the transaction itself has long since died. To find out if the transaction is alive or not (and, hence, if the record is alive or not), it is required to visit the rollback segment.
Oracle does not have a traditional lock manager, and this means that obtaining a list of all locks requires scanning all records in all objects. This would take too long.
You can obtain some special locks, like locked metadata objects (using v$locked_object
), lock waits (using v$session
) etc, but not the list of all locks on all objects in the database.
Thanks to this post, I use this style to remove the red border that appears automatically with bootstrap when a required field is displayed, but user didn't have a chance to input anything already:
input.ng-pristine.ng-invalid {
-webkit-box-shadow: none;
-ms-box-shadow: none;
box-shadow:none;
}
I recommend you just use the requests module.
It is much easier than the built in http clients: http://docs.python-requests.org/en/latest/index.html
Sample usage:
r = requests.get('http://www.thepage.com', proxies={"http":"http://myproxy:3129"})
thedata = r.content
grep
Select-String
cmdlet and -match
operator work with regexes. Also you can directly make use of .NET's regex support for more advanced functionality.
sort
Sort-Object
is more powerful (than I remember *nix's sort
). Allowing multi-level sorting on arbitrary expressions. Here PowerShell's maintenance of underlying type helps; e.g. a DateTime
property will be sorted as a DateTime
without having to ensure formatting into a sortable format.
uniq
Select-Object -Unique
Perl (how close does PowerShell come to Perl capabilities?)
In terms of Perl's breadth of domain specific support libraries: nowhere close (yet).
For general programming, PowerShell is certainly more cohesive and consistent, and easier to extend. The one gap for text munging is something equivalent to Perl's ..
operator.
AWK
It has been long enough since using AWK (must be >18 years, since later I just used Perl), so can't really comment.
sed
[See above]
file (the command that gives file information)
PowerShell's strength here isn't so much of what it can do with filesystem objects (and it gets full information here, dir
returns FileInfo
or FolderInfo
objects as appropriate) is that is the whole provider model.
You can treat the registry, certificate store, SQL Server, Internet Explorer's RSS cache, etc. as an object space navigable by the same cmdlets as the filesystem.
PowerShell is definitely the way forward on Windows. Microsoft has made it part of their requirements for future non-home products. Hence rich support in Exchange, support in SQL Server. This is only going to expand.
A recent example of this is the TFS PowerToys. Many TFS client operations are done without having to startup tf.exe each time (which requires a new TFS server connection, etc.) and is notably easier to then further process the data. As well as allowing wide access to the whole TFS client API to a greater detail than exposed in either Team Explorer of TF.exe.
@zdan. Good answer. I'd improve it like this...
I think that the closest you can come to a true return value in PowerShell is to use a local variable to pass the value and never to use return
as it may be 'corrupted' by any manner of output situations
function CheckRestart([REF]$retval)
{
# Some logic
$retval.Value = $true
}
[bool]$restart = $false
CheckRestart( [REF]$restart)
if ( $restart )
{
Restart-Computer -Force
}
The $restart
variable is used either side of the call to the function CheckRestart
making clear the scope of the variable. The return value can by convention be either the first or last parameter declared. I prefer last.
Dependent on how the API is created, normally with a 201 (created) you would return the resource which was created. For example if it was creating a user account you would do something like:
return {"data": {"username": "test","id":"fdsf345"}}, 201
Note the postfixed number is the status code returned.
Alternatively, you may want to send a message to the client such as:
return {"msg": "Created Successfully"}, 201
The language spec mentions comparison operators' behaviors:
In any comparison, the first operand must be assignable to the type of the second operand, or vice versa.
A value x is assignable to a variable of type T ("x is assignable to T") in any of these cases:
- x's type is identical to T.
- x's type V and T have identical underlying types and at least one of V or T is not a named type.
- T is an interface type and x implements T.
- x is a bidirectional channel value, T is a channel type, x's type V and T have identical element types, and at least one of V or T is not a named type.
- x is the predeclared identifier nil and T is a pointer, function, slice, map, channel, or interface type.
- x is an untyped constant representable by a value of type T.
Check out http://www.asciitable.com/
Look at the Hx
, (Hex) column; 2C
maps to ,
Any unusual encoding can be checked this way
+----+-----+----+-----+----+-----+----+-----+
| Hx | Chr | Hx | Chr | Hx | Chr | Hx | Chr |
+----+-----+----+-----+----+-----+----+-----+
| 00 | NUL | 20 | SPC | 40 | @ | 60 | ` |
| 01 | SOH | 21 | ! | 41 | A | 61 | a |
| 02 | STX | 22 | " | 42 | B | 62 | b |
| 03 | ETX | 23 | # | 43 | C | 63 | c |
| 04 | EOT | 24 | $ | 44 | D | 64 | d |
| 05 | ENQ | 25 | % | 45 | E | 65 | e |
| 06 | ACK | 26 | & | 46 | F | 66 | f |
| 07 | BEL | 27 | ' | 47 | G | 67 | g |
| 08 | BS | 28 | ( | 48 | H | 68 | h |
| 09 | TAB | 29 | ) | 49 | I | 69 | i |
| 0A | LF | 2A | * | 4A | J | 6A | j |
| 0B | VT | 2B | + | 4B | K | 6B | k |
| 0C | FF | 2C | , | 4C | L | 6C | l |
| 0D | CR | 2D | - | 4D | M | 6D | m |
| 0E | SO | 2E | . | 4E | N | 6E | n |
| 0F | SI | 2F | / | 4F | O | 6F | o |
| 10 | DLE | 30 | 0 | 50 | P | 70 | p |
| 11 | DC1 | 31 | 1 | 51 | Q | 71 | q |
| 12 | DC2 | 32 | 2 | 52 | R | 72 | r |
| 13 | DC3 | 33 | 3 | 53 | S | 73 | s |
| 14 | DC4 | 34 | 4 | 54 | T | 74 | t |
| 15 | NAK | 35 | 5 | 55 | U | 75 | u |
| 16 | SYN | 36 | 6 | 56 | V | 76 | v |
| 17 | ETB | 37 | 7 | 57 | W | 77 | w |
| 18 | CAN | 38 | 8 | 58 | X | 78 | x |
| 19 | EM | 39 | 9 | 59 | Y | 79 | y |
| 1A | SUB | 3A | : | 5A | Z | 7A | z |
| 1B | ESC | 3B | ; | 5B | [ | 7B | { |
| 1C | FS | 3C | < | 5C | \ | 7C | | |
| 1D | GS | 3D | = | 5D | ] | 7D | } |
| 1E | RS | 3E | > | 5E | ^ | 7E | ~ |
| 1F | US | 3F | ? | 5F | _ | 7F | DEL |
+----+-----+----+-----+----+-----+----+-----+
Consider an IBM 1403 impact printer. CR moved the print head to the start of the line, but did NOT advance the paper. This allowed for "overprinting", placing multiple lines of output on one line. Things like underlining were achieved this way, as was BOLD print. LF advanced the paper one line. If there was no CR, the next line would print as a staggered-step because LF didn't move the print head. FF advanced the paper to the next page. It typically also moved the print head to the start of the first line on the new page, but you might need CR for that. To be sure, most programmers coded CRFF instead of CRLF at the end of the last line on a page because an extra CR created by FF wouldn't matter.
Put the recyclerview in any other layout (Relative layout is preferable). Then change recyclerview's height/width as match parent to that layout and set the parent layout's height/width as wrap content.
Source: This comment.
In some cases (like poorly designed iterators), the class needs to keep a count or some other incidental value, that doesn't really affect the major "state" of the class. This is most often where I see mutable used. Without mutable, you'd be forced to sacrifice the entire const-ness of your design.
It feels like a hack most of the time to me as well. Useful in a very very few situations.
Go to this link here https://drive.google.com/file/d/0B9mUXEcOsbhfdFR1ZnVKNWtXQlU/view Cuodos To https://www.reddit.com/r/iOSProgramming/comments/6fmtj1/is_it_possible_to_download_xcode_9_beta_without_a/dikyeh4/
Conda itself provides a quite detailed guidance about installing non-conda packages. Details can be found here: https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-pkgs.html
The basic idea is to use conda-forge. If it doesn't work, activate the environment and use pip.
The top answer worked fine but I suggest saving your JSON data into a variable before posting it is a little bit cleaner when sending a long form or dealing with large data in general.
var Data = {_x000D_
"name":"jonsa",_x000D_
"e-mail":"[email protected]",_x000D_
"phone":1223456789_x000D_
};_x000D_
_x000D_
_x000D_
$.ajax({_x000D_
type: 'POST',_x000D_
url: '/form/',_x000D_
data: Data,_x000D_
success: function(data) { alert('data: ' + data); },_x000D_
contentType: "application/json",_x000D_
dataType: 'json'_x000D_
});
_x000D_
When using an EF model, I have a connection string in each project that consumes the EF model. For example, I have an EF EDMX model in a separate class library. I have one connection string in my web (mvc) project so that it can access the EF db.
I also have another unit test project for testing the repositories. In order for the repositories to access the EF db, the test project's app.config file has the same connection string.
DB connections should be configured, not coded, IMO.
private static readonly ICollection<string> PositiveList = new Collection<string> { "Y", "Yes", "T", "True", "1", "OK" };
public static bool ToBoolean(this string input)
{
return input != null && PositiveList.Any(? => ?.Equals(input, StringComparison.OrdinalIgnoreCase));
}
You are most likely looking for the IIS_IUSRS account.
I think in the one case that you want to multiply or divide by a power of two, you can't go wrong with using bitshift operators, even if the compiler converts them to a MUL/DIV, because some processors microcode (really, a macro) them anyway, so for those cases you will achieve an improvement, especially if the shift is more than 1. Or more explicitly, if the CPU has no bitshift operators, it will be a MUL/DIV anyway, but if the CPU has bitshift operators, you avoid a microcode branch and this is a few instructions less.
I am writing some code right now that requires a lot of doubling/halving operations because it is working on a dense binary tree, and there is one more operation that I suspect might be more optimal than an addition - a left (power of two multiply) shift with an addition. This can be replaced with a left shift and an xor if the shift is wider than the number of bits you want to add, easy example is (i<<1)^1, which adds one to a doubled value. This does not of course apply to a right shift (power of two divide) because only a left (little endian) shift fills the gap with zeros.
In my code, these multiply/divide by two and powers of two operations are very intensively used and because the formulae are quite short already, each instruction that can be eliminated can be a substantial gain. If the processor does not support these bitshift operators, no gain will happen but neither will there be a loss.
Also, in the algorithms I am writing, they visually represent the movements that occur so in that sense they are in fact more clear. The left hand side of a binary tree is bigger, and the right is smaller. As well as that, in my code, odd and even numbers have a special significance, and all left-hand children in the tree are odd and all right hand children, and the root, are even. In some cases, which I haven't encountered yet, but may, oh, actually, I didn't even think of this, x&1 may be a more optimal operation compared to x%2. x&1 on an even number will produce zero, but will produce 1 for an odd number.
Going a bit further than just odd/even identification, if I get zero for x&3 I know that 4 is a factor of our number, and same for x%7 for 8, and so on. I know that these cases have probably got limited utility but it's nice to know that you can avoid a modulus operation and use a bitwise logic operation instead, because bitwise operations are almost always the fastest, and least likely to be ambiguous to the compiler.
I am pretty much inventing the field of dense binary trees so I expect that people may not grasp the value of this comment, as very rarely do people want to only perform factorisations on only powers of two, or only multiply/divide powers of two.
I prefer combining DATEADD
and DATEDIFF
functions like this:
GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, Created),0)
Together, these two functions zero-out the date component smaller than the specified datepart (i.e. MONTH
in this example).
You can change the datepart bit to YEAR
, WEEK
, DAY
, etc... which is super handy.
Your original SQL query would then look something like this (I can't test it as I don't have your data set, but it should put you on the right track).
DECLARE @start [datetime] = '2010-04-01';
SELECT
ItemID,
UserID,
DATEADD(MONTH, DATEDIFF(MONTH, 0, Created),0) [Month],
IsPaid,
SUM(Amount)
FROM LIVE L
INNER JOIN Payments I ON I.LiveID = L.RECORD_KEY
WHERE UserID = 16178
AND PaymentDate > @start
One more thing: the Month
column is typed as a DateTime
which is also a nice advantage if you need to further process that data or map it .NET object for example.
Marc's answer should be the correct one, but in .NET 4 you couldn't also go with dynamic type.
This should be used only if you have no control over the classes you return and there are no common ancestors ( usually with interop ) and only if not using dynamic is a lot more painful then using(casting every object in every step :) ).
Few blog post trying to explain when to use dynamic: http://blogs.msdn.com/b/csharpfaq/archive/tags/dynamic/
public dynamic GetSomething()
{
Hello hello = new Hello();
Computer computer = new Computer();
Radio radio = new Radio();
return // anyobject
}
Here is my solution if you don't want to mess with additional libraries or edit your code manually. I created this Jupyter notebook to go over all java files and comment out all the Log messages. Not perfect but it got the job done for me.
To Disable scroll use this
webView.setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event)
{
return (event.getAction() == MotionEvent.ACTION_MOVE);
}
});
The order is always implied in the structure of the regular expression. To accomplish what you want, you'll have to match the input string multiple times against different expressions.
What you want to do is not possible with a single regexp.
NestedScrollView is just like ScrollView, but in NestedScrollView we can put other scrolling views as child of it, e.g. RecyclerView.
But if we put RecyclerView inside NestedScrollView, RecyclerView's smooth scrolling is disturbed. So to bring back smooth scrolling there's trick:
ViewCompat.setNestedScrollingEnabled(recyclerView, false);
put above line after setting adapter for recyclerView.
If you are using hibernate as your JPA provider you can use the annotation @OnDelete
. This annotation will add to the relation the trigger ON DELETE CASCADE
, which delegates the deletion of the children to the database.
Example:
public class Parent {
@Id
private long id;
}
public class Child {
@Id
private long id;
@ManyToOne
@OnDelete(action = OnDeleteAction.CASCADE)
private Parent parent;
}
With this solution a unidirectional relationship from the child to the parent is enough to automatically remove all children. This solution does not need any listeners etc. Also a JPQL query like DELETE FROM Parent WHERE id = 1
will remove the children.
I had the same issue on my windows 10. This is what fixed my problem
bower_components
in your root folder.bowerrc
file in the root{"directory" : "public/bower_components"}
bower install
You should see bower_components folder in your public folder now
It is recommended that you create a file named setenv.bat and place it in the Tomcat bin directory. With this file (which is run by the catalina.bat and catalina.sh scripts), you can change the following Tomcat environment settings with the JAVA_OPTS variable:
You can set the minimum and maximum memory heap size with the
JVM -Xms and -Xmx parameters.
The best limits depend on many conditions, such as transformations that Integrator ETL should execute. For Information Discovery transformations, a maximum of 1 GB is recommended. For example, to set the minimum heap size to 128 MB and the maximum heap size to 1024 MB, use
JAVA_OPTS=-Xms128m -Xmx1024m
You should set the maximum limit of the PermGen (Permanent Generation) memory space to a size larger than the default. The default of 64 MB is not enough for enterprise applications. A suitable memory limit depends on various criteria, but 256 MB would make a good choice in most cases. If the PermGen space maximum is too low, OutOfMemoryError: PermGen space errors may occur. You can set the PermGen maximum limit with the following JVM parameter
-XX:MaxPermSize=256m
For performance reasons, it is recommended that the application is run in Server mode. Apache Tomcat does not run in Server mode by default. You can set the Server mode by using the JVM -server parameter. You can set the JVM parameter in the JAVA_OPTS variable in the environment variable in the setenv file.
The following is an example of a setenv.bat file:
set "JAVA_OPTS=%JAVA_OPTS% -Xms128m -Xmx1024m -XX:MaxPermSize=256m -server"
If you are most concerned about code size and/or performance (also for WCET analysis, if you need one), I think this is probably going to be one of the more transparent solutions (for finding and removing elements):
unsigned int l=0, removed=0;
for( unsigned int i=0; i<count; i++ ) {
if( array[i] != to_remove )
array[l++] = array[i];
else
removed++;
}
count -= removed;
I solved this problem by doing the following:
The accepted answer to this question is awesome and should remain the accepted answer. However I ran into an issue with the code where the read stream was not always being ended/closed. Part of the solution was to send autoClose: true
along with start:start, end:end
in the second createReadStream
arg.
The other part of the solution was to limit the max chunksize
being sent in the response. The other answer set end
like so:
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
...which has the effect of sending the rest of the file from the requested start position through its last byte, no matter how many bytes that may be. However the client browser has the option to only read a portion of that stream, and will, if it doesn't need all of the bytes yet. This will cause the stream read to get blocked until the browser decides it's time to get more data (for example a user action like seek/scrub, or just by playing the stream).
I needed this stream to be closed because I was displaying the <video>
element on a page that allowed the user to delete the video file. However the file was not being removed from the filesystem until the client (or server) closed the connection, because that is the only way the stream was getting ended/closed.
My solution was just to set a maxChunk
configuration variable, set it to 1MB, and never pipe a read a stream of more than 1MB at a time to the response.
// same code as accepted answer
var end = positions[1] ? parseInt(positions[1], 10) : total - 1;
var chunksize = (end - start) + 1;
// poor hack to send smaller chunks to the browser
var maxChunk = 1024 * 1024; // 1MB at a time
if (chunksize > maxChunk) {
end = start + maxChunk - 1;
chunksize = (end - start) + 1;
}
This has the effect of making sure that the read stream is ended/closed after each request, and not kept alive by the browser.
I also wrote a separate StackOverflow question and answer covering this issue.
Here is a solution using moment.js:
var a = moment('7/11/2010','M/D/YYYY');
var b = moment('12/12/2010','M/D/YYYY');
var diffDays = b.diff(a, 'days');
alert(diffDays);
I used your original input values, but you didn't specify the format so I assumed the first value was July 11th. If it was intended to be November 7th, then adjust the format to D/M/YYYY
instead.
A bit more detail to Joachim Sauer's answer:
On Ubuntu at least, the metapackage tomcat6
depends on metapackage tomcat6-common
(and others), which depends on metapackage libtomcat6-java
, which depends on package libservlet2.5-java
(and others). It contains, among others, the files /usr/share/java/servlet-api-2.5.jar
and /usr/share/java/jsp-api-2.1.jar
, which are the servlet and JSP libraries you need. So if you've installed Tomcat 6 through apt-get or the Ubuntu Software Centre, you already have the libraries; all that's left is to get Tomcat to use them in your project.
Place libraries /usr/share/java/servlet-api-2.5.jar
and /usr/share/java/jsp-api-2.1.jar
on the class path like this:
For all projects, by configuring Eclipse by selecting Window -> Preferences -> Java -> Installed JREs, then selecting the JRE you're using, pressing Edit, then pressing Add External JARs, and then by selecting the files from the locations given above.
For just one project, by right-clicking on the project in the Project Explorer pane, then selecting Properties -> Java Build Path, and then pressing Add External JARs, and then by selecting the files from the locations given above.
Further note 1: These are the correct versions of those libraries for use with Tomcat 6; for the other Tomcat versions, see the table on page http://tomcat.apache.org/whichversion.html, though I would suppose each Tomcat version includes the versions of these libraries that are appropriate for it.
Further note 2: Package libservlet2.5-java
's description (dpkg-query -s libservlet2.5-java
) says: 'Apache Tomcat implements the Java Servlet and the JavaServer Pages (JSP) specifications from Sun Microsystems, and provides a "pure Java" HTTP web server environment for Java code to run. This package contains the Java Servlet and JSP library.'
If we use tMOdel.setRowCount(0);
we can get Empty table.
DefaultTableModel tMOdel = (DefaultTableModel) jtableName.getModel();
tMOdel.setRowCount(0);
It sounds like you may want to use something like SimpleDateFormat. http://java.sun.com/j2se/1.4.2/docs/api/java/text/SimpleDateFormat.html
You declare your date format and then call the parse method with your string.
private static final DateFormat DF = new SimpleDateFormat(...);
Date myDate = DF.parse("1234");
And as Guillaume says, set the timezone!
Related information, especially if you are using NTVS for working with the Visual Studio IDE. The NTVS adds both NodeJS and Express tools, scaffolding, project templates to Visual Studio 2012, 2013.
Also, the verbiage that calls ExpressJS or Connect as a "WebServer" is incorrect. You can create a basic WebServer with or without them. A basic NodeJS program can also use the http module to handle http requests, Thus becoming a rudimentary web server.
Setting the objectEquality
parameter (third parameter) of the $watch
function is definitely the correct way to watch ALL properties of the array.
$scope.$watch('columns', function(newVal) {
alert('columns changed');
},true); // <- Right here
Piran answers this well enough and mentions $watchCollection
as well.
More Detail
The reason I'm answering an already answered question is because I want to point out that wizardwerdna's answer is not a good one and should not be used.
The problem is that the digests do not happen immediately. They have to wait until the current block of code has completed before executing. Thus, watch the length
of an array may actually miss some important changes that $watchCollection
will catch.
Assume this configuration:
$scope.testArray = [
{val:1},
{val:2}
];
$scope.$watch('testArray.length', function(newLength, oldLength) {
console.log('length changed: ', oldLength, ' -> ', newLength);
});
$scope.$watchCollection('testArray', function(newArray) {
console.log('testArray changed');
});
At first glance, it may seem like these would fire at the same time, such as in this case:
function pushToArray() {
$scope.testArray.push({val:3});
}
pushToArray();
// Console output
// length changed: 2 -> 3
// testArray changed
That works well enough, but consider this:
function spliceArray() {
// Starting at index 1, remove 1 item, then push {val: 3}.
$testArray.splice(1, 1, {val: 3});
}
spliceArray();
// Console output
// testArray changed
Notice that the resulting length was the same even though the array has a new element and lost an element, so as watch as the $watch
is concerned, length
hasn't changed. $watchCollection
picked up on it, though.
function pushPopArray() {
$testArray.push({val: 3});
$testArray.pop();
}
pushPopArray();
// Console output
// testArray change
The same result happens with a push and pop in the same block.
Conclusion
To watch every property in the array, use a $watch
on the array iteself with the third parameter (objectEquality) included and set to true. Yes, this is expensive but sometimes necessary.
To watch when object enter/exit the array, use a $watchCollection
.
Do NOT use a $watch
on the length
property of the array. There is almost no good reason I can think of to do so.
In my case when i tried
$ hive --service metastore
I got
MetaException(message:Version information not found in metastore. )
The necessary tables required for the metastore are missing in MySQL. Manually create the tables and restart hive metastore.
cd $HIVE_HOME/scripts/metastore/upgrade/mysql/
< Login into MySQL >
mysql> drop database IF EXISTS <metastore db name>;
mysql> create database <metastore db name>;
mysql> use <metastore db name>;
mysql> source hive-schema-2.x.x.mysql.sql;
metastore db name should match the database name mentioned in hive-site.xml files connection property tag.
hive-schema-2.x.x.mysql.sql file depends on the version available in the current directory. Try to go for the latest because it holds many old schema files also.
Now try to execute hive --service metastore
If everything goes cool, then simply start the hive from terminal.
>hive
I hope the above answer serves your need.
Just to expand on the previous answer colorRampPalette
can handle more than two colors.
So for a more expanded "heat map" type look you can....
colfunc<-colorRampPalette(c("red","yellow","springgreen","royalblue"))
plot(rep(1,50),col=(colfunc(50)), pch=19,cex=2)
The resulting image:
Microsoft finally heard you!
Now with C# 7 you can:
switch(shape)
{
case Circle c:
WriteLine($"circle with radius {c.Radius}");
break;
case Rectangle s when (s.Length == s.Height):
WriteLine($"{s.Length} x {s.Height} square");
break;
case Rectangle r:
WriteLine($"{r.Length} x {r.Height} rectangle");
break;
default:
WriteLine("<unknown shape>");
break;
case null:
throw new ArgumentNullException(nameof(shape));
}
var trim = your_string.replace(/^\s+|\s+$/g, '');
For GUI I'd say that the Object-Oriented Paradigma is very well suited. The Window is an Object, the Textboxes are Objects, and the Okay-Button is one too. On the other Hand stuff like String Processing can be done with much less overhead and therefore more straightforward with simple procedural paradigma.
I don't think it is a question of the language neither. You can write functional, procedural or object-oriented in almost any popular language, although it might be some additional effort in some.
The error TypeError: 'numpy.ndarray' object is not callable means that you tried to call a numpy array as a function.
Use
Z=XY[0]+XY[1]
Instead of
Z=XY(i,0)+XY(i,1)
<html>
<head>
<title>Login page</title>
</head>
<body>
<h1>Simple Login Page</h1>
<form name="login">
Username<input type="text" name="userid"/>
Password<input type="password" name="pswrd"/>
<input type="button" onclick="check(this.form)" value="Login"/>
<input type="reset" value="Cancel"/>
</form>
<script language="javascript">
function check(form) { /*function to check userid & password*/
/*the following code checkes whether the entered userid and password are matching*/
if(form.userid.value == "myuserid" && form.pswrd.value == "mypswrd") {
window.open('target.html')/*opens the target page while Id & password matches*/
}
else {
alert("Error Password or Username")/*displays error message*/
}
}
</script>
</body>
</html>
Try this:
class JSONListView(ListView):
queryset = Users.objects.all()
def get(self, request, *args, **kwargs):
data = {}
data["users"] = get_json_list(queryset)
return JSONResponse(data)
def get_json_list(query_set):
list_objects = []
for obj in query_set:
dict_obj = {}
for field in obj._meta.get_fields():
try:
if field.many_to_many:
dict_obj[field.name] = get_json_list(getattr(obj, field.name).all())
continue
dict_obj[field.name] = getattr(obj, field.name)
except AttributeError:
continue
list_objects.append(dict_obj)
return list_objects
foreach (DataRow row in Datatable.Rows)
{
if (row["CountryName"].ToString() == userInput)
{
return row["CountryID"];
}
}
While this may not compile directly you should get the idea, also I'm sure it would be vastly superior to do the query through SQL as a huge datatable will take a long time to run through all the rows.
**
: exponentiation^
: exclusive-or (bitwise)%
: modulus//
: divide with integral result (discard remainder)Parameters are key-value pairs that can appear inside URL path, and start with a semicolon character (;
).
Query string appears after the path (if any) and starts with a question mark character (?
).
Both parameters and query string contain key-value pairs.
In a GET
request, parameters appear in the URL itself:
<scheme>://<username>:<password>@<host>:<port>/<path>;<parameters>?<query>#<fragment>
In a POST
request, parameters can appear in the URL itself, but also in the datastream (as known as content).
Query string is always a part of the URL.
Parameters can be buried in form-data
datastream when using POST method so they may not appear in the URL. Yes a POST
request can define parameters as form data and in the URL, and this is not inconsistent because parameters can have several values.
I've found no explaination for this behavior so far. I guess it might be useful sometimes to "unhide" parameters from a POST
request, or even let the code handling a GET
request share some parts with the code handling a POST
. Of course this can work only with server code supporting parameters in a URL.
Until you get better insights, I suggest you to use parameters only in form-data
datastream of POST
requests.
Sources:
I wanted my XAML to remain as elegant as possible so I created a class to wrap the bool which resides in one of my shared libraries, the implicit operators allow the class to be used as a bool in code-behind seamlessly
public class InvertableBool
{
private bool value = false;
public bool Value { get { return value; } }
public bool Invert { get { return !value; } }
public InvertableBool(bool b)
{
value = b;
}
public static implicit operator InvertableBool(bool b)
{
return new InvertableBool(b);
}
public static implicit operator bool(InvertableBool b)
{
return b.value;
}
}
The only changes needed to your project are to make the property you want to invert return this instead of bool
public InvertableBool IsActive
{
get
{
return true;
}
}
And in the XAML postfix the binding with either Value or Invert
IsEnabled="{Binding IsActive.Value}"
IsEnabled="{Binding IsActive.Invert}"
There is no way you can delete a pull request yourself -- you and the repo owner (and all users with push access to it) can close it, but it will remain in the log. This is part of the philosophy of not denying/hiding what happened during development.
However, if there are critical reasons for deleting it (this is mainly violation of Github Terms of Service), Github support staff will delete it for you.
Whether or not they are willing to delete your PR for you is something you can easily ask them, just drop them an email at [email protected]
UPDATE: Currently Github requires support requests to be created here: https://support.github.com/contact
VisualVm does not come with Apple JDK. You can use VisualVM Mac Application bundle(dmg) as a separate application, to compensate for that.
The answer from niaher stating that to use the fluent API you need a custom extension may have been correct at the time of writing. You can now (EF core 2.1) use the fluent API as follows:
modelBuilder.Entity<ClassName>()
.HasIndex(a => new { a.Column1, a.Column2}).IsUnique();
Is there anything I can do other than break in the middle of the tags rather than between them?
Not really. Since <img>
s are inline elements, spaces between these elements are considered by the HTML renderer as true spaces in text – redundant spaces (and line breaks) will be truncated but single spaces will be inserted into the character data of the text element.
Positioning the <img>
tags absolutely can prevent this but I'd advise against this since this would mean positioning each of the images manually to some pixel measure which can be a lot of work.