To enable the Windows Authentication on IIS7 on Windows 7 machine:
Go to Control Panel
Click Programs >> Programs and Features
Select "Turn Windows Features on or off" from left side.
Expand Internet Information Services >> World Wide Web Services >> Security
Select Windows Authentication and click OK.
Reset the IIS and Check in IIS now for windows authentication.
Enjoy
I think this will do what you want:
DateTime d1 = DateTime.Now;
DateTime d2 = DateTime.Now.AddDays(-1);
TimeSpan t = d1 - d2;
double NrOfDays = t.TotalDays;
You could put it in an Excel sheet, idk if it'll be worth it for you if its needed for other things but storing info in excel sheets is a lot nicer because you can easily read and write at the same time with the
'this gives you an excel app
oExcel = CreateObject("Excel.Application")
'this opens a work book of your choice, just set "Target" to a filepath
oBook = oExcel.Workbooks.Open(Target)
'how to read
set readVar = oExcel.Cell(1,1).value
'how to write
oExcel.Cell(1,2).value = writeVar
'Saves & Closes Book then ends excel
oBook.Save
oBook.Close
oExcel.Quit
sorry if this answer isnt helpful, first time writing an answer and just thought this might be a nicer way for you
'a' in x
and a quick search reveals some nice information about it: http://docs.python.org/3/tutorial/datastructures.html#dictionaries
You can use Theme.applyStyle to modify your theme at runtime by applying another style to it.
Let's say you have these style definitions:
<style name="DefaultTheme" parent="Theme.AppCompat.Light">
<item name="colorPrimary">@color/md_lime_500</item>
<item name="colorPrimaryDark">@color/md_lime_700</item>
<item name="colorAccent">@color/md_amber_A400</item>
</style>
<style name="OverlayPrimaryColorRed">
<item name="colorPrimary">@color/md_red_500</item>
<item name="colorPrimaryDark">@color/md_red_700</item>
</style>
<style name="OverlayPrimaryColorGreen">
<item name="colorPrimary">@color/md_green_500</item>
<item name="colorPrimaryDark">@color/md_green_700</item>
</style>
<style name="OverlayPrimaryColorBlue">
<item name="colorPrimary">@color/md_blue_500</item>
<item name="colorPrimaryDark">@color/md_blue_700</item>
</style>
Now you can patch your theme at runtime like so:
getTheme().applyStyle(R.style.OverlayPrimaryColorGreen, true);
The method applyStyle
has to be called before the layout gets inflated! So unless you load the view manually you should apply styles to the theme before calling setContentView
in your activity.
Of course this cannot be used to specify an arbitrary color, i.e. one out of 16 million (2563) colors. But if you write a small program that generates the style definitions and the Java code for you then something like one out of 512 (83) should be possible.
What makes this interesting is that you can use different style overlays for different aspects of your theme. Just add a few overlay definitions for colorAccent
for example. Now you can combine different values for primary color and accent color almost arbitrarily.
You should make sure that your overlay theme definitions don't accidentally inherit a bunch of style definitions from a parent style definition. For example a style called AppTheme.OverlayRed
implicitly inherits all styles defined in AppTheme
and all these definitions will also be applied when you patch the master theme. So either avoid dots in the overlay theme names or use something like Overlay.Red
and define Overlay
as an empty style.
While @Timar's answer works perfectly for null
default values (what was asked for), here another easy solution which allows other default values: Define an option interface as well as an according constant containing the defaults; in the constructor use the spread operator to set the options
member variable
interface IXOptions {
a?: string,
b?: any,
c?: number
}
const XDefaults: IXOptions = {
a: "default",
b: null,
c: 1
}
export class ClassX {
private options: IXOptions;
constructor(XOptions: IXOptions) {
this.options = { ...XDefaults, ...XOptions };
}
public printOptions(): void {
console.log(this.options.a);
console.log(this.options.b);
console.log(this.options.c);
}
}
Now you can use the class like this:
const x = new ClassX({ a: "set" });
x.printOptions();
Output:
set
null
1
If you're using .NET version 3.0 or lower, you have to use XmlDocument
aka the classic DOM API. Likewise you'll find there are some other APIs which will expect this.
If you get the choice, however, I would thoroughly recommend using XDocument
aka LINQ to XML. It's much simpler to create documents and process them. For example, it's the difference between:
XmlDocument doc = new XmlDocument();
XmlElement root = doc.CreateElement("root");
root.SetAttribute("name", "value");
XmlElement child = doc.CreateElement("child");
child.InnerText = "text node";
root.AppendChild(child);
doc.AppendChild(root);
and
XDocument doc = new XDocument(
new XElement("root",
new XAttribute("name", "value"),
new XElement("child", "text node")));
Namespaces are pretty easy to work with in LINQ to XML, unlike any other XML API I've ever seen:
XNamespace ns = "http://somewhere.com";
XElement element = new XElement(ns + "elementName");
// etc
LINQ to XML also works really well with LINQ - its construction model allows you to build elements with sequences of sub-elements really easily:
// Customers is a List<Customer>
XElement customersElement = new XElement("customers",
customers.Select(c => new XElement("customer",
new XAttribute("name", c.Name),
new XAttribute("lastSeen", c.LastOrder)
new XElement("address",
new XAttribute("town", c.Town),
new XAttribute("firstline", c.Address1),
// etc
));
It's all a lot more declarative, which fits in with the general LINQ style.
Now as Brannon mentioned, these are in-memory APIs rather than streaming ones (although XStreamingElement
supports lazy output). XmlReader
and XmlWriter
are the normal ways of streaming XML in .NET, but you can mix all the APIs to some extent. For example, you can stream a large document but use LINQ to XML by positioning an XmlReader
at the start of an element, reading an XElement
from it and processing it, then moving on to the next element etc. There are various blog posts about this technique, here's one I found with a quick search.
Note that in general, IDE's like Visual Studio will markup a comment in the context of the current language, by selecting the text you wish to turn into a comment, and then using the Ctrl+K Ctrl+C shortcut, or if you are using Resharper / Intelli-J style shortcuts, then Ctrl+/.
Server side Comments:
Razor .cshtml
@* Comment goes here *@
.aspx
For those looking for the older .aspx
view (and Asp.Net WebForms) server side comment syntax:
<%-- Comment goes here --%>
Client Side Comments
HTML Comment
<!-- Comment goes here -->
Javascript Comment
// One line Comment goes Here
/* Multiline comment
goes here */
As OP mentions, although not displayed on the browser, client side comments will still be generated for the page / script file on the server and downloaded by the page over HTTP, which unless removed (e.g. minification), will waste I/O, and, since the comment can be viewed by the user by viewing the page source or intercepting the traffic with the browser's Dev Tools or a tool like Fiddler or Wireshark, can also pose a security risk, hence the preference to use server side comments on server generated code (like MVC views or .aspx pages).
Although my answer is not related to datatables it addresses the issue of DOM manipulation and e.g. jQuery plugin initialization for directives used on elements which have their contents updated in async manner.
Instead of implementing a timeout one could just add a watch that will listen to content changes (or even additional external triggers).
In my case I used this workaround for initializing a jQuery plugin once the ng-repeat was done which created my inner DOM - in another case I used it for just manipulating the DOM after the scope property was altered at controller. Here is how I did ...
HTML:
<div my-directive my-directive-watch="!!myContent">{{myContent}}</div>
JS:
app.directive('myDirective', [ function(){
return {
restrict : 'A',
scope : {
myDirectiveWatch : '='
},
compile : function(){
return {
post : function(scope, element, attributes){
scope.$watch('myDirectiveWatch', function(newVal, oldVal){
if (newVal !== oldVal) {
// Do stuff ...
}
});
}
}
}
}
}]);
Note: Instead of just casting the myContent variable to bool at my-directive-watch attribute one could imagine any arbitrary expression there.
Note: Isolating the scope like in the above example can only be done once per element - trying to do this with multiple directives on the same element will result in a $compile:multidir Error - see: https://docs.angularjs.org/error/$compile/multidir
Firefox does not support the MPEG H.264 (mp4) format at this time, due to a philosophical disagreement with the closed-source nature of the format.
To play videos in all browsers without using plugins, you will need to host multiple copies of each video, in different formats. You will also need to use an alternate form of the video
tag, as seen in the JSFiddle from @TimHayes above, reproduced below. Mozilla claims that only mp4 and WebM are necessary to ensure complete coverage of all major browsers, but you may wish to consult the Video Formats and Browser Support heading on W3C's HTML5 Video page to see which browser supports what formats.
Additionally, it's worth checking out the HTML5 Video page on Wikipedia for a basic comparison of the major file formats.
Below is the appropriate video
tag (you will need to re-encode your video in WebM or OGG formats as well as your existing mp4):
<video id="video" controls='controls'>
<source src="videos/clip.mp4" type="video/mp4"/>
<source src="videos/clip.webm" type="video/webm"/>
<source src="videos/clip.ogv" type="video/ogg"/>
Your browser doesn't seem to support the video tag.
</video>
Updated Nov. 8, 2013
Network infrastructure giant Cisco has announced plans to open-source an implementation of the H.264 codec, removing the licensing fees that have so far proved a barrier to use by Mozilla. Without getting too deep into the politics of it (see following link for that) this will allow Firefox to support H.264 starting in "early 2014". However, as noted in that link, this still comes with a caveat. The H.264 codec is merely for video, and in the MPEG-4 container it is most commonly paired with the closed-source AAC audio codec. Because of this, playback of H.264 video will work, but audio will depend on whether the end-user has the AAC codec already present on their machine.
The long and short of this is that progress is being made, but you still can't avoid using multiple encodings without using a plugin.
A bit late to the game but for the sake of completion...
Instead of 'waiting' for all tasks to finish, you can think in terms of the Hollywood principle, "don't call me, I'll call you" - when I'm finished. I think the resulting code is more elegant...
Guava offers some interesting tools to accomplish this.
An example:
Wrap an ExecutorService into a ListeningExecutorService:
ListeningExecutorService service = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(10));
Submit a collection of callables for execution ::
for (Callable<Integer> callable : callables) {
ListenableFuture<Integer> lf = service.submit(callable);
// listenableFutures is a collection
listenableFutures.add(lf)
});
Now the essential part:
ListenableFuture<List<Integer>> lf = Futures.successfulAsList(listenableFutures);
Attach a callback to the ListenableFuture, that you can use to be notified when all futures complete:
Futures.addCallback(lf, new FutureCallback<List<Integer>> () {
@Override
public void onSuccess(List<Integer> result) {
// do something with all the results
}
@Override
public void onFailure(Throwable t) {
// log failure
}
});
This also offers the advantage that you can collect all the results in one place once the processing is finished...
More information here
In C, the type specifier keywords of structures, unions and enumerations are mandatory, ie you always have to prefix the type's name (its tag) with struct
, union
or enum
when referring to the type.
You can get rid of the keywords by using a typedef
, which is a form of information hiding as the actual type of an object will no longer be visible when declaring it.
It is therefore recommended (see eg the Linux kernel coding style guide, Chapter 5) to only do this when you actually want to hide this information and not just to save a few keystrokes.
An example of when you should use a typedef
would be an opaque type which is only ever used with corresponding accessor functions/macros.
IIF
is the same as CASE WHEN <Condition> THEN <true part> ELSE <false part> END
. The query plan will be the same. It is, perhaps, "syntactical sugar" as initially implemented.
CASE is portable across all SQL platforms whereas IIF is SQL SERVER 2012+ specific.
To quote the specifications:
The docstring of a script (a stand-alone program) should be usable as its "usage" message, printed when the script is invoked with incorrect or missing arguments (or perhaps with a "-h" option, for "help"). Such a docstring should document the script's function and command line syntax, environment variables, and files. Usage messages can be fairly elaborate (several screens full) and should be sufficient for a new user to use the command properly, as well as a complete quick reference to all options and arguments for the sophisticated user.
The docstring for a module should generally list the classes, exceptions and functions (and any other objects) that are exported by the module, with a one-line summary of each. (These summaries generally give less detail than the summary line in the object's docstring.) The docstring for a package (i.e., the docstring of the package's
__init__.py
module) should also list the modules and subpackages exported by the package.The docstring for a class should summarize its behavior and list the public methods and instance variables. If the class is intended to be subclassed, and has an additional interface for subclasses, this interface should be listed separately (in the docstring). The class constructor should be documented in the docstring for its
__init__
method. Individual methods should be documented by their own docstring.
The docstring of a function or method is a phrase ending in a period. It prescribes the function or method's effect as a command ("Do this", "Return that"), not as a description; e.g. don't write "Returns the pathname ...". A multiline-docstring for a function or method should summarize its behavior and document its arguments, return value(s), side effects, exceptions raised, and restrictions on when it can be called (all if applicable). Optional arguments should be indicated. It should be documented whether keyword arguments are part of the interface.
if file is committed and pushed to github then you should run
git rm --fileName
git ls-files
to make sure that the file is removed or untracked
git commit -m "UntrackChanges"
git push
Important to note with elementFormDefault is that it applies to locally defined elements, typically named elements inside a complexType block, as opposed to global elements defined on the top-level of the schema. With elementFormDefault="qualified" you can address local elements in the schema from within the xml document using the schema's target namespace as the document's default namespace.
In practice, use elementFormDefault="qualified" to be able to declare elements in nested blocks, otherwise you'll have to declare all elements on the top level and refer to them in the schema in nested elements using the ref attribute, resulting in a much less compact schema.
This bit in the XML Schema Primer talks about it: http://www.w3.org/TR/xmlschema-0/#NS
If you are using Apache reverse proxy for serving an app running on a localhost port you must add a location to your vhost.
<Location />
ProxyPass http://localhost:1339/ retry=0
ProxyPassReverse http://localhost:1339/
ProxyPreserveHost On
ProxyErrorOverride Off
</Location>
To get the IP address have following options
console.log(">>>", req.ip);// this works fine for me returned a valid ip address
console.log(">>>", req.headers['x-forwarded-for'] );// returned a valid IP address
console.log(">>>", req.headers['X-Real-IP'] ); // did not work returned undefined
console.log(">>>", req.connection.remoteAddress );// returned the loopback IP address
So either use req.ip or req.headers['x-forwarded-for']
Join like this:
ON a.userid = b.sourceid AND a.listid = b.destinationid;
declare @hash nvarchar(50)
--declare @hash varchar(50)
set @hash = '1111111-2;20190110143334;001' -- result a5cd84bfc56e245bbf81210f05b7f65f
declare @value varbinary(max);
set @value = convert(varbinary(max),@hash);
select
SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5', '1111111-2;20190110143334;001')),3,32) as 'OK'
,SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5', @hash)),3,32) as 'ERROR_01'
,SUBSTRING(sys.fn_sqlvarbasetostr(HASHBYTES('MD5',convert(varbinary(max),@hash))),3,32) as 'ERROR_02'
,SUBSTRING(sys.fn_sqlvarbasetostr(sys.fn_repl_hash_binary(convert(varbinary(max),@hash))),3,32)
,SUBSTRING(sys.fn_sqlvarbasetostr(master.sys.fn_repl_hash_binary(@value)),3,32)
Improved Lukas Knuth's version:
public class TweakedWebView extends WebView {
private ZoomButtonsController zoomButtons;
public TweakedWebView(Context context) {
super(context);
init();
}
public TweakedWebView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public TweakedWebView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
getSettings().setBuiltInZoomControls(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getSettings().setDisplayZoomControls(false);
} else {
try {
Method method = getClass()
.getMethod("getZoomButtonsController");
zoomButtons = (ZoomButtonsController) method.invoke(this);
} catch (Exception e) {
// pass
}
}
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
boolean result = super.onTouchEvent(ev);
if (zoomButtons != null) {
zoomButtons.setVisible(false);
zoomButtons.getZoomControls().setVisibility(View.GONE);
}
return result;
}
}
If you want to execute a function when something is done. One of a good solution is to listen to events.
For example, I'll implement a Dispatcher
, a DispatcherEvent
class with ES6,then:
let Notification = new Dispatcher()
Notification.on('Load data success', loadSuccessCallback)
const loadSuccessCallback = (data) =>{
...
}
//trigger a event whenever you got data by
Notification.dispatch('Load data success')
Dispatcher:
class Dispatcher{
constructor(){
this.events = {}
}
dispatch(eventName, data){
const event = this.events[eventName]
if(event){
event.fire(data)
}
}
//start listen event
on(eventName, callback){
let event = this.events[eventName]
if(!event){
event = new DispatcherEvent(eventName)
this.events[eventName] = event
}
event.registerCallback(callback)
}
//stop listen event
off(eventName, callback){
const event = this.events[eventName]
if(event){
delete this.events[eventName]
}
}
}
DispatcherEvent:
class DispatcherEvent{
constructor(eventName){
this.eventName = eventName
this.callbacks = []
}
registerCallback(callback){
this.callbacks.push(callback)
}
fire(data){
this.callbacks.forEach((callback=>{
callback(data)
}))
}
}
Happy coding!
p/s: My code is missing handle some error exceptions
If you need the exact functionality of the back button in your custom button, why not just call yourActivity.onBackPressed() that way if you override the functionality of the backbutton your custom button will behave the same.
Orabig is correct.
You can bind 10.0.2.15 in Ubuntu (VirtualBox) then do a port forwarding from host to guest Ubuntu.
in /etc/redis/redis.conf
bind 10.0.2.15
then, restart redis:
sudo systemctl restart redis
It shall work!
You're looking for $(this).attr("href");
I would avoid using a relative path. Remember that docker is a daemon/client relationship.
When you are executing the compose, it's essentially just breaking down into various docker client commands, which are then passed to the daemon. That ./database
is then relative to the daemon, not the client.
Now, the docker dev team has some back and forth on this issue, but the bottom line is it can have some unexpected results.
In short, don't use a relative path, use an absolute path.
Based on an issue on Github of PhantomJS, the quit() does not terminate PhantomJS process. You should use:
import signal
driver = webdriver.PhantomJS(service_args=service_args)
# Do your work here
driver.service.process.send_signal(signal.SIGTERM)
driver.quit()
The file is truncated, so you can call read()
(no exceptions raised, unlike when opened using 'w') but you'll get an empty string.
Simply use fs
module and something like this:
fs.appendFile('server.log', 'string to append', function (err) {
if (err) return console.log(err);
console.log('Appended!');
});
If you do not intend to use jQuery, you can use simple javascript like this
document.querySelector('input[name="Choose"]:checked').checked = false;
Only benefit with this is you don't have to use loops for two radio buttons
As of 2018 and beyond, you have a more modern option which is to incorporate async/await in your ReactJS application. A promise-based HTTP client library such as axios can be used. The sample code is given below:
import axios from 'axios';
...
class Login extends Component {
constructor(props, context) {
super(props, context);
this.onLogin = this.onLogin.bind(this);
...
}
async onLogin() {
const { email, password } = this.state;
try {
const response = await axios.post('/login', { email, password });
console.log(response);
} catch (err) {
...
}
}
...
}
Old version includes kafka-simple-consumer-shell.sh
(https://kafka.apache.org/downloads#1.1.1) which is convenient since we do not need cltr+c
to exit.
For example
kafka-simple-consumer-shell.sh --broker-list $BROKERIP:$BROKERPORT --topic $TOPIC1 --property print.key=true --property key.separator=":" --no-wait-at-logend
You could use XML.
E.g.
declare @xmlstring as varchar(100)
set @xmlstring = '<args><arg value="42" /><arg2>-1</arg2></args>'
declare @docid int
exec sp_xml_preparedocument @docid output, @xmlstring
select [id],parentid,nodetype,localname,[text]
from openxml(@docid, '/args', 1)
The command sp_xml_preparedocument is built in.
This would produce the output:
id parentid nodetype localname text
0 NULL 1 args NULL
2 0 1 arg NULL
3 2 2 value NULL
5 3 3 #text 42
4 0 1 arg2 NULL
6 4 3 #text -1
which has all (more?) of what you you need.
if (!$variablename) { Write-Host "variable is null" }
I hope this simple answer will is resolve the question. Source
Ok to generalize the technique of how many bits you need to represent a number is done this way. You have R symbols for a representation and you want to know how many bits, solve this equation R=2^n or log2(R)=n. Where n is the numbers of bits and R is the number of symbols for the representation.
For the decimal number system R=9 so we solve 9=2^n, the answer is 3.17 bits per decimal digit. Thus a 3 digit number will need 9.51 bits or 10. A 1000 digit number needs 3170 bits
grep command can be used
CA = mydata[grep("CA", mydata$sCode, ]
nrow(CA)
Pull in a reference to Visual Basic in your project and use its Information.IsNumeric method such as shown below and be able to capture floats as well as integers unlike the answer above which only catches ints.
// Using Microsoft.VisualBasic;
var txt = "ABCDEFG";
if (Information.IsNumeric(txt))
Console.WriteLine ("Numeric");
IsNumeric("12.3"); // true
IsNumeric("1"); // true
IsNumeric("abc"); // false
I had the same issue and tried almost everything then found after I came to know I was trying it in the wrong block. I was trying it in steps block whereas it needs to be in the environment block.
stage('Release') {
environment {
my_var = sh(script: "/bin/bash ${assign_version} || ls ", , returnStdout: true).trim()
}
steps {
println my_var
}
}
Fixnum#to_r is not mentioned here, it was introduced since ruby 1.9. It converts Fixnum into rational form. Below are examples of its uses. This also can give exact division as long as all the numbers used are Fixnum.
a = 1.to_r #=> (1/1)
a = 10.to_r #=> (10/1)
a = a / 3 #=> (10/3)
a = a * 3 #=> (10/1)
a.to_f #=> 10.0
Example where a float operated on a rational number coverts the result to float.
a = 5.to_r #=> (5/1)
a = a * 5.0 #=> 25.0
I know an answer has already been accepted for this problem but someone asked in the comments if there was a solution that could be done outside the web.config. I had a ListView producing the exact same error and setting EnableViewState to false resolved this problem for me.
UTF-8 is prepared for world domination, Latin1 isn't.
If you're trying to store non-Latin characters like Chinese, Japanese, Hebrew, Russian, etc using Latin1 encoding, then they will end up as mojibake. You may find the introductory text of this article useful (and even more if you know a bit Java).
Note that full 4-byte UTF-8 support was only introduced in MySQL 5.5. Before that version, it only goes up to 3 bytes per character, not 4 bytes per character. So, it supported only the BMP plane and not e.g. the Emoji plane. If you want full 4-byte UTF-8 support, upgrade MySQL to at least 5.5 or go for another RDBMS like PostgreSQL. In MySQL 5.5+ it's called utf8mb4
.
cURL is going to be your only real choice here (either that, or using non-blocking sockets and some custom logic).
This link should send you in the right direction. There is no asynchronous processing in PHP, but if you're trying to make multiple simultaneous web requests, cURL multi will take care of that for you.
I found that my Pantech Burst had a problem similar to what you all described. After reading through many such posts everywhere I noticed many people reported having to use a USB cable that they got else where other than the phone manufacturer. What I decided to do was use a different USB port on my PC and the problem was fixed. My Pantech Burst does not go offline in the middle of a debug session any more. The port I used to use was the front port on my box, but it was wired to the motherboard without shielding inside the box. Now I use the port on the back of the box that is directly attached to the motherboard.
Even after adding @Autowire if your class is not a RestController or Configuration Class, the applicationContext object was coming as null. Tried Creating new class with below and it is working fine:
@Component
public class SpringContext implements ApplicationContextAware{
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws
BeansException {
this.applicationContext=applicationContext;
}
}
you can then implement a getter method in the same class as per your need like getting the Implemented class reference by:
applicationContext.getBean(String serviceName,Interface.Class)
To use quotes just for completeness.
"/Users/my/work/a project with space"/**
If not recursive, remove the /**
I would like to mention that IE9 does not raise the error if you use console.log with developer tools closed on all versions of Windows. On XP it does, but on Windows 7 it doesn't. So if you dropped support for WinXP in general, you're fine using console.log directly.
Git in Windows is quite well supported now.
Check out GitExtensions = http://code.google.com/p/gitextensions/
and the manual for a better Windows Git experience.
As an alternative to Activator.CreateInstance, FastObjectFactory in the linked url preforms better than Activator (as of .NET 4.0 and significantly better than .NET 3.5. No tests/stats done with .NET 4.5). See StackOverflow post for stats, info and code:
How to pass ctor args in Activator.CreateInstance or use IL?
@echo off
title Test
echo Select a language. (de/en)
set /p language=
IF /i "%language%"=="de" goto languageDE
IF /i "%language%"=="en" goto languageEN
echo Not found.
goto commonexit
:languageDE
echo German
goto commonexit
:languageEN
echo English
goto commonexit
:commonexit
pause
The point is that batch simply continues through instructions, line by line until it reaches a goto
, exit
or end-of-file. It has no concept of sections
to control flow.
Hence, entering de
would jump to :languagede
then simply continue executing instructions until the file ends, showing de
then en
then not found
.
What you're basically doing here is relying on Date#toString()
which already has a fixed pattern. To convert a Java Date
object into another human readable String pattern, you need SimpleDateFormat#format()
.
private String modifyDateLayout(String inputDate) throws ParseException{
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").parse(inputDate);
return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date);
}
By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse()
. This means that the inputDate
isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z"
. You'll probably need to modify the pattern to match the inputDate
's actual pattern.
Update: Okay, I did a test:
public static void main(String[] args) throws Exception {
String inputDate = "2010-01-04 01:32:27 UTC";
String newDate = new Test().modifyDateLayout(inputDate);
System.out.println(newDate);
}
This correctly prints:
03.01.2010 21:32:27
(I'm on GMT-4)
Update 2: as per your edit, you really got a ParseException
on that. The most suspicious part would then be the timezone of UTC
. Is this actually known at your Java environment? What Java version and what OS version are you using? Check TimeZone.getAvailableIDs()
. There must be a UTC
in between.
set.seed(1)
example <- data.frame(col1 = rnorm(10, 0, 1), col2 = rnorm(10, 2, 3))
namevector <- c("col3", "col4")
example[ , namevector] <- NA
example
# col1 col2 col3 col4
# 1 -0.6264538 6.5353435 NA NA
# 2 0.1836433 3.1695297 NA NA
# 3 -0.8356286 0.1362783 NA NA
# 4 1.5952808 -4.6440997 NA NA
# 5 0.3295078 5.3747928 NA NA
# 6 -0.8204684 1.8651992 NA NA
# 7 0.4874291 1.9514292 NA NA
# 8 0.7383247 4.8315086 NA NA
# 9 0.5757814 4.4636636 NA NA
# 10 -0.3053884 3.7817040 NA NA
Use this
$array = array();
$subArray=array();
$sql_results = mysql_query('SELECT * FROM `location`');
while($row = mysql_fetch_array($sql_results))
{
$subArray[location_id]=$row['location']; //location_id is key and $row['location'] is value which come fron database.
$subArray[x]=$row['x'];
$subArray[y]=$row['y'];
$array[] = $subArray ;
}
echo'{"ProductsData":'.json_encode($array).'}';
You must set the setOpaque(true) to true other wise the background will not be painted to the form. I think from reading that if it is not set to true that it will paint some or not any of its pixels to the form. The background is transparent by default which seems odd to me at least but in the way of programming you have to set it to true as shown below.
JLabel lb = new JLabel("Test");
lb.setBackground(Color.red);
lb.setOpaque(true); <--This line of code must be set to true or otherwise the
From the JavaDocs
setOpaque
public void setOpaque(boolean isOpaque)
If true the component paints every pixel within its bounds. Otherwise,
the component may not paint some or all of its pixels, allowing the underlying
pixels to show through.
The default value of this property is false for JComponent. However,
the default value for this property on most standard JComponent subclasses
(such as JButton and JTree) is look-and-feel dependent.
Parameters:
isOpaque - true if this component should be opaque
See Also:
isOpaque()
Given the code snippet of a template type with a friend operator (or function);
template <typename T>
class Foo {
friend std::ostream& operator<< (std::ostream& os, const Foo<T>& a);
};
The operator<<
is being declared as a non-template function. For every type T
used with Foo
, there needs to be a non-templated operator<<
. For example, if there is a type Foo<int>
declared, then there must be an operator implementation as follows;
std::ostream& operator<< (std::ostream& os, const Foo<int>& a) {/*...*/}
Since it is not implemented, the linker fails to find it and results in the error.
To correct this, you can declare a template operator before the Foo
type and then declare as a friend, the appropriate instantiation. The syntax is a little awkward, but is looks as follows;
// forward declare the Foo
template <typename>
class Foo;
// forward declare the operator <<
template <typename T>
std::ostream& operator<<(std::ostream&, const Foo<T>&);
template <typename T>
class Foo {
friend std::ostream& operator<< <>(std::ostream& os, const Foo<T>& a);
// note the required <> ^^^^
// ...
};
template <typename T>
std::ostream& operator<<(std::ostream&, const Foo<T>&)
{
// ... implement the operator
}
The above code limits the friendship of the operator to the corresponding instantiation of Foo
, i.e. the operator<< <int>
instantiation is limited to access the private members of the instantiation of Foo<int>
.
Alternatives include;
Allowing the friendship to extend to all instantiations of the templates, as follows;
template <typename T>
class Foo {
template <typename T1>
friend std::ostream& operator<<(std::ostream& os, const Foo<T1>& a);
// ...
};
Or, the implementation for the operator<<
can be done inline inside the class definition;
template <typename T>
class Foo {
friend std::ostream& operator<<(std::ostream& os, const Foo& a)
{ /*...*/ }
// ...
};
Note, when the declaration of the operator (or function) only appears in the class, the name is not available for "normal" lookup, only for argument dependent lookup, from cppreference;
A name first declared in a friend declaration within class or class template X becomes a member of the innermost enclosing namespace of X, but is not accessible for lookup (except argument-dependent lookup that considers X) unless a matching declaration at the namespace scope is provided...
There is further reading on template friends at cppreference and the C++ FAQ.
Code listing showing the techniques above.
As a side note to the failing code sample; g++ warns about this as follows
warning: friend declaration 'std::ostream& operator<<(...)' declares a non-template function [-Wnon-template-friend]
note: (if this is not what you intended, make sure the function template has already been declared and add <> after the function name here)
Go to your Models and check, because you might have truncated a number of words for that particular column eg. max_length="150".
Your arguments are in the wrong order. The connection comes first according to the docs
<?php
require("constants.php");
// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);
if (!$connection) {
error_log("Failed to connect to MySQL: " . mysqli_error($connection));
die('Internal server error');
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
error_log("Database selection failed: " . mysqli_error($connection));
die('Internal server error');
}
?>
For linebreaks, PHP as "\n"
(see double quote strings) and PHP_EOL
.
Here, you are using <br />
, which is not a PHP line-break : it's an HTML linebreak.
Here, you can simplify what you posted (with HTML linebreaks) : no need for the strings concatenations : you can put everything in just one string, like this :
$var = "Hi there<br/>Welcome to my website<br/>";
Or, using PHP linebreaks :
$var = "Hi there\nWelcome to my website\n";
Note : you might also want to take a look at the nl2br()
function, which inserts <br>
before \n
.
If you are looking for a solution to your particular case, it would be:
Date date = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").parse("2012-05-20T09:00:00.000Z");
String formattedDate = new SimpleDateFormat("dd/MM/yyyy, Ka").format(date);
From the "Updating Chosen Dynamically" section in the docs: You need to trigger the 'chosen:updated' event on the field
$(document).ready(function() {
$('select').chosen();
$('button').click(function() {
$('select').val(2);
$('select').trigger("chosen:updated");
});
});
NOTE: versions prior to 1.0 used the following:
$('select').trigger("liszt:updated");
The "responsible" answer would be for me to suggest building a ViewModel for the dialog and use two-way databinding on the TextBox so that the ViewModel had some "ResponseText" property or what not. This is easy enough to do but probably overkill.
The pragmatic answer would be to just give your text box an x:Name so that it becomes a member and expose the text as a property in your code behind class like so:
<!-- Incredibly simplified XAML -->
<Window x:Class="MyDialog">
<StackPanel>
<TextBlock Text="Enter some text" />
<TextBox x:Name="ResponseTextBox" />
<Button Content="OK" Click="OKButton_Click" />
</StackPanel>
</Window>
Then in your code behind...
partial class MyDialog : Window {
public MyDialog() {
InitializeComponent();
}
public string ResponseText {
get { return ResponseTextBox.Text; }
set { ResponseTextBox.Text = value; }
}
private void OKButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
DialogResult = true;
}
}
Then to use it...
var dialog = new MyDialog();
if (dialog.ShowDialog() == true) {
MessageBox.Show("You said: " + dialog.ResponseText);
}
@vladima replied to this issue on GitHub:
The way the compiler resolves modules is controlled by moduleResolution option that can be either
node
orclassic
(more details and differences can be found here). If this setting is omitted the compiler treats this setting to benode
if module iscommonjs
andclassic
- otherwise. In your case if you wantclassic
module resolution strategy to be used withcommonjs
modules - you need to set it explicitly by using{ "compilerOptions": { "moduleResolution": "node" } }
Here is an elegant way to do similar thing. But why do partly JSON unmarshal? That doesn't make sense.
Look below at the working code. Copy and paste it.
import (
"bytes"
"encoding/json" // Encoding and Decoding Package
"fmt"
)
var messeging = `{
"say":"Hello",
"sendMsg":{
"user":"ANisus",
"msg":"Trying to send a message"
}
}`
type SendMsg struct {
User string `json:"user"`
Msg string `json:"msg"`
}
type Chat struct {
Say string `json:"say"`
SendMsg *SendMsg `json:"sendMsg"`
}
func main() {
/** Clean way to solve Json Decoding in Go */
/** Excellent solution */
var chat Chat
r := bytes.NewReader([]byte(messeging))
chatErr := json.NewDecoder(r).Decode(&chat)
errHandler(chatErr)
fmt.Println(chat.Say)
fmt.Println(chat.SendMsg.User)
fmt.Println(chat.SendMsg.Msg)
}
func errHandler(err error) {
if err != nil {
fmt.Println(err)
return
}
}
Kind of old question, but with the latest XCode, codesign
is easy:
$ codesign -s my_certificate example.ipa
$ codesign -vv example.ipa
example.ipa: valid on disk
example.ipa: satisfies its Designated Requirement
You can parse the JSONArray
directly, don't need to wrap your Post
class with PostEntity
one more time and don't need new JSONObject().toString()
either:
Gson gson = new Gson();
String jsonOutput = "Your JSON String";
Type listType = new TypeToken<List<Post>>(){}.getType();
List<Post> posts = gson.fromJson(jsonOutput, listType);
Hope that helps.
I agree with VinnyD that what you need to do is add "&" in front of your __get function, as to make it to return the needed result as a reference:
public function &__get ( $propertyname )
But be aware of two things:
1) You should also do
return &$something;
or you might still be returning a value and not a reference...
2) Remember that in any case that __get returns a reference this also means that the corresponding __set will NEVER be called; this is because php resolves this by using the reference returned by __get, which is called instead!
So:
$var = $object->NonExistentArrayProperty;
means __get is called and, since __get has &__get and return &$something, $var is now, as intended, a reference to the overloaded property...
$object->NonExistentArrayProperty = array();
works as expected and __set is called as expected...
But:
$object->NonExistentArrayProperty[] = $value;
or
$object->NonExistentArrayProperty["index"] = $value;
works as expected in the sense that the element will be correctly added or modified in the overloaded array property, BUT __set WILL NOT BE CALLED: __get will be called instead!
These two calls would NOT work if not using &__get and return &$something, but while they do work in this way, they NEVER call __set, but always call __get.
This is why I decided to return a reference
return &$something;
when $something is an array(), or when the overloaded property has no special setter method, and instead return a value
return $something;
when $something is NOT an array or has a special setter function.
In any case, this was quite tricky to understand properly for me! :)
Even after following the instructions from the valuable answers above, calling python from the command line would open the Microsoft Store and redirect me to a page to download the software.
I discovered this was caused by a 0 Ko python.exe file in AppData\Local\Microsoft\WindowsApps
which was taking precedence over my python executable in my PATH.
Removing this folder from my PATH solved it.
This works on keyup and paste, it colors the text red when you are almost up to the limit, truncates it when you go over and alerts you to edit your text, which you can do.
var t2= /* textarea reference*/
t2.onkeyup= t2.onpaste= function(e){
e= e || window.event;
var who= e.target || e.srcElement;
if(who){
var val= who.value, L= val.length;
if(L> 175){
who.style.color= 'red';
}
else who.style.color= ''
if(L> 180){
who.value= who.value.substring(0, 175);
alert('Your message is too long, please shorten it to 180 characters or less');
who.style.color= '';
}
}
}
@ and @@ in modules also work differently when a class extends or includes that module.
So given
module A
@a = 'module'
@@a = 'module'
def get1
@a
end
def get2
@@a
end
def set1(a)
@a = a
end
def set2(a)
@@a = a
end
def self.set1(a)
@a = a
end
def self.set2(a)
@@a = a
end
end
Then you get the outputs below shown as comments
class X
extend A
puts get1.inspect # nil
puts get2.inspect # "module"
@a = 'class'
@@a = 'class'
puts get1.inspect # "class"
puts get2.inspect # "module"
set1('set')
set2('set')
puts get1.inspect # "set"
puts get2.inspect # "set"
A.set1('sset')
A.set2('sset')
puts get1.inspect # "set"
puts get2.inspect # "sset"
end
class Y
include A
def doit
puts get1.inspect # nil
puts get2.inspect # "module"
@a = 'class'
@@a = 'class'
puts get1.inspect # "class"
puts get2.inspect # "class"
set1('set')
set2('set')
puts get1.inspect # "set"
puts get2.inspect # "set"
A.set1('sset')
A.set2('sset')
puts get1.inspect # "set"
puts get2.inspect # "sset"
end
end
Y.new.doit
So use @@ in modules for variables you want common to all their uses, and use @ in modules for variables you want separate for every use context.
The earth is an annoyingly irregular surface, so there is no simple formula to do this exactly. You have to live with an approximate model of the earth, and project your coordinates onto it. The model I typically see used for this is WGS 84. This is what GPS devices usually use to solve the exact same problem.
NOAA has some software you can download to help with this on their website.
I think you have not fonts folder in your root folder like where stay css folder.
Demo
And css folder is like
And fonts folder like
I hope it will work for you.
Thanks you.
You can use Character.toString(char)
. Note that this method simply returns a call to String.valueOf(char)
, which also works.
As others have noted, string concatenation works as a shortcut as well:
String s = "" + 's';
But this compiles down to:
String s = new StringBuilder().append("").append('s').toString();
which is less efficient because the StringBuilder
is backed by a char[]
(over-allocated by StringBuilder()
to 16
), only for that array to be defensively copied by the resulting String
.
String.valueOf(char)
"gets in the back door" by wrapping the char
in a single-element array and passing it to the package private constructor String(char[], boolean)
, which avoids the array copy.
User.FindFirst(ClaimTypes.NameIdentifier).Value
EDIT for constructor
Below code works:
public Controller(IHttpContextAccessor httpContextAccessor)
{
var userId = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value
}
Edit for RTM
You should register IHttpContextAccessor
:
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpContextAccessor();
}
The result of exit() function and die() function is allways same. But as explained in alias manual page (http://php.net/manual/en/aliases.php), it says that die() function calls exit function. I think it is hard coded like below:
function die($msg){
exit($msg);
}
This is not a performance issue for small, medium and large projects but if project has billions multiply billions multiply billions processes, this happens very important performance optimization state.
But very most of people don't thinks this is a problem, because if you have that much processes, you must think more problem than if a function is master or alias.
But, exact answer is that; allways master function is more faster than alias.
Finally; Alias manual page says that, you may no longer use die. It is only an alias, and it is deprecated.
It is usually a bad idea to use these kind of aliases, as they may be bound to obsolescence or renaming, which will lead to unportable script. This list is provided to help those who want to upgrade their old scripts to newer syntax.
Here's how to use a Jet OLEDB or Ace OLEDB Access DB:
using System.Data;
using System.Data.OleDb;
string myConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=C:\myPath\myFile.mdb;" +
"Persist Security Info=True;" +
"Jet OLEDB:Database Password=myPassword;";
try
{
// Open OleDb Connection
OleDbConnection myConnection = new OleDbConnection();
myConnection.ConnectionString = myConnectionString;
myConnection.Open();
// Execute Queries
OleDbCommand cmd = myConnection.CreateCommand();
cmd.CommandText = "SELECT * FROM `myTable`";
OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); // close conn after complete
// Load the result into a DataTable
DataTable myDataTable = new DataTable();
myDataTable.Load(reader);
}
catch (Exception ex)
{
Console.WriteLine("OLEDB Connection FAILED: " + ex.Message);
}
You can use either sbt or maven to compile spark programs. Simply add the spark as dependency to maven
<repository>
<id>Spark repository</id>
<url>http://www.sparkjava.com/nexus/content/repositories/spark/</url>
</repository>
And then the dependency:
<dependency>
<groupId>spark</groupId>
<artifactId>spark</artifactId>
<version>1.2.0</version>
</dependency>
In terms of running a file with spark commands: you can simply do this:
echo"
import org.apache.spark.sql.*
ssc = new SQLContext(sc)
ssc.sql("select * from mytable").collect
" > spark.input
Now run the commands script:
cat spark.input | spark-shell
If you open the references folder and locate system.data.entity, click the item, then check the runtime version number in the Properties explorer, you will see the sub version as well. Mine for instance shows v4.0.30319 with the Version property showing 4.0.0.0.
try this:
Dim ws as Worksheet
Set ws = Thisworkbook.Sheets("Sheet2")
With ws
.Range("E2").Formula = "=VLOOKUP(D2,Sheet1!$A:$C,1,0)"
End With
End Sub
This just the simplified version of what you want.
No need to use Application
if you will just output the answer in the Range("E2")
.
If you want to stick with your logic, declare the variables.
See below for example.
Sub Test()
Dim rng As Range
Dim ws1, ws2 As Worksheet
Dim MyStringVar1 As String
Set ws1 = ThisWorkbook.Sheets("Sheet1")
Set ws2 = ThisWorkbook.Sheets("Sheet2")
Set rng = ws2.Range("D2")
With ws2
On Error Resume Next 'add this because if value is not found, vlookup fails, you get 1004
MyStringVar1 = Application.WorksheetFunction.VLookup(rng, ws1.Range("A1:C65536").Value, 1, False)
On Error GoTo 0
If MyStringVar1 = "" Then MsgBox "Item not found" Else MsgBox MyStringVar1
End With
End Sub
Hope this get's you started.
$ mkdir -p "$BACKUP_DIR/$client/$year/$month/$day"
DO NOT have a wrapper that creates a new instance of HttpClient. If you do that, you will run out of sockets at runtime (even though you are disposing the HttpClient object).
If using MOQ, the correct way to do this is to add using Moq.Protected;
to your test and then write code like the following:
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("It worked!")
};
var mockHttpMessageHandler = new Mock<HttpMessageHandler>();
mockHttpMessageHandler
.Protected()
.Setup<Task<HttpResponseMessage>>(
"SendAsync",
ItExpr.IsAny<HttpRequestMessage>(),
ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(() => response);
var httpClient = new HttpClient(mockHttpMessageHandler.Object);
These are all great suggestions, but if you know location of text in another file use sed with ease. :r! sed -n '1,10 p' < input_file.txt
This will insert 10 lines in an already open file at the current position of the cursor.
The only way that a Class can be unloaded is if the Classloader used is garbage collected. This means, references to every single class and to the classloader itself need to go the way of the dodo.
One possible solution to your problem is to have a Classloader for every jar file, and a Classloader for each of the AppServers that delegates the actual loading of classes to specific Jar classloaders. That way, you can point to different versions of the jar file for every App server.
This is not trivial, though. The OSGi platform strives to do just this, as each bundle has a different classloader and dependencies are resolved by the platform. Maybe a good solution would be to take a look at it.
If you don't want to use OSGI, one possible implementation could be to use one instance of JarClassloader class for every JAR file.
And create a new, MultiClassloader class that extends Classloader. This class internally would have an array (or List) of JarClassloaders, and in the defineClass() method would iterate through all the internal classloaders until a definition can be found, or a NoClassDefFoundException is thrown. A couple of accessor methods can be provided to add new JarClassloaders to the class. There is several possible implementations on the net for a MultiClassLoader, so you might not even need to write your own.
If you instanciate a MultiClassloader for every connection to the server, in principle it is possible that every server uses a different version of the same class.
I've used the MultiClassloader idea in a project, where classes that contained user-defined scripts had to be loaded and unloaded from memory and it worked quite well.
I needed to read a huge ResultSet and update some records in the table. I tried to use chunks as suggested in Drew Noakes's answer.
Unfortunately after 50000 records I've got OutofMemoryException. The answer Entity framework large data set, out of memory exception explains, that
EF creates second copy of data which uses for change detection (so that it can persist changes to the database). EF holds this second set for the lifetime of the context and its this set thats running you out of memory.
The recommendation is to re-create your context for each batch.
So I've retrieved Minimal and Maximum values of the primary key- the tables have primary keys as auto incremental integers.Then I retrieved from the database chunks of records by opening context for each chunk. After processing the chunk context closes and releases the memory. It insures that memory usage is not growing.
Below is a snippet from my code:
public void ProcessContextByChunks ()
{
var tableName = "MyTable";
var startTime = DateTime.Now;
int i = 0;
var minMaxIds = GetMinMaxIds();
for (int fromKeyID= minMaxIds.From; fromKeyID <= minMaxIds.To; fromKeyID = fromKeyID+_chunkSize)
{
try
{
using (var context = InitContext())
{
var chunk = GetMyTableQuery(context).Where(r => (r.KeyID >= fromKeyID) && (r.KeyID < fromKeyID+ _chunkSize));
try
{
foreach (var row in chunk)
{
foundCount = UpdateRowIfNeeded(++i, row);
}
context.SaveChanges();
}
catch (Exception exc)
{
LogChunkException(i, exc);
}
}
}
catch (Exception exc)
{
LogChunkException(i, exc);
}
}
LogSummaryLine(tableName, i, foundCount, startTime);
}
private FromToRange<int> GetminMaxIds()
{
var minMaxIds = new FromToRange<int>();
using (var context = InitContext())
{
var allRows = GetMyTableQuery(context);
minMaxIds.From = allRows.Min(n => (int?)n.KeyID ?? 0);
minMaxIds.To = allRows.Max(n => (int?)n.KeyID ?? 0);
}
return minMaxIds;
}
private IQueryable<MyTable> GetMyTableQuery(MyEFContext context)
{
return context.MyTable;
}
private MyEFContext InitContext()
{
var context = new MyEFContext();
context.Database.Connection.ConnectionString = _connectionString;
//context.Database.Log = SqlLog;
return context;
}
FromToRange is a simple structure with From and To properties.
I think your code is trying to "divide by zero" or "divide by NaN". If you are aware of that and don't want it to bother you, then you can try:
import numpy as np
np.seterr(divide='ignore', invalid='ignore')
For more details see:
var distinctItems = items.GroupBy(x => x.Id).Select(y => y.First());
You may also try standard sql un-pivoting method by using a sequence of logic with the following code.. The following code has 3 steps:
remove any null combinations ( if exists, table expression can be fully avoided if there are strictly no null values in base table)
select *
from
(
select name, subject,
case subject
when 'Maths' then maths
when 'Science' then science
when 'English' then english
end as Marks
from studentmarks
Cross Join (values('Maths'),('Science'),('English')) AS Subjct(Subject)
)as D
where marks is not null;
I'll post a solution with a bit more elaboration, in addition to code, as the initial mistake and the subsequent ones that have been demonstrated in comments are common errors in this sort of string concatenation problem.
From the initial question, as has been adequately explained by @djechlin, we see that there is the need to print a new line after each line of your table has been completed. So, we need this statement:
System.out.println();
However, printing that immediately after the first print statement gives erroneous results. What gives?
1
2
...
n
This is a problem of scope. Notice that there are two loops for a reason -- one loop handles rows, while the other handles columns. Your inner loop, the "j" loop, iterates through each array element "j" for a given "i." Therefore, at the end of the j loop, you should have a single row. You can think of each iterate of this "j" loop as building the "columns" of your table. Since the inner loop builds our columns, we don't want to print our line there -- it would make a new line for each element!
Once you are out of the j loop, you need to terminate that row before moving on to the next "i" iterate. This is the correct place to handle a new line, because it is the "scope" of your table's rows, instead of your table's columns.
for(i=0;i<7;i++){
for(j=0;j<5;j++) {
System.out.print(twoDm[i][j]+" ");
}
System.out.println();
}
And you can see that this new line will hold true, even if you change the dimensions of your table by changing the end values of your "i" and "j" loops.
This is a prompt to create a bunch of object, such as sp_help_diagram (?), that do not exist.
This should have nothing to do with the owner of the db.
Here's my solution to the problem using MooTools which works in Firefox 3.6, Safari 4.0.4 and Internet Explorer 7:
var iframe_container = $('iframe_container_id');
var iframe_style = {
height: 300,
width: '100%'
};
if (!Browser.Engine.trident) {
// IE has hasLayout issues if iframe display is none, so don't use the loading class
iframe_container.addClass('loading');
iframe_style.display = 'none';
}
this.iframe = new IFrame({
frameBorder: 0,
src: "http://www.youriframeurl.com/",
styles: iframe_style,
events: {
'load': function() {
var innerDoc = (this.contentDocument) ? this.contentDocument : this.contentWindow.document;
var h = this.measure(function(){
return innerDoc.body.scrollHeight;
});
this.setStyles({
height: h.toInt(),
display: 'block'
});
if (!Browser.Engine.trident) {
iframe_container.removeClass('loading');
}
}
}
}).inject(iframe_container);
Style the "loading" class to show an Ajax loading graphic in the middle of the iframe container. Then for browsers other than Internet Explorer, it will display the full height IFRAME once the loading of its content is complete and remove the loading graphic.
\ef <function_name>
in psql. It will give the whole function with editable text.
The fastest way, which also consumes the least resource could be:
String s = "abc-def";
int p = s.indexOf('-');
if (p >= 0) {
String left = s.substring(0, p);
String right = s.substring(p + 1);
} else {
// s does not contain '-'
}
It depends on the kind of test double you want to interact with:
In other words, with mocking the only useful interactions with a collaborator are the ones that you provide. By default functions will return null, void methods do nothing.
From http://psoug.org/reference/roles.html, create a procedure on your database for your user to do it:
CREATE OR REPLACE PROCEDURE GRANT_SELECT(to_user in varchar2) AS
CURSOR ut_cur IS SELECT table_name FROM user_tables;
RetVal NUMBER;
sCursor INT;
sqlstr VARCHAR2(250);
BEGIN
FOR ut_rec IN ut_cur
LOOP
sqlstr := 'GRANT SELECT ON '|| ut_rec.table_name || ' TO ' || to_user;
sCursor := dbms_sql.open_cursor;
dbms_sql.parse(sCursor,sqlstr, dbms_sql.native);
RetVal := dbms_sql.execute(sCursor);
dbms_sql.close_cursor(sCursor);
END LOOP;
END grant_select;
Count all files and subfolders, windows style:
dir=/YOUR/PATH;f=$(find $dir -type f | wc -l); d=$(find $dir -mindepth 1 -type d | wc -l); echo "$f Files, $d Folders"
If you're using express@~3.0.0 change the line below from your example:
app.use(express.staticProvider(__dirname + '/public'));
to something like this:
app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));
I made it as described on express api page and it works like charm. With that setup you don't have to write additional code so it becomes easy enough to use for your micro production or testing.
Full code listed below:
var express = require('express');
var app = express.createServer();
app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));
app.get('/', function(req, res) {
res.render('index.html');
});
app.listen(8080, '127.0.0.1')
Used the answer above, but altered it for my needs.
I used the following function and imported to my REACT file where I needed to download the csv file.
I had a span
tag within my th
elements. Added comments to what most functions/methods do.
import { tableToCSV, downloadCSV } from './../Helpers/exportToCSV';
export function tableToCSV(){
let tableHeaders = Array.from(document.querySelectorAll('th'))
.map(item => {
// title = splits elem tags on '\n',
// then filter out blank "" that appears in array.
// ex ["Timestamp", "[Full time]", ""]
let title = item.innerText.split("\n").filter(str => (str !== 0)).join(" ")
return title
}).join(",")
const rows = Array.from(document.querySelectorAll('tr'))
.reduce((arr, currRow) => {
// if tr tag contains th tag.
// if null return array.
if (currRow.querySelector('th')) return arr
// concats individual cells into csv format row.
const cells = Array.from(currRow.querySelectorAll('td'))
.map(item => item.innerText)
.join(',')
return arr.concat([cells])
}, [])
return tableHeaders + '\n' + rows.join('\n')
}
export function downloadCSV(csv){
const csvFile = new Blob([csv], { type: 'text/csv' })
const downloadLink = document.createElement('a')
// sets the name for the download file
downloadLink.download = `CSV-${currentDateUSWritten()}.csv`
// sets the url to the window URL created from csv file above
downloadLink.href = window.URL.createObjectURL(csvFile)
// creates link, but does not display it.
downloadLink.style.display = 'none'
// add link to body so click function below works
document.body.appendChild(downloadLink)
downloadLink.click()
}
When user click export to csv it trigger the following function in react.
handleExport = (e) => {
e.preventDefault();
const csv = tableToCSV()
return downloadCSV(csv)
}
Example html table elems.
<table id="datatable">
<tbody>
<tr id="tableHeader" className="t-header">
<th>Timestamp
<span className="block">full time</span></th>
<th>current rate
<span className="block">alt view</span>
</th>
<th>Battery Voltage
<span className="block">current voltage
</span>
</th>
<th>Temperature 1
<span className="block">[C]</span>
</th>
<th>Temperature 2
<span className="block">[C]</span>
</th>
<th>Time & Date </th>
</tr>
</tbody>
<tbody>
{this.renderData()}
</tbody>
</table>
</div>
Unfortunately SQL Developer doesn't fully honour the set echo off
command that would (appear to) solve this in SQL*Plus.
The only workaround I've found for this is to save what you're doing as a script, e.g. test.sql
with:
set echo off
spool c:\test.csv
select /*csv*/ username, user_id, created from all_users;
spool off;
And then from SQL Developer, only have a call to that script:
@test.sql
And run that as a script (F5).
Saving as a script file shouldn't be much of a hardship anyway for anything other than an ad hoc query; and running that with @
instead of opening the script and running it directly is only a bit of a pain.
A bit of searching found the same solution on the SQL Developer forum, and the development team suggest it's intentional behaviour to mimic what SQL*Plus does; you need to run a script with @
there too in order to hide the query text.
I needed C++ implementation working on std::string. None of answers satisfied my needs, I needed simple two-function solution for encoding and decoding, but I was too lazy to write my own code, so I found this:
http://www.adp-gmbh.ch/cpp/common/base64.html
Credits for code go to René Nyffenegger.
Putting the code below in case the site goes down:
base64.cpp
/*
base64.cpp and base64.h
Copyright (C) 2004-2008 René Nyffenegger
This source code is provided 'as-is', without any express or implied
warranty. In no event will the author be held liable for any damages
arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this source code must not be misrepresented; you must not
claim that you wrote the original source code. If you use this source code
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original source code.
3. This notice may not be removed or altered from any source distribution.
René Nyffenegger [email protected]
*/
#include "base64.h"
#include <iostream>
static const std::string base64_chars =
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz"
"0123456789+/";
static inline bool is_base64(unsigned char c) {
return (isalnum(c) || (c == '+') || (c == '/'));
}
std::string base64_encode(unsigned char const* bytes_to_encode, unsigned int in_len) {
std::string ret;
int i = 0;
int j = 0;
unsigned char char_array_3[3];
unsigned char char_array_4[4];
while (in_len--) {
char_array_3[i++] = *(bytes_to_encode++);
if (i == 3) {
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for(i = 0; (i <4) ; i++)
ret += base64_chars[char_array_4[i]];
i = 0;
}
}
if (i)
{
for(j = i; j < 3; j++)
char_array_3[j] = '\0';
char_array_4[0] = (char_array_3[0] & 0xfc) >> 2;
char_array_4[1] = ((char_array_3[0] & 0x03) << 4) + ((char_array_3[1] & 0xf0) >> 4);
char_array_4[2] = ((char_array_3[1] & 0x0f) << 2) + ((char_array_3[2] & 0xc0) >> 6);
char_array_4[3] = char_array_3[2] & 0x3f;
for (j = 0; (j < i + 1); j++)
ret += base64_chars[char_array_4[j]];
while((i++ < 3))
ret += '=';
}
return ret;
}
std::string base64_decode(std::string const& encoded_string) {
int in_len = encoded_string.size();
int i = 0;
int j = 0;
int in_ = 0;
unsigned char char_array_4[4], char_array_3[3];
std::string ret;
while (in_len-- && ( encoded_string[in_] != '=') && is_base64(encoded_string[in_])) {
char_array_4[i++] = encoded_string[in_]; in_++;
if (i ==4) {
for (i = 0; i <4; i++)
char_array_4[i] = base64_chars.find(char_array_4[i]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (i = 0; (i < 3); i++)
ret += char_array_3[i];
i = 0;
}
}
if (i) {
for (j = i; j <4; j++)
char_array_4[j] = 0;
for (j = 0; j <4; j++)
char_array_4[j] = base64_chars.find(char_array_4[j]);
char_array_3[0] = (char_array_4[0] << 2) + ((char_array_4[1] & 0x30) >> 4);
char_array_3[1] = ((char_array_4[1] & 0xf) << 4) + ((char_array_4[2] & 0x3c) >> 2);
char_array_3[2] = ((char_array_4[2] & 0x3) << 6) + char_array_4[3];
for (j = 0; (j < i - 1); j++) ret += char_array_3[j];
}
return ret;
}
base64.h
#include <string>
std::string base64_encode(unsigned char const* , unsigned int len);
std::string base64_decode(std::string const& s);
Usage
const std::string s = "test";
std::string encoded = base64_encode(reinterpret_cast<const unsigned char*>(s.c_str()), s.length());
std::string decoded = base64_decode(encoded);
You usually use padding to add distance between a border and a content.However, background are spread on padding.
You can still do it with nested element.
html :
<div id="outter">
<div id="inner">
test
</div>
</div>
outter div :
border-style: ridge;
border-color: #567498;
border-spacing:10px;
min-width: 100px;
min-height: 100px;
float:left;
inner div :
width: 100px;
min-height: 100px;
margin: 10px;
background-image: -webkit-gradient(
linear,
left bottom,
left top,
color-stop(0, rgb(39,54,73)),
color-stop(1, rgb(30,42,54))
);
background-image: -moz-linear-gradient(
center bottom,
rgb(39,54,73) 0%,
rgb(30,42,54) 100%
);}
For dev work you can use (express 4) https://github.com/appsmatics/simple-httpserver.git
Apache HttpComponents also have an async http client now too:
/**
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpasyncclient</artifactId>
<version>4.0-beta4</version>
</dependency>
**/
import java.io.IOException;
import java.nio.CharBuffer;
import java.util.concurrent.Future;
import org.apache.http.HttpResponse;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.nio.IOControl;
import org.apache.http.nio.client.methods.AsyncCharConsumer;
import org.apache.http.nio.client.methods.HttpAsyncMethods;
import org.apache.http.protocol.HttpContext;
public class HttpTest {
public static void main(final String[] args) throws Exception {
final CloseableHttpAsyncClient httpclient = HttpAsyncClients
.createDefault();
httpclient.start();
try {
final Future<Boolean> future = httpclient.execute(
HttpAsyncMethods.createGet("http://www.google.com/"),
new MyResponseConsumer(), null);
final Boolean result = future.get();
if (result != null && result.booleanValue()) {
System.out.println("Request successfully executed");
} else {
System.out.println("Request failed");
}
System.out.println("Shutting down");
} finally {
httpclient.close();
}
System.out.println("Done");
}
static class MyResponseConsumer extends AsyncCharConsumer<Boolean> {
@Override
protected void onResponseReceived(final HttpResponse response) {
}
@Override
protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl)
throws IOException {
while (buf.hasRemaining()) {
System.out.print(buf.get());
}
}
@Override
protected void releaseResources() {
}
@Override
protected Boolean buildResult(final HttpContext context) {
return Boolean.TRUE;
}
}
}
Since none of these dealt with real world financial numbers in excel and word docs that I needed to find, here is my variation. It handles ints, floats, negative numbers, currency numbers (because it doesn't reply on split), and has the option to drop the decimal part and just return ints, or return everything.
It also handles Indian Laks number system where commas appear irregularly, not every 3 numbers apart.
It does not handle scientific notation or negative numbers put inside parentheses in budgets -- will appear positive.
It also does not extract dates. There are better ways for finding dates in strings.
import re
def find_numbers(string, ints=True):
numexp = re.compile(r'[-]?\d[\d,]*[\.]?[\d{2}]*') #optional - in front
numbers = numexp.findall(string)
numbers = [x.replace(',','') for x in numbers]
if ints is True:
return [int(x.replace(',','').split('.')[0]) for x in numbers]
else:
return numbers
Here is my attempt at validating JSON properties. I used @casey-foster 's approach, but added recursion for deeper validation. The third parameter in function is optional and only used for testing.
//compare json2 to json1
function isValidJson(json1, json2, showInConsole) {
if (!showInConsole)
showInConsole = false;
var aKeys = Object.keys(json1).sort();
var bKeys = Object.keys(json2).sort();
for (var i = 0; i < aKeys.length; i++) {
if (showInConsole)
console.log("---------" + JSON.stringify(aKeys[i]) + " " + JSON.stringify(bKeys[i]))
if (JSON.stringify(aKeys[i]) === JSON.stringify(bKeys[i])) {
if (typeof json1[aKeys[i]] === 'object'){ // contains another obj
if (showInConsole)
console.log("Entering " + JSON.stringify(aKeys[i]))
if (!isValidJson(json1[aKeys[i]], json2[bKeys[i]], showInConsole))
return false; // if recursive validation fails
if (showInConsole)
console.log("Leaving " + JSON.stringify(aKeys[i]))
}
} else {
console.warn("validation failed at " + aKeys[i]);
return false; // if attribute names dont mactch
}
}
return true;
}
Before the scanf put fflush(stdin);
to clear buffer.
I've had a similar requirement: I needed to inject a Spring-managed repository bean into my Person
entity class ("entity" as in "something with an identity", for example an JPA entity). A Person
instance has friends, and for this Person
instance to return its friends, it shall delegate to its repository and query for friends there.
@Entity
public class Person {
private static PersonRepository personRepository;
@Id
@GeneratedValue
private long id;
public static void setPersonRepository(PersonRepository personRepository){
this.personRepository = personRepository;
}
public Set<Person> getFriends(){
return personRepository.getFriends(id);
}
...
}
.
@Repository
public class PersonRepository {
public Person get Person(long id) {
// do database-related stuff
}
public Set<Person> getFriends(long id) {
// do database-related stuff
}
...
}
So how did I inject that PersonRepository
singleton into the static field of the Person
class?
I created a @Configuration
, which gets picked up at Spring ApplicationContext construction time. This @Configuration
gets injected with all those beans that I need to inject as static fields into other classes. Then with a @PostConstruct
annotation, I catch a hook to do all static field injection logic.
@Configuration
public class StaticFieldInjectionConfiguration {
@Inject
private PersonRepository personRepository;
@PostConstruct
private void init() {
Person.setPersonRepository(personRepository);
}
}
This problem is because of your https that means SSL certification. Try on Localhost.
For Chrome:::::::::::::::::
Ctrl+P => Select the Click On More Settings => In the Options Menu Select the Background and Graphics Options
:) Will Work
**Why wasn't it working!Reason:**Chrome Browser had Fonts And Headers Enabled
General Case:::::
When you dont need to turn on this option manually.In body in CSS type:::::
-webkit-print-color-adjust:exact !important;
:)Works
To resolve this issue, while checking out the code from git
itself, u need to give the command like below:
git checkout -b branchname origin/branchname
Here, by default we are setting the upstream branch
, so you will not be facing the mentioned issue.
I am also new to MVC and I received the same error and found that it is not passing proper routeValues
in the Index
view or whatever view is present to view the all data.
It was as below
<td>
@Html.ActionLink("Edit", "Edit", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
I changed it to the as show below and started to work properly.
<td>
@Html.ActionLink("Edit", "Edit", new { EmployeeID=item.EmployeeID }) |
@Html.ActionLink("Details", "Details", new { /* id=item.PrimaryKey */ }) |
@Html.ActionLink("Delete", "Delete", new { /* id=item.PrimaryKey */ })
</td>
Basically this error can also come because of improper navigation also.
My solution.
Before doing anything check:
if (!$this->entityManager->isOpen()) {
$this->entityManager = $this->entityManager->create(
$this->entityManager->getConnection(),
$this->entityManager->getConfiguration()
);
}
All entities will be saved. But it is handy for particular class or some cases. If you have some services with injected entitymanager, it still be closed.
Done.
Try this
self.tables.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 10.0f)];
It's not smart enough to realize it's still a "vector" in math terms.
Say rather that it's smart enough to recognize a difference in dimensionality. :-)
I think the simplest thing you can do is select that row positionally using iloc
, which gives you a Series with the columns as the new index and the values as the values:
>>> df = pd.DataFrame([list(range(5))], columns=["a{}".format(i) for i in range(5)])
>>> df
a0 a1 a2 a3 a4
0 0 1 2 3 4
>>> df.iloc[0]
a0 0
a1 1
a2 2
a3 3
a4 4
Name: 0, dtype: int64
>>> type(_)
<class 'pandas.core.series.Series'>
Without using inline CSS you could set the text size of all your buttons using:
input[type="submit"], input[type="button"] {
font-size: 14px;
}
The syntax you wrote as first is not valid. You can achieve something using the follow:
var map = {"aaa": "rrr", "bbb": "ppp" /* etc */ };
iOS 11
Setting a custom button using constraint:
let buttonWidth = CGFloat(30)
let buttonHeight = CGFloat(30)
let button = UIButton(type: .custom)
button.setImage(UIImage(named: "img name"), for: .normal)
button.addTarget(self, action: #selector(buttonTapped(sender:)), for: .touchUpInside)
button.widthAnchor.constraint(equalToConstant: buttonWidth).isActive = true
button.heightAnchor.constraint(equalToConstant: buttonHeight).isActive = true
self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: button)
It is possible to parse dynamic values in a couple of way.
Interpolation with double-curly braces:
ng-style="{'background-image':'url({{myBackgroundUrl}})'}"
String concatenation:
ng-style="{'background-image': 'url(' + myBackgroundUrl + ')'}"
ES6 template literals:
ng-style="{'background-image': `url(${myBackgroundUrl})`}"
docker-compose
and multiple Dockerfile
in separate directoriesDon't rename your
Dockerfile
toDockerfile.db
orDockerfile.web
, it may not be supported by your IDE and you will lose syntax highlighting.
As Kingsley Uchnor said, you can have multiple Dockerfile
, one per directory, which represent something you want to build.
I like to have a docker
folder which holds each applications and their configuration. Here's an example project folder hierarchy for a web application that has a database.
docker-compose.yml
docker
+-- web
¦  +-- Dockerfile
+-- db
  +-- Dockerfile
