Chrome will never implement support RTSP streaming.
At least, in the words of a Chromium developer here:
we're never going to add support for this
If you are reencoding in your ffmpeg command line, that may be the reason why it is CPU intensive. You need to simply copy the streams to the single container. Since I do not have your command line I cannot suggest a specific improvement here. Your acodec and vcodec should be set to copy is all I can say.
EDIT: On seeing your command line and given you have already tried it, this is for the benefit of others who come across the same question. The command:
ffmpeg -i rtsp://@192.168.241.1:62156 -acodec copy -vcodec copy c:/abc.mp4
will not do transcoding and dump the file for you in an mp4. Of course this is assuming the streamed contents are compatible with an mp4 (which in all probability they are).
Or you can use the more obvious solution, right in the GUI: Tools -> Messages (set verbosity to 2)...
Another streaming command I've had good results with is piping the ffmpeg output to vlc to create a stream. If you don't have these installed, you can add them:
sudo apt install vlc ffmpeg
In the example I use an mpeg transport stream (ts) over http, instead of rtsp. I've tried both, but the http ts stream seems to work glitch-free on my playback devices.
I'm using a video capture HDMI>USB device that sets itself up on the video4linux2 driver as input. Piping through vlc must be CPU-friendly, because my old dual-core Pentium CPU is able to do the real-time encoding with no dropped frames. I've also had audio-sync issues with some of the other methods, where this method always has perfect audio-sync.
You will have to adjust the command for your device or file. If you're using a file as input, you won't need all that v4l2 and alsa stuff. Here's the ffmpeg|vlc command:
ffmpeg -thread_queue_size 1024 -f video4linux2 -input_format mjpeg -i /dev/video0 -r 30 -f alsa -ac 1 -thread_queue_size 1024 -i hw:1,0 -acodec aac -vcodec libx264 -preset ultrafast -crf 18 -s hd720 -vf format=yuv420p -profile:v main -threads 0 -f mpegts -|vlc -I dummy - --sout='#std{access=http,mux=ts,dst=:8554}'
For example, lets say your server PC IP is 192.168.0.10, then the stream can be played by this command:
ffplay http://192.168.0.10:8554
#or
vlc http://192.168.0.10:8554
Check the media stream library by Axis which relay on Media Source extension
They implement a pipeline similar to Gstreamer in JS with the h264 depay in it. Note: the streaming consumed in the js is not directly rtsp but encapsulated into a ws:// by the library itself on a node.js rtsp-websocket proxy.
AFAIK, RTSP does not transmit streams at all, it is just an out-of-band control protocol with functions like PLAY and STOP.
Raw UDP or RTP over UDP are transmission protocols for streams just like raw TCP or HTTP over TCP.
To be able to stream a certain program over the given transmission protocol, an encapsulation method has to be defined for your container format. For example TS container can be transmitted over UDP but Matroska can not.
Pretty much everything can be transported through TCP though.
(The fact that which codec do you use also matters indirectly as it restricts the container formats you can use.)
I'd store it in the database as a BIGINT
and I'd store the number of ticks (eg. TimeSpan.Ticks property).
That way, if I wanted to get a TimeSpan object when I retrieve it, I could just do TimeSpan.FromTicks(value) which would be easy.
toggleAttr()
is provided by this very nice and tiny plugin.
$('#my_radio').click(function() {
$(this).toggleAttr('checked');
});
/**
* toggleAttr Plugin
*/
jQuery.fn.toggleAttr = function(attr) {
return this.each(function() {
var $this = $(this);
$this.attr(attr) ? $this.removeAttr(attr) : $this.attr(attr, attr);
});
};
You can use place your radio button inside label or button tags and do some nice things.
If you want the variable inside the function available outside of the function, return the results of the variable inside the function.
var x = function returnX { var x = 0; return x; }
is the idea...
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script type="text/javascript">
var offsetfrommouse = [10, -20];
var displayduration = 0;
var obj_selected = 0;
function makeObj(address) {
var trailimage = [address, 50, 50];
document.write('<img id="trailimageid" src="' + trailimage[0] + '" border="0" style=" position: absolute; visibility:visible; left: 0px; top: 0px; width: ' + trailimage[1] + 'px; height: ' + trailimage[2] + 'px">');
obj_selected = 1;
return trailimage;
}
function truebody() {
return (!window.opera && document.compatMode && document.compatMode != "BackCompat") ? document.documentElement : document.body;
}
function hidetrail() {
var x = document.getElementById("trailimageid").style;
x.visibility = "hidden";
document.onmousemove = "";
}
function followmouse(e) {
var xcoord = offsetfrommouse[0];
var ycoord = offsetfrommouse[1];
var x = document.getElementById("trailimageid").style;
if (typeof e != "undefined") {
xcoord += e.pageX;
ycoord += e.pageY;
}
else if (typeof window.event != "undefined") {
xcoord += truebody().scrollLeft + event.clientX;
ycoord += truebody().scrollTop + event.clientY;
}
var docwidth = 1395;
var docheight = 676;
if (xcoord + trailimage[1] + 3 > docwidth || ycoord + trailimage[2] > docheight) {
x.display = "none";
alert("inja");
}
else
x.display = "";
x.left = xcoord + "px";
x.top = ycoord + "px";
}
if (obj_selected = 1) {
alert("obj_selected = true");
document.onmousemove = followmouse;
if (displayduration > 0)
setTimeout("hidetrail()", displayduration * 1000);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<img alt="" id="house" src="Pictures/sides/right.gif" style="z-index: 1; left: 372px; top: 219px; position: absolute; height: 138px; width: 120px" onclick="javascript:makeObj('Pictures/sides/sides-not-clicked.gif');" />
</form>
</body>
</html>
I haven't tested this, but if your code worked prior to that small change, then it should work.
I was not absolutely happy with any of the answers. But I have picked up some ideas from @Matt Way.
Here is my solution:
Definitions:
const Switch = props => {
const { test, children = null } = props;
return children && children.find(child => child && child.props && child.props.casevalue === test) || null;
}
const Case = ({ casevalue = false, children = null }) => <div casevalue={`${casevalue}`}>{children}</div>;
Case.propTypes = {
casevalue: PropTypes.string.isRequired,
children: PropTypes.node.isRequired,
}
const Default = ({ children }) => children || <h1>NO_RESULT</h1>;
const SwitchCase = ({ test, cases = [], defaultValue = null }) => {
const defaultVal = defaultValue
&& React.cloneElement(defaultValue, { key: 'default-key', casevalue: `${test}` })
|| <Default key='default-key' casevalue={`${test}`} />;
return (
<Switch test={`${test}`} >
{
cases.map((cas, i) => {
const { props = {} } = cas || {};
const { casevalue = false, ...rest } = props || {};
return <Case key={`case-key-${i}`} casevalue={`${casevalue}`}>{ React.cloneElement(cas, rest)}</Case>
})
.concat(defaultVal)
}
</Switch>
);
}
Usage:
<SwitchCase
cases={[
<div casevalue={`${false}`}>#1</div>,
<div casevalue={`${true}`}>#2</div>,
<div casevalue={`${false}`}>#3</div>,
]}
defaultValue={<h1>...nothing to see here</h1>} // You can leave it blank.
test={`${true}`}
/>
Your PHP was compiled with MySQL 5.1 but now it is linking a mysql library of 5.5.X family. You have to upgrade PHP to a version compiled with MySQL 5.5 or revert back mysql client libraries to 5.1.x.
chmod +w <directory>
This API has been available for a long time and enables to get access to market data (including live) if you are running a Bloomberg Terminal or have access to a Bloomberg Server, which is chargeable.
The only difference is that the API (not its code) has been open sourced, so it can now be used as a dependency in an open source project for example, without any copyrights issues, which was not the case before.
"how can i return a array in a c++ method and how must i declare it? int[] test(void); ??"
template <class X>
class Array
{
X *m_data;
int m_size;
public:
// there constructor, destructor, some methods
int Get(X* &_null_pointer)
{
if(!_null_pointer)
{
_null_pointer = new X [m_size];
memcpy(_null_pointer, m_data, m_size * sizeof(X));
return m_size;
}
return 0;
}
};
just for int
class IntArray
{
int *m_data;
int m_size;
public:
// there constructor, destructor, some methods
int Get(int* &_null_pointer)
{
if(!_null_pointer)
{
_null_pointer = new int [m_size];
memcpy(_null_pointer, m_data, m_size * sizeof(int));
return m_size;
}
return 0;
}
};
example
Array<float> array;
float *n_data = NULL;
int data_size;
if(data_size = array.Get(n_data))
{ // work with array }
delete [] n_data;
example for int
IntArray array;
int *n_data = NULL;
int data_size;
if(data_size = array.Get(n_data))
{ // work with array }
delete [] n_data;
If supported by your browser, you may use CSS3 :read-only
selector:
input[type="text"]:read-only {
cursor: normal;
background-color: #f8f8f8;
color: #999;
}
You should use method array_push to add value or array to array exists
$stack = array("orange", "banana");
array_push($stack, "apple", "raspberry");
print_r($stack);
/** GENERATED OUTPUT
Array
(
[0] => orange
[1] => banana
[2] => apple
[3] => raspberry
)
*/
You can use HttpEntity to read both Body and Headers.
@RequestMapping(value = "/restURL")
public String serveRest(HttpEntity<String> httpEntity){
MultiValueMap<String, String> headers =
httpEntity.getHeaders();
Iterator<Map.Entry<String, List<String>>> s =
headers.entrySet().iterator();
while(s.hasNext()) {
Map.Entry<String, List<String>> obj = s.next();
String key = obj.getKey();
List<String> value = obj.getValue();
}
String body = httpEntity.getBody();
}
+ (NSArray *)getArrayListFromDictionary:(NSDictionary *)dictMain paramName:(NSString *)paramName
{
if([dictMain isKindOfClass:[NSDictionary class]])
{
if ([dictMain objectForKey:paramName])
{
if ([[dictMain objectForKey:paramName] isKindOfClass:[NSArray class]])
{
NSArray *dataArray = [dictMain objectForKey:paramName];
return dataArray;
}
}
}
return [[NSArray alloc] init];
}
Hope this helps!
Exporting without default
means it's a "named export". You can have multiple named exports in a single file. So if you do this,
class Template {}
class AnotherTemplate {}
export { Template, AnotherTemplate }
then you have to import these exports using their exact names. So to use these components in another file you'd have to do,
import {Template, AnotherTemplate} from './components/templates'
Alternatively if you export as the default
export like this,
export default class Template {}
Then in another file you import the default export without using the {}
, like this,
import Template from './components/templates'
There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.
You're free to rename the default export as you import it,
import TheTemplate from './components/templates'
And you can import default and named exports at the same time,
import Template,{AnotherTemplate} from './components/templates'
I was searching to get a result for this either and I ended up with;
const MyObject = {
SubObject: {
'eu': [0, "asd", true, undefined],
'us': [0, "asd", false, null],
'aus': [0, "asd", false, 0]
}
};
For those who wanted the result as a string:
Object.keys(MyObject.SubObject).toString()
output: "eu,us,aus"
For those who wanted the result as an array:
Array.from(Object.keys(MyObject))
output: Array ["eu", "us", "aus"]
For those who are looking for a "contains" type method: as numeric result:
console.log(Object.keys(MyObject.SubObject).indexOf("k"));
output: -1
console.log(Object.keys(MyObject.SubObject).indexOf("eu"));
output: 0
console.log(Object.keys(MyObject.SubObject).indexOf("us"));
output: 3
as boolean result:
console.log(Object.keys(MyObject.SubObject).includes("eu"));
output: true
In your case;
var myVar = { typeA: { option1: "one", option2: "two" } }_x000D_
_x000D_
// Example 1_x000D_
console.log(Object.keys(myVar.typeA).toString()); // Result: "option1, option2"_x000D_
_x000D_
// Example 2_x000D_
console.log(Array.from(Object.keys(myVar.typeA))); // Result: Array ["option1", "option2" ]_x000D_
_x000D_
// Example 3 as numeric_x000D_
console.log((Object.keys(myVar.typeA).indexOf("option1")>=0)?'Exist!':'Does not exist!'); // Result: Exist!_x000D_
_x000D_
// Example 3 as boolean_x000D_
console.log(Object.keys(myVar.typeA).includes("option2")); // Result: True!_x000D_
_x000D_
// if you would like to know about SubObjects_x000D_
for(var key in myVar){_x000D_
// do smt with SubObject_x000D_
console.log(key); // Result: typeA_x000D_
}_x000D_
_x000D_
// if you already know your "SubObject"_x000D_
for(var key in myVar.typeA){_x000D_
// do smt with option1, option2_x000D_
console.log(key); // Result: option1 // Result: option2_x000D_
}
_x000D_
I couldn't get access to remote machines unless I had UAC disabled.
That has to be done locally, either from control panel or running the following through cmd:
reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System /v EnableLUA /t REG_DWORD /d 0 /f
While UAC is enabled, make sure you run cmd as administrator.
You are setting your cron to run on 10th minute in every hour.
To set it to every 5 mins
change to */5 * * * * /usr/bin/php /mydomain.in/cronmail.php > /dev/null 2>&1
Hemnath
If your variable is the percentage:
var myWidth = 70;
$('div#somediv').width(myWidth + '%');
If your variable is in pixels, and you want the percentage it take up of the parent:
var myWidth = 140;
var myPercentage = (myWidth / $('div#somediv').parent().width()) * 100;
$('div#somediv').width(myPercentage + '%');
A priority queue is an abstract data type that captures the idea of a container whose elements have "priorities" attached to them. An element of highest priority always appears at the front of the queue. If that element is removed, the next highest priority element advances to the front.
The C++ standard library defines a class template priority_queue, with the following operations:
push: Insert an element into the prioity queue.
top: Return (without removing it) a highest priority element from the priority queue.
pop: Remove a highest priority element from the priority queue.
size: Return the number of elements in the priority queue.
empty: Return true or false according to whether the priority queue is empty or not.
The following code snippet shows how to construct two priority queues, one that can contain integers and another one that can contain character strings:
#include <queue>
priority_queue<int> q1;
priority_queue<string> q2;
The following is an example of priority queue usage:
#include <string>
#include <queue>
#include <iostream>
using namespace std; // This is to make available the names of things defined in the standard library.
int main()
{
piority_queue<string> pq; // Creates a priority queue pq to store strings, and initializes the queue to be empty.
pq.push("the quick");
pq.push("fox");
pq.push("jumped over");
pq.push("the lazy dog");
// The strings are ordered inside the priority queue in lexicographic (dictionary) order:
// "fox", "jumped over", "the lazy dog", "the quick"
// The lowest priority string is "fox", and the highest priority string is "the quick"
while (!pq.empty()) {
cout << pq.top() << endl; // Print highest priority string
pq.pop(); // Remmove highest priority string
}
return 0;
}
The output of this program is:
the quick
the lazy dog
jumped over
fox
Since a queue follows a priority discipline, the strings are printed from highest to lowest priority.
Sometimes one needs to create a priority queue to contain user defined objects. In this case, the priority queue needs to know the comparison criterion used to determine which objects have the highest priority. This is done by means of a function object belonging to a class that overloads the operator (). The overloaded () acts as < for the purpose of determining priorities. For example, suppose we want to create a priority queue to store Time objects. A Time object has three fields: hours, minutes, seconds:
struct Time {
int h;
int m;
int s;
};
class CompareTime {
public:
bool operator()(Time& t1, Time& t2) // Returns true if t1 is earlier than t2
{
if (t1.h < t2.h) return true;
if (t1.h == t2.h && t1.m < t2.m) return true;
if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
return false;
}
}
A priority queue to store times according the the above comparison criterion would be defined as follows:
priority_queue<Time, vector<Time>, CompareTime> pq;
Here is a complete program:
#include <iostream>
#include <queue>
#include <iomanip>
using namespace std;
struct Time {
int h; // >= 0
int m; // 0-59
int s; // 0-59
};
class CompareTime {
public:
bool operator()(Time& t1, Time& t2)
{
if (t1.h < t2.h) return true;
if (t1.h == t2.h && t1.m < t2.m) return true;
if (t1.h == t2.h && t1.m == t2.m && t1.s < t2.s) return true;
return false;
}
};
int main()
{
priority_queue<Time, vector<Time>, CompareTime> pq;
// Array of 4 time objects:
Time t[4] = { {3, 2, 40}, {3, 2, 26}, {5, 16, 13}, {5, 14, 20}};
for (int i = 0; i < 4; ++i)
pq.push(t[i]);
while (! pq.empty()) {
Time t2 = pq.top();
cout << setw(3) << t2.h << " " << setw(3) << t2.m << " " <<
setw(3) << t2.s << endl;
pq.pop();
}
return 0;
}
The program prints the times from latest to earliest:
5 16 13
5 14 20
3 2 40
3 2 26
If we wanted earliest times to have the highest priority, we would redefine CompareTime like this:
class CompareTime {
public:
bool operator()(Time& t1, Time& t2) // t2 has highest prio than t1 if t2 is earlier than t1
{
if (t2.h < t1.h) return true;
if (t2.h == t1.h && t2.m < t1.m) return true;
if (t2.h == t1.h && t2.m == t1.m && t2.s < t1.s) return true;
return false;
}
};
You could try the following
select case when mydatetime IS NULL THEN '' else convert(varchar(20),@mydatetime,120) end as converted_date from sometable
-- Testing it out could do --
declare @mydatetime datetime
set @mydatetime = GETDATE() -- comment out for null value
--set @mydatetime = GETDATE()
select
case when @mydatetime IS NULL THEN ''
else convert(varchar(20),@mydatetime,120)
end as converted_date
Hope this helps!
{{p.User['first_name'] or 'My default string'}}
This should be an answer
str2.equals( str )
If you want to ignore case
str2.equalsIgnoreCase( str )
For anyone having this problem with docker-compose
.
When you have more than one project (i.e. in different folders) with similar services you need to run docker-compose stop
in each of your other projects.
Should be :
<h2 class="col-md-4 col-md-offset-1">Browse.</h2>
<h2 class="col-md-4 col-md-offset-2">create.</h2>
<h2 class="col-md-4 col-md-offset-3">share.</h2>
<?php
session_start();
if (time()<$_SESSION['time']+10){
$_SESSION['time'] = time();
echo "welcome old user";
}
else{
session_destroy();
session_start();
$_SESSION['time'] = time();
echo "welcome new user";
}
?>
Support for BUILD_PATH
just landed into v4.0.2.
Add BUILD_PATH
variable to .env
file and run build
script command:
// .env file
BUILD_PATH=foo
That should place all build files into foo
folder.
Addressing the first question, if you need to take several rows grouped by certain criteria with the other column with max value you can do something like this:
var query =
from u1 in table
join u2 in (
from u in table
group u by u.GroupId into g
select new { GroupId = g.Key, MaxStatus = g.Max(x => x.Status) }
) on new { u1.GroupId, u1.Status } equals new { u2.GroupId, Status = u2.MaxStatus}
select u1;
With the new version of sdk, the accepted answer does not work - it does not wait for the object to be downloaded. The following code snippet will help with the new version:
// dependencies
const AWS = require('aws-sdk');
// get reference to S3 client
const s3 = new AWS.S3();
exports.handler = async (event, context, callback) => {
var bucket = "TestBucket"
var key = "TestKey"
try {
const params = {
Bucket: Bucket,
Key: Key
};
var theObject = await s3.getObject(params).promise();
} catch (error) {
console.log(error);
return;
}
}
The answer you want depends very much on how and why you want to break up the data frame.
For example, if you want to leave out some variables, you can create new data frames from specific columns of the database. The subscripts in brackets after the data frame refer to row and column numbers. Check out Spoetry for a complete description.
newdf <- mydf[,1:3]
Or, you can choose specific rows.
newdf <- mydf[1:3,]
And these subscripts can also be logical tests, such as choosing rows that contain a particular value, or factors with a desired value.
What do you want to do with the chunks left over? Do you need to perform the same operation on each chunk of the database? Then you'll want to ensure that the subsets of the data frame end up in a convenient object, such as a list, that will help you perform the same command on each chunk of the data frame.
I wrote this method:
private string GetUrlParameter(HttpRequestBase request, string parName)
{
string result = string.Empty;
var urlParameters = HttpUtility.ParseQueryString(request.Url.Query);
if (urlParameters.AllKeys.Contains(parName))
{
result = urlParameters.Get(parName);
}
return result;
}
And I call it like this:
string fooBar = GetUrlParameter(Request, "FooBar");
if (!string.IsNullOrEmpty(fooBar))
{
}
The string
class has a constructor that takes a NULL-terminated C-string:
char arr[ ] = "This is a test";
string str(arr);
// You can also assign directly to a string.
str = "This is another string";
// or
str = arr;
Any uncomitted transaction will leave the server locked and other queries won't execute on the server. You either need to rollback the transaction or commit it. Closing out of SSMS will also terminate the transaction which will allow other queries to execute.
If you are going by android guide lines and you are using the ContentProviders
to get data from Database
and you are displaying it in the ListView
using the CursorLoader
and CursorAdapters
,then you all changes to the related data will automatically be reflected in the ListView.
Your getContext().getContentResolver().notifyChange(uri, null);
on the cursor in the ContentProvider
will be enough to reflect the changes .No need for the extra work around.
But when you are not using these all then you need to tell the adapter when the dataset is changing. Also you need to re-populate / reload your dataset (say list) and then you need to call notifyDataSetChanged()
on the adapter.
notifyDataSetChanged()
wont work if there is no the changes in the datset.
Here is the comment above the method in docs-
/**
* Notifies the attached observers that the underlying data has been changed
* and any View reflecting the data set should refresh itself.
*/
Array(...Array(9)).map((_, i) => i);_x000D_
_x000D_
console.log(Array(...Array(9)).map((_, i) => i))
_x000D_
It means that the method accepts a variable number of arguments ("varargs") of type JID
. Within the method, recipientJids
is presented.
This is handy for cases where you've a method that can optionally handle more than one argument in a natural way, and allows you to write calls which can pass one, two or three parameters to the same method, without having the ugliness of creating an array on the fly.
It also enables idioms such as sprintf
from C; see String.format()
, for example.
just call your function inside the events.
load:
$(document).ready(function(){ // or $(window).load(function(){
topInViewport($(mydivname));
});
resize:
$(window).resize(function () {
topInViewport($(mydivname));
});
scroll:
$(window).scroll(function () {
topInViewport($(mydivname));
});
or bind all event in one function
$(window).on("load scroll resize",function(e){
I needed to rotate a 3D model around one of the three axes {x, y, z} in which that model was embedded and this was the top result for a search of how to do this in numpy. I used the following simple function:
def rotate(X, theta, axis='x'):
'''Rotate multidimensional array `X` `theta` degrees around axis `axis`'''
c, s = np.cos(theta), np.sin(theta)
if axis == 'x': return np.dot(X, np.array([
[1., 0, 0],
[0 , c, -s],
[0 , s, c]
]))
elif axis == 'y': return np.dot(X, np.array([
[c, 0, -s],
[0, 1, 0],
[s, 0, c]
]))
elif axis == 'z': return np.dot(X, np.array([
[c, -s, 0 ],
[s, c, 0 ],
[0, 0, 1.],
]))
I'd just like to add to Jon's example. To get a reference to your own assembly, you can use:
Assembly myAssembly = Assembly.GetExecutingAssembly();
System.Reflection
namespace.
If you want to examine an assembly that you have no reference to, you can use either of these:
Assembly assembly = Assembly.ReflectionOnlyLoad(fullAssemblyName);
Assembly assembly = Assembly.ReflectionOnlyLoadFrom(fileName);
If you intend to instantiate your type once you've found it:
Assembly assembly = Assembly.Load(fullAssemblyName);
Assembly assembly = Assembly.LoadFrom(fileName);
See the Assembly class documentation for more information.
Once you have the reference to the Assembly
object, you can use assembly.GetTypes()
like Jon already demonstrated.
add "throws IOException" to your method like this:
public static void main(String args[]) throws IOException{
FileReader reader=new FileReader("db.properties");
Properties p=new Properties();
p.load(reader);
}
You can see in here: http://apidock.com/rails/ActionView/Helpers/FormBuilder/select
Or here: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select
Select tag has maximun 4 agrument, and last agrument is html option, it mean you can put class, require, selection option in here.
= f.select :sms_category_id, @sms_category_collect, {}, {class: 'form-control', required: true, selected: @set}
As far as I understand, the question is NOT about recursion. We can easily call main
method of another class in your class. Following example illustrates static and calling by object. Note omission of word static
in Class2
class Class1{
public static void main(String[] args) {
System.out.println("this is class 1");
}
}
class Class2{
public void main(String[] args) {
System.out.println("this is class 2");
}
}
class MyInvokerClass{
public static void main(String[] args) {
System.out.println("this is MyInvokerClass");
Class2 myClass2 = new Class2();
Class1.main(args);
myClass2.main(args);
}
}
Output Should be:
this is wrapper class
this is class 1
this is class 2
TelephonyManager tManager = (TelephonyManager)myActivity.getSystemService(Context.TELEPHONY_SERVICE);
String uid = tManager.getDeviceId();
getSystemService is a method from the Activity class. getDeviceID() will return the MDN or MEID of the device depending on which radio the phone uses (GSM or CDMA).
Each device MUST return a unique value here (assuming it's a phone). This should work for any Android device with a sim slot or CDMA radio. You're on your own with that Android powered microwave ;-)
Add this to the end of your proc: option(recompile)
This will make the report run almost as fast as the stored procedure
I tried adding a block like so:
@section styles{
<link rel="Stylesheet" href="@Href("~/Content/MyStyles.css")" />
}
And a corresponding block in the _Layout.cshtml file:
<head>
<title>@ViewBag.Title</title>
@RenderSection("styles", false);
</head>
Which works! But I can't help but think there's a better way. UPDATE: Added "false" in the @RenderSection
statement so your view won't 'splode when you neglect to add a @section
called head
.
It's possible in ggplot and you can use scale_date for this task
library(ggplot2)
Lines <- "Date Visits
11/1/2010 696537
11/2/2010 718748
11/3/2010 799355
11/4/2010 805800
11/5/2010 701262
11/6/2010 531579
11/7/2010 690068
11/8/2010 756947
11/9/2010 718757
11/10/2010 701768
11/11/2010 820113
11/12/2010 645259"
dm <- read.table(textConnection(Lines), header = TRUE)
dm <- mutate(dm, Date = as.Date(dm$Date, "%m/%d/%Y"))
ggplot(data = dm, aes(Date, Visits)) +
geom_line() +
scale_x_date(format = "%b %d", major = "1 day")
here is a solution if you are not using jquery:
myArray = myArray.filter(function( obj ) {
return obj.id !== id;
});
One major difference that is important to know is that ActiveX controls show up as objects that you can use in your code- try inserting an ActiveX control into a worksheet, bring up the VBA editor (ALT + F11) and you will be able to access the control programatically. You can't do this with form controls (macros must instead be explicitly assigned to each control), but form controls are a little easier to use. If you are just doing something simple, it doesn't matter which you use but for more advanced scripts ActiveX has better possibilities.
ActiveX is also more customizable.
It's indeed a very bad design, let alone singleton by itself is bad design.
However, if you really do need to delay execution, here's what you may do:
BackgroundWorker barInvoker = new BackgroundWorker();
barInvoker.DoWork += delegate
{
Thread.Sleep(TimeSpan.FromSeconds(1));
bar();
};
barInvoker.RunWorkerAsync();
This will, however, invoke bar()
on a separate thread. If you need to call bar()
in the original thread you might need to move bar()
invocation to RunWorkerCompleted
handler or do a bit of hacking with SynchronizationContext
.
Note: Recent npm
versions do this automatically when package-locks are enabled, so this is not necessary except for removing development packages with the --production
flag.
Run npm prune
to remove modules not listed in package.json
.
From npm help prune
:
This command removes "extraneous" packages. If a package name is provided, then only packages matching one of the supplied names are removed.
Extraneous packages are packages that are not listed on the parent package's dependencies list.
If the
--production
flag is specified, this command will remove the packages specified in your devDependencies.
I was looking for same and finally I found the solution
using (CString conn = new CString())
{
USER user = conn.USERs.Find(CMN.CurrentUser.ID);
user.PASSWORD = txtPass.Text;
conn.SaveChanges();
}
believe me it work for me like a charm.
if you fetching it from database then
<select id="cmbMake" name="Make" >
<option value="">Select Manufacturer</option>
<?php $s2="select * from <tablename>";
$q2=mysql_query($s2);
while($rw2=mysql_fetch_array($q2)) {
?>
<option value="<?php echo $rw2['id']; ?>"><?php echo $rw2['carname']; ?></option><?php } ?>
</select>
You can also use cat ~/.gitconfig
.
@JustinCave - The "when value_error" replacement for "when others" is a nice refinement to your approach above. This slight additional tweak, while conceptually the same, removes the requirement for the definition of and consequent memory allocation to your l_num variable:
function validNumber(vSomeValue IN varchar2)
return varchar2 DETERMINISTIC PARALLEL_ENABLE
is
begin
return case when abs(vSomeValue) >= 0 then 'T' end;
exception
when value_error then
return 'F';
end;
Just a note also to anyone preferring to emulate Oracle number format logic using the "riskier" REGEXP approach, please don't forget to consider NLS_NUMERIC_CHARACTERS and NLS_TERRITORY.
In Style.xml pre-define the style:
<style name="largeText">
<item name="android:textAppearance">@android:style/TextAppearance.Large.Inverse</item>
<item name="android:textStyle">bold</item>
</style>
in code:
text.setTextAppearance(context, R.style.largeText);
First of all you should stop using mysql_*. MySQL supports multiple inserting like
INSERT INTO example
VALUES
(100, 'Name 1', 'Value 1', 'Other 1'),
(101, 'Name 2', 'Value 2', 'Other 2'),
(102, 'Name 3', 'Value 3', 'Other 3'),
(103, 'Name 4', 'Value 4', 'Other 4');
You just have to build one string in your foreach loop which looks like that
$values = "(100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1'), (100, 'Name 1', 'Value 1', 'Other 1')";
and then insert it after the loop
$sql = "INSERT INTO email_list (R_ID, EMAIL, NAME) VALUES ".$values;
Another way would be Prepared Statements, which are even more suited for your situation.
In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
When you start a thread you are executing a method of some chosen class. All attributes of that class are visible.
Worker myWorker = new Worker( /* arguments */ );
Thread myThread = new Thread(new ThreadStart(myWorker.doWork));
myThread.Start();
Your thread is now in the doWork() method and can see any atrributes of myWorker, which may themselves be other objects. Now you just need to be careful to deal with the cases of having several threads all hitting those attributes at the same time.
You need to use a pointer to a member function, not just a pointer to a function.
class A {
int f() { return 1; }
public:
int (A::*x)();
A() : x(&A::f) {}
};
int main() {
A a;
std::cout << (a.*a.x)();
return 0;
}
Refer the scripts inside the angular-cli.json
(angular.json
when using angular 6+) file.
"scripts": [
"../path"
];
then add in typings.d.ts
(create this file in src
if it does not already exist)
declare var variableName:any;
Import it in your file as
import * as variable from 'variableName';
1 Either you can include that jar in your classpath of application
2 you can install particular jar file in your maven reopos by
mvn install:install-file -Dfile=<path-to-file> -DgroupId=<group-id> \
-DartifactId=<artifact-id> -Dversion=<version> -Dpackaging=<packaging>
If you have a version of find
(such as GNU find
) that supports -printf
then there's no need to call stat
repeatedly:
find /some/dir -printf "%T+\n" | sort -nr | head -n 1
or
find /some/dir -printf "%TY-%Tm-%Td %TT\n" | sort -nr | head -n 1
If you don't need recursion, though:
stat --printf="%y\n" *
Another important detail, the expires= should use the following date time format: Wdy, DD-Mon-YYYY HH:MM:SS GMT (RFC6265 - Section 4.1.1).
Set-Cookie:
name=value;
domain=localhost;
expires=Thu, 16-07-2019 21:25:05 GMT;
path=/
Note that Git 1.9/2.0 (Q1 2014) has removed that limitation.
See commit 82fba2b, from Nguy?n Thái Ng?c Duy (pclouds
):
Now that git supports data transfer from or to a shallow clone, these limitations are not true anymore.
--depth <depth>::
Create a 'shallow' clone with a history truncated to the specified number of revisions.
That stems from commits like 0d7d285, f2c681c, and c29a7b8 which support clone, send-pack /receive-pack with/from shallow clones.
smart-http now supports shallow fetch/clone too.
All the details are in "shallow.c
: the 8 steps to select new commits for .git/shallow
".
Update June 2015: Git 2.5 will even allow for fetching a single commit!
(Ultimate shallow case)
Update January 2016: Git 2.8 (Mach 2016) now documents officially the practice of getting a minimal history.
See commit 99487cf, commit 9cfde9e (30 Dec 2015), commit 9cfde9e (30 Dec 2015), commit bac5874 (29 Dec 2015), and commit 1de2e44 (28 Dec 2015) by Stephen P. Smith (``).
(Merged by Junio C Hamano -- gitster
-- in commit 7e3e80a, 20 Jan 2016)
This is "Documentation/user-manual.txt
"
A
<<def_shallow_clone,shallow clone>>
is created by specifying thegit-clone --depth
switch.
The depth can later be changed with thegit-fetch --depth
switch, or full history restored with--unshallow
.Merging inside a
<<def_shallow_clone,shallow clone>>
will work as long as a merge base is in the recent history.
Otherwise, it will be like merging unrelated histories and may have to result in huge conflicts.
This limitation may make such a repository unsuitable to be used in merge based workflows.
Update 2020:
git fetch --shallow-exclude=
to prevent fetching all historygit fetch --shallow-since=
to prevent fetching old commits.For more on the shallow clone update process, see "How to update a git shallow clone?".
As commented by Richard Michael:
to backfill history:
git pull --unshallow
And Olle Härstedt adds in the comments:
To backfill part of the history:
git fetch --depth=100
.
Nice way to handle not found error in Django.
https://docs.djangoproject.com/en/3.1/topics/http/shortcuts/#get-object-or-404
from django.shortcuts import get_object_or_404
def get_data(request):
obj = get_object_or_404(Model, pk=1)
I worked in a place where the coding standard was one giant WTF: strange Hungarian notation, prefixing globals with 'g' and members with 'm' (so there were gems like gsSomeVariable), adding 'ref string sError' to every single function, instead of throwing exceptions (which was a BIG nono!).
The killer, though, was prefixing the function parameters with I_ for input parameters, and O_ for output parameters.
I work now in a much better place :)
Just delete the whole directory. This will delete all the projects but also the Eclipse cache and settings for the workspace. These are kept in the .metadata
folder of an Eclipse workspace. Note that you can configure Eclipse to use project folders that are outside the workspace folder as well, so you may want to verify the location of each of the projects.
You can remove the workspace from the suggested workspaces by going into the General/Startup and Shutdown/Workspaces section of the preferences (via Preferences > General > Startup & Shudown > Workspaces > [Remove] ). Note that this does not remove the files itself. For old versions of Eclipse you will need to edit the org.eclipse.ui.ide.prefs
file in the configuration/.settings
directory under your installation directory (or in ~/.eclipse
on Unix, IIRC).
git fetch && git checkout <your friend's branch name>
should do the trick
If you get your string from stdin().read_line
, you have to trim it first.
let my_num: i32 = my_num.trim().parse()
.expect("please give me correct string number!");
a = range(1,10)
itemsToRemove = set([2, 3, 7])
b = filter(lambda x: x not in itemsToRemove, a)
or
b = [x for x in a if x not in itemsToRemove]
Don't create the set inside the lambda
or inside the comprehension. If you do, it'll be recreated on every iteration, defeating the point of using a set at all.
To properly add IOException (to RuntimeException) handling code, your method will look like this:
Stream<Account> s = accounts.values().stream();
s = s.filter(a -> { try { return a.isActive(); }
catch (IOException e) { throw new RuntimeException(e); }});
Stream<String> ss = s.map(a -> { try { return a.getNumber() }
catch (IOException e) { throw new RuntimeException(e); }});
return ss.collect(Collectors.toSet());
The problem now is that the IOException
will have to be captured as a RuntimeException
and converted back to an IOException
-- and that will add even more code to the above method.
Why use Stream
when it can be done just like this -- and the method throws IOException
so no extra code is needed for that too:
Set<String> set = new HashSet<>();
for(Account a: accounts.values()){
if(a.isActive()){
set.add(a.getNumber());
}
}
return set;
Try this:
$.each(result,function(index, value){
console.log('My array has at position ' + index + ', this value: ' + value);
});
User match = users.stream().filter((user) -> user.getId()== 1).findAny().orElseThrow(()-> new IllegalArgumentException());
If you're only interested in the output from the process, it's easiest to use subprocess' check_output function:
output = subprocess.check_output(["command", "arg1", "arg2"]);
Then output holds the program output to stdout. Check the link above for more info.
Using this as the background for your button might help, change the color to your needs
<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" >
<shape android:shape="rectangle">
<solid android:color="@color/app_theme_light" />
<padding
android:left="8dp"
android:top="4dp"
android:right="8dp"
android:bottom="4dp" />
</shape>
</item>
<item>
<shape android:shape="rectangle">
<solid android:color="@color/app_theme_dark" />
<padding
android:left="8dp"
android:top="4dp"
android:right="8dp"
android:bottom="4dp" />
</shape>
</item>
</selector>
you can use inner join :
DELETE
ps
FROM
posts ps INNER JOIN
(SELECT
distinct id
FROM
posts
GROUP BY id
HAVING COUNT(id) > 1 ) dubids on dubids.id = ps.id
The restrict option is typically set to:
Here is the documentation link.
Try using;
PHP_EOL
To terminate each new line in your CSV output.
I'm assuming that the text is delimiting, but isn't moving to the next row?
That's a PHP constant. It will determine the correct end of line you need.
Windows, for example, uses "\r\n". I wracked my brains with that one when my output wasn't breaking to a new line.
Does it have to be done in Java? I.e. does it need to be platform independent? If not, I'd suggest using the 'split' command in *nix. If you really wanted, you could execute this command via your java program. While I haven't tested, I imagine it perform faster than whatever Java IO implementation you could come up with.
It is not supported by design. The sortBy pipe can cause real performance issues for a production scale app. This was an issue with angular version 1.
You should not create a custom sort function. Instead, you should sort your array first in the typescript file and then display it. If the order needs to be updated when for example a dropdown is selected then have this dropdown selection trigger a function and call your sort function called from that. This sort function can be extracted to a service so that it can be re-used. This way, the sorting will only be applied when it is required and your app performance will be much better.
To kill the puma process first run
lsof -wni tcp:3000
to show what is using port 3000. Then use the PID that comes with the result to run the kill process.
For example after running lsof -wni tcp:3000 you might get something like
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
ruby 3366 dummy 8u IPv4 16901 0t0 TCP 127.0.0.1:3000 (LISTEN)
Now run the following to kill the process. (where 3366 is the PID)
kill -9 3366
Should resolve the issue
Most ASP.NET sites are easy to identify from the .aspx in the URLs. There are also telltale signs in the HTML source, like a hidden form field named __VIEWSTATE
or the WebResource.axd JavaScript. HTML elements will often have id attributes starting with something like _ctl0
.
Rails sites will usually include stylesheets from /stylesheets and JavaScript files from /javascripts and each URL will usually have a query string containing a timestamp to thwart caching. Form fields will often follow the naming convention of model_name[attribute_name]
.
The logcat shows the error, you should call super.onCreate(savedInstanceState)
:
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
//... your code
}
#!/bin/bash
#Note: this script works only when u use Bash. So, don't remove the first line.
TUNECOUNT=$(ifconfig |grep -c -o tune0) #Some command with "Grep".
echo $TUNECOUNT #This will return 0
#if you don't have tune0 interface.
#Or count of installed tune0 interfaces.
How's this for a work around (using an actual table)?
table {
border-collapse: collapse;
}
tr.row {
border-bottom: solid white 30px; /* change "white" to your background color */
}
It's not as dynamic, since you have to explicitly set the color of the border (unless there's a way around that too), but this is something I'm experimenting with on a project of my own.
Edit to include comments regarding transparent
:
tr.row {
border-bottom: 30px solid transparent;
}
The for-in statement is really there to enumerate over object properties, which is how it is implemented in TypeScript. There are some issues with using it on arrays.
I can't speak on behalf of the TypeScript team, but I believe this is the reason for the implementation in the language.
I recommend two steps to address the bloated SDK problem.
First, I removed all but two versions of Android:
The current version, e.g. 6.0 Marshmallow as of this writing. This version is to test and develop to the latest and greatest that the current Nexus handsets are running plus a couple of other brands.
An older version, e.g. 4.04 Ice Cream Sandwich. This is to provide compatibility for the vast majority of handsets. You lose some functionality of the newer versions, but you gain a lowest common denominator of compatibility.
Second, I removed the emulators, and kept only the above two. I told it not to store the complete system state to disk, which it does indeed warn you will take up a lot of space, though it does make start-up faster. Just start up the emulator before you go make your coffee in the morning :)
If that's too much space, remove the emulators completely. Pick up a couple of older handsets off Ebay that will provide you with all the test platforms you need. They don't even have to be completely functional -- many apps don't need a SIM and cellular connectivity, for example.
My Android environment was taking up 32 gigs on my 128-gig Macbook Air. Couldn't keep doing this. Some day they'll make terabyte Macbook Airs but until then, got to slim down.
def LongestEntry(lstName):
totalEntries = len(lstName)
currentEntry = 0
longestLength = 0
while currentEntry < totalEntries:
thisEntry = len(str(lstName[currentEntry]))
if int(thisEntry) > int(longestLength):
longestLength = thisEntry
longestEntry = currentEntry
currentEntry += 1
return longestLength
You should set the src
attribute after the onload
event, f.ex:
el.onload = function() { //...
el.src = script;
You should also append the script to the DOM before attaching the onload
event:
$body.append(el);
el.onload = function() { //...
el.src = script;
Remember that you need to check readystate
for IE support. If you are using jQuery, you can also try the getScript()
method: http://api.jquery.com/jQuery.getScript/
In newer versions of eclipse (I'm using 4.9.0) there is another, possibly easier, methods. As well as Project Facets, there are now Project Natures. Here the process is simple get the Project Natures property page up, and then click the Add... button. This will come up with possible natures included Java Nature and Eclipse Faceted Project Properties. Just add the Java Nature and ignore the various warning messages and your done.
This method might be better as you don't have to convert to Faceted form first. Furthermore Java was not offered in the add Facet menu.
I only have a workaround here.
In this special case, I would use the FILTER
function instead of QUERY
:
=FILTER(Responses!B:B,Responses!G:G=B1)
Assuming that your data is on the "Responses" sheet, but your condition (cell reference) is in the actual sheet's B1 cell.
Hope it helps.
UPDATE:
After some search for the original question: The problem with your formula is definitely the second &
sign which assumes that you would like to concatenate something more to your WHERE
statement. Try to remove it. If it still doesn't work, then try this:
=QUERY(Responses!B1:I, "Select B where G matches '^.\*($" & B1 & ").\*$'")
- I have not tried it, but it helped in another post: Query with range of values for WHERE clause?
This thread was helpful in finding the solution in my particular case (bootstrap 3)
@media (max-width: 767px) {
.container-fluid, .row {
padding:0px;
}
.navbar-header {
margin:0px;
}
}
I did clean build using below command.. Surprisingly worked.
sh gradlew clean build
Hopefully someone get help!
Docker, basically containers, supports OS virtualization i.e. your application feels that it has a complete instance of an OS whereas VM supports hardware virtualization. You feel like it is a physical machine in which you can boot any OS.
In Docker, the containers running share the host OS kernel, whereas in VMs they have their own OS files. The environment (the OS) in which you develop an application would be same when you deploy it to various serving environments, such as "testing" or "production".
For example, if you develop a web server that runs on port 4000, when you deploy it to your "testing" environment, that port is already used by some other program, so it stops working. In containers there are layers; all the changes you have made to the OS would be saved in one or more layers and those layers would be part of image, so wherever the image goes the dependencies would be present as well.
In the example shown below, the host machine has three VMs. In order to provide the applications in the VMs complete isolation, they each have their own copies of OS files, libraries and application code, along with a full in-memory instance of an OS. Whereas the figure below shows the same scenario with containers. Here, containers simply share the host operating system, including the kernel and libraries, so they don’t need to boot an OS, load libraries or pay a private memory cost for those files. The only incremental space they take is any memory and disk space necessary for the application to run in the container. While the application’s environment feels like a dedicated OS, the application deploys just like it would onto a dedicated host. The containerized application starts in seconds and many more instances of the application can fit onto the machine than in the VM case.
Source: https://azure.microsoft.com/en-us/blog/containers-docker-windows-and-trends/
Swift 3/4 with @IBDesignable
While almost all the above solutions work fine but I would suggest an @IBDesignable
custom class for this.
@IBDesignable
class CustomLabel: UILabel {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
@IBInspectable var borderColor: UIColor = UIColor.white {
didSet {
layer.borderColor = borderColor.cgColor
}
}
@IBInspectable var borderWidth: CGFloat = 2.0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable var cornerRadius: CGFloat = 0.0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
}
Yes, you can do it by:
-- Install Atom
-- Install Python on your system. Atom requires the latest version of Python (currently 3.8.5). Note that Anaconda sometimes may not have this version, and depending on how you installed it, it may not have been added to the PATH. Install Python via https://www.python.org/ and make sure to check the option of "Add to PATH"
-- Install "scripts" on Atom via "Install packages"
-- Install any other autocomplete package like Kite on Atom if you want that feature.
-- Run it
I tried the normal way (I had Python installed via Anaconda) but Atom did not detect it & gave me an error when I tried to run Python. This is the way around it.
Using data.table
:
# convert to data.table
setDT(df)
# order, group, filter
df[order(stopSequence)][, .SD[c(1, .N)], by = id]
id stopId stopSequence
1: 1 a 1
2: 1 c 3
3: 2 b 1
4: 2 c 4
5: 3 b 1
6: 3 a 3
Although many answers do point in the right direction I think none of them answers what the author of the question was thinking about. Or at least I understood the question differently because I was looking for answer to similar problem. The problem is "How to know when the user stops typing without him pressing a button" and trigger some action (for example auto-complete). If you want to do this start the Timer in onTextChanged with a delay that you would consider user stopped typing (for example 500-700ms), for each new letter when you start the timer cancel the earlier one (or at least use some sort of flag that when they tick they don't do anything). Here is similar code to what I have used:
new Timer().schedule(new TimerTask() {
@Override
public void run() {
if (!running) {
new DoPost().execute(s.toString());
});
}
}, 700);
Note that I modify running boolean flag inside my async task (Task gets the json from the server for auto-complete).
Also keep in mind that this creates many timer tasks (I think they are scheduled on the same Thread thou but would have to check this), so there are probably many places to improve but this approach also works and the bottom line is that you should use a Timer since there is no "User stopped typing event"
n=int(input())
for i in range(n):
n=input()
n=int(n)
arr1=list(map(int,input().split()))
the for loop shall run 'n' number of times . the second 'n' is the length of the array. the last statement maps the integers to a list and takes input in space separated form . you can also return the array at the end of for loop.
With the new achievements in JS here is how one can add query param to the URL:
var protocol = window.location.protocol,
host = '//' + window.location.host,
path = window.location.pathname,
query = window.location.search;
var newUrl = protocol + host + path + query + (query ? '&' : '?') + 'param=1';
window.history.pushState({path:newUrl}, '' , newUrl);
Also see this possibility Moziila URLSearchParams.append()
Since v1.0 you can toggle word wrap:
It can also be controlled with the following settings:
Known issues:
If you'd like these bugs fixed, please vote for them.
I've had to do this a few times to-date. Note that this only works on 1 file at a time.
Get a list of all commits that modified a file. The one at the bottom will the the first commit:
git log --pretty=oneline --branches -- pathToFile
To remove the file from history use the first commit sha1 and the path to file from the previous command, and fill them into this command:
git filter-branch --index-filter 'git rm --cached --ignore-unmatch <path-to-file>' -- <sha1-where-the-file-was-first-added>..
It's because you cannot access protected member data through its class instance. You should correct your code as follows:
namespace homeworkchap8
{
class main
{
static void Main(string[] args)
{
SteelClubs myClub = new SteelClubs();
Console.WriteLine("How far to the hole?");
myClub.mydistance = Console.ReadLine();
Console.WriteLine("what club are you going to hit?");
myClub.myclub = Console.ReadLine();
myClub.SwingClub();
SteelClubs mycleanclub = new SteelClubs();
Console.WriteLine("\nDid you clean your club after?");
mycleanclub.mycleanclub = Console.ReadLine();
mycleanclub.clean();
SteelClubs myScoreonHole = new SteelClubs();
Console.WriteLine("\nWhat hole are you on?");
myScoreonHole.myhole = Console.ReadLine();
Console.WriteLine("What did you score on the hole?");
myScoreonHole.myscore = Console.ReadLine();
Console.WriteLine("What is the par of the hole?");
myScoreonHole.parhole = Console.ReadLine();
myScoreonHole.score();
Console.ReadKey();
}
}
}
Here's a flow chart that illustrates a for loop:
The equivalent C code would be
for(i = 2; i <= 6; i = i + 2) {
printf("%d\t", i + 1);
}
I found this and several other examples on one of Tenouk's C Laboratory practice worksheets.
This variant is most portable for putting multi-line scripts on command-line on Windows and *nix, py2/3, without pipes:
python -c "exec(\"import sys \nfor r in range(10): print('rob') \")"
(None of the other examples seen here so far did so)
Neat on Windows is:
python -c exec"""import sys \nfor r in range(10): print 'rob' """
python -c exec("""import sys \nfor r in range(10): print('rob') """)
Neat on bash/*nix is:
python -c $'import sys \nfor r in range(10): print("rob")'
This function turns any multiline-script into a portable command-one-liner:
def py2cmdline(script):
exs = 'exec(%r)' % re.sub('\r\n|\r', '\n', script.rstrip())
print('python -c "%s"' % exs.replace('"', r'\"'))
Usage:
>>> py2cmdline(getcliptext())
python -c "exec('print \'AA\tA\'\ntry:\n for i in 1, 2, 3:\n print i / 0\nexcept:\n print \"\"\"longer\nmessage\"\"\"')"
Input was:
print 'AA A'
try:
for i in 1, 2, 3:
print i / 0
except:
print """longer
message"""
Two options:
originalList.removeAll(valuesToRemove)
at the endremove()
method on the iterator itself. Note that this means you can't use the enhanced for loop.As an example of the second option, removing any strings with a length greater than 5 from a list:
List<String> list = new ArrayList<String>();
...
for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); ) {
String value = iterator.next();
if (value.length() > 5) {
iterator.remove();
}
}
Try it like,
<?php
$name='your name';
echo '<table>
<tr><th>Name</th></tr>
<tr><td>'.$name.'</td></tr>
</table>';
?>
Updated
<?php
echo '<table>
<tr><th>Rst</th><th>Marks</th></tr>
<tr><td>'.$rst4.'</td><td>'.$marks4.'</td></tr>
</table>';
?>
I think you can use db.collection.distinct(fields,query)
You will be able to get the distinct values in your case for NetworkID.
It should be something like this :
Db.collection.distinct('NetworkID')
Can't upvote so I'll repost @jfs comment cause I think it should be more visible.
@AnneTheAgile: shell=True is not required. Moreover you should not use it unless it is necessary (see @ valid's comment). You should pass each command-line argument as a separate list item instead e.g., use ['command', 'arg 1', 'arg 2'] instead of "command 'arg 1' 'arg 2'". – jfs Mar 3 '15 at 10:02
Here's a funny answer.
You can declare a final one-element array and change the elements of the array all you want apparently. I'm sure it breaks the very reason why this compiler rule was implemented in the first place but it's handy when you're in a time-bind as I was today.
I actually can't claim credit for this one. It was IntelliJ's recommendation! Feels a bit hacky. But doesn't seem as bad as a global variable so I thought it worth mentioning here. It's just one solution to the problem. Not necessarily the best one.
final int[] tapCount = {0};
addSiteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
tapCount[0]++;
}
});
Is very simple to clone the last row with jquery pressing a button:
Your Table HTML:
<table id="tableExample">
<thead>
<tr>
<th>ID</th>
<th>Header 1</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Line 1</td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="2"><button type="button" id="addRowButton">Add row</button></td>
</tr>
</tfoot>
</table>
JS:
$(document).on('click', '#addRowButton', function() {
var table = $('#tableExample'),
lastRow = table.find('tbody tr:last'),
rowClone = lastRow.clone();
table.find('tbody').append(rowClone);
});
Regards!
I've found the Linux zip
file to be cumbersome for replacing a single file in a zip. The jar
utility from the Java Development Kit may be easier. Consider the common task of updating WEB/web.xml
in a JAR file (which is just a zip file):
jar -uf path/to/myapp.jar -C path/to/dir WEB-INF/web.xml
Here, path/to/dir
is the path to a directory containing the WEB-INF
directory (which in turn contains web.xml
).
i was able to fix mine by adding this lines of code after the build tag in the pom.xml file, i compared it from my running project and discovered that was the difference, now i'm all good.
<repositories>
<repository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</repository>
<repository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>spring-snapshots</id>
<name>Spring Snapshots</name>
<url>https://repo.spring.io/snapshot</url>
<snapshots>
<enabled>true</enabled>
</snapshots>
</pluginRepository>
<pluginRepository>
<id>spring-milestones</id>
<name>Spring Milestones</name>
<url>https://repo.spring.io/milestone</url>
</pluginRepository>
</pluginRepositories>
This example run ok
var currency = "$1,123,456.00";
var number = Number(currency.replace(/[^0-9\.]+/g,""));
console.log(number);
_x000D_
Here is a way to change the owner on ALL DBS (excluding System)
EXEC sp_msforeachdb'
USE [?]
IF ''?'' <> ''master'' AND ''?'' <> ''model'' AND ''?'' <> ''msdb'' AND ''?'' <> ''tempdb''
BEGIN
exec sp_changedbowner ''sa''
END
'
Here is a simple linear alternative to the RegEx solution. I am not sure which is faster; you'd have to benchmark it.
static string RemoveWhitespace(string input)
{
StringBuilder output = new StringBuilder(input.Length);
for (int index = 0; index < input.Length; index++)
{
if (!Char.IsWhiteSpace(input, index))
{
output.Append(input[index]);
}
}
return output.ToString();
}
I hope following program will solve your problem
String dateStr = "Mon Jun 18 00:00:00 IST 2012";
DateFormat formatter = new SimpleDateFormat("E MMM dd HH:mm:ss Z yyyy");
Date date = (Date)formatter.parse(dateStr);
System.out.println(date);
Calendar cal = Calendar.getInstance();
cal.setTime(date);
String formatedDate = cal.get(Calendar.DATE) + "/" + (cal.get(Calendar.MONTH) + 1) + "/" + cal.get(Calendar.YEAR);
System.out.println("formatedDate : " + formatedDate);
Of course.
That is normal and sane behaviour.
Instead of closing and re-opening, you could rewind
the file.
In general, this is probably not a great idea, since your html file should only be loading JS files that they actually make use of. Regardless, this would be trivial to do with any server-side scripting language. Just insert the script tags before serving the pages to the client.
If you want to do it without using server-side scripting, you could drop your JS files into a directory that allows listing the directory contents, and then use XMLHttpRequest to read the contents of the directory, and parse out the file names and load them.
Option #3 is to have a "loader" JS file that uses getScript() to load all of the other files. Put that in a script tag in all of your html files, and then you just need to update the loader file whenever you upload a new script.
you can use a string formatter to pad any integer with zeros. It acts just like C's printf
.
>>> d = datetime.date.today()
>>> '%02d' % d.month
'03'
Updated for py36: Use f-strings! For general int
s you can use the d
formatter and explicitly tell it to pad with zeros:
>>> d = datetime.date.today()
>>> f"{d.month:02d}"
'07'
But datetime
s are special and come with special formatters that are already zero padded:
>>> f"{d:%d}" # the day
'01'
>>> f"{d:%m}" # the month
'07'
You can try this
s="Hello World!"
echo $s # Hello World!
a=${s,,}
echo $a # hello world!
b=${s^^}
echo $b # HELLO WORLD!
ref : http://wiki.workassis.com/shell-script-convert-text-to-lowercase-and-uppercase/
Please do not mark this response as correct as smitec has already answered correctly. I'm including a convenience function I keep in my .First library that makes converting a windows path to the format that works in R (the methods described by Sacha Epskamp). Simply copy the path to your clipboard (ctrl + c) and then run the function as pathPrep()
. No need for an argument. The path is printed to your console correctly and written to your clipboard for easy pasting to a script. Hope this is helpful.
pathPrep <- function(path = "clipboard") {
y <- if (path == "clipboard") {
readClipboard()
} else {
cat("Please enter the path:\n\n")
readline()
}
x <- chartr("\\", "/", y)
writeClipboard(x)
return(x)
}
You can use node-php to run php with node js: https://github.com/mkschreder/node-php
The simplest solution in general form:
def get_subclasses(cls):
for subclass in cls.__subclasses__():
yield from get_subclasses(subclass)
yield subclass
And a classmethod in case you have a single class where you inherit from:
@classmethod
def get_subclasses(cls):
for subclass in cls.__subclasses__():
yield from subclass.get_subclasses()
yield subclass
While you can use a ForEach
extension method, if you want to use just the framework you can do
collection.Select(c => {c.PropertyToSet = value; return c;}).ToList();
The ToList
is needed in order to evaluate the select immediately due to lazy evaluation.
"top" is usually available on Solaris.
If not then revert to "vmstat" which is available on most UNIX system.
It should look something like this (from an AIX box)
vmstat System configuration: lcpu=4 mem=12288MB ent=2.00 kthr memory page faults cpu ----- ----------- ------------------------ ------------ ----------------------- r b avm fre re pi po fr sr cy in sy cs us sy id wa pc ec 2 1 1614644 585722 0 0 1 22 104 0 808 29047 2767 12 8 77 3 0.45 22.3
the colums "avm" and "fre" tell you the total memory and free memery.
a "man vmstat" should get you the gory details.
One of the top answers did not work for me, because, after a little bit trial and error, the li:before also needed the css rule display:inline-block.
So this is a fully working answer for me:
ul.dashes{
list-style: none;
padding-left: 2em;
li{
&:before{
content: "-";
text-indent: -2em;
display: inline-block;
}
}
}
Might be a little late but for new issues like this I use this code:
moment(timestamp, 'X').format('lll');
You can change the format to match your needs and also add timezone like this:
moment(timestamp, 'X').tz(timezone).format('lll');
SQL Server returns messages after a batch of statements has been executed. Normally, you'd use SQL GO
to indicate the end of a batch and to retrieve the results:
PRINT '1'
GO
WAITFOR DELAY '00:00:05'
PRINT '2'
GO
WAITFOR DELAY '00:00:05'
PRINT '3'
GO
In this case, however, the print statement you want returned immediately is in the middle of a loop, so the print statements cannot be in their own batch. The only command I know of that will return in the middle of a batch is RAISERROR (...) WITH NOWAIT
, which gbn has provided as an answer as I type this.
this should work:
svn commit -m "<Your message here>" path/to/your/file
you can also add multiple files like this:
svn commit -m "<Your message here>" path/to/your/file [path/to/your/file] [path/to/your/file]
This is what worked for me:
This happens because there are too many unused methods. Most of these methods are coming from included libraries in your build.gradle
Use minify and shrink resources to fix this with gradle and clean up your code at the same time.
buildTypes {
release {
minifyEnabled true
shrinkResources true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
minifyEnabled true
shrinkResources true
}
}
None of the above worked for me. This is what worked for me on Enzyme ^3.1.1:
input.instance().props.onChange(({ target: { value: '19:00' } }));
Here is the rest of the code for context:
const fakeHandleChangeValues = jest.fn();
const fakeErrors = {
errors: [{
timePeriod: opHoursData[0].timePeriod,
values: [{
errorIndex: 2,
errorTime: '19:00',
}],
}],
state: true,
};
const wrapper = mount(<AccessibleUI
handleChangeValues={fakeHandleChangeValues}
opHoursData={opHoursData}
translations={translationsForRendering}
/>);
const input = wrapper.find('#input-2').at(0);
input.instance().props.onChange(({ target: { value: '19:00' } }));
expect(wrapper.state().error).toEqual(fakeErrors);
I would ensure all containers are docker-compose
'd to the same network by composing them together at the same time, using:
docker compose --file ~/front/docker-compose.yml --file ~/api/docker-compose.yml up -d
Did you write return true
somewhere? You should have written it, otherwise function returns nothing and program may think that it's false, too.
function isValid(str) {
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
for (var i = 0; i < str.length; i++) {
if (iChars.indexOf(str.charAt(i)) != -1) {
alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
return false;
}
}
return true;
}
I tried this in my chrome console and it worked well.
We also log old and new values and the column they are from as well as the primary key of the table being audited in an audit detail table. Think what you need the audit table for? Not only do you want to know who made a change and when, but when a bad change happens, you want a fast way to put the data back.
While you are designing, you should write the code to recover data. When you need to recover, it is usually in a hurry, best to already be prepared.
assertTrue()/assertFalse() : to use only to assert boolean result returned
assertTrue(Iterables.elementsEqual(argumentComponents, returnedComponents));
You want to use Assert.assertTrue()
or Assert.assertFalse()
as the method under test returns a boolean
value.
As the method returns a specific thing such as a List
that should contain some expected elements, asserting with assertTrue()
in this way : Assert.assertTrue(myActualList.containsAll(myExpectedList)
is an anti pattern.
It makes the assertion easy to write but as the test fails, it also makes it hard to debug because the test runner will only say to you something like :
expected
true
but actual isfalse
Assert.assertEquals(Object, Object)
in JUnit4 or Assertions.assertIterableEquals(Iterable, Iterable)
in JUnit 5 : to use only as both equals()
and toString()
are overrided for the classes (and deeply) of the compared objects
It matters because the equality test in the assertion relies on equals()
and the test failure message relies on toString()
of the compared objects.
As String
overrides both equals()
and toString()
, it is perfectly valid to assert the List<String>
with assertEquals(Object,Object)
.
And about this matter : you have to override equals()
in a class because it makes sense in terms of object equality, not only to make assertions easier in a test with JUnit.
To make assertions easier you have other ways (that you can see in the next points of the answer).
Is Guava a way to perform/build unit test assertions ?
Is Google Guava Iterables.elementsEqual() the best way, provided I have the library in my build path, to compare those two lists?
No it is not. Guava is not an library to write unit test assertions.
You don't need it to write most (all I think) of unit tests.
What's the canonical way to compare lists for unit tests?
As a good practice I favor assertion/matcher libraries.
I cannot encourage JUnit to perform specific assertions because this provides really too few and limited features : it performs only an assertion with a deep equals.
Sometimes you want to allow any order in the elements, sometimes you want to allow that any elements of the expected match with the actual, and so for...
So using a unit test assertion/matcher library such as Hamcrest or AssertJ is the correct way.
The actual answer provides a Hamcrest solution. Here is a AssertJ solution.
org.assertj.core.api.ListAssert.containsExactly()
is what you need : it verifies that the actual group contains exactly the given values and nothing else, in order as stated :
Verifies that the actual group contains exactly the given values and nothing else, in order.
Your test could look like :
import org.assertj.core.api.Assertions;
import org.junit.jupiter.api.Test;
@Test
void ofComponent_AssertJ() throws Exception {
MyObject myObject = MyObject.ofComponents("One", "Two", "Three");
Assertions.assertThat(myObject.getComponents())
.containsExactly("One", "Two", "Three");
}
A AssertJ good point is that declaring a List
as expected is needless : it makes the assertion straighter and the code more readable :
Assertions.assertThat(myObject.getComponents())
.containsExactly("One", "Two", "Three");
And if the test fails :
// Fail : Three was not expected
Assertions.assertThat(myObject.getComponents())
.containsExactly("One", "Two");
you get a very clear message such as :
java.lang.AssertionError:
Expecting:
<["One", "Two", "Three"]>
to contain exactly (and in same order):
<["One", "Two"]>
but some elements were not expected:
<["Three"]>
Assertion/matcher libraries are a must because these will really further
Suppose that MyObject
doesn't store String
s but Foo
s instances such as :
public class MyFooObject {
private List<Foo> values;
@SafeVarargs
public static MyFooObject ofComponents(Foo... values) {
// ...
}
public List<Foo> getComponents(){
return new ArrayList<>(values);
}
}
That is a very common need.
With AssertJ the assertion is still simple to write. Better you can assert that the list content are equal even if the class of the elements doesn't override equals()/hashCode()
while JUnit ways require that :
import org.assertj.core.api.Assertions;
import static org.assertj.core.groups.Tuple.tuple;
import org.junit.jupiter.api.Test;
@Test
void ofComponent() throws Exception {
MyFooObject myObject = MyFooObject.ofComponents(new Foo(1, "One"), new Foo(2, "Two"), new Foo(3, "Three"));
Assertions.assertThat(myObject.getComponents())
.extracting(Foo::getId, Foo::getName)
.containsExactly(tuple(1, "One"),
tuple(2, "Two"),
tuple(3, "Three"));
}
The specific instructions for what you are looking for are in here: https://support.google.com/docs/answer/3093281
Remember your Google Spreadsheets Formulas might use semicolon (;) instead of comma (,) depending on Regional Settings.
Once made the replacement on some examples would look like this:
=GoogleFinance("CURRENCY:USDEUR")
=INDEX(GoogleFinance("USDEUR","price",today()-30,TODAY()),2,2)
=SPARKLINE(GoogleFinance("USDEUR","price",today()-30,today()))
For check of email use email_validator
from email_validator import validate_email, EmailNotValidError
def check_email(email):
try:
v = validate_email(email) # validate and get info
email = v["email"] # replace with normalized form
print("True")
except EmailNotValidError as e:
# email is not valid, exception message is human-readable
print(str(e))
check_email("test@gmailcom")
you first would need to convert string into datetime tuple, and then convert that datetime tuple to string, it would go like this:
lastconnection = datetime.strptime("21/12/2008", "%d/%m/%Y").strftime('%Y-%m-%d')
it is saved in your Documents and Settings\%user%\Local Settings\Application Data......etc search for a file called user.config there
the location may change however.
Even though setting a CSS height value to the select element does not work, the padding attribute works alright. Setting a top and bottom padding will make your select element look taller.
public void ProcessRequest(HttpContext context)
{
string constring = ConfigurationManager.ConnectionStrings["SQL_Connection_String"].ConnectionString;
SqlConnection conn = new SqlConnection(constring);
conn.Open();
SqlCommand cmd = new SqlCommand("select image1 from TestGo where TestId=1", conn);
SqlDataReader dr = cmd.ExecuteReader();
dr.Read();
MemoryStream str = new MemoryStream();
context.Response.Clear();
Byte[] bytes = (Byte[])dr[0];
string d = System.Text.Encoding.Default.GetString(bytes);
byte[] bytes2 = Convert.FromBase64String(d);
//context.Response.Write(d);
Image img = Image.FromStream(new MemoryStream(bytes2));
img.Save(context.Response.OutputStream, ImageFormat.Png);
context.Response.Flush();
str.WriteTo(context.Response.OutputStream);
str.Dispose();
str.Close();
conn.Close();
context.Response.End();
}
Ok, so I finally got it to work. If I use the JRE 6 instead of 7 everything works great. No idea why, but it works.
Direct link to the .Net-3.5-Full-Setup
http://download.microsoft.com/download/6/0/f/60fc5854-3cb8-4892-b6db-bd4f42510f28/dotnetfx35.exe
Direct link to the .Net-3.5-SP1-Full-Setup
http://download.microsoft.com/download/2/0/e/20e90413-712f-438c-988e-fdaa79a8ac3d/dotnetfx35.exe
Thanks to Dzmitry Lahoda!
I was getting below exception
System.InvalidOperationException: Unable to resolve service for type 'System.Func`1[IBlogContext]'
while attempting to activate 'BlogContextFactory'.\r\n at
Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, ISet`1 callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(Type serviceType, Type implementationType, ISet`1 callSiteChain)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, ISet`1 callSiteChain)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(Type serviceType, ISet`1 callSiteChain)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, ISet`1 callSiteChain)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, ISet`1 callSiteChain, ParameterInfo[] parameters, Boolean throwIfCallSiteNotFound)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(Type serviceType, Type implementationType, ISet`1 callSiteChain)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(ServiceDescriptor descriptor, Type serviceType, ISet`1 callSiteChain)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.TryCreateExact(Type serviceType, ISet`1 callSiteChain)\r\n at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateCallSite(Type serviceType, ISet`1 callSiteChain)\r\n at Microsoft.Extensions.DependencyInjection.ServiceProvider.CreateServiceAccessor(Type serviceType, ServiceProvider serviceProvider)\r\n at System.Collections.Concurrent.ConcurrentDictionaryExtensions.GetOrAdd[TKey, TValue, TArg] (ConcurrentDictionary`2 dictionary, TKey key, Func`3 valueFactory, TArg arg)\r\n at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)\r\n at Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)\r\n at lambda_method(Closure , IServiceProvider , Object[] )\r\n at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)\r\n at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)\r\n at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()\r\n at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextExceptionFilterAsync()
Because I wanted register Factory to create instances of DbContext Derived class IBlogContextFactory and use Create method to instantiate instance of Blog Context so that I can use below pattern along with dependency Injection and can also use mocking for unit testing.
the pattern I wanted to use is
public async Task<List<Blog>> GetBlogsAsync()
{
using (var context = new BloggingContext())
{
return await context.Blogs.ToListAsync();
}
}
But Instead of new BloggingContext() I want to Inject factory via constructor as in below BlogController class
[Route("blogs/api/v1")]
public class BlogController : ControllerBase
{
IBloggingContextFactory _bloggingContextFactory;
public BlogController(IBloggingContextFactory bloggingContextFactory)
{
_bloggingContextFactory = bloggingContextFactory;
}
[HttpGet("blog/{id}")]
public async Task<Blog> Get(int id)
{
//validation goes here
Blog blog = null;
// Instantiage context only if needed and dispose immediately
using (IBloggingContext context = _bloggingContextFactory.CreateContext())
{
blog = await context.Blogs.FindAsync(id);
}
//Do further processing without need of context.
return blog;
}
}
here is my service registration code
services
.AddDbContext<BloggingContext>()
.AddTransient<IBloggingContext, BloggingContext>()
.AddTransient<IBloggingContextFactory, BloggingContextFactory>();
and below are my models and factory classes
public interface IBloggingContext : IDisposable
{
DbSet<Blog> Blogs { get; set; }
DbSet<Post> Posts { get; set; }
}
public class BloggingContext : DbContext, IBloggingContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseInMemoryDatabase("blogging.db");
//optionsBuilder.UseSqlite("Data Source=blogging.db");
}
}
public interface IBloggingContextFactory
{
IBloggingContext CreateContext();
}
public class BloggingContextFactory : IBloggingContextFactory
{
private Func<IBloggingContext> _contextCreator;
public BloggingContextFactory(Func<IBloggingContext> contextCreator)// This is fine with .net and unity, this is treated as factory function, but creating problem in .netcore service provider
{
_contextCreator = contextCreator;
}
public IBloggingContext CreateContext()
{
return _contextCreator();
}
}
public class Blog
{
public Blog()
{
CreatedAt = DateTime.Now;
}
public Blog(int id, string url, string deletedBy) : this()
{
BlogId = id;
Url = url;
DeletedBy = deletedBy;
if (!string.IsNullOrWhiteSpace(deletedBy))
{
DeletedAt = DateTime.Now;
}
}
public int BlogId { get; set; }
public string Url { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime? DeletedAt { get; set; }
public string DeletedBy { get; set; }
public ICollection<Post> Posts { get; set; }
public override string ToString()
{
return $"id:{BlogId} , Url:{Url} , CreatedAt : {CreatedAt}, DeletedBy : {DeletedBy}, DeletedAt: {DeletedAt}";
}
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public int BlogId { get; set; }
public Blog Blog { get; set; }
}
----- To Fix this in .net Core MVC project -- I did below changes on dependency registration
services
.AddDbContext<BloggingContext>()
.AddTransient<IBloggingContext, BloggingContext>()
.AddTransient<IBloggingContextFactory, BloggingContextFactory>(
sp => new BloggingContextFactory( () => sp.GetService<IBloggingContext>())
);
In short in .net core developer is responsible to inject factory function, which in case of Unity and .Net Framework was taken care of.
I had the exact same issue. However when I tried opening the website manually in the browser the certificate was correct, but in the details the name was "DONOTTRUST".
The difference of certificate was caused by Fiddler that was running in background and decrypting all HTTPS content before reencrypting it.
To fix my problem, just close Fiddler on machine. If you need to keep Fiddler opened, then you can uncheck Decrypt SSL in Fiddler Settings.
You may be able to use the built-in function dir()
to produce similar behavior to PHP's isset()
, something like:
if 'foo' in dir(): # returns False, foo is not defined yet.
pass
foo = 'b'
if 'foo' in dir(): # returns True, foo is now defined and in scope.
pass
dir()
returns a list of the names in the current scope, more information can be found here: http://docs.python.org/library/functions.html#dir.
I personally would just use the JavaScript code to switch between 2 classes.
Have the CSS outline everything you need on your div MINUS the background rule, then add two classes (e.g: expanded & collapsed) as rules each with the correct background image (or background position if using a sprite).
CSS with different images
.div {
/* button size etc properties */
}
.expanded {background: url(img/x.gif) no-repeat left top;}
.collapsed {background: url(img/y.gif) no-repeat left top;}
Or CSS with image sprite
.div {
background: url(img/sprite.gif) no-repeat left top;
/* Other styles */
}
.expanded {background-position: left bottom;}
Then...
JavaScript code with images
$(function){
$('#button').click(function(){
if($(this).hasClass('expanded'))
{
$(this).addClass('collapsed').removeClass('expanded');
}
else
{
$(this).addClass('expanded').removeClass('collapsed');
}
});
}
JavaScript with sprite
Note: the elegant toggleClass does not work in Internet Explorer 6, but the below addClass
/removeClass
method will work fine in this situation as well
The most elegant solution (unfortunately not Internet Explorer 6 friendly)
$(function){
$('#button').click(function(){
$(this).toggleClass('expanded');
});
}
$(function){
$('#button').click(function(){
if($(this).hasClass('expanded'))
{
$(this).removeClass('expanded');
}
else
{
$(this).addClass('expanded');
}
});
}
As far as I know this method will work accross browsers, and I would feel much more comfortable playing with CSS and classes than with URL changes in the script.
In swift 4:
let paraStyle = NSMutableParagraphStyle.init()
paraStyle.alignment = .left
let str = "Test Message"
let attribute = [NSAttributedStringKey.font: UIFont.boldSystemFont(ofSize: 12)]
let attrMessage = NSMutableAttributedString(string: str, attributes: attribute)
attrMessage.addAttribute(kCTParagraphStyleAttributeName as NSAttributedStringKey, value: paraStyle, range: NSMakeRange(0, str.count))
Maybe you only need a shallow copy, in that case use Object.MemberWiseClone()
.
There are good recommendations in the documentation for MemberWiseClone()
for strategies to deep copy: -
http://msdn.microsoft.com/en-us/library/system.object.memberwiseclone.aspx
Sadly the other posters are correct that you're
...actually as corrected by kRON, you are ok with your IE7 and a strict doc, but most of us with IE6 requirements are reduced to JS or class references for this, but it is a CSS2 property, just one without sufficient support from IE^h^h browsers.
Out of completeness, the type selector is - similar to xpath - of the form [attribute=value]
but many interesting variants exist. It will be quite powerful when it's available, good thing to keep in your head for IE8.
Here is a more general way that is a bit cleaner:
Create your form like this (can be a dummy form that does nothing):
<form class="validateDontSubmit">
...
Bind all forms that you dont really want to submit:
$(document).on('submit','.validateDontSubmit',function (e) {
//prevent the form from doing a submit
e.preventDefault();
return false;
})
Now lets say you have an <a>
(within the <form>
) that on click you want to validate the form:
$('#myLink').click(function(e){
//Leverage the HTML5 validation w/ ajax. Have to submit to get em. Wont actually submit cuz form
//has .validateDontSubmit class
var $theForm = $(this).closest('form');
//Some browsers don't implement checkValidity
if (( typeof($theForm[0].checkValidity) == "function" ) && !$theForm[0].checkValidity()) {
return;
}
//if you've gotten here - play on playa'
});
Few notes here:
checkValidity()
is enough (at least in chrome). If others could add comments with testing this theory on other browsers I'll update this answer.<form>
. This was just a clean and flexible way to have a general purpose solution..To add to the excellent Andy E answer a function of common usage could be:
Date.createFromMysql = function(mysql_string)
{
var t, result = null;
if( typeof mysql_string === 'string' )
{
t = mysql_string.split(/[- :]/);
//when t[3], t[4] and t[5] are missing they defaults to zero
result = new Date(t[0], t[1] - 1, t[2], t[3] || 0, t[4] || 0, t[5] || 0);
}
return result;
}
In this way given a MySQL date/time in the form "YYYY-MM-DD HH:MM:SS"
or even the short form (only date) "YYYY-MM-DD"
you can do:
var d1 = Date.createFromMysql("2011-02-20");
var d2 = Date.createFromMysql("2011-02-20 17:16:00");
alert("d1 year = " + d1.getFullYear());
Try converting your procedure in to an Inline Function which returns a table as follows:
CREATE FUNCTION MyProc()
RETURNS TABLE AS
RETURN (SELECT * FROM MyTable)
And then you can call it as
SELECT * FROM MyProc()
You also have the option of passing parameters to the function as follows:
CREATE FUNCTION FuncName (@para1 para1_type, @para2 para2_type , ... )
And call it
SELECT * FROM FuncName ( @para1 , @para2 )
If you $
is defined then You can iterate
var data={"id" : 1, "second" : "abcd"};
$.each(data, function() {
var key = Object.keys(this)[0];
var value = this[key];
//do something with value;
});
You can access it by following way If you know the values of keys
data.id
or
data["id"]
You only need to calculate it for IE7 and older (and only if your content doesn't have fixed size). I suggest using HTML conditional comments to limit hack to old IEs that don't support CSS2. For all other browsers use this:
<style type="text/css">
html,body {display:table; height:100%;width:100%;margin:0;padding:0;}
body {display:table-cell; vertical-align:middle;}
div {display:table; margin:0 auto; background:red;}
</style>
<body><div>test<br>test</div></body>
This is the perfect solution. It centers <div>
of any size, and shrink-wraps it to size of its content.
Perform a hard reboot of your phone. The easiest way to do this is to remove the phone's battery. Wait for at least 30 seconds, then replace the battery. The phone will reboot, and upon completing its restart will have an empty DNS cache.
Read more: How to Flush the DNS on an Android Phone | eHow.com http://www.ehow.com/how_10021288_flush-dns-android-phone.html#ixzz1gRJnmiJb
Here's some background on the mechanism you should use, called Package Configurations: Understanding Integration Services Package Configurations. The article describes 5 types of configurations:
Here's a walkthrough of setting up a configuration on a Connection Manager: SQL Server Integration Services SSIS Package Configuration - I do realize this is using an environment variable for the connection string (not a great idea), but the basics are identical to using an XML file. The only step(s) you have to change in that walkthrough are the configuration type, and then a path.
SELECT (vg.id, name) FROM v_groups vg
INNER JOIN people2v_groups p2vg ON vg.id = p2vg.v_group_id
WHERE p2vg.people_id = 0;
In addition to @Ceki 's answer, If you are using logback and setup a config file in your project (usually logback.xml), you can define the log to plot the stack trace as well using
<encoder>
<pattern>%date |%-5level| [%thread] [%file:%line] - %msg%n%ex{full}</pattern>
</encoder>
the %ex in pattern is what makes the difference
If you want a lighter footprint, but a longer script, get the elements innerHTML and only create and clone the empty parent-
function getHTML(who,lines){
if(!who || !who.tagName) return '';
var txt, ax, str, el= document.createElement('div');
el.appendChild(who.cloneNode(false));
txt= el.innerHTML;
ax= txt.indexOf('>')+1;
str= txt.substring(0, ax)+who.innerHTML+ txt.substring(ax);
el= null;
return lines? str.replace(/> *</g,'>\n<'): str;
//easier to read if elements are separated
}
you can use this query to do the above task
DECLARE @test NVARCHAR(max)
SELECT @test = COALESCE(@test + ',', '') + field2 FROM #test SELECT field2= @test
for detail and step by step explanation visit the following link
http://oops-solution.blogspot.com/2011/11/sql-server-convert-table-column-data.html
Looks like you don't have the development libraries installed. Install them using:
sudo apt-get install libqt4-dev
As you said int the comments that you have them installed, just re-install it. Now. to update the locate's database, issue this command $sudo updatedb
Then $locate QApplication
to check that you now have the header file installed.
Now, goto the the folder where you have the code & type these commands
qmake -project
qmake
make
Then you can find the binary created.
Alternatively, you can use Qt Creator if you want the GUI.
See the official documentation for more info. http://developer.qt.nokia.com/doc/qt-4.8/gettingstartedqt.html
To learn how to use Qt Creator, use http://doc.qt.nokia.com/qtcreator-2.2/creator-qml-application.html
try this javascript
Snippet for getting the parameters from URL. Use javascript to get the URL parameters either from current window location or static URL into the argument for the function call.
javascript
function getUrlParameters(parameter, staticURL, decode){
var currLocation = (staticURL.length)? staticURL : window.location.search,
parArr = currLocation.split("?")[1].split("&"),
returnBool = true;
for(var i = 0; i < parArr.length; i++){
parr = parArr[i].split("=");
if(parr[0] == parameter){
return (decode) ? decodeURIComponent(parr[1]) : parr[1];
returnBool = true;
}else{
returnBool = false;
}
}
if(!returnBool) return false;
}
To get the parameter “id” from above static URL, use the following:
var idParameter = getUrlParameters("id", "http://www.example.com?id=1234&auth=true", true);
or
var idParameter = getUrlParameters("id", "", true);
Use the following query:
SELECT * FROM SAMPLE_TABLE ORDER BY ROWID ASC LIMIT 1
Note: Sqlite's row id references are detailed here.
Firstly remove duplicates:
arrayList1.removeAll(arrayList2);
Then merge two arrayList:
arrayList1.addAll(arrayList2);
Lastly, sort your arrayList if you wish:
collections.sort(arrayList1);
In case you don't want to make any changes on the existing list, first create their backup lists:
arrayList1Backup = new ArrayList(arrayList1);
I've just had this problem with MariaDB/InnoDB and was able to fix it by
str.replace(/[[\]]/g,'')
Month // Enum class, predefining and naming a dozen objects, one for each month of the year.
.of( 12 ) // Retrieving one of the enum objects by number, 1-12.
.getDisplayName(
TextStyle.FULL_STANDALONE ,
Locale.CANADA_FRENCH // Locale determines the human language and cultural norms used in localizing.
)
Since Java 1.8 (or 1.7 & 1.6 with the ThreeTen-Backport) you can use this:
Month.of(integerMonth).getDisplayName(TextStyle.FULL_STANDALONE, locale);
Note that integerMonth
is 1-based, i.e. 1 is for January. Range is always from 1 to 12 for January-December (i.e. Gregorian calendar only).
... 7 years later, in the desert, a tumbleweed blows by ...
I wasn't satisfied with the accepted answer so I created some scripts to do this for you available on Github. These should help anyone who wants to use git svn clone
but doesn't want to clone the entire repository and doesn't want to hunt for a specific revision to clone from in the middle of the history (maybe you're cloning a bunch of repos). Here we can just clone the last N revisions:
Use git svn clone
to clone the last 50 revisions
# -u The SVN URL to clone
# -l The limit of revisions
# -o The output directory
./git-svn-cloneback.sh -u https://server/project/trunk -l 50 -o myproj --authors-file=svn-authors.txt
Find the previous N revision from an SVN repo
# -u The SVN URL to clone
# -l The limit of revisions
./svn-lookback.sh -u https://server/project/trunk -l 5
Since you have not replied to my comment above, I am posting a solution for both.
You are missing '
in Extended Properties
For Excel 2003 try this (TRIED AND TESTED)
private void button1_Click(object sender, EventArgs e)
{
String name = "Items";
String constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" +
"C:\\Sample.xls" +
";Extended Properties='Excel 8.0;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
grid_items.DataSource = data;
}
BTW, I stopped working with Jet longtime ago. I use ACE now.
private void button1_Click(object sender, EventArgs e)
{
String name = "Items";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
"C:\\Sample.xls" +
";Extended Properties='Excel 8.0;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
grid_items.DataSource = data;
}
For Excel 2007+
private void button1_Click(object sender, EventArgs e)
{
String name = "Items";
String constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" +
"C:\\Sample.xlsx" +
";Extended Properties='Excel 12.0 XML;HDR=YES;';";
OleDbConnection con = new OleDbConnection(constr);
OleDbCommand oconn = new OleDbCommand("Select * From [" + name + "$]", con);
con.Open();
OleDbDataAdapter sda = new OleDbDataAdapter(oconn);
DataTable data = new DataTable();
sda.Fill(data);
grid_items.DataSource = data;
}
This may be due to version incompatibility between your code and the version you have installed.
In my case I was using v8.12.0 for development (locally) and installed latest version v13.7.0 on the server.
So using nvm I switched the node version to v8.12.0 with the below command:
> nvm install 8.12.0 // to install the version I wanted
> nvm use 8.12.0 // use the installed version
NOTE: You need to install nvm on your system to use nvm.
You should try this solution before trying solutions like installing build-essentials or uninstalling the current node version because you could switch between versions easily than reverting all the installations/uninstallations that you've done.
In HTML ids should be unique. I suggest you change your code to something like this:
<div id="div1" >
<input type="text" name="edit1" id="edit1" />
<input type="text" name="edit2" id="edit2" />
</div>
<div id="div2" >
<input type="text" name="edit1" id="edit3" />
<input type="text" name="edit2" id="edit4" />
</div>
coalesce
is supported in both Oracle and SQL Server and serves essentially the same function as nvl
and isnull
. (There are some important differences, coalesce
can take an arbitrary number of arguments, and returns the first non-null one. The return type for isnull
matches the type of the first argument, that is not true for coalesce
, at least on SQL Server.)
Transparent background will help you see what behind the element, in this case what behind your td
is in fact the parent table. So we have no way to achieve what you want using pure CSS. Even using script can't solve it in a direct way. We can just have a workaround using script based on the idea of using the same background for both the body and the td
. However we have to update the background-position
accordingly whenver the window is resized. Here is the code you can use with the default background position of body
(which is left top
, otherwise you have to change the code to update the background-position
of the td
correctly):
HTML:
<table id = "MainTable">
<tr>
<td width = "20%"></td>
<td width = "80%" id='test'>
<table>
<tr><td>something interesting here</td></tr>
<tr><td>another thing also interesting out there</td></tr>
</table>
</td>
</tr>
</table>
CSS:
/* use the same background for the td #test and the body */
#test {
padding:40px;
background:url('http://placekitten.com/800/500');
}
body {
background:url('http://placekitten.com/800/500');
}
JS (better use jQuery):
//code placed in onload event handler
function updateBackgroundPos(){
var pos = $('#test').offset();
$('#test').css('background-position',
-pos.left + 'px' + " " + (-pos.top + 'px'));
};
updateBackgroundPos();
$(window).resize(updateBackgroundPos);
Try resizing the viewport, you'll see the background-position
updated correctly, which will make an effect looking like the background of the td
is transparent to the body.
Yep, both and
and or
operators short-circuit -- see the docs.
below formula worked form me in MS EXEL
=TEXT(CELL_VALUE/24/60/60/1000 + 25569,"YYYY-MM-DD HH:MM")
CELL_VALUE is timestamp in milliseconds
here is explanation for text function.
In my case i have used following code for enabling gzip compression in apache web server.
# Compress HTML File, CSS File, JavaScript File, Text File, XML File and Fonts
AddOutputFilterByType DEFLATE text/plain
AddOutputFilterByType DEFLATE text/html
AddOutputFilterByType DEFLATE text/xml
AddOutputFilterByType DEFLATE application/json
AddOutputFilterByType DEFLATE application/x-httpd-php
AddOutputFilterByType DEFLATE text/css
AddOutputFilterByType DEFLATE application/xml
AddOutputFilterByType DEFLATE application/xhtml+xml
AddOutputFilterByType DEFLATE application/rss+xml
AddOutputFilterByType DEFLATE application/javascript
AddOutputFilterByType DEFLATE application/x-javascript
AddOutputFilterByType DEFLATE font/otf
AddOutputFilterByType DEFLATE font/ttf
I have taken reference from http://www.tutsway.com/enable-gzip-compression-using-htacess.php.
Assertj is good at this.
import static org.assertj.core.api.Assertions.assertThat;
assertThat(myClass.getMyItems()).extracting("name").contains("foo", "bar");
Big plus for assertj compared to hamcrest is easy use of code completion.
Well, it's clearly not a number since it has dashes in it. The error message and the two comments tell you that it is a factor but the commentators are apparently waiting and letting the message sink in. Dirk is suggesting that you do this:
EPL2011_12$Date2 <- as.Date( as.character(EPL2011_12$Date), "%d-%m-%y")
After that you can do this:
EPL2011_12FirstHalf <- subset(EPL2011_12, Date2 > as.Date("2012-01-13") )
R date functions assume the format is either "YYYY-MM-DD" or "YYYY/MM/DD". You do need to compare like classes: date to date, or character to character.
Various answers and notes are claiming that finish() can skip onPause() and onStop() and directly execute onDestroy(). To be fair, the Android documentation on this (http://developer.android.com/reference/android/app/Activity.html) notes "Activity is finishing or being destroyed by the system" which is pretty ambiguous but might suggest that finish() can jump to onDestroy().
The JavaDoc on finish() is similarly disappointing (http://developer.android.com/reference/android/app/Activity.html#finish()) and does not actually note what method(s) are called in response to finish().
So I wrote this mini-app below which logs each state upon entry. It includes a button which calls finish() -- so you can see the logs of which methods get fired. This experiment would suggested that finish() does indeed also call onPause() and onStop(). Here is the output I get:
2170-2170/? D/LIFECYCLE_DEMO? INSIDE: onCreate
2170-2170/? D/LIFECYCLE_DEMO? INSIDE: onStart
2170-2170/? D/LIFECYCLE_DEMO? INSIDE: onResume
2170-2170/? D/LIFECYCLE_DEMO? User just clicked button to initiate finish()
2170-2170/? D/LIFECYCLE_DEMO? INSIDE: onPause
2170-2170/? D/LIFECYCLE_DEMO? INSIDE: onStop
2170-2170/? D/LIFECYCLE_DEMO? INSIDE: onDestroy
package com.mvvg.apps.lifecycle;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Toast;
public class AndroidLifecycle extends Activity {
private static final String TAG = "LIFECYCLE_DEMO";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d(TAG, "INSIDE: onCreate");
setContentView(R.layout.activity_main);
LinearLayout layout = (LinearLayout) findViewById(R.id.myId);
Button button = new Button(this);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(AndroidLifecycle.this, "Initiating finish()",
Toast.LENGTH_SHORT).show();
Log.d(TAG, "User just clicked button to initiate finish()");
finish();
}
});
layout.addView(button);
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "INSIDE: onStart");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "INSIDE: onStop");
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d(TAG, "INSIDE: onDestroy");
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "INSIDE: onPause");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "INSIDE: onResume");
}
}
There are actually two ways of doing this:
st = "Line 1" + vbCrLf + "Line 2"
st = "Line 1" + vbNewLine + "Line 2"
These even work for message boxes (and all other places where strings are used).
With New-Item you can add the Force parameter
New-Item -Force -ItemType directory -Path foo
Or the ErrorAction parameter
New-Item -ErrorAction Ignore -ItemType directory -Path foo
Found that solution today. Works great for me. Even rendering PDF pages to PNG images. http://www.swftools.org/gfx_tutorial.html
usermod -m -d /newhome username
curl: command not found
is a big hint, you have to install it with :
apt-get update; apt-get install curl
You could define a message to throw when a certain error occurs:
throw std::invalid_argument( "received negative value" );
or you could define it like this:
std::runtime_error greatScott("Great Scott!");
double getEnergySync(int year) {
if (year == 1955 || year == 1885) throw greatScott;
return 1.21e9;
}
Typically, you would have a try ... catch
block like this:
try {
// do something that causes an exception
}catch (std::exception& e){ std::cerr << "exception: " << e.what() << std::endl; }
Programmatically sending an submitted form to multiple email address is a possible thing, however the best practice for this is by creating a mailing list. On the code the list address will be place and any change or update on email addresses to the recipients list can be done without changing in the code.
In your Dockerfile, run this first:
apt-get update && apt-get install -y gnupg2
XmlDocument doc = new XmlDocument();
doc.Load("MonFichierXML.xml");
XmlNode node = doc.SelectSingleNode("Magasin");
XmlNodeList prop = node.SelectNodes("Items");
foreach (XmlNode item in prop)
{
items Temp = new items();
Temp.AssignInfo(item);
lstitems.Add(Temp);
}
You have the join statement backwards try:
print ', '.join(set_3)
Just looking for the right place to put this piece of code.
let's say you have the following property:
[Display(Name = "Solar Radiation (Average)", ShortName = "SolarRadiationAvg")]
public int SolarRadiationAvgSensorId { get; set; }
And you want to get the ShortName value. You can do:
((DisplayAttribute)(typeof(SensorsModel).GetProperty(SolarRadiationAvgSensorId).GetCustomAttribute(typeof(DisplayAttribute)))).ShortName;
Or to make it general:
internal static string GetPropertyAttributeShortName(string propertyName)
{
return ((DisplayAttribute)(typeof(SensorsModel).GetProperty(propertyName).GetCustomAttribute(typeof(DisplayAttribute)))).ShortName;
}
It depends.
Start with Basic I/O, take a look at Properties, take a look at Preferences API and maybe even Java API for XML Processing and Java Architecture for XML Binding
And if none of those meet your particular needs, you could even look at using some kind of Database
DECLARE @isAvailable BIT = 0;
IF EXISTS(SELECT 1 FROM [User] WHERE (UserID = 20070022))
BEGIN
SET @isAvailable = 1
END
initially isAvailable boolean value is set to 0
I think you could also do something like this:
Create and .aspx page, and put this at the end of the OnLoad method, or call it manually.
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htmlTW = new HtmlTextWriter(sw);
this.Render(htmlTW);
I'm not sure if there are any potential issues with this, but it looks like it would work. This way, you could use a full featured .aspx page, instead of the MailDefinition class which only supports Text replacements.
An alternative approach is resample
, which can handle duplicate dates in addition to missing dates. For example:
df.resample('D').mean()
resample
is a deferred operation like groupby
so you need to follow it with another operation. In this case mean
works well, but you can also use many other pandas methods like max
, sum
, etc.
Here is the original data, but with an extra entry for '2013-09-03':
val
date
2013-09-02 2
2013-09-03 10
2013-09-03 20 <- duplicate date added to OP's data
2013-09-06 5
2013-09-07 1
And here are the results:
val
date
2013-09-02 2.0
2013-09-03 15.0 <- mean of original values for 2013-09-03
2013-09-04 NaN <- NaN b/c date not present in orig
2013-09-05 NaN <- NaN b/c date not present in orig
2013-09-06 5.0
2013-09-07 1.0
I left the missing dates as NaNs to make it clear how this works, but you can add fillna(0)
to replace NaNs with zeroes as requested by the OP or alternatively use something like interpolate()
to fill with non-zero values based on the neighboring rows.
.NET XSLT implementation allows to write custom managed functions in the stylesheet. For lower-case() it can be:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:utils="urn:myExtension" exclude-result-prefixes="msxsl">
<xsl:output method="xml" indent="yes"/>
<msxsl:script implements-prefix="utils" language="C#">
<![CDATA[
public string ToLower(string stringValue)
{
string result = String.Empty;
if(!String.IsNullOrEmpty(stringValue))
{
result = stringValue.ToLower();
}
return result;
}
]]>
</msxsl:script>
<!-- using of our custom function -->
<lowercaseValue>
<xsl:value-of select="utils:ToLower($myParam)"/>
</lowercaseValue>
Assume, that can be slow, but still acceptable.
Do not forget to enable embedded scripts support for transform:
// Create the XsltSettings object with script enabled.
XsltSettings xsltSettings = new XsltSettings(false, true);
XslCompiledTransform xslt = new XslCompiledTransform();
// Load stylesheet
xslt.Load(xsltPath, xsltSettings, new XmlUrlResolver());
What you mean is either
SELECT DISTINCT a, b FROM pairs;
or
SELECT a, b FROM pairs GROUP BY a, b;