docker-compose.yml
example:
version: '3'
services:
web:
# will build ./docker/web/Dockerfile
build: ./docker/web
ports:
- "5000:5000"
volumes:
- .:/code
db:
# will build ./docker/db/Dockerfile
build: ./docker/db
ports:
- "3306:3306"
redis:
# will use docker hub's redis prebuilt image from here:
# https://hub.docker.com/_/redis/
image: "redis:alpine"
docker-compose
command line usage example:
# The following command will create and start all containers in the background
# using docker-compose.yml from current directory
docker-compose up -d
# get help
docker-compose --help
You can still use the above solution and place your Dockerfile
in a directory such as docker/web/Dockerfile
, all you need is to set the build context
in your docker-compose.yml
like this:
version: '3'
services:
web:
build:
context: .
dockerfile: ./docker/web/Dockerfile
ports:
- "5000:5000"
volumes:
- .:/code
This way, you'll be able to have things like this:
config-on-root.ini
docker-compose.yml
docker
+-- web
  +-- Dockerfile
  +-- some-other-config.ini
and a ./docker/web/Dockerfile
like this:
FROM alpine:latest
COPY config-on-root.ini /
COPY docker/web/some-other-config.ini /
Here are some quick commands from tldr docker-compose. Make sure you refer to official documentation for more details.
$(document).ready(function() {
$('#btnSun').click(function(){
myFunction();
});
$.fn.myFunction = function() {
alert('hi');
};
});
Put ' ; ' after function definition...
Are you committing the cell before pressing the button (pressing Enter)? The contents of the cell must be stored before it can be used to name a sheet.
A better way to do this is to pop up a dialog box and get the name you wish to use.
You can use strip() or split() to control the spaces values as in the following:
words = " first second "
# Remove end spaces
def remove_end_spaces(string):
return "".join(string.rstrip())
# Remove the first and end spaces
def remove_first_end_spaces(string):
return "".join(string.rstrip().lstrip())
# Remove all spaces
def remove_all_spaces(string):
return "".join(string.split())
# Show results
print(words)
print(remove_end_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))
I use something like this
>>> import datetime
>>> regex = datetime.datetime.strptime
>>>
>>> # TEST
>>> assert regex('2020-08-03', '%Y-%m-%d')
>>>
>>> assert regex('2020-08', '%Y-%m-%d')
ValueError: time data '2020-08' does not match format '%Y-%m-%d'
>>> assert regex('08/03/20', '%m/%d/%y')
>>>
>>> assert regex('08-03-2020', '%m/%d/%y')
ValueError: time data '08-03-2020' does not match format '%m/%d/%y'
Nowadays, you can just use
$("#password").prop("type", "text");
But of course, you should really just do this
<input type="password" placeholder="Password" />
in all but IE. There are placeholder shims out there to mimic that functionality in IE as well.
std::copy
cannot be used to insert into an empty container. To do that, you need to use an insert_iterator like so:
std::set<double> input;
input.insert(5);
input.insert(6);
std::vector<double> output;
std::copy(input.begin(), input.end(), inserter(output, output.begin()));
As mentioned above by others,
Scrum is an iterative and incremental agile software development method for managing software projects and product or application development. So Scrum is in fact a type of Agile approach which is used widely in software developments.
So, Scrum is a specific flavor of Agile, specifically it is referred to as an agile project management framework.
Also Scrum has mainly two roles inside it, which are: 1. Main/Core Role 2. Ancillary Role
Main/Core role: It consists of mainly three roles: a). Scrum Master, b). Product Owner, c). Development Team.
Ancillary Role: The ancillary roles in Scrum teams are those with no formal role and infrequent involvement in the Scrum procession but nonetheless, they must be taken into account. viz. Stakeholders, Managers.
Scrum Master:- There are 6 types of meetings in scrum:
Let me know if any one need more inputs on this.
Just little elaboration of regex for search a directory and file
Find a directroy with name like book
find . -name "*book*" -type d
Find a file with name like book word
find . -name "*book*" -type f
Dynamic programming problems can be solved using either bottom-up or top-down approaches.
Generally, the bottom-up approach uses the tabulation technique, while the top-down approach uses the recursion (with memorization) technique.
But you can also have bottom-up and top-down approaches using recursion as shown below.
Bottom-Up: Start with the base condition and pass the value calculated until now recursively. Generally, these are tail recursions.
int n = 5;
fibBottomUp(1, 1, 2, n);
private int fibBottomUp(int i, int j, int count, int n) {
if (count > n) return 1;
if (count == n) return i + j;
return fibBottomUp(j, i + j, count + 1, n);
}
Top-Down: Start with the final condition and recursively get the result of its sub-problems.
int n = 5;
fibTopDown(n);
private int fibTopDown(int n) {
if (n <= 1) return 1;
return fibTopDown(n - 1) + fibTopDown(n - 2);
}
I use this code to post HttpRequests.
/// <summary>
/// Post this message.
/// </summary>
/// <param name="url">URL of the document.</param>
/// <param name="bytes">The bytes.</param>
public T Post<T>(string url, byte[] bytes)
{
T item;
var request = WritePost(url, bytes);
using (var response = request.GetResponse() as HttpWebResponse)
{
item = DeserializeResponse<T>(response);
response.Close();
}
return item;
}
/// <summary>
/// Writes the post.
/// </summary>
/// <param name="url">The URL.</param>
/// <param name="bytes">The bytes.</param>
/// <returns></returns>
private static HttpWebRequest WritePost(string url, byte[] bytes)
{
ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
Stream stream = null;
try
{
request.Headers.Clear();
request.PreAuthenticate = true;
request.Connection = null;
request.Expect = null;
request.KeepAlive = false;
request.ContentLength = bytes.Length;
request.Timeout = -1;
request.Method = "POST";
stream = request.GetRequestStream();
stream.Write(bytes, 0, bytes.Length);
}
catch (Exception e)
{
GetErrorResponse(url, e);
}
finally
{
if (stream != null)
{
stream.Flush();
stream.Close();
}
}
return request;
}
In regards to your code, try it without the content.Type (request.ContentType = "application/x-www-form-urlencoded";
)
update
I believe the problem lies with how you are trying to retrieve the value. When you do a POST and send bytes via the Stream, they will not be passed into the action as a parameter. You'll need to retrieve the bytes via the stream on the server.
On the server, try getting the bytes from stream. The following code is what I use.
/// <summary> Gets the body. </summary>
/// <returns> The body. </returns>
protected byte[] GetBytes()
{
byte[] bytes;
using (var binaryReader = new BinaryReader(Request.InputStream))
{
bytes = binaryReader.ReadBytes(Request.ContentLength);
}
return bytes;
}
I think this script is what exactly you need
var t = document.getElementById('myTable');
var r =document.createElement('TR');
t.tBodies[0].appendChild(r)
WordPress have the function get_metadata this get all meta of object (Post, term, user...)
Just use
get_metadata( 'post', 15 );
I prefer slightly more "literate" code. I'm much more likely to do something like this in practice:
bool shouldContinue = true;
while (shouldContinue)
{
// ...
shouldContinue = CheckSomething();
}
Yes, you need the full path.
log = open(os.path.join(root, f), 'r')
Is the quick fix. As the comment pointed out, os.walk
decends into subdirs so you do need to use the current directory root rather than indir
as the base for the path join.
AFAIK there isn't a built-in mechanism in Eclipse for this.
The closest you can get is to create a wrapper that prompts you for these values and invokes the (hardcoded) main. You then get you execution history as long as you don't clear terminated processes. Two variations on this are either to use JUNit, or to use injection or parameter so that your wrapper always connects to the correct class for its main.
In my case the instance of program was already running in background. I just stop the running instance and program built successfully.
@HostListener('window:click', ['$event']) onClick(event){ }
check this below link to detect CapsLock on click, keyup and keydown on current window. No need to add any event in html doc
You should create a method within your fragment that accepts the type of object you wish to pass into it. In this case i named it "setObject" (creative huh? :) ) That method can then perform whatever action you need with that object.
MyFragment fragment;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
if (getSupportFragmentManager().findFragmentById(android.R.id.content) == null) {
fragment = new MyFragment();
getSupportFragmentManager().beginTransaction().add(android.R.id.content, detailsFragment)
.commit();
} else {
fragment = (MyFragment) getSupportFragmentManager().findFragmentById(
android.R.id.content);
}
fragment.setObject(yourObject); //create a method like this in your class "MyFragment"
}
Note that i'm using the support library and calls to getSupportFragmentManager() might be just getFragmentManager() for you depending on what you're working with
Mac & Big Sur. Python 3.8.6 w/vs code. While it should have been included in diagrams package, I had to manually install graphviz.
(mymltools) ? infrastructure git:(master) pip list
Package Version
---------- -------
diagrams 0.18.0
graphviz 0.13.2
Jinja2 2.11.2
MarkupSafe 1.1.1
pip 20.3.2
setuptools 51.0.0
wheel 0.36.2
Running diagrams failed. Then manually ran
pipenv install graphviz
Works like a charm.
To resolve, Update Spring Frame Work to 3.2.0 or above!
It's an array of the parameters/arguments (hence args) that you send to the program. For example ping 172.16.0.1 -t -4
These arguments are passed to the program as an array of strings.
string[] args
// Array of Strings containing arguments.
I couldn't get The DataRowAttribute
to work in Visual Studio 2015, and this is what I ended up with:
[TestClass]
public class Tests
{
private Foo _toTest;
[TestInitialize]
public void Setup()
{
this._toTest = new Foo();
}
[TestMethod]
public void ATest()
{
this.Perform_ATest(1, 1, 2);
this.Setup();
this.Perform_ATest(100, 200, 300);
this.Setup();
this.Perform_ATest(817001, 212, 817213);
this.Setup();
}
private void Perform_ATest(int a, int b, int expected)
{
// Obviously this would be way more complex...
Assert.IsTrue(this._toTest.Add(a,b) == expected);
}
}
public class Foo
{
public int Add(int a, int b)
{
return a + b;
}
}
The real solution here is to just use NUnit (unless you're stuck in MSTest like I am in this particular instance).
You can add an extra exit command after the return statement/command so that it works for both, executing the script from the command line and sourcing from the terminal.
Example exit code in the script:
if [ $# -lt 2 ]; then
echo "Needs at least two arguments"
return 1 2>/dev/null
exit 1
fi
The line with the exit
command will not be called when you source the script after the return
command.
When you execute the script, return
command gives an error. So, we suppress the error message by forwarding it to /dev/null
.
$this->db->select('overal_points');
$this->db->where('point_publish', 1);
$this->db->order_by('overal_points', 'desc');
$query = $this->db->get('company', 4)->result();
When we create a customer directive, the scope of the directive could be in Isolated scope, It means the directive does not share a scope with the controller; both directive and controller have their own scope. However, data can be passed to the directive scope in three possible ways.
@
string literal, pass string value, one way binding.=
string literal, pass object, 2 ways binding.&
string literal, calls external function, can pass data from directive to controller.So, I would like to explain the scenario where I had to make use of this solution. Basically, I wanted to undo the background-color attribute set by another CSS. The expected end result was to make it look as though the original CSS had never applied the background-color attribute . Setting background-color:transparent;
made that effective.
Add the following 6 lines to any class to make it "Singleton".
class MySingleton
{
private constructor(){ /* ... */}
private static _instance: MySingleton;
public static getInstance(): MySingleton
{
return this._instance || (this._instance = new this());
};
}
var test = MySingleton.getInstance(); // will create the first instance
var test2 = MySingleton.getInstance(); // will return the first instance
alert(test === test2); // true
[Edit]: Use Alex answer if you prefer to get the instance through a property rather a method.
import cv2
img=cv2.imread('my_test.jpg')
img_info = img.shape
print("Image height :",img_info[0])
print("Image Width :", img_info[1])
print("Image channels :", img_info[2])
My_test.jpg link ---> https://i.pinimg.com/originals/8b/ca/f5/8bcaf5e60433070b3210431e9d2a9cd9.jpg
remove float: left
from image css and add text-align: center
property in parent element body
<!DOCTYPE html>_x000D_
<html>_x000D_
<body style="text-align: center;">_x000D_
_x000D_
<img_x000D_
src="http://icons.iconarchive.com/icons/rokey/popo-emotions/128/big-smile-icon.png"_x000D_
width="42" height="42"_x000D_
align="middle"_x000D_
style="_x000D_
_x000D_
display: block;_x000D_
margin-left: auto;_x000D_
margin-right: auto;_x000D_
z-index: 1;"_x000D_
>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
No they do not exist in C# 3.0 and will not be added in 4.0. It's on the list of feature wants for C# so it may be added at a future date.
At this point the best you can do is GetXXX style extension methods.
This should work !!!
file_name
= Name of the file you want to split.
10000
= Number of rows each split file would contain
file_part_
= Prefix of split file name (file_part_0,file_part_1,file_part_2..etc goes on)
split -d -l 10000 file_name.csv file_part_
In summary :
<input type="submit">
<button type="submit"> Submit </button>
Both by default will visually draw a button that performs the same action (submit the form).
However, it is recommended to use <button type="submit">
because it has better semantics, better ARIA support and it is easier to style.
There are some quirks to be aware of here.
HTMLIFrameElement.contentWindow
is probably the easier way, but it's not quite a standard property and some browsers don't support it, mostly older ones. This is because the DOM Level 1 HTML standard has nothing to say about the window
object.
You can also try HTMLIFrameElement.contentDocument.defaultView
, which a couple of older browsers allow but IE doesn't. Even so, the standard doesn't explicitly say that you get the window
object back, for the same reason as (1), but you can pick up a few extra browser versions here if you care.
window.frames['name']
returning the window is the oldest and hence most reliable interface. But you then have to use a name="..."
attribute to be able to get a frame by name, which is slightly ugly/deprecated/transitional. (id="..."
would be better but IE doesn't like that.)
window.frames[number]
is also very reliable, but knowing the right index is the trick. You can get away with this eg. if you know you only have the one iframe on the page.
It is entirely possible the child iframe hasn't loaded yet, or something else went wrong to make it inaccessible. You may find it easier to reverse the flow of communications: that is, have the child iframe notify its window.parent
script when it has finished loaded and is ready to be called back. By passing one of its own objects (eg. a callback function) to the parent script, that parent can then communicate directly with the script in the iframe without having to worry about what HTMLIFrameElement it is associated with.
The worse thing is not having a decent stack trace which you simply cannot generate using an HttpInterceptor
(hope to stand corrected). All you get is a load of zone and rxjs useless bloat, and not the line or class that generated the error.
To do this you will need to generate a stack in an extended HttpClient
, so its not advisable to do this in a production environment.
/**
* Extended HttpClient that generates a stack trace on error when not in a production build.
*/
@Injectable()
export class TraceHttpClient extends HttpClient {
constructor(handler: HttpHandler) {
super(handler);
}
request(...args: [any]): Observable<any> {
const stack = environment.production ? null : Error().stack;
return super.request(...args).pipe(
catchError((err) => {
// tslint:disable-next-line:no-console
if (stack) console.error('HTTP Client error stack\n', stack);
return throwError(err);
})
);
}
}
short recommendation: don't use isReachable(), call the system ping, as proposed in some of the answers above.
long explanation:
You are not using Oracle, so you should be using the modulus operator:
SELECT * FROM Orders where OrderID % 2 = 0;
The MOD()
function exists in Oracle, which is the source of your confusion.
Have a look at this SO question which discusses your problem.
i would suggest the following way:
@PropertySource(ignoreResourceNotFound = true, value = "classpath:otherprops.properties")
@Controller
public class ClassA {
@Value("${myName}")
private String name;
@RequestMapping(value = "/xyz")
@ResponseBody
public void getName(){
System.out.println(name);
}
}
Here your new properties file name is "otherprops.properties" and the property name is "myName". This is the simplest implementation to access properties file in spring boot version 1.5.8.
The solution to the problem is:
Find the .gitconfig file
[user] name = 1wQasdTeedFrsweXcs234saS56Scxs5423 email = [email protected] [credential] helper = osxkeychain [url ""] insteadOf = git:// [url "https://"] [url "https://"] insteadOf = git://
there would be a blank url="" replace it with url="https://"
[user]
name = 1wQasdTeedFrsweXcs234saS56Scxs5423
email = [email protected]
[credential]
helper = osxkeychain
[url "https://"]
insteadOf = git://
[url "https://"]
[url "https://"]
insteadOf = git://
This will work :)
Happy Bower-ing
Bootstrap leverages HTML5 standards in order to access DOM element attributes easily within javascript.
Forms a class of attributes, called custom data attributes, that allow proprietary information to be exchanged between the HTML and its DOM representation that may be used by scripts. All such custom data are available via the HTMLElement interface of the element the attribute is set on. The HTMLElement.dataset property gives access to them.
If you're using display:table-row
etc., then you need proper markup, which includes a containing table. Without it your original question basically provides the equivalent bad markup of:
<tr style="width:100%">
<td>Type</td>
<td style="float:right">Name</td>
</tr>
Where's the table in the above? You can't just have a row out of nowhere (tr must be contained in either table
, thead
, tbody
, etc.)
Instead, add an outer element with display:table
, put the 100% width on the containing element. The two inside cells will automatically go 50/50 and align the text right on the second cell. Forget floats
with table elements. It'll cause so many headaches.
markup:
<div class="view-table">
<div class="view-row">
<div class="view-type">Type</div>
<div class="view-name">Name</div>
</div>
</div>
CSS:
.view-table
{
display:table;
width:100%;
}
.view-row,
{
display:table-row;
}
.view-row > div
{
display: table-cell;
}
.view-name
{
text-align:right;
}
You can use the focusout event to detect keyboard dismissal. It's like blur, but bubbles. It will fire when the keyboard closes (but also in other cases, of course). In Safari and Chrome the event can only be registered with addEventListener, not with legacy methods. Here is an example I used to restore a Phonegap app after keyboard dismissal.
document.addEventListener('focusout', function(e) {window.scrollTo(0, 0)});
Without this snippet, the app container stayed in the up-scrolled position until page refresh.
This is the complex (curly) syntax for string interpolation. From the manual:
Complex (curly) syntax
This isn't called complex because the syntax is complex, but because it allows for the use of complex expressions.
Any scalar variable, array element or object property with a string representation can be included via this syntax. Simply write the expression the same way as it would appear outside the string, and then wrap it in
{
and}
. Since{
can not be escaped, this syntax will only be recognised when the$
immediately follows the{
. Use{\$
to get a literal{$
. Some examples to make it clear:<?php // Show all errors error_reporting(E_ALL); $great = 'fantastic'; // Won't work, outputs: This is { fantastic} echo "This is { $great}"; // Works, outputs: This is fantastic echo "This is {$great}"; echo "This is ${great}"; // Works echo "This square is {$square->width}00 centimeters broad."; // Works, quoted keys only work using the curly brace syntax echo "This works: {$arr['key']}"; // Works echo "This works: {$arr[4][3]}"; // This is wrong for the same reason as $foo[bar] is wrong outside a string. // In other words, it will still work, but only because PHP first looks for a // constant named foo; an error of level E_NOTICE (undefined constant) will be // thrown. echo "This is wrong: {$arr[foo][3]}"; // Works. When using multi-dimensional arrays, always use braces around arrays // when inside of strings echo "This works: {$arr['foo'][3]}"; // Works. echo "This works: " . $arr['foo'][3]; echo "This works too: {$obj->values[3]->name}"; echo "This is the value of the var named $name: {${$name}}"; echo "This is the value of the var named by the return value of getName(): {${getName()}}"; echo "This is the value of the var named by the return value of \$object->getName(): {${$object->getName()}}"; // Won't work, outputs: This is the return value of getName(): {getName()} echo "This is the return value of getName(): {getName()}"; ?>
Often, this syntax is unnecessary. For example, this:
$a = 'abcd';
$out = "$a $a"; // "abcd abcd";
behaves exactly the same as this:
$out = "{$a} {$a}"; // same
So the curly braces are unnecessary. But this:
$out = "$aefgh";
will, depending on your error level, either not work or produce an error because there's no variable named $aefgh
, so you need to do:
$out = "${a}efgh"; // or
$out = "{$a}efgh";
As an alternative to the other answers, django-devserver outputs SQL to the console.
i used using this code
<sourceDirectory>src_controller</sourceDirectory>
<testSourceDirectory>src_test</testSourceDirectory>
to my pom.xml, just ensure that testng file in specific there
<suiteXmlFile>/Users/mac/xxx/xxx/xx.xxxx.xx/xxx.restassured.xx/testng.xml</suiteXmlFile>
If your url looks something like this:
somesite.com/something/123
Where '123' is a parameter named 'id' (url like /something/:id), try with:
this.$route.params.id
Putting the javascript at the top would seem neater, but functionally, its better to go after the HTML. That way, your javascript won't run and try to reference HTML elements before they are loaded. This sort of problem often only becomes apparent when you load the page over an actual internet connection, especially a slow one.
You could also try to dynamically load the javascript by adding a header element from other javascript code, although that only makes sense if you aren't using all of the code all the time.
As well as \singlespacing
mentioned previously to reduce the height of the table, a useful way to reduce the width of the table is to add \tabcolsep=0.11cm
before the \begin{tabular}
command and take out all the vertical lines between columns. It's amazing how much space is used up between the columns of text. You could reduce the font size to something smaller than \small
but I normally wouldn't use anything smaller than \footnotesize
.
You are most likely not using the correct credentials for the MySQL server. You also need to ensure the user you are connecting as has the correct privileges to view databases/tables, and that you can connect from your current location in network topographic terms (localhost).
For the benefit of anyone reading this later, you need to link against it as Fred said:
gcc fib.c -lm -o fibo
One good way to find out what library you need to link is by checking the man page if one exists. For example, man pow
and man floor
will both tell you:
Link with -lm
.
An explanation for linking math library in C programming - Linking in C
If you have a ConstraintLayout
with some size, and a child View
with some smaller size, you can achieve centering by constraining the child's two edges to the same two edges of the parent. That is, you can write:
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
or
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
Because the view is smaller, these constraints are impossible. But ConstraintLayout
will do the best it can, and each constraint will "pull" at the child view equally, thereby centering it.
This concept works with any target view, not just the parent.
Below is XML that achieves your desired UI with no nesting of views and no Guideline
s (though guidelines are not inherently evil).
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#eee">
<TextView
android:id="@+id/title1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:gravity="center"
android:textColor="#777"
android:textSize="22sp"
android:text="10"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="@+id/divider1"
app:layout_constraintBottom_toBottomOf="parent"/>
<TextView
android:id="@+id/label1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#777"
android:textSize="12sp"
android:text="Streak"
app:layout_constraintTop_toBottomOf="@+id/title1"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toLeftOf="@+id/divider1"/>
<View
android:id="@+id/divider1"
android:layout_width="1dp"
android:layout_height="55dp"
android:layout_marginTop="12dp"
android:layout_marginBottom="12dp"
android:background="#ccc"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toRightOf="@+id/title1"
app:layout_constraintRight_toLeftOf="@+id/title2"
app:layout_constraintBottom_toBottomOf="parent"/>
<TextView
android:id="@+id/title2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:gravity="center"
android:textColor="#777"
android:textSize="22sp"
android:text="243"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toRightOf="@+id/divider1"
app:layout_constraintRight_toLeftOf="@+id/divider2"
app:layout_constraintBottom_toBottomOf="parent"/>
<TextView
android:id="@+id/label2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#777"
android:textSize="12sp"
android:text="Calories Burned"
app:layout_constraintTop_toBottomOf="@+id/title2"
app:layout_constraintLeft_toRightOf="@+id/divider1"
app:layout_constraintRight_toLeftOf="@+id/divider2"/>
<View
android:id="@+id/divider2"
android:layout_width="1dp"
android:layout_height="55dp"
android:layout_marginTop="12dp"
android:layout_marginBottom="12dp"
android:background="#ccc"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toRightOf="@+id/title2"
app:layout_constraintRight_toLeftOf="@+id/title3"
app:layout_constraintBottom_toBottomOf="parent"/>
<TextView
android:id="@+id/title3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginBottom="12dp"
android:gravity="center"
android:textColor="#777"
android:textSize="22sp"
android:text="3200"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintLeft_toRightOf="@+id/divider2"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintBottom_toBottomOf="parent"/>
<TextView
android:id="@+id/label3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:gravity="center"
android:textColor="#777"
android:textSize="12sp"
android:text="Steps"
app:layout_constraintTop_toBottomOf="@+id/title3"
app:layout_constraintLeft_toRightOf="@+id/divider2"
app:layout_constraintRight_toRightOf="parent"/>
</android.support.constraint.ConstraintLayout>
Although the answers proposing to use ArrayList do make sense in most scenario, the actual question of relative performance has not really been answered.
There are a few things you can do with an array:
Although get and set operations are somewhat slower on an ArrayList (resp. 1 and 3 nanosecond per call on my machine), there is very little overhead of using an ArrayList vs. an array for any non-intensive use. There are however a few things to keep in mind:
list.add(...)
) are costly and one should try to set the initial capacity at an adequate level when possible (note that the same issue arises when using an array)Here are the results I measured for those three operations using the jmh benchmarking library (times in nanoseconds) with JDK 7 on a standard x86 desktop machine. Note that ArrayList are never resized in the tests to make sure results are comparable. Benchmark code available here.
I ran 4 tests, executing the following statements:
Integer[] array = new Integer[1];
List<Integer> list = new ArrayList<> (1);
Integer[] array = new Integer[10000];
List<Integer> list = new ArrayList<> (10000);
Results (in nanoseconds per call, 95% confidence):
a.p.g.a.ArrayVsList.CreateArray1 [10.933, 11.097]
a.p.g.a.ArrayVsList.CreateList1 [10.799, 11.046]
a.p.g.a.ArrayVsList.CreateArray10000 [394.899, 404.034]
a.p.g.a.ArrayVsList.CreateList10000 [396.706, 401.266]
Conclusion: no noticeable difference.
I ran 2 tests, executing the following statements:
return list.get(0);
return array[0];
Results (in nanoseconds per call, 95% confidence):
a.p.g.a.ArrayVsList.getArray [2.958, 2.984]
a.p.g.a.ArrayVsList.getList [3.841, 3.874]
Conclusion: getting from an array is about 25% faster than getting from an ArrayList, although the difference is only on the order of one nanosecond.
I ran 2 tests, executing the following statements:
list.set(0, value);
array[0] = value;
Results (in nanoseconds per call):
a.p.g.a.ArrayVsList.setArray [4.201, 4.236]
a.p.g.a.ArrayVsList.setList [6.783, 6.877]
Conclusion: set operations on arrays are about 40% faster than on lists, but, as for get, each set operation takes a few nanoseconds - so for the difference to reach 1 second, one would need to set items in the list/array hundreds of millions of times!
ArrayList's copy constructor delegates to Arrays.copyOf
so performance is identical to array copy (copying an array via clone
, Arrays.copyOf
or System.arrayCopy
makes no material difference performance-wise).
Below code absolutely worked for me to update File extension.
Ex: abc.pdf to abc.txt
Filepath = "Pls mention your Filepath"
Set objFso = CreateObject("Scripting.FileSystemObject")
'' Below line of code is to get the object for Folder where list of files are located
Set objFolder = objFso.GetFolder(Filepath)
'' Below line of code used to get the collection object to hold list of files located in the Filepath.
Set FileCollection = objFolder.Files
For Each file In FileCollection
WScript.Echo "File name ->" + file.Name
''Instr used to Return the position of the first occurrence of "." within the File name
s = InStr(1, file.Name, ".",1)
WScript.Echo s
WScript.Echo "Extn --> " + Mid(file.Name, s, Len(file.Name))
'Left(file.Name,s-1) = Used to fetch the file name without extension
' Move method is used to move the file in the Desitnation folder you mentioned
file.Move(Filepath & Left(file.Name,s-1)&".txt")
Next
Here are two other software packages which can be used for DNS caching on Linux:
After configuring the software for DNS forwarding and caching, you then set the system's DNS resolver to 127.0.0.1 in /etc/resolv.conf.
If your system is using NetworkManager you can either try using the dns=dnsmasq
option in /etc/NetworkManager/NetworkManager.conf
or you can change your connection settings to Automatic (Address Only) and then use a script in the /etc/NetworkManager/dispatcher.d
directory to get the DHCP nameserver, set it as the DNS forwarding server in your DNS cache software and then trigger a configuration reload.
So, say you have your View with PartialView, which have to be updated by button click:
<div class="target">
@{ Html.RenderAction("UpdatePoints");}
</div>
<input class="button" value="update" />
There are some ways to do it. For example you may use jQuery:
<script type="text/javascript">
$(function(){
$('.button').on("click", function(){
$.post('@Url.Action("PostActionToUpdatePoints", "Home")').always(function(){
$('.target').load('/Home/UpdatePoints');
})
});
});
</script>
PostActionToUpdatePoints
is your Action
with [HttpPost]
attribute, which you use to update points
If you use logic in your action UpdatePoints() to update points, maybe you forgot to add [HttpPost] attribute to it:
[HttpPost]
public ActionResult UpdatePoints()
{
ViewBag.points = _Repository.Points;
return PartialView("UpdatePoints");
}
With accordance with the answer by daveraja, here is a bash script which will solve the purpose.
Consider a situation if you are using C-shell and you want to execute a command without leaving the C-shell context/window as follows,
Command to be executed: Search exact word 'Testing' in current directory recursively only in *.h, *.c files
grep -nrs --color -w --include="*.{h,c}" Testing ./
Solution 1: Enter into bash from C-shell and execute the command
bash
grep -nrs --color -w --include="*.{h,c}" Testing ./
exit
Solution 2: Write the intended command into a text file and execute it using bash
echo 'grep -nrs --color -w --include="*.{h,c}" Testing ./' > tmp_file.txt
bash tmp_file.txt
Solution 3: Run command on the same line using bash
bash -c 'grep -nrs --color -w --include="*.{h,c}" Testing ./'
Solution 4: Create a sciprt (one-time) and use it for all future commands
alias ebash './execute_command_on_bash.sh'
ebash grep -nrs --color -w --include="*.{h,c}" Testing ./
The script is as follows,
#!/bin/bash
# =========================================================================
# References:
# https://stackoverflow.com/a/13343457/5409274
# https://stackoverflow.com/a/26733366/5409274
# https://stackoverflow.com/a/2853811/5409274
# https://stackoverflow.com/a/2853811/5409274
# https://www.linuxquestions.org/questions/other-%2Anix-55/how-can-i-run-a-command-on-another-shell-without-changing-the-current-shell-794580/
# https://www.tldp.org/LDP/abs/html/internalvariables.html
# https://stackoverflow.com/a/4277753/5409274
# =========================================================================
# Enable following line to see the script commands
# getting printing along with their execution. This will help for debugging.
#set -o verbose
E_BADARGS=85
if [ ! -n "$1" ]
then
echo "Usage: `basename $0` grep -nrs --color -w --include=\"*.{h,c}\" Testing ."
echo "Usage: `basename $0` find . -name \"*.txt\""
exit $E_BADARGS
fi
# Create a temporary file
TMPFILE=$(mktemp)
# Add stuff to the temporary file
#echo "echo Hello World...." >> $TMPFILE
#initialize the variable that will contain the whole argument string
argList=""
#iterate on each argument
for arg in "$@"
do
#if an argument contains a white space, enclose it in double quotes and append to the list
#otherwise simply append the argument to the list
if echo $arg | grep -q " "; then
argList="$argList \"$arg\""
else
argList="$argList $arg"
fi
done
#remove a possible trailing space at the beginning of the list
argList=$(echo $argList | sed 's/^ *//')
# Echoing the command to be executed to tmp file
echo "$argList" >> $TMPFILE
# Note: This should be your last command
# Important last command which deletes the tmp file
last_command="rm -f $TMPFILE"
echo "$last_command" >> $TMPFILE
#echo "---------------------------------------------"
#echo "TMPFILE is $TMPFILE as follows"
#cat $TMPFILE
#echo "---------------------------------------------"
check_for_last_line=$(tail -n 1 $TMPFILE | grep -o "$last_command")
#echo $check_for_last_line
#if tail -n 1 $TMPFILE | grep -o "$last_command"
if [ "$check_for_last_line" == "$last_command" ]
then
#echo "Okay..."
bash $TMPFILE
exit 0
else
echo "Something is wrong"
echo "Last command in your tmp file should be removing itself"
echo "Aborting the process"
exit 1
fi
Structure is much more faster than Class. Also, if you need inheritance then you must use Class. Most important point is that Class is reference type whereas Structure is value type. for example,
class Flight {
var id:Int?
var description:String?
var destination:String?
var airlines:String?
init(){
id = 100
description = "first ever flight of Virgin Airlines"
destination = "london"
airlines = "Virgin Airlines"
}
}
struct Flight2 {
var id:Int
var description:String
var destination:String
var airlines:String
}
now lets create instance of both.
var flightA = Flight()
var flightB = Flight2.init(id: 100, description:"first ever flight of Virgin Airlines", destination:"london" , airlines:"Virgin Airlines" )
now lets pass these instance to two functions which modify the id, description, destination etc..
func modifyFlight(flight:Flight) -> Void {
flight.id = 200
flight.description = "second flight of Virgin Airlines"
flight.destination = "new york"
flight.airlines = "Virgin Airlines"
}
also,
func modifyFlight2(flight2: Flight2) -> Void {
var passedFlight = flight2
passedFlight.id = 200
passedFlight.description = "second flight from virgin airlines"
}
so,
modifyFlight(flight: flightA)
modifyFlight2(flight2: flightB)
now if we print the flightA's id and description, we get
id = 200
description = "second flight of Virgin Airlines"
Here, we can see the id and description of FlightA is changed because the parameter passed to the modify method actually points to the memory address of flightA object(reference type).
now if we print the id and description of FLightB instance we get,
id = 100
description = "first ever flight of Virgin Airlines"
Here we can see that the FlightB instance is not changed because in modifyFlight2 method, actual instance of Flight2 is passes rather than reference ( value type).
Tags and Elements are not the same.
Elements
They are the pieces themselves, i.e. a paragraph is an element, or a header is an element, even the body is an element. Most elements can contain other elements, as the body element would contain header elements, paragraph elements, in fact pretty much all of the visible elements of the DOM.
Eg:
<p>This is the <span>Home</span> page</p>
Tags
Tags are not the elements themselves, rather they're the bits of text you use to tell the computer where an element begins and ends. When you 'mark up' a document, you generally don't want those extra notes that are not really part of the text to be presented to the reader. HTML borrows a technique from another language, SGML, to provide an easy way for a computer to determine which parts are "MarkUp" and which parts are the content. By using '<' and '>' as a kind of parentheses, HTML can indicate the beginning and end of a tag, i.e. the presence of '<' tells the browser 'this next bit is markup, pay attention'.
The browser sees the letters '
' and decides 'A new paragraph is starting, I'd better start a new line and maybe indent it'. Then when it sees '
' it knows that the paragraph it was working on is finished, so it should break the line there before going on to whatever is next.- Opening tag.
- Closing tagThis is what is working for me right now:
iPhone 6
@media only screen and (max-device-width: 667px)
and (-webkit-device-pixel-ratio: 2) {
iPhone 6+
@media screen and (min-device-width : 414px)
and (-webkit-device-pixel-ratio: 3)
If you aren't interested in keeping the unstaged changes (especially if the staged changes are new files), I found this handy:
git diff | git apply --reverse
if (Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null) {
Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);
String userid=currentPerson.getId(); //BY THIS CODE YOU CAN GET CURRENT LOGIN USER ID
}
brilliant example Jonathan Leffler, to make your code work on SLES, I needed to add an additional header to allow the pid_t object :)
#include <sys/types.h>
use some thing like
import java.io.*;
import javax.xml.transform.*;
import javax.xml.transform.dom.*;
import javax.xml.transform.stream.*;
//method to convert Document to String
public String getStringFromDocument(Document doc)
{
try
{
DOMSource domSource = new DOMSource(doc);
StringWriter writer = new StringWriter();
StreamResult result = new StreamResult(writer);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.transform(domSource, result);
return writer.toString();
}
catch(TransformerException ex)
{
ex.printStackTrace();
return null;
}
}
In SQL, anything you evaluate / compute with NULL
results into UNKNOWN
This is why SELECT * FROM MyTable WHERE MyColumn != NULL
or SELECT * FROM MyTable WHERE MyColumn <> NULL
gives you 0 results.
To provide a check for NULL
values, isNull function is provided.
Moreover, you can use the IS
operator as you used in the third query.
Hope this helps.
It might be easier with vlookup. Try this:
=IFERROR(VLOOKUP(D2,G:H,2,0),"")
The IFERROR()
is for no matches, so that it throws ""
in such cases.
VLOOKUP
's first parameter is the value to 'look for' in the reference table, which is column G and H.
VLOOKUP
will thus look for D2
in column G and return the value in the column index 2
(column G has column index 1, H will have column index 2), meaning that the value from column H will be returned.
The last parameter is 0
(or equivalently FALSE
) to mean an exact match. That's what you need as opposed to approximate match.
The key bits of dynamic programming are "overlapping sub-problems" and "optimal substructure". These properties of a problem mean that an optimal solution is composed of the optimal solutions to its sub-problems. For instance, shortest path problems exhibit optimal substructure. The shortest path from A to C is the shortest path from A to some node B followed by the shortest path from that node B to C.
In greater detail, to solve a shortest-path problem you will:
Because we are working bottom-up, we already have solutions to the sub-problems when it comes time to use them, by memoizing them.
Remember, dynamic programming problems must have both overlapping sub-problems, and optimal substructure. Generating the Fibonacci sequence is not a dynamic programming problem; it utilizes memoization because it has overlapping sub-problems, but it does not have optimal substructure (because there is no optimization problem involved).
You can also use svg instead of an image map. ;)
There is a tutorial on how to do this.
.hover_group:hover {_x000D_
opacity: 1;_x000D_
}_x000D_
#projectsvg {_x000D_
position: relative;_x000D_
width: 100%;_x000D_
padding-bottom: 77%;_x000D_
vertical-align: middle;_x000D_
margin: 0;_x000D_
overflow: hidden;_x000D_
}_x000D_
#projectsvg svg {_x000D_
display: inline-block;_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
}
_x000D_
<figure id="projectsvg">_x000D_
<svg version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="0 0 1920 1080" preserveAspectRatio="xMinYMin meet" >_x000D_
<!-- set your background image -->_x000D_
<image width="1920" height="1080" xlink:href="http://placehold.it/1920x1080" />_x000D_
<g class="hover_group" opacity="0">_x000D_
<a xlink:href="https://example.com/link1.html">_x000D_
<text x="652" y="706.9" font-size="20">First zone</text>_x000D_
<rect x="572" y="324.1" opacity="0.2" fill="#FFFFFF" width="264.6" height="387.8"></rect>_x000D_
</a>_x000D_
</g>_x000D_
<g class="hover_group" opacity="0">_x000D_
<a xlink:href="https://example.com/link2.html">_x000D_
<text x="1230.7" y="952" font-size="20">Second zone</text>_x000D_
<rect x="1081.7" y="507" opacity="0.2" fill="#FFFFFF" width="390.2" height="450"></rect>_x000D_
</a>_x000D_
</g>_x000D_
</svg>_x000D_
</figure>
_x000D_
You may want to look into Maven release plugin's release:update-versions goal. It will update the parent's version as well as all the modules under it.
Update: Please note that the above is the release plugin. If you are not releasing, you may want to use versions:set
mvn versions:set -DnewVersion=1.2.3-SNAPSHOT
public class A
{
public int i = 0;
internal virtual void test()
{
Console.WriteLine("A test");
}
}
public class B : A
{
public new int i = 1;
public new void test()
{
Console.WriteLine("B test");
}
}
public class C : B
{
public new int i = 2;
public new void test()
{
Console.WriteLine("C test - ");
(this as A).test();
}
}
just to help, if any one want to limit post length at home page
.. then can use below code to do that..
the below code is simply a modification of @bfred.it
Sir
add_filter("the_content", "break_text");
function limit_text($text){
if(is_front_page())
{
$length = 250;
if(strlen($text)<$length+10) return $text; //don't cut if too short
$break_pos = strpos($text, ' ', $length); //find next space after desired length
$visible = substr($text, 0, $break_pos);
return balanceTags($visible) . "... <a href='".get_permalink()."'>read more</a>";
}else{
return $text;
}
}
You have to define your TASK_CAT
column first and then set foreign key on it.
private static final String TASK_TABLE_CREATE = "create table "
+ TASK_TABLE + " ("
+ TASK_ID + " integer primary key autoincrement, "
+ TASK_TITLE + " text not null, "
+ TASK_NOTES + " text not null, "
+ TASK_DATE_TIME + " text not null,"
+ TASK_CAT + " integer,"
+ " FOREIGN KEY ("+TASK_CAT+") REFERENCES "+CAT_TABLE+"("+CAT_ID+"));";
More information you can find on sqlite foreign keys doc.
@Justin Pollard xml code works really good. As a side note you can add a ripple effect with the following xml lines.
<item>
<ripple
xmlns:android="http://schemas.android.com/apk/res/android"
android:color="?android:colorControlHighlight" >
<item android:id="@android:id/mask">
<shape android:shape="oval" >
<solid android:color="#FFBB00" />
</shape>
</item>
<item>
<shape android:shape="oval" >
<solid android:color="@color/ColorPrimary" />
</shape>
</item>
</ripple>
</item>
Change directory to tomcat/bin directory in cmd prompt
cd C:\Program Files\Apache Software Foundation\Tomcat 8.0\bin
Run the below command to start:
On Linux: >startup.sh
On Windows: >startup.bat
Run these commands to stop
On Linux: shutdown.sh
On Windows: shutdown.bat
convert string to Date fromat (you have to know server timezone)
new Date('2015-06-16 11:00:00'.replace(/\s+/g, 'T').concat('.000+08:00')).getTime()
where +08:00 = timeZone from server
This is the solution I came up with:
import time
from threading import Thread
from threading import Lock
def myfunc(i, mutex):
mutex.acquire(1)
time.sleep(1)
print "Thread: %d" %i
mutex.release()
mutex = Lock()
for i in range(0,10):
t = Thread(target=myfunc, args=(i,mutex))
t.start()
print "main loop %d" %i
Output:
main loop 0
main loop 1
main loop 2
main loop 3
main loop 4
main loop 5
main loop 6
main loop 7
main loop 8
main loop 9
Thread: 0
Thread: 1
Thread: 2
Thread: 3
Thread: 4
Thread: 5
Thread: 6
Thread: 7
Thread: 8
Thread: 9
For me, using OS X Catalina:
Changing from AllowOverride None
to AllowOverride All
is the one that works.
httpd.conf
is located on /etc/apache2/httpd.conf
.
Env: PHP7. MySQL8.
Add new column to DataTable
and use column Expression
property to set your Status expression.
Here you can find good example: DataColumn.Expression
Property
DataTable and DataColumn Expressions in ADO.NET - Calculated Columns
UPDATE
Code sample:
DataTable dt = new DataTable();
dt.Columns.Add(new DataColumn("colBestBefore", typeof(DateTime)));
dt.Columns.Add(new DataColumn("colStatus", typeof(string)));
dt.Columns["colStatus"].Expression = String.Format("IIF(colBestBefore < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
dt.Rows.Add(DateTime.Now.AddDays(-1));
dt.Rows.Add(DateTime.Now.AddDays(1));
dt.Rows.Add(DateTime.Now.AddDays(2));
dt.Rows.Add(DateTime.Now.AddDays(-2));
demoGridView.DataSource = dt;
UPDATE #2
dt.Columns["colStatus"].Expression = String.Format("IIF(CONVERT(colBestBefore, 'System.DateTime') < #{0}#, 'Ok','Not ok')", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
/** length should be less than 4 (for int) **/
public long byteToInt(byte[] bytes, int length) {
int val = 0;
if(length>4) throw new RuntimeException("Too big to fit in int");
for (int i = 0; i < length; i++) {
val=val<<8;
val=val|(bytes[i] & 0xFF);
}
return val;
}
This should work:
public static final byte[] intToByteArray(int value) {
return new byte[] {
(byte)(value >>> 24),
(byte)(value >>> 16),
(byte)(value >>> 8),
(byte)value};
}
Code taken from here.
Edit An even simpler solution is given in this thread.
Mysql 5.7.24 get root first login
step 1: get password from log
grep root@localhost /var/log/mysqld.log
Output
2019-01-17T09:58:34.459520Z 1 [Note] A temporary password is generated for root@localhost: wHkJHUxeR4)w
step 2: login with him to mysql
mysql -uroot -p'wHkJHUxeR4)w'
step 3: you put new root password
SET PASSWORD = PASSWORD('xxxxx');
you get ERROR 1819 (HY000): Your password does not satisfy the current policy requirements
how fix it?
run this SET GLOBAL validate_password_policy=LOW;
Try Again SET PASSWORD = PASSWORD('xxxxx');