Using .Select and .Where in a single LINQ statement
Did you add the Select()
after the Where()
or before?
You should add it after, because of the concurrency logic:
1 Take the entire table
2 Filter it accordingly
3 Select only the ID's
4 Make them distinct.
If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.
Update: For clarity, this order of operators should work:
db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();
Probably want to add a .toList()
at the end but that's optional :)
Difference between List, List<?>, List<T>, List<E>, and List<Object>
1) Correct
2) You can think of that one as "read only" list, where you don't care about the type of the items.Could e.g. be used by a method that is returning the length of the list.
3) T, E and U are the same, but people tend to use e.g. T for type, E for Element, V for value and K for key. The method that compiles says that it took an array of a certain type, and returns an array of the same type.
4) You can't mix oranges and apples. You would be able to add an Object to your String list if you could pass a string list to a method that expects object lists. (And not all objects are strings)
What represents a double in sql server?
A Float
represents double
in SQL server. You can find a proof from the coding in C# in visual studio. Here I have declared Overtime
as a Float
in SQL server and in C#. Thus I am able to convert
int diff=4;
attendance.OverTime = Convert.ToDouble(diff);
Here OverTime
is declared float type
How do you do exponentiation in C?
To add to what Evan said: C does not have a built-in operator for exponentiation, because it is not a primitive operation for most CPUs. Thus, it's implemented as a library function.
Also, for computing the function e^x, you can use the exp(double)
, expf(float)
, and expl(long double)
functions.
Note that you do not want to use the ^
operator, which is the bitwise exclusive OR operator.
Eclipse error: "Editor does not contain a main type"
private int user_movie_matrix[][];Th
. should be `private int user_movie_matrix[][];
.
private int user_movie_matrix[][];
should be private static int user_movie_matrix[][];
cfiltering(numberOfUsers, numberOfMovies);
should be new cfiltering(numberOfUsers, numberOfMovies);
Whether or not the code works as intended after these changes is beyond the scope of this answer; there were several syntax/scoping errors.
SQL Server - SELECT FROM stored procedure
Try converting your procedure in to an Inline Function which returns a table as follows:
CREATE FUNCTION MyProc()
RETURNS TABLE AS
RETURN (SELECT * FROM MyTable)
And then you can call it as
SELECT * FROM MyProc()
You also have the option of passing parameters to the function as follows:
CREATE FUNCTION FuncName (@para1 para1_type, @para2 para2_type , ... )
And call it
SELECT * FROM FuncName ( @para1 , @para2 )
Set position / size of UI element as percentage of screen size
Use the PercentRelativeLayout or PercentFrameLayout from the Percent Supoort Library
<android.support.percent.PercentFrameLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
app:layout_heightPercent="68%"/>
<Gallery
android:id="@+id/gallery"
android:layout_width="match_parent"
app:layout_heightPercent="16%"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_width="match_parent"/>
</android.support.percent.PercentFrameLayout>
How to specify test directory for mocha?
I am on Windows 7 using node.js v0.10.0 and mocha v1.8.2 and npm v1.2.14.
I was just trying to get mocha to use the path test/unit to find my tests,
After spending to long and trying several things I landed,
Using the "test/unit/*.js" option does not work on windows.
For good reasons that windows shell doesn't expand wildcards like unixen.
However using "test/unit" does work, without the file pattern.
eg. "mocha test/unit" runs all files found in test/unit folder.
This only still runs one folder files as tests but you can pass multiple directory names as parameters.
Also to run a single test file you can specify the full path and filename.
eg. "mocha test/unit/mytest1.js"
I actually setup in package.json for npm
"scripts": {
"test": "mocha test/unit"
},
So that 'npm test' runs my unit tests.
Responsive css background images
Try using background-size
but using TWO ARGUMENTS One for the width and the other one for the height
background-image:url('../images/bg.png');
background-repeat:no-repeat;
background-size: 100% 100%; // Here the first argument will be the width
// and the second will be the height.
background-position:center;
Search File And Find Exact Match And Print Line?
To check for an exact match you would use num == line
. But line
has an end-of-line character \n
or \r\n
which will not be in num
since raw_input
strips the trailing newline. So it may be convenient to remove all whitespace at the end of line
with
line = line.rstrip()
with open("file.txt") as search:
for line in search:
line = line.rstrip() # remove '\n' at end of line
if num == line:
print(line )
Best way to require all files from a directory in ruby?
Instead of concatenating paths like in some answers, I use File.expand_path
:
Dir[File.expand_path('importers/*.rb', File.dirname(__FILE__))].each do |file|
require file
end
Update:
Instead of using File.dirname
you could do the following:
Dir[File.expand_path('../importers/*.rb', __FILE__)].each do |file|
require file
end
Where ..
strips the filename of __FILE__
.
What is tail recursion?
Tail Recursion is pretty fast as compared to normal recursion.
It is fast because the output of the ancestors call will not be written in stack to keep the track.
But in normal recursion all the ancestor calls output written in stack to keep the track.
How can I clear an HTML file input with JavaScript?
tl;dr: For modern browsers, just use
input.value = '';
Old answer:
How about:
input.type = "text";
input.type = "file";
I still have to understand why this does not work with webkit.
Anyway, this works with IE9>, Firefox and Opera.
The situation with webkit is that I seem to be unable to change it back to file.
With IE8, the situation is that it throws a security exception.
Edit:
For webkit, Opera and firefox this works, though:
input.value = '';
(check the above answer with this proposal)
I'll see if I can find a nice cleaner way of doing this cross-browser without the need of the GC.
Edit2:
try{
inputs[i].value = '';
if(inputs[i].value){
inputs[i].type = "text";
inputs[i].type = "file";
}
}catch(e){}
Works with most browsers. Does not work with IE < 9, that's all.
Tested on firefox 20, chrome 24, opera 12, IE7, IE8, IE9, and IE10.
How to style a div to be a responsive square?
To achieve what you are looking for you can use the viewport-percentage length vw
.
Here is a quick example I made on jsfiddle.
HTML:
<div class="square">
<h1>This is a Square</h1>
</div>
CSS:
.square {
background: #000;
width: 50vw;
height: 50vw;
}
.square h1 {
color: #fff;
}
I am sure there are many other ways to do this but this way seemed the best to me.
Javascript Object push() function
Objects does not support push property, but you can save it as well using the index as key,
_x000D_
_x000D_
var tempData = {};_x000D_
for ( var index in data ) {_x000D_
if ( data[index].Status == "Valid" ) { _x000D_
tempData[index] = data; _x000D_
} _x000D_
}_x000D_
data = tempData;
_x000D_
_x000D_
_x000D_
I think this is easier if remove the object if its status is invalid, by doing.
_x000D_
_x000D_
for(var index in data){_x000D_
if(data[index].Status == "Invalid"){ _x000D_
delete data[index]; _x000D_
} _x000D_
}
_x000D_
_x000D_
_x000D_
And finally you don't need to create a var temp –
How to make a ssh connection with python?
Twisted has SSH support : http://www.devshed.com/c/a/Python/SSH-with-Twisted/
The twisted.conch package adds SSH support to Twisted. This chapter shows how you can use the modules in twisted.conch to build SSH servers and clients.
Setting Up a Custom SSH Server
The command line is an incredibly efficient interface for certain tasks. System administrators love the ability to manage applications by typing commands without having to click through a graphical user interface. An SSH shell is even better, as it’s accessible from anywhere on the Internet.
You can use twisted.conch to create an SSH server that provides access to a custom shell with commands you define. This shell will even support some extra features like command history, so that you can scroll through the commands you’ve already typed.
How Do I Do That?
Write a subclass of twisted.conch.recvline.HistoricRecvLine that implements your shell protocol. HistoricRecvLine is similar to twisted.protocols.basic.LineReceiver , but with higher-level features for controlling the terminal.
Write a subclass of twisted.conch.recvline.HistoricRecvLine that implements your shell protocol. HistoricRecvLine is similar to twisted.protocols.basic.LineReceiver, but with higher-level features for controlling the terminal.
To make your shell available through SSH, you need to implement a few different classes that twisted.conch needs to build an SSH server. First, you need the twisted.cred authentication classes: a portal, credentials checkers, and a realm that returns avatars. Use twisted.conch.avatar.ConchUser as the base class for your avatar. Your avatar class should also implement twisted.conch.interfaces.ISession , which includes an openShell method in which you create a Protocol to manage the user’s interactive session. Finally, create a twisted.conch.ssh.factory.SSHFactory object and set its portal attribute to an instance of your portal.
Example 10-1 demonstrates a custom SSH server that authenticates users by their username and password. It gives each user a shell that provides several commands.
Example 10-1. sshserver.py
from twisted.cred import portal, checkers, credentials
from twisted.conch import error, avatar, recvline, interfaces as conchinterfaces
from twisted.conch.ssh import factory, userauth, connection, keys, session, common from twisted.conch.insults import insults from twisted.application import service, internet
from zope.interface import implements
import os
class SSHDemoProtocol(recvline.HistoricRecvLine):
def __init__(self, user):
self.user = user
def connectionMade(self) :
recvline.HistoricRecvLine.connectionMade(self)
self.terminal.write("Welcome to my test SSH server.")
self.terminal.nextLine()
self.do_help()
self.showPrompt()
def showPrompt(self):
self.terminal.write("$ ")
def getCommandFunc(self, cmd):
return getattr(self, ‘do_’ + cmd, None)
def lineReceived(self, line):
line = line.strip()
if line:
cmdAndArgs = line.split()
cmd = cmdAndArgs[0]
args = cmdAndArgs[1:]
func = self.getCommandFunc(cmd)
if func:
try:
func(*args)
except Exception, e:
self.terminal.write("Error: %s" % e)
self.terminal.nextLine()
else:
self.terminal.write("No such command.")
self.terminal.nextLine()
self.showPrompt()
def do_help(self, cmd=”):
"Get help on a command. Usage: help command"
if cmd:
func = self.getCommandFunc(cmd)
if func:
self.terminal.write(func.__doc__)
self.terminal.nextLine()
return
publicMethods = filter(
lambda funcname: funcname.startswith(‘do_’), dir(self))
commands = [cmd.replace(‘do_’, ”, 1) for cmd in publicMethods]
self.terminal.write("Commands: " + " ".join(commands))
self.terminal.nextLine()
def do_echo(self, *args):
"Echo a string. Usage: echo my line of text"
self.terminal.write(" ".join(args))
self.terminal.nextLine()
def do_whoami(self):
"Prints your user name. Usage: whoami"
self.terminal.write(self.user.username)
self.terminal.nextLine()
def do_quit(self):
"Ends your session. Usage: quit"
self.terminal.write("Thanks for playing!")
self.terminal.nextLine()
self.terminal.loseConnection()
def do_clear(self):
"Clears the screen. Usage: clear"
self.terminal.reset()
class SSHDemoAvatar(avatar.ConchUser):
implements(conchinterfaces.ISession)
def __init__(self, username):
avatar.ConchUser.__init__(self)
self.username = username
self.channelLookup.update({‘session’:session.SSHSession})
def openShell(self, protocol):
serverProtocol = insults.ServerProtocol(SSHDemoProtocol, self)
serverProtocol.makeConnection(protocol)
protocol.makeConnection(session.wrapProtocol(serverProtocol))
def getPty(self, terminal, windowSize, attrs):
return None
def execCommand(self, protocol, cmd):
raise NotImplementedError
def closed(self):
pass
class SSHDemoRealm:
implements(portal.IRealm)
def requestAvatar(self, avatarId, mind, *interfaces):
if conchinterfaces.IConchUser in interfaces:
return interfaces[0], SSHDemoAvatar(avatarId), lambda: None
else:
raise Exception, "No supported interfaces found."
def getRSAKeys():
if not (os.path.exists(‘public.key’) and os.path.exists(‘private.key’)):
# generate a RSA keypair
print "Generating RSA keypair…"
from Crypto.PublicKey import RSA
KEY_LENGTH = 1024
rsaKey = RSA.generate(KEY_LENGTH, common.entropy.get_bytes)
publicKeyString = keys.makePublicKeyString(rsaKey)
privateKeyString = keys.makePrivateKeyString(rsaKey)
# save keys for next time
file(‘public.key’, ‘w+b’).write(publicKeyString)
file(‘private.key’, ‘w+b’).write(privateKeyString)
print "done."
else:
publicKeyString = file(‘public.key’).read()
privateKeyString = file(‘private.key’).read()
return publicKeyString, privateKeyString
if __name__ == "__main__":
sshFactory = factory.SSHFactory()
sshFactory.portal = portal.Portal(SSHDemoRealm())
users = {‘admin’: ‘aaa’, ‘guest’: ‘bbb’}
sshFactory.portal.registerChecker(
checkers.InMemoryUsernamePasswordDatabaseDontUse(**users))
pubKeyString, privKeyString =
getRSAKeys()
sshFactory.publicKeys = {
‘ssh-rsa’: keys.getPublicKeyString(data=pubKeyString)}
sshFactory.privateKeys = {
‘ssh-rsa’: keys.getPrivateKeyObject(data=privKeyString)}
from twisted.internet import reactor
reactor.listenTCP(2222, sshFactory)
reactor.run()
{mospagebreak title=Setting Up a Custom SSH Server continued}
sshserver.py will run an SSH server on port 2222. Connect to this server with an SSH client using the username admin and password aaa, and try typing some commands:
$ ssh admin@localhost -p 2222
admin@localhost’s password: aaa
>>> Welcome to my test SSH server.
Commands: clear echo help quit whoami
$ whoami
admin
$ help echo
Echo a string. Usage: echo my line of text
$ echo hello SSH world!
hello SSH world!
$ quit
Connection to localhost closed.
How to "properly" create a custom object in JavaScript?
var Person = function (lastname, age, job){
this.name = name;
this.age = age;
this.job = job;
this.changeName = function(name){
this.lastname = name;
}
}
var myWorker = new Person('Adeola', 23, 'Web Developer');
myWorker.changeName('Timmy');
console.log("New Worker" + myWorker.lastname);
How to generate Class Diagram (UML) on Android Studio (IntelliJ Idea)
I have managed to to do it in a way. Perform all the steps as referenced by Michal Rowicki above.
- Open Visual Paradigm software.
- Create a new Project
- There would be an option on the
Tools
bar above that states Code
and select Instant Reverse...
from the drop down menu with Java
language(or other)
- Select your application folder where your project is located and
add it to the project(i have selected the complete folder
application)
- The application should now appear on the left pane in Class
Repository
- Then all you do is right click the project that you have added and
select Reverse to new class diagram
- Select either you wish to have the packages included in the class
diagram or just the class diagram of the project
Then it should appear on your screen and customize it as you wish
However i do not know if the plugin in Android Studio was necessary nevertheless it has worked in a way for me.
How do I display image in Alert/confirm box in Javascript?
Alert boxes in JavaScript can only display pure text. You could use a JavaScript library like jQuery to display a modal instead?
This might be useful:
http://jqueryui.com/dialog/
You can do it like this:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Dialog - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<script>
body {
font-family: "Trebuchet MS", "Helvetica", "Arial", "Verdana", "sans-serif";
font-size: 62.5%;
}
</script>
<script>
$(function() {
$( "#dialog" ).dialog();
});
</script>
</head>
<body>
<div id="dialog" title="Basic dialog">
<p>Image:</p>
<img src="http://placehold.it/50x50" alt="Placeholder Image" />
</div>
</body>
</html>
How to loop in excel without VBA or macros?
I was just searching for something similar:
I want to sum every odd row column.
SUMIF
has TWO possible ranges, the range to sum from, and a range to consider criteria in.
SUMIF(B1:B1000,1,A1:A1000)
This function will consider if a cell in the B range is "=1", it will sum the corresponding A cell only if it is.
To get "=1" to return in the B range I put this in B:
=MOD(ROWNUM(B1),2)
Then auto fill down to get the modulus to fill, you could put and calculatable criteria here to get the SUMIF or SUMIFS conditions you need to loop through each cell.
Easier than ARRAY stuff and hides the back-end of loops!
How can I get client information such as OS and browser
Here's my code that works, as of today, with some of the latest browsers.
Naturally, it will break as User-Agent's evolve, but it's simple, and easy to fix.
String userAgent = "Unknown";
String osType = "Unknown";
String osVersion = "Unknown";
String browserType = "Unknown";
String browserVersion = "Unknown";
String deviceType = "Unknown";
try {
userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.165";
//userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0";
//userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36";
//userAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.140 Safari/537.36 Edge/17.17134";
//userAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 12_3_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/12.1.1 Mobile/15E148 Safari/604.1";
boolean exceptionTest = false;
if(exceptionTest) throw new Exception("EXCEPTION TEST");
if (userAgent.indexOf("Windows NT") >= 0) {
osType = "Windows";
osVersion = userAgent.substring(userAgent.indexOf("Windows NT ")+11, userAgent.indexOf(";"));
} else if (userAgent.indexOf("Mac OS") >= 0) {
osType = "Mac";
osVersion = userAgent.substring(userAgent.indexOf("Mac OS ")+7, userAgent.indexOf(")"));
if(userAgent.indexOf("iPhone") >= 0) {
deviceType = "iPhone";
} else if(userAgent.indexOf("iPad") >= 0) {
deviceType = "iPad";
}
} else if (userAgent.indexOf("X11") >= 0) {
osType = "Unix";
osVersion = "Unknown";
} else if (userAgent.indexOf("android") >= 0) {
osType = "Android";
osVersion = "Unknown";
}
logger.trace("end of os section");
if (userAgent.contains("Edge/")) {
browserType = "Edge";
browserVersion = userAgent.substring(userAgent.indexOf("Edge")).split("/")[1];
} else if (userAgent.contains("Safari/") && userAgent.contains("Version/")) {
browserType = "Safari";
browserVersion = userAgent.substring(userAgent.indexOf("Version/")+8).split(" ")[0];
} else if (userAgent.contains("OPR/") || userAgent.contains("Opera/")) {
browserType = "Opera";
browserVersion = userAgent.substring(userAgent.indexOf("OPR")).split("/")[1];
} else if (userAgent.contains("Chrome/")) {
browserType = "Chrome";
browserVersion = userAgent.substring(userAgent.indexOf("Chrome")).split("/")[1];
browserVersion = browserVersion.split(" ")[0];
} else if (userAgent.contains("Firefox/")) {
browserType = "Firefox";
browserVersion = userAgent.substring(userAgent.indexOf("Firefox")).split("/")[1];
}
logger.trace("end of browser section");
} catch (Exception ex) {
logger.error("ERROR: " +ex);
}
logger.debug(
"\n userAgent: " + userAgent
+ "\n osType: " + osType
+ "\n osVersion: " + osVersion
+ "\n browserType: " + browserType
+ "\n browserVersion: " + browserVersion
+ "\n deviceType: " + deviceType
);
Logger Output:
userAgent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36 OPR/60.0.3255.165
osType: Windows
osVersion: 10.0
browserType: Opera
browserVersion: 60.0.3255.165
deviceType: Unknown
JavaScript: Create and save file
_x000D_
_x000D_
function download(text, name, type) {_x000D_
var a = document.getElementById("a");_x000D_
var file = new Blob([text], {type: type});_x000D_
a.href = URL.createObjectURL(file);_x000D_
a.download = name;_x000D_
}
_x000D_
<a href="" id="a">click here to download your file</a>_x000D_
<button onclick="download('file text', 'myfilename.json', 'text/json')">Create file</button>
_x000D_
_x000D_
_x000D_
I think this can work with json files too if you change the mime type.
Entry point for Java applications: main(), init(), or run()?
The main
method is the entry point of a Java application.
Specifically?when the Java Virtual Machine is told to run an application by specifying its class (by using the java
application launcher), it will look for the main
method with the signature of public static void main(String[])
.
From Sun's java
command page:
The java tool launches a Java application. It does this by starting
a Java runtime environment, loading a specified class, and invoking that
class's main method.
The method must be declared public and static, it must not return any
value, and it must accept a String
array as a parameter. The method
declaration must look like the following:
public static void main(String args[])
For additional resources on how an Java application is executed, please refer to the following sources:
- Chapter 12: Execution from the Java Language Specification, Third Edition.
- Chapter 5: Linking, Loading, Initializing from the Java Virtual Machine Specifications, Second Edition.
- A Closer Look at the "Hello World" Application from the Java Tutorials.
The run
method is the entry point for a new Thread
or an class implementing the Runnable
interface. It is not called by the Java Virutal Machine when it is started up by the java
command.
As a Thread
or Runnable
itself cannot be run directly by the Java Virtual Machine, so it must be invoked by the Thread.start()
method. This can be accomplished by instantiating a Thread
and calling its start
method in the main
method of the application:
public class MyRunnable implements Runnable
{
public void run()
{
System.out.println("Hello World!");
}
public static void main(String[] args)
{
new Thread(new MyRunnable()).start();
}
}
For more information and an example of how to start a subclass of Thread
or a class implementing Runnable
, see Defining and Starting a Thread from the Java Tutorials.
The init
method is the first method called in an Applet or JApplet.
When an applet is loaded by the Java plugin of a browser or by an applet viewer, it will first call the Applet.init
method. Any initializations that are required to use the applet should be executed here. After the init
method is complete, the start
method is called.
For more information about when the init
method of an applet is called, please read about the lifecycle of an applet at The Life Cycle of an Applet from the Java Tutorials.
See also: How to Make Applets from the Java Tutorial.
Query error with ambiguous column name in SQL
We face this error when we are selecting data from more than one tables by joining tables and at least one of the selected columns (it will also happen when use * to select all columns) exist with same name in more than one tables (our selected/joined tables). In that case we must have to specify from which table we are selecting out column.
Following is a an example solution implementation of concept explained above
I think you have ambiguity only in InvoiceID
that exists both in InvoiceLineItems
and Invoices
Other fields seem distinct. So try This
I just replace InvoiceID with Invoices.InvoiceID
SELECT
VendorName, Invoices.InvoiceID, InvoiceSequence, InvoiceLineItemAmount
FROM Vendors
JOIN Invoices ON (Vendors.VendorID = Invoices.VendorID)
JOIN InvoiceLineItems ON (Invoices.InvoiceID = InvoiceLineItems.InvoiceID)
WHERE
Invoices.InvoiceID IN
(SELECT InvoiceSequence
FROM InvoiceLineItems
WHERE InvoiceSequence > 1)
ORDER BY
VendorName, Invoices.InvoiceID, InvoiceSequence, InvoiceLineItemAmount
You can use tablename.columnnae for all columns (in selection,where,group by and order by) without using any alias. However you can use an alias as guided by other answers
How to get the second column from command output?
This should work to get a specific column out of the command output "docker images":
REPOSITORY TAG IMAGE ID CREATED SIZE
ubuntu 16.04 12543ced0f6f 10 months ago 122 MB
ubuntu latest 12543ced0f6f 10 months ago 122 MB
selenium/standalone-firefox-debug 2.53.0 9f3bab6e046f 12 months ago 613 MB
selenium/node-firefox-debug 2.53.0 d82f2ab74db7 12 months ago 613 MB
docker images | awk '{print $3}'
IMAGE
12543ced0f6f
12543ced0f6f
9f3bab6e046f
d82f2ab74db7
This is going to print the third column
jQuery .attr("disabled", "disabled") not working in Chrome
Mostly disabled attribute doesn't work with the anchor tags from HTML-5 onwards. Hence we have change it to ,let's say 'button' and style it accordingly with appropriate color,border-style etc. That's the most apt solution for any similar issue users are facing in Chrome . Only few elements support 'disabled' attribute:
Span , select, option, textarea, input , button.
Is key-value observation (KVO) available in Swift?
Yes.
KVO requires dynamic dispatch, so you simply need to add the dynamic
modifier to a method, property, subscript, or initializer:
dynamic var foo = 0
The dynamic
modifier ensures that references to the declaration will be dynamically dispatched and accessed through objc_msgSend
.
Specifying onClick event type with Typescript and React.Konva
As posted in my update above, a potential solution would be to use Declaration Merging as suggested by @Tyler-sebastion. I was able to define two additional interfaces and add the index property on the EventTarget
in this way.
interface KonvaTextEventTarget extends EventTarget {
index: number
}
interface KonvaMouseEvent extends React.MouseEvent<HTMLElement> {
target: KonvaTextEventTarget
}
I then can declare the event as KonvaMouseEvent
in my onclick MouseEventHandler function.
onClick={(event: KonvaMouseEvent) => {
makeMove(ownMark, event.target.index)
}}
I'm still not 100% if this is the best approach as it feels a bit Kludgy and overly verbose just to get past the tslint error.
Warning: mysqli_query() expects at least 2 parameters, 1 given. What?
the mysqli_query
excepts 2 parameters , first variable is mysqli_connect
equivalent variable , second one is the query you have provided
$name1 = mysqli_connect(localhost,tdoylex1_dork,dorkk,tdoylex1_dork);
$name2 = mysqli_query($name1,"SELECT name FROM users ORDER BY RAND() LIMIT 1");
OpenSSL: unable to verify the first certificate for Experian URL
Adding additional information to emboss's answer.
To put it simply, there is an incorrect cert in your certificate chain.
For example, your certificate authority will have most likely given you 3 files.
- your_domain_name.crt
- DigiCertCA.crt # (Or whatever the name of your certificate authority is)
- TrustedRoot.crt
You most likely combined all of these files into one bundle.
-----BEGIN CERTIFICATE-----
(Your Primary SSL certificate: your_domain_name.crt)
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
(Your Intermediate certificate: DigiCertCA.crt)
-----END CERTIFICATE-----
-----BEGIN CERTIFICATE-----
(Your Root certificate: TrustedRoot.crt)
-----END CERTIFICATE-----
If you create the bundle, but use an old, or an incorrect version of your Intermediate Cert (DigiCertCA.crt in my example), you will get the exact symptoms you are describing.
Redownload all certs from your certificate authority and make a fresh bundle.
How to define a Sql Server connection string to use in VB.NET?
Use the following Imports
Imports System.Data.SqlClient
Imports System.Data.Sql
Public SQLConn As New SqlConnection With {.ConnectionString = "Server=Desktop1[enter image description here][1];Database=Infostudio; Trusted_Connection=true;"}
Full string:
JPA and Hibernate - Criteria vs. JPQL or HQL
Criteria is an object-oriented API, while HQL means string concatenation. That means all of the benefits of object-orientedness apply:
- All else being equal, the OO version is somewhat less prone to error. Any old string could get appended into the HQL query, whereas only valid Criteria objects can make it into a Criteria tree. Effectively, the Criteria classes are more constrained.
- With auto-complete, the OO is more discoverable (and thus easier to use, for me at least). You don't necessarily need to remember which parts of the query go where; the IDE can help you
- You also don't need to remember the particulars of the syntax (like which symbols go where). All you need to know is how to call methods and create objects.
Since HQL is very much like SQL (which most devs know very well already) then these "don't have to remember" arguments don't carry as much weight. If HQL was more different, then this would be more importatnt.
How to hide the keyboard when I press return key in a UITextField?
Ok, I think for a novice things might be a bit confusing. I think the correct answer is a mix of all the above, at least in Swift4.
Either create an extension or use the ViewController in which you'd like to use this but make sure to implement UITextFieldDelegate. For reusability's sake I found it easier to use an extension:
extension UIViewController : UITextFieldDelegate {
...
}
but the alternative works as well:
class MyViewController: UIViewController {
...
}
Add the method textFieldShouldReturn (depending on your previous option, either in the extension or in your ViewController)
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
return textField.endEditing(false)
}
In your viewDidLoad method, set the textfield's delegate to self
@IBOutlet weak var myTextField: UITextField!
...
override func viewDidLoad() {
..
myTextField.delegte = self;
..
}
That should be all. Now, when you press return
the textFieldShouldReturn
should be called.
jQuery counter to count up to a target number
You can use jquery animate function for that.
$({ countNum: $('.code').html() }).animate({ countNum: 4000 }, {
duration: 8000,
easing: 'linear',
step: function () {
$('.code').html(Math.floor(this.countNum) );
},
complete: function () {
$('.code').html(this.countNum);
//alert('finished');
}
});
Here's the original article
Performing a Stress Test on Web Application?
Blaze meter has a chrome extension for recording sessions and exporting them to JMeter (currently requires login). You also have the option of paying them money to run it on their cluster of JMeter servers (their pricing seems much better than LoadImpact which I've just stopped using):
I don't have any association with them, I just like the look of their service, although I haven't used the paid version yet.
How to use S_ISREG() and S_ISDIR() POSIX Macros?
[Posted on behalf of fossuser] Thanks to "mu is too short" I was able to fix the bug. Here is my working code has been edited in for those looking for a nice example (since I couldn't find any others online).
#include <sys/types.h>
#include <sys/stat.h>
#include <stdlib.h>
#include <dirent.h>
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
void helper(DIR *, struct dirent *, struct stat, char *, int, char **);
void dircheck(DIR *, struct dirent *, struct stat, char *, int, char **);
int main(int argc, char *argv[]){
DIR *dip;
struct dirent *dit;
struct stat statbuf;
char currentPath[FILENAME_MAX];
int depth = 0; /*Used to correctly space output*/
/*Open Current Directory*/
if((dip = opendir(".")) == NULL)
return errno;
/*Store Current Working Directory in currentPath*/
if((getcwd(currentPath, FILENAME_MAX)) == NULL)
return errno;
/*Read all items in directory*/
while((dit = readdir(dip)) != NULL){
/*Skips . and ..*/
if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
continue;
/*Correctly forms the path for stat and then resets it for rest of algorithm*/
getcwd(currentPath, FILENAME_MAX);
strcat(currentPath, "/");
strcat(currentPath, dit->d_name);
if(stat(currentPath, &statbuf) == -1){
perror("stat");
return errno;
}
getcwd(currentPath, FILENAME_MAX);
/*Checks if current item is of the type file (type 8) and no command line arguments*/
if(S_ISREG(statbuf.st_mode) && argv[1] == NULL)
printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
/*If a command line argument is given, checks for filename match*/
if(S_ISREG(statbuf.st_mode) && argv[1] != NULL)
if(strcmp(dit->d_name, argv[1]) == 0)
printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
/*Checks if current item is of the type directory (type 4)*/
if(S_ISDIR(statbuf.st_mode))
dircheck(dip, dit, statbuf, currentPath, depth, argv);
}
closedir(dip);
return 0;
}
/*Recursively called helper function*/
void helper(DIR *dip, struct dirent *dit, struct stat statbuf,
char currentPath[FILENAME_MAX], int depth, char *argv[]){
int i = 0;
if((dip = opendir(currentPath)) == NULL)
printf("Error: Failed to open Directory ==> %s\n", currentPath);
while((dit = readdir(dip)) != NULL){
if(strcmp(dit->d_name, ".") == 0 || strcmp(dit->d_name, "..") == 0)
continue;
strcat(currentPath, "/");
strcat(currentPath, dit->d_name);
stat(currentPath, &statbuf);
getcwd(currentPath, FILENAME_MAX);
if(S_ISREG(statbuf.st_mode) && argv[1] == NULL){
for(i = 0; i < depth; i++)
printf(" ");
printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
}
if(S_ISREG(statbuf.st_mode) && argv[1] != NULL){
if(strcmp(dit->d_name, argv[1]) == 0){
for(i = 0; i < depth; i++)
printf(" ");
printf("%s (%d bytes)\n", dit->d_name, (int)statbuf.st_size);
}
}
if(S_ISDIR(statbuf.st_mode))
dircheck(dip, dit, statbuf, currentPath, depth, argv);
}
/*Changing back here is necessary because of how stat is done*/
chdir("..");
closedir(dip);
}
void dircheck(DIR *dip, struct dirent *dit, struct stat statbuf,
char currentPath[FILENAME_MAX], int depth, char *argv[]){
int i = 0;
strcat(currentPath, "/");
strcat(currentPath, dit->d_name);
/*If two directories exist at the same level the path
is built wrong and needs to be corrected*/
if((chdir(currentPath)) == -1){
chdir("..");
getcwd(currentPath, FILENAME_MAX);
strcat(currentPath, "/");
strcat(currentPath, dit->d_name);
for(i = 0; i < depth; i++)
printf (" ");
printf("%s (subdirectory)\n", dit->d_name);
depth++;
helper(dip, dit, statbuf, currentPath, depth, argv);
}
else{
for(i =0; i < depth; i++)
printf(" ");
printf("%s (subdirectory)\n", dit->d_name);
chdir(currentPath);
depth++;
helper(dip, dit, statbuf, currentPath, depth, argv);
}
}
How to round a numpy array?
It is worth noting that the accepted answer will round small floats down to zero.
>>> import numpy as np
>>> arr = np.asarray([2.92290007e+00, -1.57376965e-03, 4.82011728e-08, 1.92896977e-12])
>>> print(arr)
[ 2.92290007e+00 -1.57376965e-03 4.82011728e-08 1.92896977e-12]
>>> np.round(arr, 2)
array([ 2.92, -0. , 0. , 0. ])
You can use set_printoptions
and a custom formatter to fix this and get a more numpy-esque printout with fewer decimal places:
>>> np.set_printoptions(formatter={'float': "{0:0.2e}".format})
>>> print(arr)
[2.92e+00 -1.57e-03 4.82e-08 1.93e-12]
This way, you get the full versatility of format
and maintain the full precision of numpy's datatypes.
Also note that this only affects printing, not the actual precision of the stored values used for computation.
How to load Spring Application Context
Add this at the start of main
ApplicationContext context = new ClassPathXmlApplicationContext("path/to/applicationContext.xml");
JobLauncher launcher=(JobLauncher)context.getBean("launcher");
Job job=(Job)context.getBean("job");
//Get as many beans you want
//Now do the thing you were doing inside test method
StopWatch sw = new StopWatch();
sw.start();
launcher.run(job, jobParameters);
sw.stop();
//initialize the log same way inside main
logger.info(">>> TIME ELAPSED:" + sw.prettyPrint());
When and Why to use abstract classes/methods?
At a very high level:
Abstraction of any kind comes down to separating concerns. "Client" code of an abstraction doesn't care how the contract exposed by the abstraction is fulfilled. You usually don't care if a string class uses a null-terminated or buffer-length-tracked internal storage implementation, for example. Encapsulation hides the details, but by making classes/methods/etc. abstract, you allow the implementation to change or for new implementations to be added without affecting the client code.
Can we write our own iterator in Java?
Here is the complete answer to the question.
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.NoSuchElementException;
class ListIterator implements Iterator<String>{
List<String> list;
int pos = 0;
public ListIterator(List<String> list) {
this.list = list;
}
@Override
public boolean hasNext() {
while(pos < list.size()){
if (list.get(pos).startsWith("a"))
return true;
pos++;
}
return false;
}
@Override
public String next() {
if (hasNext())
return list.get(pos++);
throw new NoSuchElementException();
}
}
public class IteratorTest {
public static void main(String[] args) {
List<String> list = Arrays.asList("alice", "bob", "abigail", "charlie");
ListIterator itr = new ListIterator(list);
while(itr.hasNext())
System.out.println(itr.next()); // prints alice, abigail
}
}
ListIterator
is the iterator for the array which returns the elements that start with 'a'.
- There is no need for implementing an Iterable interface. But that is a possibility.
- There is no need to implement this generically.
- It fully satisfies the contract for hasNext() and next(). ie if hasNext() says there are still elements, next() will return those elements. And if hasNext() says no more elements, it returns a valid
NoSuchElementException
exception.
Open files always in a new tab
you need edit setting.json file,
settings.json, located at
Windows %APPDATA%\Code\User\settings.json
macOS $HOME/Library/Application Support/Code/User/settings.json
Linux $HOME/.config/Code/User/settings.json
{
"workbench.editor.showTabs": true,
"workbench.editor.enablePreview": false
}
Read pdf files with php
There is a php library (pdfparser) that does exactly what you want.
project website
http://www.pdfparser.org/
github
https://github.com/smalot/pdfparser
Demo page/api
http://www.pdfparser.org/demo
After including pdfparser in your project you can get all text from mypdf.pdf
like so:
<?php
$parser = new \installpath\PdfParser\Parser();
$pdf = $parser->parseFile('mypdf.pdf');
$text = $pdf->getText();
echo $text;//all text from mypdf.pdf
?>
Simular you can get the metadata from the pdf as wel as getting the pdf objects (for example images).
About the Full Screen And No Titlebar from manifest
Try using these theme: Theme.AppCompat.Light.NoActionBar
Mi Style XML file looks like these and works just fine:
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
stopPropagation vs. stopImmediatePropagation
Here I am adding my JSfiddle example for stopPropagation vs stopImmediatePropagation.
JSFIDDLE
_x000D_
_x000D_
let stopProp = document.getElementById('stopPropagation');_x000D_
let stopImmediate = document.getElementById('stopImmediatebtn');_x000D_
let defaultbtn = document.getElementById("defalut-btn");_x000D_
_x000D_
_x000D_
stopProp.addEventListener("click", function(event){_x000D_
event.stopPropagation();_x000D_
console.log('stopPropagation..')_x000D_
_x000D_
})_x000D_
stopProp.addEventListener("click", function(event){_x000D_
console.log('AnotherClick')_x000D_
_x000D_
})_x000D_
stopImmediate.addEventListener("click", function(event){_x000D_
event.stopImmediatePropagation();_x000D_
console.log('stopimmediate')_x000D_
})_x000D_
_x000D_
stopImmediate.addEventListener("click", function(event){_x000D_
console.log('ImmediateStop Another event wont work')_x000D_
})_x000D_
_x000D_
defaultbtn.addEventListener("click", function(event){_x000D_
alert("Default Clik");_x000D_
})_x000D_
defaultbtn.addEventListener("click", function(event){_x000D_
console.log("Second event defined will also work same time...")_x000D_
})
_x000D_
div{_x000D_
margin: 10px;_x000D_
}
_x000D_
<p>_x000D_
The simple example for event.stopPropagation and stopImmediatePropagation?_x000D_
Please open console to view the results and click both button._x000D_
</p>_x000D_
<div >_x000D_
<button id="stopPropagation">_x000D_
stopPropagation-Button_x000D_
</button>_x000D_
</div>_x000D_
<div id="grand-div">_x000D_
<div class="new" id="parent-div">_x000D_
<button id="stopImmediatebtn">_x000D_
StopImmediate_x000D_
</button>_x000D_
</div>_x000D_
</div>_x000D_
<div>_x000D_
<button id="defalut-btn">_x000D_
Normat Button_x000D_
</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_
Setting HTTP headers
If you don't want to override your router (if you don't have your app configured in a way that supports this, or want to configure CORS on a route by route basis), add an OPTIONS handler to handle the pre flight request.
Ie, with Gorilla Mux your routes would look like:
accounts := router.Path("/accounts").Subrouter()
accounts.Methods("POST").Handler(AccountsCreate)
accounts.Methods("OPTIONS").Handler(AccountsCreatePreFlight)
Note above that in addition to our POST handler, we're defining a specific OPTIONS method handler.
And then to actual handle the OPTIONS preflight method, you could define AccountsCreatePreFlight like so:
// Check the origin is valid.
origin := r.Header.Get("Origin")
validOrigin, err := validateOrigin(origin)
if err != nil {
return err
}
// If it is, allow CORS.
if validOrigin {
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", "POST")
w.Header().Set("Access-Control-Allow-Headers",
"Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
}
What really made this all click for me (in addition to actually understanding how CORS works) is that the HTTP Method of a preflight request is different from the HTTP Method of the actual request. To initiate CORS, the browser sends a preflight request with HTTP Method OPTIONS, which you have to handle explicitly in your router, and then, if it receives the appropriate response "Access-Control-Allow-Origin": origin
(or "*" for all) from your application, it initiates the actual request.
I also believe that you can only do "*" for standard types of requests (ie: GET), but for others you'll have to explicitly set the origin like I do above.
Facebook key hash does not match any stored key hashes
While generating release Hash key, Note this
For Windows
When generating the hash key for production you need to use openssl-0.9.8e_X64.zip on windows, you cannot use openssl-0.9.8k_X64.zip
The versions produce different hash keys, for some reason 9.8k does not work correctly... 9.8e does.
OR
Use this below flow
This is how i solved this problem Download your APK to your PC in java jdk\bin folder in my case C:\Program Files\Java\jdk1.7.0_121\bin go to java jdk\bin folder and run cmd then copy the following command in your cmd
keytool -list -printcert -jarfile yourapkname.apk
Copy the SHA1 value to your clip board like this CD:A1:EA:A3:5C:5C:68:FB:FA:0A:6B:E5:5A:72:64:DD:26:8D:44:84 and open http://tomeko.net/online_tools/hex_to_base64.php to convert your SHA1 value to base64.
For MAC
Step 1:
Generate SHA1 key by using below command
keytool -list -v -keystore Keystore path
Enter Keystore password.
Copy SHA1 Key.
Step 2:
Open this link - http://tomeko.net/online_tools/hex_to_base64.php
Paste the SHA1 Key in Hex String
Click convert button
Get the Release Keyhash in Output value
What does ** (double star/asterisk) and * (star/asterisk) do for parameters?
I want to give an example which others haven't mentioned
* can also unpack a generator
An example from Python3 Document
x = [1, 2, 3]
y = [4, 5, 6]
unzip_x, unzip_y = zip(*zip(x, y))
unzip_x will be [1, 2, 3], unzip_y will be [4, 5, 6]
The zip() receives multiple iretable args, and return a generator.
zip(*zip(x,y)) -> zip((1, 4), (2, 5), (3, 6))
Border in shape xml
If you want make a border in a shape xml. You need to use:
For the external border,you need to use:
<stroke/>
For the internal background,you need to use:
<solid/>
If you want to set corners,you need to use:
<corners/>
If you want a padding betwen border and the internal elements,you need to use:
<padding/>
Here is a shape xml example using the above items. It works for me
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="2dp" android:color="#D0CFCC" />
<solid android:color="#F8F7F5" />
<corners android:radius="10dp" />
<padding android:left="2dp" android:top="2dp" android:right="2dp" android:bottom="2dp" />
</shape>
How to display raw html code in PRE or something like it but without escaping it
Cheap and cheerful answer:
<textarea>Some raw content</textarea>
The textarea will handle tabs, multiple spaces, newlines, line wrapping all verbatim.
It copies and pastes nicely and its valid HTML all the way. It also allows the user to resize the code box.
You don't need any CSS, JS, escaping, encoding.
You can alter the appearance and behaviour as well.
Here's a monospace font, editing disabled, smaller font, no border:
<textarea
style="width:100%; font-family: Monospace; font-size:10px; border:0;"
rows="30" disabled
>Some raw content</textarea>
This solution is probably not semantically correct. So if you need that, it might be best to choose a more sophisticated answer.
How to append rows to an R data frame
Update
Not knowing what you are trying to do, I'll share one more suggestion: Preallocate vectors of the type you want for each column, insert values into those vectors, and then, at the end, create your data.frame
.
Continuing with Julian's f3
(a preallocated data.frame
) as the fastest option so far, defined as:
# pre-allocate space
f3 <- function(n){
df <- data.frame(x = numeric(n), y = character(n), stringsAsFactors = FALSE)
for(i in 1:n){
df$x[i] <- i
df$y[i] <- toString(i)
}
df
}
Here's a similar approach, but one where the data.frame
is created as the last step.
# Use preallocated vectors
f4 <- function(n) {
x <- numeric(n)
y <- character(n)
for (i in 1:n) {
x[i] <- i
y[i] <- i
}
data.frame(x, y, stringsAsFactors=FALSE)
}
microbenchmark
from the "microbenchmark" package will give us more comprehensive insight than system.time
:
library(microbenchmark)
microbenchmark(f1(1000), f3(1000), f4(1000), times = 5)
# Unit: milliseconds
# expr min lq median uq max neval
# f1(1000) 1024.539618 1029.693877 1045.972666 1055.25931 1112.769176 5
# f3(1000) 149.417636 150.529011 150.827393 151.02230 160.637845 5
# f4(1000) 7.872647 7.892395 7.901151 7.95077 8.049581 5
f1()
(the approach below) is incredibly inefficient because of how often it calls data.frame
and because growing objects that way is generally slow in R. f3()
is much improved due to preallocation, but the data.frame
structure itself might be part of the bottleneck here. f4()
tries to bypass that bottleneck without compromising the approach you want to take.
Original answer
This is really not a good idea, but if you wanted to do it this way, I guess you can try:
for (i in 1:10) {
df <- rbind(df, data.frame(x = i, y = toString(i)))
}
Note that in your code, there is one other problem:
- You should use
stringsAsFactors
if you want the characters to not get converted to factors. Use: df = data.frame(x = numeric(), y = character(), stringsAsFactors = FALSE)
less than 10 add 0 to number
You can always do
('0' + deg).slice(-2)
See slice()
:
You can also use negative numbers to select from the end of an array
Hence
('0' + 11).slice(-2) // '11'
('0' + 4).slice(-2) // '04'
For ease of access, you could of course extract it to a function, or even extend Number
with it:
Number.prototype.pad = function(n) {
return new Array(n).join('0').slice((n || 2) * -1) + this;
}
Which will allow you to write:
c += deg.pad() + '° '; // "04° "
The above function pad
accepts an argument specifying the length of the desired string. If no such argument is used, it defaults to 2. You could write:
deg.pad(4) // "0045"
Note the obvious drawback that the value of n
cannot be higher than 11, as the string of 0's is currently just 10 characters long. This could of course be given a technical solution, but I did not want to introduce complexity in such a simple function. (Should you elect to, see alex's answer for an excellent approach to that).
Note also that you would not be able to write 2.pad()
. It only works with variables. But then, if it's not a variable, you'll always know beforehand how many digits the number consists of.
find . -type f -exec chmod 644 {} ;
A good alternative is this:
find . -type f | xargs chmod -v 644
and for directories:
find . -type d | xargs chmod -v 755
and to be more explicit:
find . -type f | xargs -I{} chmod -v 644 {}
Winforms TableLayoutPanel adding rows programmatically
Create a table layout panel with two columns in your form and name it tlpFields
.
Then, simply add new control to table layout panel (in this case I added 5 labels in column-1 and 5 textboxes in column-2).
tlpFields.RowStyles.Clear(); //first you must clear rowStyles
for (int ii = 0; ii < 5; ii++)
{
Label l1= new Label();
TextBox t1 = new TextBox();
l1.Text = "field : ";
tlpFields.Controls.Add(l1, 0, ii); // add label in column0
tlpFields.Controls.Add(t1, 1, ii); // add textbox in column1
tlpFields.RowStyles.Add(new RowStyle(SizeType.Absolute,30)); // 30 is the rows space
}
Finally, run the code.
Maven: How to change path to target directory from command line?
Colin is correct that a profile should be used. However, his answer hard-codes the target directory in the profile. An alternate solution would be to add a profile like this:
<profile>
<id>alternateBuildDir</id>
<activation>
<property>
<name>alt.build.dir</name>
</property>
</activation>
<build>
<directory>${alt.build.dir}</directory>
</build>
</profile>
Doing so would have the effect of changing the build directory to whatever is given by the alt.build.dir property, which can be given in a POM, in the user's settings, or on the command line. If the property is not present, the compilation will happen in the normal target directory.
MySQL: #1075 - Incorrect table definition; autoincrement vs another key?
First create table without auto_increment,
CREATE TABLE `members`(
`id` int(11) NOT NULL,
`memberid` VARCHAR( 30 ) NOT NULL ,
`Time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
`firstname` VARCHAR( 50 ) NULL ,
`lastname` VARCHAR( 50 ) NULL
PRIMARY KEY (memberid)
) ENGINE = MYISAM;
after set id as index,
ALTER TABLE `members` ADD INDEX(`id`);
after set id as auto_increment,
ALTER TABLE `members` CHANGE `id` `id` INT(11) NOT NULL AUTO_INCREMENT;
Or
CREATE TABLE IF NOT EXISTS `members` (
`id` int(11) NOT NULL,
`memberid` VARCHAR( 30 ) NOT NULL ,
`Time` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
`firstname` VARCHAR( 50 ) NULL ,
`lastname` VARCHAR( 50 ) NULL,
PRIMARY KEY (`memberid`),
KEY `id` (`id`)
) ENGINE=MYISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
SQL Server - Create a copy of a database table and place it in the same database?
Use SELECT ... INTO
:
SELECT *
INTO ABC_1
FROM ABC;
This will create a new table ABC_1
that has the same column structure as ABC
and contains the same data. Constraints (e.g. keys, default values), however, are -not- copied.
You can run this query multiple times with a different table name each time.
If you don't need to copy the data, only to create a new empty table with the same column structure, add a WHERE
clause with a falsy expression:
SELECT *
INTO ABC_1
FROM ABC
WHERE 1 <> 1;
Jenkins not executing jobs (pending - waiting for next executor)
I'm a little late to the game, but this may help others.
In my case my jenkins master has a shared external resource, which is allocated to jenkins jobs by the external-resource-dispatcher-plugin. Due to bug JENKINS-19439 in the plugin (which is in beta), I found that my resource had been locked by a previous job, but wasn't unlocked when that previous job was cancelled.
To find out if a resource is currently in the locked state, navigate to the affected jenkins node, Jenkins -> Manage Jenkins -> Manage Nodes -> master
You should see the current state of any external resources. If any are unexpectedly locked this may be the reason why jobs are waiting for an executor.
I couldn't find any details of how to manually resolve this issue.
Restarting jenkins didn't resolve the problem.
In the end I went with the brutal approach:
- Remove the external resource
(see Jenkins -> Manage Jenkins -> Manage Nodes -> master -> configure)
- Restart jenkins
- Re-create the external resource
How can I rebuild indexes and update stats in MySQL innoDB?
Why? One almost never needs to update the statistics. Rebuilding an index is even more rarely needed.
OPTIMIZE TABLE tbl;
will rebuild the indexes and do ANALYZE
; it takes time.
ANALYZE TABLE tbl;
is fast for InnoDB to rebuild the stats. With 5.6.6 it is even less needed.
Prevent form submission on Enter key press
A react js solution
handleChange: function(e) {
if (e.key == 'Enter') {
console.log('test');
}
<div>
<Input type="text"
ref = "input"
placeholder="hiya"
onKeyPress={this.handleChange}
/>
</div>
Appending items to a list of lists in python
import csv
cols = [' V1', ' I1'] # define your columns here, check the spaces!
data = [[] for col in cols] # this creates a list of **different** lists, not a list of pointers to the same list like you did in [[]]*len(positions)
with open('data.csv', 'r') as f:
for rec in csv.DictReader(f):
for l, col in zip(data, cols):
l.append(float(rec[col]))
print data
# [[3.0, 3.0], [0.01, 0.01]]
Selenium IDE - Command to wait for 5 seconds
For those working with ant
, I use this to indicate a pause of 5 seconds:
<tr>
<td>pause</td>
<td>5000</td>
<td></td>
</tr>
That is, target: 5000
and value
empty. As the reference indicates:
pause(waitTime)
Arguments:
- waitTime - the amount of time to sleep (in milliseconds)
Wait for the specified amount of time (in milliseconds)
How To change the column order of An Existing Table in SQL Server 2008
Relying on column order is generally a bad idea in SQL. SQL is based on Relational theory where order is never guaranteed - by design. You should treat all your columns and rows as having no order and then change your queries to provide the correct results:
For Columns:
- Try not to use SELECT *, but instead specify the order of columns in the select list as in: SELECT Member_ID, MemberName, MemberAddress from TableName. This will guarantee order and will ease maintenance if columns get added.
For Rows:
- Row order in your result set is only guaranteed if you specify the ORDER BY clause.
- If no ORDER BY clause is specified the result set may differ as the Query Plan might differ or the database pages might have changed.
Hope this helps...
What does %s and %d mean in printf in the C language?
%d is print as an int
%s is print as a string
%f is print as floating point
It should be noted that it is incorrect to say that this is different from Java. Printf stands for print format, if you do a formatted print in Java, this is exactly the same usage. This may allow you to solve interesting and new problems in both C and Java!
Which comment style should I use in batch files?
James K, I'm sorry I was wrong in a fair portion of what I said. The test I did was the following:
@ECHO OFF
(
:: But
: neither
:: does
: this
:: also.
)
This meets your description of alternating but fails with a ") was unexpected at this time." error message.
I did some farther testing today and found that alternating isn't the key but it appears the key is having an even number of lines, not having any two lines in a row starting with double colons (::) and not ending in double colons. Consider the following:
@ECHO OFF
(
: But
: neither
: does
: this
: cause
: problems.
)
This works!
But also consider this:
@ECHO OFF
(
: Test1
: Test2
: Test3
: Test4
: Test5
ECHO.
)
The rule of having an even number of comments doesn't seems to apply when ending in a command.
Unfortunately this is just squirrelly enough that I'm not sure I want to use it.
Really, the best solution, and the safest that I can think of, is if a program like Notepad++ would read REM as double colons and then would write double colons back as REM statements when the file is saved. But I'm not aware of such a program and I'm not aware of any plugins for Notepad++ that does that either.
How to use sys.exit() in Python
I think you can use
sys.exit(0)
You may check it here in the python 2.7 doc:
The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like.
Can you write virtual functions / methods in Java?
All functions in Java are virtual by default.
You have to go out of your way to write non-virtual functions by adding the "final" keyword.
This is the opposite of the C++/C# default. Class functions are non-virtual by default; you make them so by adding the "virtual" modifier.
Get Country of IP Address with PHP
Install and use PHP's GeoIP extension if you can. On debian lenny:
sudo wget http://geolite.maxmind.com/download/geoip/database/GeoLiteCity.dat.gz
sudo gunzip GeoLiteCity.dat.gz
sudo mkdir -v /usr/share/GeoIP
sudo mv -v GeoLiteCity.dat /usr/share/GeoIP/GeoIPCity.dat
sudo apt-get install php5-geoip
# or sudo apt-get install php-geoip for PHP7
and then try it in PHP:
$ip = $_SERVER['REMOTE_ADDR'];
$country = geoip_country_name_by_name($ip);
echo 'The current user is located in: ' . $country;
returns:
The current user is located in: Cameroon
Creating SVG graphics using Javascript?
Currently all major browsers support svg. Create svg in JS is very simple
(currently innerHTML=...
is quite fast)
element.innerHTML = `
<svg viewBox="0 0 400 100" >
<circle id="circ" cx="50" cy="50" r="50" fill="red" />
</svg>
`;
_x000D_
_x000D_
function createSVG() {
box.innerHTML = `
<svg viewBox="0 0 400 100" >
<circle id="circ" cx="50" cy="50" r="50" fill="red" />
</svg>
`;
}
function decRadius() {
r=circ.getAttribute('r');
circ.setAttribute('r',r*0.5);
}
_x000D_
<button onclick="createSVG()">Create SVG</button>
<button onclick="decRadius()">Decrease radius</button>
<div id="box"></div>
_x000D_
_x000D_
_x000D_
Check if current date is between two dates Oracle SQL
TSQL: Dates- need to look for gaps in dates between Two Date
select
distinct
e1.enddate,
e3.startdate,
DATEDIFF(DAY,e1.enddate,e3.startdate)-1 as [Datediff]
from #temp e1
join #temp e3 on e1.enddate < e3.startdate
/* Finds the next start Time */
and e3.startdate = (select min(startdate) from #temp e5
where e5.startdate > e1.enddate)
and not exists (select * /* Eliminates e1 rows if it is overlapped */
from #temp e5
where e5.startdate < e1.enddate and e5.enddate > e1.enddate);
In a URL, should spaces be encoded using %20 or +?
It shouldn't matter, any more than if you encoded the letter A as %41.
However, if you're dealing with a system that doesn't recognize one form, it seems like you're just going to have to give it what it expects regardless of what the "spec" says.
Finding median of list in Python
I posted my solution at Python implementation of "median of medians" algorithm , which is a little bit faster than using sort(). My solution uses 15 numbers per column, for a speed ~5N which is faster than the speed ~10N of using 5 numbers per column. The optimal speed is ~4N, but I could be wrong about it.
Per Tom's request in his comment, I added my code here, for reference. I believe the critical part for speed is using 15 numbers per column, instead of 5.
#!/bin/pypy
#
# TH @stackoverflow, 2016-01-20, linear time "median of medians" algorithm
#
import sys, random
items_per_column = 15
def find_i_th_smallest( A, i ):
t = len(A)
if(t <= items_per_column):
# if A is a small list with less than items_per_column items, then:
#
# 1. do sort on A
# 2. find i-th smallest item of A
#
return sorted(A)[i]
else:
# 1. partition A into columns of k items each. k is odd, say 5.
# 2. find the median of every column
# 3. put all medians in a new list, say, B
#
B = [ find_i_th_smallest(k, (len(k) - 1)/2) for k in [A[j:(j + items_per_column)] for j in range(0,len(A),items_per_column)]]
# 4. find M, the median of B
#
M = find_i_th_smallest(B, (len(B) - 1)/2)
# 5. split A into 3 parts by M, { < M }, { == M }, and { > M }
# 6. find which above set has A's i-th smallest, recursively.
#
P1 = [ j for j in A if j < M ]
if(i < len(P1)):
return find_i_th_smallest( P1, i)
P3 = [ j for j in A if j > M ]
L3 = len(P3)
if(i < (t - L3)):
return M
return find_i_th_smallest( P3, i - (t - L3))
# How many numbers should be randomly generated for testing?
#
number_of_numbers = int(sys.argv[1])
# create a list of random positive integers
#
L = [ random.randint(0, number_of_numbers) for i in range(0, number_of_numbers) ]
# Show the original list
#
# print L
# This is for validation
#
# print sorted(L)[int((len(L) - 1)/2)]
# This is the result of the "median of medians" function.
# Its result should be the same as the above.
#
print find_i_th_smallest( L, (len(L) - 1) / 2)
How to roundup a number to the closest ten?
You can use the function MROUND(<reference cell>, <round to multiple of digit needed>)
.
Example:
For a value A1 = 21
round to multiple of 10 it would be written as
=MROUND(A1,10)
for which Result = 20
For a value Z4 = 55.1
round to multiple of 10 it would be written as
=MROUND(Z4,10)
for which Result = 60
Why does Lua have no "continue" statement?
The way that the language manages lexical scope creates issues with including both goto
and continue
. For example,
local a=0
repeat
if f() then
a=1 --change outer a
end
local a=f() -- inner a
until a==0 -- test inner a
The declaration of local a
inside the loop body masks the outer variable named a
, and the scope of that local extends across the condition of the until
statement so the condition is testing the innermost a
.
If continue
existed, it would have to be restricted semantically to be only valid after all of the variables used in the condition have come into scope. This is a difficult condition to document to the user and enforce in the compiler. Various proposals around this issue have been discussed, including the simple answer of disallowing continue
with the repeat ... until
style of loop. So far, none have had a sufficiently compelling use case to get them included in the language.
The work around is generally to invert the condition that would cause a continue
to be executed, and collect the rest of the loop body under that condition. So, the following loop
-- not valid Lua 5.1 (or 5.2)
for k,v in pairs(t) do
if isstring(k) then continue end
-- do something to t[k] when k is not a string
end
could be written
-- valid Lua 5.1 (or 5.2)
for k,v in pairs(t) do
if not isstring(k) then
-- do something to t[k] when k is not a string
end
end
It is clear enough, and usually not a burden unless you have a series of elaborate culls that control the loop operation.
Using querySelectorAll to retrieve direct children
I Use This:
You can avoid typing "myDiv" twice AND using the arrow.
There are of course always more possibilities.
A modern browser is probably required.
<!-- Sample Code -->
<div id="myDiv">
<div class="foo">foo 1</div>
<div class="foo">foo 2
<div class="bar">bar</div>
</div>
<div class="foo">foo 3</div>
</div>
// Return HTMLCollection (Matches 3 Elements)
var allMyChildren = document.querySelector("#myDiv").children;
// Return NodeList (Matches 7 Nodes)
var allMyChildren = document.querySelector("#myDiv").childNodes;
// Match All Children With Class Of Foo (Matches 3 Elements)
var myFooChildren = document.querySelector("#myDiv").querySelectorAll(".foo");
// Match Second Child With Class Of Foo (Matches 1 Element)
var mySecondChild = document.querySelector("#myDiv").querySelectorAll(".foo")[1];
// Match All Children With Class Of Bar (Matches 1 Element)
var myBarChild = document.querySelector("#myDiv").querySelector(".bar");
// Match All Elements In "myDiv" (Matches 4 Elements)
var myDescendants = document.querySelector("#myDiv").querySelectorAll("*");
load Js file in HTML
I had the same problem, and found the answer.
If you use node.js with express, you need to give it its own function in order for the js file to be reached.
For example:
const script = path.join(__dirname, 'script.js');
const server = express().get('/', (req, res) => res.sendFile(script))
Always pass weak reference of self into block in ARC?
As Leo points out, the code you added to your question would not suggest a strong reference cycle (a.k.a., retain cycle). One operation-related issue that could cause a strong reference cycle would be if the operation is not getting released. While your code snippet suggests that you have not defined your operation to be concurrent, but if you have, it wouldn't be released if you never posted isFinished
, or if you had circular dependencies, or something like that. And if the operation isn't released, the view controller wouldn't be released either. I would suggest adding a breakpoint or NSLog
in your operation's dealloc
method and confirm that's getting called.
You said:
I understand the notion of retain cycles, but I am not quite sure what happens in blocks, so that confuses me a little bit
The retain cycle (strong reference cycle) issues that occur with blocks are just like the retain cycle issues you're familiar with. A block will maintain strong references to any objects that appear within the block, and it will not release those strong references until the block itself is released. Thus, if block references self
, or even just references an instance variable of self
, that will maintain strong reference to self, that is not resolved until the block is released (or in this case, until the NSOperation
subclass is released.
For more information, see the Avoid Strong Reference Cycles when Capturing self section of the Programming with Objective-C: Working with Blocks document.
If your view controller is still not getting released, you simply have to identify where the unresolved strong reference resides (assuming you confirmed the NSOperation
is getting deallocated). A common example is the use of a repeating NSTimer
. Or some custom delegate
or other object that is erroneously maintaining a strong
reference. You can often use Instruments to track down where objects are getting their strong references, e.g.:
Or in Xcode 5:
How do I return multiple values from a function in C?
I don't know what your string
is, but I'm going to assume that it manages its own memory.
You have two solutions:
1: Return a struct
which contains all the types you need.
struct Tuple {
int a;
string b;
};
struct Tuple getPair() {
Tuple r = { 1, getString() };
return r;
}
void foo() {
struct Tuple t = getPair();
}
2: Use pointers to pass out values.
void getPair(int* a, string* b) {
// Check that these are not pointing to NULL
assert(a);
assert(b);
*a = 1;
*b = getString();
}
void foo() {
int a, b;
getPair(&a, &b);
}
Which one you choose to use depends largely on personal preference as to whatever semantics you like more.
Remove CSS from a Div using JQuery
i have same prob too,
just remove the value
<script>
$("#play").toggle(function(){$(this).css("background","url(player.png) -100px 0px no-repeat");},
function(){$(this).css("background","");});
</script>
How to create a temporary directory/folder in Java?
The Google Guava library has a ton of helpful utilities. One of note here is the Files class. It has a bunch of useful methods including:
File myTempDir = Files.createTempDir();
This does exactly what you asked for in one line. If you read the documentation here you'll see that the proposed adaptation of File.createTempFile("install", "dir")
typically introduces security vulnerabilities.
How to run composer from anywhere?
How to run Composer From Anywhere (on MacOS X) via Terminal
Background:
Actually in getComposer website it clearly states that, install the Composer by using the following curl command,
curl -sS https://getcomposer.org/installer |php
And it certainly does what it's intended to do. And then it says to move the composer.phar to the directory /usr/local/bin/composer and then composer will be available Globally, by using the following command line in terminal!
mv composer.phar /usr/local/bin/composer
Question:
So the problem which leads me to Google over it is when I executed the above line in Mac OS X Terminal, it said that, Permission denied. Like as follows:
mv: rename composer.phar to /usr/local/bin/composer: Permission denied
Answer:
Following link led me to the solution like a charm and I'm thankful to that. The thing I just missed was sudo command before the above stated "Move" command line.
Now my Move command is as follows:
sudo mv composer.phar /usr/local/bin/composer
Password:
It directly prompts you to authenticate yourself and see if you are authorized. So if you enter a valid password, then the Moving will be done, and you can just check if composer is globally installed, by using the following line.
composer about
I hope this answer helped you to broaden your view and finally resolve your problem.
Cheers!
Angular 4: How to include Bootstrap?
npm install --save bootstrap
afterwards, inside angular-cli.json (inside the project's root folder), find styles
and add the bootstrap css file like this:
"styles": [
"../node_modules/bootstrap/dist/css/bootstrap.min.css",
"styles.css"
],
UPDATE:
in angular 6+ angular-cli.json
was changed to angular.json
.
How to use *ngIf else?
Syntax for ngIf/Else
<div *ngIf=”condition; else elseBlock”>Truthy condition</div>
<ng-template #elseBlock>Falsy condition</ng-template>
Using NgIf / Else/ Then explicit syntax
To add then template we just have to bind it to a template explicitly.
<div *ngIf=”condition; then thenBlock else elseBlock”> ... </div>
<ng-template #thenBlock>Then template</ng-template>
<ng-template #elseBlock>Else template</ng-template>
Observables with NgIf and Async Pipe
For more details
log4net vs. Nlog
For anyone getting to this thread late, you may want to take a look back at the .Net Base Class Library (BCL). Many people missed the changes between .Net 1.1 and .Net 2.0 when the TraceSource class was introduced (circa 2005).
Using the TraceSource is analagous to other logging frameworks, with granular control of logging, configuration in app.config/web.config, and programmatic access - without the overhead of the enterprise application block.
There are also a number of comparisons floating around: "log4net vs TraceSource"
CSS3 Transform Skew One Side
Maybe you want to use CSS "clip-path" (Works with transparency and background)
"clip-path" reference: https://developer.mozilla.org/en-US/docs/Web/CSS/clip-path
Generator: http://bennettfeely.com/clippy/
Example:
_x000D_
_x000D_
/* With percent */_x000D_
.element-percent {_x000D_
background: red;_x000D_
width: 150px;_x000D_
height: 48px;_x000D_
display: inline-block;_x000D_
_x000D_
clip-path: polygon(0 0, 100% 0%, 75% 100%, 0% 100%);_x000D_
}_x000D_
_x000D_
/* With pixel */_x000D_
.element-pixel {_x000D_
background: blue;_x000D_
width: 150px;_x000D_
height: 48px;_x000D_
display: inline-block;_x000D_
_x000D_
clip-path: polygon(0 0, 100% 0%, calc(100% - 32px) 100%, 0% 100%);_x000D_
}_x000D_
_x000D_
/* With background */_x000D_
.element-background {_x000D_
background: url(https://images.pexels.com/photos/170811/pexels-photo-170811.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260) no-repeat center/cover;_x000D_
width: 150px;_x000D_
height: 48px;_x000D_
display: inline-block;_x000D_
_x000D_
clip-path: polygon(0 0, 100% 0%, calc(100% - 32px) 100%, 0% 100%);_x000D_
}
_x000D_
<div class="element-percent"></div>_x000D_
_x000D_
<br />_x000D_
_x000D_
<div class="element-pixel"></div>_x000D_
_x000D_
<br />_x000D_
_x000D_
<div class="element-background"></div>
_x000D_
_x000D_
_x000D_
Detecting scroll direction
It can be detected by storing the previous scrollTop
value and comparing the current scrollTop value with it.
JavaScript :
var lastScrollTop = 0;
// element should be replaced with the actual target element on which you have applied scroll, use window in case of no target element.
element.addEventListener("scroll", function(){ // or window.addEventListener("scroll"....
var st = window.pageYOffset || document.documentElement.scrollTop; // Credits: "https://github.com/qeremy/so/blob/master/so.dom.js#L426"
if (st > lastScrollTop){
// downscroll code
} else {
// upscroll code
}
lastScrollTop = st <= 0 ? 0 : st; // For Mobile or negative scrolling
}, false);
How to remove html special chars?
You may want take a look at htmlentities() and html_entity_decode() here
$orig = "I'll \"walk\" the <b>dog</b> now";
$a = htmlentities($orig);
$b = html_entity_decode($a);
echo $a; // I'll "walk" the <b>dog</b> now
echo $b; // I'll "walk" the <b>dog</b> now
How to set the color of an icon in Angular Material?
Or simply
add to your element
[ngStyle]="{'color': myVariableColor}"
eg
<mat-icon [ngStyle]="{'color': myVariableColor}">{{ getActivityIcon() }}</mat-icon>
Where color
can be defined at another component etc
XPath to fetch SQL XML value
Update
My recomendation would be to shred the XML into relations and do searches and joins on the resulted relation, in a set oriented fashion, rather than the procedural fashion of searching specific nodes in the XML. Here is a simple XML query that shreds out the nodes and attributes of interest:
select x.value(N'../../../../@stepId', N'int') as StepID
, x.value(N'../../@id', N'int') as ComponentID
, x.value(N'@nom',N'nvarchar(100)') as Nom
, x.value(N'@valeur', N'nvarchar(100)') as Valeur
from @x.nodes(N'/xml/box/components/component/variables/variable') t(x)
However, if you must use an XPath that retrieves exactly the value of interest:
select x.value(N'@valeur', N'nvarchar(100)') as Valeur
from @x.nodes(N'/xml/box[@stepId=sql:variable("@stepID")]/
components/component[@id = sql:variable("@componentID")]/
variables/variable[@nom="Enabled"]') t(x)
If the stepID and component ID are columns, not variables, the you should use sql:column() instead of sql:variable in the XPath filters. See Binding Relational Data Inside XML Data.
And finaly if all you need is to check for existance you can use the exist() XML method:
select @x.exist(
N'/xml/box[@stepId=sql:variable("@stepID")]/
components/component[@id = sql:variable("@componentID")]/
variables/variable[@nom="Enabled" and @valeur="Yes"]')
403 Forbidden vs 401 Unauthorized HTTP responses
In English:
401
You are potentially allowed access but for some reason on this request you were
denied. Such as a bad password? Try again, with the correct request
you will get a success response instead.
403
You are not, ever, allowed. Your name is not on the list, you won't
ever get in, go away, don't send a re-try request, it will be refused,
always. Go away.
Getting MAC Address
You can do this with psutil which is cross-platform:
import psutil
nics = psutil.net_if_addrs()
print [j.address for j in nics[i] for i in nics if i!="lo" and j.family==17]
What are the RGB codes for the Conditional Formatting 'Styles' in Excel?
I imagine that these might possibly be changed with some styling options. But as far as default values go, these are taken from my version of Excel 2010 which should have the defaults.
"Bad" Red Font: 156, 0, 6; Fill: 255, 199, 206
"Good" Green Font: 0, 97, 0; Fill: 198, 239, 206
"Neutral" Yellow Font: 156, 101, 0; Fill: 255, 235, 156
Java : Sort integer array without using Arrays.sort()
This will surely help you.
int n[] = {4,6,9,1,7};
for(int i=n.length;i>=0;i--){
for(int j=0;j<n.length-1;j++){
if(n[j] > n[j+1]){
swapNumbers(j,j+1,n);
}
}
}
printNumbers(n);
}
private static void swapNumbers(int i, int j, int[] array) {
int temp;
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private static void printNumbers(int[] input) {
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + ", ");
}
System.out.println("\n");
}
HTTP Content-Type Header and JSON
Recently ran into a problem with this and a Chrome extension that was corrupting a JSON stream when the response header labeled the content-type as 'text/html' apparently extensions can and will use the response header to alter the content prior to further processing by the browser. Changing the content-type fixed the issue.
Swipe ListView item From right to left show delete button
see there link was very nice and simple. its working fine...
u don't want any library its working fine. click here
OnTouchListener gestureListener = new View.OnTouchListener() {
private int padding = 0;
private int initialx = 0;
private int currentx = 0;
private ViewHolder viewHolder;
public boolean onTouch(View v, MotionEvent event) {
if ( event.getAction() == MotionEvent.ACTION_DOWN) {
padding = 0;
initialx = (int) event.getX();
currentx = (int) event.getX();
viewHolder = ((ViewHolder) v.getTag());
}
if ( event.getAction() == MotionEvent.ACTION_MOVE) {
currentx = (int) event.getX();
padding = currentx - initialx;
}
if ( event.getAction() == MotionEvent.ACTION_UP ||
event.getAction() == MotionEvent.ACTION_CANCEL) {
padding = 0;
initialx = 0;
currentx = 0;
}
if(viewHolder != null) {
if(padding == 0) {
v.setBackgroundColor(0xFF000000 );
if(viewHolder.running)
v.setBackgroundColor(0xFF058805);
}
if(padding > 75) {
viewHolder.running = true;
v.setBackgroundColor(0xFF00FF00 );
viewHolder.icon.setImageResource(R.drawable.clock_running);
}
if(padding < -75) {
viewHolder.running = false;
v.setBackgroundColor(0xFFFF0000 );
}
v.setPadding(padding, 0,0, 0);
}
return true;
}
};
How can I format DateTime to web UTC format?
You want to use DateTimeOffset class.
var date = new DateTimeOffset(2009, 9, 1, 0, 0, 0, 0, new TimeSpan(0L));
var stringDate = date.ToString("u");
sorry I missed your original formatting with the miliseconds
var stringDate = date.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fff'Z'");
How do I convert csv file to rdd
Firstly I must say that it's much much simpler if you put your headers in separate files - this is the convention in big data.
Anyway Daniel's answer is pretty good, but it has an inefficiency and a bug, so I'm going to post my own. The inefficiency is that you don't need to check every record to see if it's the header, you just need to check the first record for each partition. The bug is that by using .split(",")
you could get an exception thrown or get the wrong column when entries are the empty string and occur at the start or end of the record - to correct that you need to use .split(",", -1)
. So here is the full code:
val header =
scala.io.Source.fromInputStream(
hadoop.fs.FileSystem.get(new java.net.URI(filename), sc.hadoopConfiguration)
.open(new hadoop.fs.Path(path)))
.getLines.head
val columnIndex = header.split(",").indexOf(columnName)
sc.textFile(path).mapPartitions(iterator => {
val head = iterator.next()
if (head == header) iterator else Iterator(head) ++ iterator
})
.map(_.split(",", -1)(columnIndex))
Final points, consider Parquet if you want to only fish out certain columns. Or at least consider implementing a lazily evaluated split function if you have wide rows.
Include headers when using SELECT INTO OUTFILE?
The easiest way is to hard code the columns yourself to better control the output file:
SELECT 'ColName1', 'ColName2', 'ColName3'
UNION ALL
SELECT ColName1, ColName2, ColName3
FROM YourTable
INTO OUTFILE '/path/outfile'
How to round an average to 2 decimal places in PostgreSQL?
According to Bryan's response you can do this to limit decimals in a query. I convert from km/h to m/s and display it in dygraphs but when I did it in dygraphs it looked weird. Looks fine when doing the calculation in the query instead. This is on postgresql 9.5.1.
select date,(wind_speed/3.6)::numeric(7,1) from readings;
How to Calculate Execution Time of a Code Snippet in C++
You could also look at the [cxx-rtimers][1]
on GitHub, which provide some header-only routines for gathering statistics on the run-time of any code-block where you can create a local variable. Those timers have versions that use std::chrono on C++11, or timers from the Boost library, or standard POSIX timer functions. These timers will report the average, maximum & minimum duration spent within a function, as well as the number of times it is called. They can be used as simply as follows:
#include <rtimers/cxx11.hpp>
void expensiveFunction() {
static rtimers::cxx11::DefaultTimer timer("expensive");
auto scopedStartStop = timer.scopedStart();
// Do something costly...
}
Selenium webdriver click google search
public class GoogleSearch {
public static void main(String[] args) {
WebDriver driver=new FirefoxDriver();
driver.get("http://www.google.com");
driver.findElement(By.xpath("//input[@type='text']")).sendKeys("Cheese");
driver.findElement(By.xpath("//button[@name='btnG']")).click();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
driver.findElement(By.xpath("(//h3[@class='r']/a)[3]")).click();
driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS);
}
}
Removing duplicate objects with Underscore for Javascript
If you're looking to remove duplicates based on an id you could do something like this:
var res = [
{id: 1, content: 'heeey'},
{id: 2, content: 'woah'},
{id: 1, content:'foo'},
{id: 1, content: 'heeey'},
];
var uniques = _.map(_.groupBy(res,function(doc){
return doc.id;
}),function(grouped){
return grouped[0];
});
//uniques
//[{id: 1, content: 'heeey'},{id: 2, content: 'woah'}]
Why use double indirection? or Why use pointers to pointers?
If you want to have a list of characters (a word), you can use char *word
If you want a list of words (a sentence), you can use char **sentence
If you want a list of sentences (a monologue), you can use char ***monologue
If you want a list of monologues (a biography), you can use char ****biography
If you want a list of biographies (a bio-library), you can use char *****biolibrary
If you want a list of bio-libraries (a ??lol), you can use char ******lol
... ...
yes, I know these might not be the best data structures
Usage example with a very very very boring lol
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int wordsinsentence(char **x) {
int w = 0;
while (*x) {
w += 1;
x++;
}
return w;
}
int wordsinmono(char ***x) {
int w = 0;
while (*x) {
w += wordsinsentence(*x);
x++;
}
return w;
}
int wordsinbio(char ****x) {
int w = 0;
while (*x) {
w += wordsinmono(*x);
x++;
}
return w;
}
int wordsinlib(char *****x) {
int w = 0;
while (*x) {
w += wordsinbio(*x);
x++;
}
return w;
}
int wordsinlol(char ******x) {
int w = 0;
while (*x) {
w += wordsinlib(*x);
x++;
}
return w;
}
int main(void) {
char *word;
char **sentence;
char ***monologue;
char ****biography;
char *****biolibrary;
char ******lol;
//fill data structure
word = malloc(4 * sizeof *word); // assume it worked
strcpy(word, "foo");
sentence = malloc(4 * sizeof *sentence); // assume it worked
sentence[0] = word;
sentence[1] = word;
sentence[2] = word;
sentence[3] = NULL;
monologue = malloc(4 * sizeof *monologue); // assume it worked
monologue[0] = sentence;
monologue[1] = sentence;
monologue[2] = sentence;
monologue[3] = NULL;
biography = malloc(4 * sizeof *biography); // assume it worked
biography[0] = monologue;
biography[1] = monologue;
biography[2] = monologue;
biography[3] = NULL;
biolibrary = malloc(4 * sizeof *biolibrary); // assume it worked
biolibrary[0] = biography;
biolibrary[1] = biography;
biolibrary[2] = biography;
biolibrary[3] = NULL;
lol = malloc(4 * sizeof *lol); // assume it worked
lol[0] = biolibrary;
lol[1] = biolibrary;
lol[2] = biolibrary;
lol[3] = NULL;
printf("total words in my lol: %d\n", wordsinlol(lol));
free(lol);
free(biolibrary);
free(biography);
free(monologue);
free(sentence);
free(word);
}
Output:
total words in my lol: 243
The difference between sys.stdout.write and print?
Are there situations in which sys.stdout.write() is preferable to print?
I have found that stdout works better than print in a multithreading situation. I use a queue (FIFO) to store the lines to print and I hold all threads before the print line until my print queue is empty. Even so, using print I sometimes lose the final \n on the debug I/O (using the Wing Pro IDE).
When I use std.out with \n in the string, the debug I/O formats correctly and the \n's are accurately displayed.
"Cannot send session cache limiter - headers already sent"
"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.
Check that you don't send ANY content before calling session_start
. Better yet, just make session_start
the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).
Adding CSRFToken to Ajax request
If you are working in node.js with lusca try also this:
$.ajax({
url: "http://test.com",
type:"post"
headers: {'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')}
})
How to increase font size in the Xcode editor?
For Xcode 4.1
Still a huge pain. Poor UI design (But my mindset does not seem to match the mindset of software engineers that make 100+ character variable and method names. Enough of my complaining)
I'll modify a previous post for the current version.
- Close any projects you have open in Xcode (Otherwise the Font window will be inaccessible while a project is open.)
- Go to XCode > Preferences > Fonts & Color
- From the 'Theme' box select the theme you want to modify (or select the theme you want to modify and click the "+" button at the bottom of the theme list to clone it first for backup, for there is no undo option)
In the source editor box there is a list of types of text that you may set the font for:
Plain text
Comments
Documentation Comments
.
.
.
Select any or all items from the source editor list and the name and size of the font for
that particular text will show up in the 'Font' window below the 'Source Editor' window.
(If you happen to skip highlighting one of these, you will be able to get to the Font
Inspector and select new sizes, but will wonder why the changes you make are not being
applied!)
- In the 'Font' window, click the small, almost hidden, and surely poorly design 'T' icon
to the right of the font name and size.
- Voila! In only 14 keystrokes you are able to get the Font inspector window!
- Your existing font will be preselected in the font inspector. Whatever changes you make now
will be applied to the text types you selected in the 'Source Editor' window.
e.g. All Fonts > Menlo > Regular > 14
- Close the windows you opened on this hunt for the holy grail.
Congratulations. Your may now read your code.
Wasn't that painless?
How to get last inserted row ID from WordPress database?
just like this :
global $wpdb;
$table_name='lorem_ipsum';
$results = $wpdb->get_results("SELECT * FROM $table_name ORDER BY ID DESC LIMIT 1");
print_r($results[0]->id);
simply your selecting all the rows then order them DESC by id , and displaying only the first
python setup.py uninstall
At {virtualenv}/lib/python2.7/site-packages/
(if not using virtualenv then {system_dir}/lib/python2.7/dist-packages/
)
- Remove the egg file (e.g.
distribute-0.6.34-py2.7.egg
)
- If there is any from file
easy-install.pth
, remove the corresponding line (it should be a path to the source directory or of an egg file).
Get DateTime.Now with milliseconds precision
As far as I understand the question, you can go for:
DateTime dateTime = DateTime.Now;
DateTime dateTimeInMilliseconds = dateTime.AddTicks(-1 * dateTime.Ticks % 10000);
This will cut off ticks smaller than 1 millisecond.
Auto reloading python Flask app upon code changes
I got a different idea:
First:
pip install python-dotenv
Install the python-dotenv
module, which will read local preference for your project environment.
Second:
Add .flaskenv
file in your project directory. Add following code:
FLASK_ENV=development
It's done!
With this config for your Flask project, when you run flask run
and you will see this output in your terminal:
And when you edit your file, just save the change. You will see auto-reload is there for you:
With more explanation:
Of course you can manually hit export FLASK_ENV=development
every time you need. But using different configuration file to handle the actual working environment seems like a better solution, so I strongly recommend this method I use.
npx command not found
Remove NodeJs and npm in your system and reinstall it by following commands
Uninlstallation
sudo apt remove nodejs
sudo apt remove npm
Fresh Installation
sudo apt install nodejs
sudo apt install npm
Configuration optional, in some cases users may face permission errors.
user defined directory where npm will install packages
mkdir ~/.npm-global
configure npm
npm config set prefix '~/.npm-global'
add directory to path
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.profile
refresh path for the current session
source ~/.profile
cross-check npm and node modules installed successfully in our system
node -v
npm -v
Installation of npx
sudo npm i -g npx
npx -v
Well-done we are ready to go... now you can easily use npx
anywhere in your system.
Showing the stack trace from a running Python application
You can use PuDB, a Python debugger with a curses interface to do this. Just add
from pudb import set_interrupt_handler; set_interrupt_handler()
to your code and use Ctrl-C when you want to break. You can continue with c
and break again multiple times if you miss it and want to try again.
Access to Image from origin 'null' has been blocked by CORS policy
In this case the CORS problem has been caused by using the wrong source constructor in OpenLayers. ol.source.OSM is intended for accessing the default OpenStreetMap tiles from the web and for that reason defaults to crossOrigin:'anonymous'. If you are using a local source URL you should use the generic ol.source.XYZ constructor which doesn't default the crossOrigin setting (which is why setting crossOrigin:null above happened to work). And it is perfectly legitimate want to use file protocol for maps, for example on an SD card of a mobile device.
SQL Server: Invalid Column Name
This error may ALSO occur in encapsulated SQL statements e.g.
DECLARE @tableName nvarchar(20) SET @tableName = 'GROC'
DECLARE @updtStmt nvarchar(4000)
SET @updtStmt = 'Update tbProductMaster_' +@tableName +' SET
department_str = ' + @tableName exec sp_executesql @updtStmt
Only to discover that there are missing quotations to encapsulate the parameter "@tableName" further like the following:
SET @updtStmt = 'Update tbProductMaster_' +@tableName +' SET
department_str = ''' + @tableName + ''' '
Thanks
fastest MD5 Implementation in JavaScript
I only need to support HTML5 browsers that support typed arrays (DataView, ArrayBuffer, etc.)
I think I took the Joseph Myers code and modified it to support passing in a Uint8Array. I did not catch all the improvements, and there are still probably some char() array artifacts that can be improved on. I needed this for adding to the PouchDB project.
var PouchUtils = {};
PouchUtils.Crypto = {};
(function () {
PouchUtils.Crypto.MD5 = function (uint8Array) {
function md5cycle(x, k) {
var a = x[0], b = x[1], c = x[2], d = x[3];
a = ff(a, b, c, d, k[0], 7, -680876936);
d = ff(d, a, b, c, k[1], 12, -389564586);
c = ff(c, d, a, b, k[2], 17, 606105819);
b = ff(b, c, d, a, k[3], 22, -1044525330);
a = ff(a, b, c, d, k[4], 7, -176418897);
d = ff(d, a, b, c, k[5], 12, 1200080426);
c = ff(c, d, a, b, k[6], 17, -1473231341);
b = ff(b, c, d, a, k[7], 22, -45705983);
a = ff(a, b, c, d, k[8], 7, 1770035416);
d = ff(d, a, b, c, k[9], 12, -1958414417);
c = ff(c, d, a, b, k[10], 17, -42063);
b = ff(b, c, d, a, k[11], 22, -1990404162);
a = ff(a, b, c, d, k[12], 7, 1804603682);
d = ff(d, a, b, c, k[13], 12, -40341101);
c = ff(c, d, a, b, k[14], 17, -1502002290);
b = ff(b, c, d, a, k[15], 22, 1236535329);
a = gg(a, b, c, d, k[1], 5, -165796510);
d = gg(d, a, b, c, k[6], 9, -1069501632);
c = gg(c, d, a, b, k[11], 14, 643717713);
b = gg(b, c, d, a, k[0], 20, -373897302);
a = gg(a, b, c, d, k[5], 5, -701558691);
d = gg(d, a, b, c, k[10], 9, 38016083);
c = gg(c, d, a, b, k[15], 14, -660478335);
b = gg(b, c, d, a, k[4], 20, -405537848);
a = gg(a, b, c, d, k[9], 5, 568446438);
d = gg(d, a, b, c, k[14], 9, -1019803690);
c = gg(c, d, a, b, k[3], 14, -187363961);
b = gg(b, c, d, a, k[8], 20, 1163531501);
a = gg(a, b, c, d, k[13], 5, -1444681467);
d = gg(d, a, b, c, k[2], 9, -51403784);
c = gg(c, d, a, b, k[7], 14, 1735328473);
b = gg(b, c, d, a, k[12], 20, -1926607734);
a = hh(a, b, c, d, k[5], 4, -378558);
d = hh(d, a, b, c, k[8], 11, -2022574463);
c = hh(c, d, a, b, k[11], 16, 1839030562);
b = hh(b, c, d, a, k[14], 23, -35309556);
a = hh(a, b, c, d, k[1], 4, -1530992060);
d = hh(d, a, b, c, k[4], 11, 1272893353);
c = hh(c, d, a, b, k[7], 16, -155497632);
b = hh(b, c, d, a, k[10], 23, -1094730640);
a = hh(a, b, c, d, k[13], 4, 681279174);
d = hh(d, a, b, c, k[0], 11, -358537222);
c = hh(c, d, a, b, k[3], 16, -722521979);
b = hh(b, c, d, a, k[6], 23, 76029189);
a = hh(a, b, c, d, k[9], 4, -640364487);
d = hh(d, a, b, c, k[12], 11, -421815835);
c = hh(c, d, a, b, k[15], 16, 530742520);
b = hh(b, c, d, a, k[2], 23, -995338651);
a = ii(a, b, c, d, k[0], 6, -198630844);
d = ii(d, a, b, c, k[7], 10, 1126891415);
c = ii(c, d, a, b, k[14], 15, -1416354905);
b = ii(b, c, d, a, k[5], 21, -57434055);
a = ii(a, b, c, d, k[12], 6, 1700485571);
d = ii(d, a, b, c, k[3], 10, -1894986606);
c = ii(c, d, a, b, k[10], 15, -1051523);
b = ii(b, c, d, a, k[1], 21, -2054922799);
a = ii(a, b, c, d, k[8], 6, 1873313359);
d = ii(d, a, b, c, k[15], 10, -30611744);
c = ii(c, d, a, b, k[6], 15, -1560198380);
b = ii(b, c, d, a, k[13], 21, 1309151649);
a = ii(a, b, c, d, k[4], 6, -145523070);
d = ii(d, a, b, c, k[11], 10, -1120210379);
c = ii(c, d, a, b, k[2], 15, 718787259);
b = ii(b, c, d, a, k[9], 21, -343485551);
x[0] = add32(a, x[0]);
x[1] = add32(b, x[1]);
x[2] = add32(c, x[2]);
x[3] = add32(d, x[3]);
}
function cmn(q, a, b, x, s, t) {
a = add32(add32(a, q), add32(x, t));
return add32((a << s) | (a >>> (32 - s)), b);
}
function ff(a, b, c, d, x, s, t) {
return cmn((b & c) | ((~b) & d), a, b, x, s, t);
}
function gg(a, b, c, d, x, s, t) {
return cmn((b & d) | (c & (~d)), a, b, x, s, t);
}
function hh(a, b, c, d, x, s, t) {
return cmn(b ^ c ^ d, a, b, x, s, t);
}
function ii(a, b, c, d, x, s, t) {
return cmn(c ^ (b | (~d)), a, b, x, s, t);
}
function md51(s) {
txt = '';
var n = s.length,
state = [1732584193, -271733879, -1732584194, 271733878], i;
for (i = 64; i <= s.length; i += 64) {
md5cycle(state, md5blk(s.subarray(i - 64, i)));
}
s = s.subarray(i - 64);
var tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for (i = 0; i < s.length; i++)
tail[i >> 2] |= s[i] << ((i % 4) << 3);
tail[i >> 2] |= 0x80 << ((i % 4) << 3);
if (i > 55) {
md5cycle(state, tail);
for (i = 0; i < 16; i++) tail[i] = 0;
}
tail[14] = n * 8;
md5cycle(state, tail);
return state;
}
/* there needs to be support for Unicode here,
* unless we pretend that we can redefine the MD-5
* algorithm for multi-byte characters (perhaps
* by adding every four 16-bit characters and
* shortening the sum to 32 bits). Otherwise
* I suggest performing MD-5 as if every character
* was two bytes--e.g., 0040 0025 = @%--but then
* how will an ordinary MD-5 sum be matched?
* There is no way to standardize text to something
* like UTF-8 before transformation; speed cost is
* utterly prohibitive. The JavaScript standard
* itself needs to look at this: it should start
* providing access to strings as preformed UTF-8
* 8-bit unsigned value arrays.
*/
function md5blk(s) { /* I figured global was faster. */
var md5blks = [], i; /* Andy King said do it this way. */
for (i = 0; i < 64; i += 4) {
md5blks[i >> 2] = s[i]
+ (s[i + 1] << 8)
+ (s[i + 2] << 16)
+ (s[i + 3] << 24);
}
return md5blks;
}
var hex_chr = '0123456789abcdef'.split('');
function rhex(n) {
var s = '', j = 0;
for (; j < 4; j++)
s += hex_chr[(n >> (j * 8 + 4)) & 0x0F]
+ hex_chr[(n >> (j * 8)) & 0x0F];
return s;
}
function hex(x) {
for (var i = 0; i < x.length; i++)
x[i] = rhex(x[i]);
return x.join('');
}
function md5(s) {
return hex(md51(s));
}
function add32(a, b) {
return (a + b) & 0xFFFFFFFF;
}
return md5(uint8Array);
};
})();
Ajax passing data to php script
You can also use bellow code for pass data using ajax.
var dataString = "album" + title;
$.ajax({
type: 'POST',
url: 'test.php',
data: dataString,
success: function(response) {
content.html(response);
}
});
Hide/Show components in react native
// You can use a state to control wether the component is showing or not
const [show, setShow] = useState(false); // By default won't show
// In return(
{
show && <ComponentName />
}
/* Use this to toggle the state, this could be in a function in the
main javascript or could be triggered by an onPress */
show == true ? setShow(false) : setShow(true)
// Example:
const triggerComponent = () => {
show == true ? setShow(false) : setShow(true)
}
// Or
<SomeComponent onPress={() => {show == true ? setShow(false) : setShow(true)}}/>
Convert python datetime to epoch with strftime
If you want to convert a python datetime to seconds since epoch you could do it explicitly:
>>> (datetime.datetime(2012,04,01,0,0) - datetime.datetime(1970,1,1)).total_seconds()
1333238400.0
In Python 3.3+ you can use timestamp()
instead:
>>> datetime.datetime(2012,4,1,0,0).timestamp()
1333234800.0
Why you should not use datetime.strftime('%s')
Python doesn't actually support %s as an argument to strftime (if you check at http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior it's not in the list), the only reason it's working is because Python is passing the information to your system's strftime, which uses your local timezone.
>>> datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'
How to send file contents as body entity using cURL
I know the question has been answered, but in my case I was trying to send the content of a text file to the Slack Webhook api and for some reason the above answer did not work. Anywho, this is what finally did the trick for me:
curl -X POST -H --silent --data-urlencode "payload={\"text\": \"$(cat file.txt | sed "s/\"/'/g")\"}" https://hooks.slack.com/services/XXX
JavaScript Infinitely Looping slideshow with delays?
Expanding on Ender's answer, let's explore our options with the improvements from ES2015.
First off, the problem in the asker's code is the fact that setTimeout
is asynchronous while loops are synchronous. So the logical flaw is that they wrote multiple calls to an asynchronous function from a synchronous loop, expecting them to execute synchronously.
function slide() {
var num = 0;
for (num=0;num<=10;num++) {
setTimeout("document.getElementById('container').style.marginLeft='-600px'",3000);
setTimeout("document.getElementById('container').style.marginLeft='-1200px'",6000);
setTimeout("document.getElementById('container').style.marginLeft='-1800px'",9000);
setTimeout("document.getElementById('container').style.marginLeft='0px'",12000);
}
}
What happens in reality, though, is that...
- The loop "simultaneously" creates 44 async timeouts set to execute 3, 6, 9 and 12 seconds in the future. Asker expected the 44 calls to execute one-after-the-other, but instead, they all execute simultaneously.
- 3 seconds after the loop finishes,
container
's marginLeft is set to "-600px"
11 times.
- 3 seconds after that, marginLeft is set to
"-1200px"
11 times.
- 3 seconds later,
"-1800px"
, 11 times.
And so on.
You could solve this by changing it to:
function setMargin(margin){
return function(){
document.querySelector("#container").style.marginLeft = margin;
};
}
function slide() {
for (let num = 0; num <= 10; ++num) {
setTimeout(setMargin("-600px"), + (3000 * (num + 1)));
setTimeout(setMargin("-1200px"), + (6000 * (num + 1)));
setTimeout(setMargin("-1800px"), + (9000 * (num + 1)));
setTimeout(setMargin("0px"), + (12000 * (num + 1)));
}
}
But that is just a lazy solution that doesn't address the other issues with this implementation. There's a lot of hardcoding and general sloppiness here that ought to be fixed.
Lessons learnt from a decade of experience
As mentioned at the top of this answer, Ender already proposed a solution, but I would like to add on to it, to factor in good practice and modern innovations in the ECMAScript specification.
function format(str, ...args){
return str.split(/(%)/).map(part => (part == "%") ? (args.shift()) : (part)).join("");
}
function slideLoop(margin, selector){
const multiplier = -600;
let contStyle = document.querySelector(selector).style;
return function(){
margin = ++margin % 4;
contStyle.marginLeft = format("%px", margin * multiplier);
}
}
function slide() {
return setInterval(slideLoop(0, "#container"), 3000);
}
Let's go over how this works for the total beginners (note that not all of this is directly related to the question):
format
function format
It's immensely useful to have a printf-like string formatter function in any language. I don't understand why JavaScript doesn't seem to have one.
format(str, ...args)
...
is a snazzy feature added in ES6 that lets you do lots of stuff. I believe it's called the spread operator. Syntax: ...identifier
or ...array
. In a function header, you can use it to specify variable arguments, and it will take every argument at and past the position of said variable argument, and stuff them into an array. You can also call a function with an array like so: args = [1, 2, 3]; i_take_3_args(...args)
, or you can take an array-like object and transform it into an array: ...document.querySelectorAll("div.someclass").forEach(...)
. This would not be possible without the spread operator, because querySelectorAll
returns an "element list", which isn't a true array.
str.split(/(%)/)
I'm not good at explaining how regex works. JavaScript has two syntaxes for regex. There's the OO way (new RegExp("regex", "gi")
) and there's the literal way (/insert regex here/gi
). I have a profound hatred for regex because the terse syntax it encourages often does more harm than good (and also because they're extremely non-portable), but there are some instances where regex is helpful, like this one. Normally, if you called split with "%"
or /%/
, the resulting array would exclude the "%" delimiters from the array. But for the algorithm used here, we need them included. /(%)/
was the first thing I tried and it worked. Lucky guess, I suppose.
.map(...)
map
is a functional idiom. You use map to apply a function to a list. Syntax: array.map(function)
. Function: must return a value and take 1-2 arguments. The first argument will be used to hold each value in the array, while the second will be used to hold the current index in the array. Example: [1,2,3,4,5].map(x => x * x); // returns [1,4,9,16,25]
. See also: filter, find, reduce, forEach.
part => ...
This is an alternative form of function. Syntax: argument-list => return-value
, e.g. (x, y) => (y * width + x)
, which is equivalent to function(x, y){return (y * width + x);}
.
(part == "%") ? (args.shift()) : (part)
The ?:
operator pair is a 3-operand operator called the ternary conditional operator. Syntax: condition ? if-true : if-false
, although most people call it the "ternary" operator, since in every language it appears in, it's the only 3-operand operator, every other operator is binary (+, &&, |, =) or unary (++, ..., &, *). Fun fact: some languages (and vendor extensions of languages, like GNU C) implement a two-operand version of the ?:
operator with syntax value ?: fallback
, which is equivalent to value ? value : fallback
, and will use fallback
if value
evaluates to false. They call it the Elvis Operator.
I should also mention the difference between an expression
and an expression-statement
, as I realize this may not be intuitive to all programmers. An expression
represents a value, and can be assigned to an l-value
. An expression can be stuffed inside parentheses and not be considered a syntax error. An expression can itself be an l-value
, although most statements are r-values
, as the only l-value expressions are those formed from an identifier or (e.g. in C) from a reference/pointer. Functions can return l-values, but don't count on it. Expressions can also be compounded from other, smaller expressions. (1, 2, 3)
is an expression formed from three r-value expressions joined by two comma operators. The value of the expression is 3. expression-statements
, on the other hand, are statements formed from a single expression. ++somevar
is an expression, as it can be used as the r-value in the assignment expression-statement newvar = ++somevar;
(the value of the expression newvar = ++somevar
, for example, is the value that gets assigned to newvar
). ++somevar;
is also an expression-statement.
If ternary operators confuse you at all, apply what I just said to the ternary operator: expression ? expression : expression
. Ternary operator can form an expression or an expression-statement, so both of these things:
smallest = (a < b) ? (a) : (b);
(valueA < valueB) ? (backup_database()) : (nuke_atlantic_ocean());
are valid uses of the operator. Please don't do the latter, though. That's what if
is for. There are cases for this sort of thing in e.g. C preprocessor macros, but we're talking about JavaScript here.
args.shift()
Array.prototype.shift
. It's the mirror version of pop
, ostensibly inherited from shell languages where you can call shift
to move onto the next argument. shift
"pops" the first argument out of the array and returns it, mutating the array in the process. The inverse is unshift
. Full list:
array.shift()
[1,2,3] -> [2,3], returns 1
array.unshift(new-element)
[element, ...] -> [new-element, element, ...]
array.pop()
[1,2,3] -> [1,2], returns 3
array.push(new-element)
[..., element] -> [..., element, new-element]
See also: slice, splice
.join("")
Array.prototype.join(string)
. This function turns an array into a string. Example: [1,2,3].join(", ") -> "1, 2, 3"
slide
return setInterval(slideLoop(0, "#container"), 3000);
First off, we return setInterval
's return value so that it may be used later in a call to clearInterval
. This is important, because JavaScript won't clean that up by itself. I strongly advise against using setTimeout
to make a loop. That is not what setTimeout
is designed for, and by doing that, you're reverting to GOTO. Read Dijkstra's 1968 paper, Go To Statement Considered Harmful, to understand why GOTO loops are bad practice.
Second off, you'll notice I did some things differently. The repeating interval is the obvious one. This will run forever until the interval is cleared, and at a delay of 3000ms. The value for the callback is the return value of another function, which I have fed the arguments 0
and "#container"
. This creates a closure, and you will understand how this works shortly.
slideLoop
function slideLoop(margin, selector)
We take margin (0) and selector ("#container") as arguments. The margin is the initial margin value and the selector is the CSS selector used to find the element we're modifying. Pretty straightforward.
const multiplier = -600;
let contStyle = document.querySelector(selector).style;
I've moved some of the hard coded elements up. Since the margins are in multiples of -600, we have a clearly labeled constant multiplier with that base value.
I've also created a reference to the element's style property via the CSS selector. Since style
is an object, this is safe to do, as it will be treated as a reference rather than a copy (read up on Pass By Sharing to understand these semantics).
return function(){
margin = ++margin % 4;
contStyle.marginLeft = format("%px", margin * multiplier);
}
Now that we have the scope defined, we return a function that uses said scope. This is called a closure. You should read up on those, too. Understanding JavaScript's admittedly bizarre scoping rules will make the language a lot less painful in the long run.
margin = ++margin % 4;
contStyle.marginLeft = format("%px", margin * multiplier);
Here, we simply increment margin and modulus it by 4. The sequence of values this will produce is 1->2->3->0->1->...
, which mimics exactly the behavior from the question without any complicated or hard-coded logic.
Afterwards, we use the format
function defined earlier to painlessly set the marginLeft CSS property of the container. It's set to the currnent margin value multiplied by the multiplier, which as you recall was set to -600. -600 -> -1200 -> -1800 -> 0 -> -600 -> ...
There are some important differences between my version and Ender's, which I mentioned in a comment on their answer. I'm gonna go over the reasoning now:
Use document.querySelector(css_selector)
instead of document.getElementById(id)
querySelector was added in ES6, if I'm not mistaken. querySelector (returns first found element) and querySelectorAll (returns a list of all found elements) are part of the prototype chain of all DOM elements (not just document
), and take a CSS selector, so there are other ways to find an element than just by its ID. You can search by ID (#idname
), class (.classname
), relationships (div.container div div span
, p:nth-child(even)
), and attributes (div[name]
, a[href=https://google.com]
), among other things.
Always track setInterval(fn, interval)
's return value so it can later be closed with clearInterval(interval_id)
It's not good design to leave an interval running forever. It's also not good design to write a function that calls itself via setTimeout
. That is no different from a GOTO loop. The return value of setInterval
should be stored and used to clear the interval when it's no longer needed. Think of it as a form of memory management.
Put the interval's callback into its own formal function for readability and maintainability
Constructs like this
setInterval(function(){
...
}, 1000);
Can get clunky pretty easily, especially if you are storing the return value of setInterval. I strongly recommend putting the function outside of the call and giving it a name so that it's clear and self-documenting. This also makes it possible to call a function that returns an anonymous function, in case you're doing stuff with closures (a special type of object that contains the local state surrounding a function).
Array.prototype.forEach
is fine.
If state is kept with the callback, the callback should be returned from another function (e.g. slideLoop
) to form a closure
You don't want to mush state and callbacks together the way Ender did. This is mess-prone and can become hard to maintain. The state should be in the same function that the anonymous function comes from, so as to clearly separate it from the rest of the world. A better name for slideLoop
could be makeSlideLoop
, just to make it extra clear.
Use proper whitespace. Logical blocks that do different things should be separated by one empty line
This:
print(some_string);
if(foo && bar)
baz();
while((some_number = some_fn()) !== SOME_SENTINEL && ++counter < limit)
;
quux();
is much easier to read than this:
print(some_string);
if(foo&&bar)baz();
while((some_number=some_fn())!==SOME_SENTINEL&&++counter<limit);
quux();
A lot of beginners do this. Including little 14-year-old me from 2009, and I didn't unlearn that bad habit until probably 2013. Stop trying to crush your code down so small.
Avoid "string" + value + "string" + ...
. Make a format function or use String.prototype.replace(string/regex, new_string)
Again, this is a matter of readability. This:
format("Hello %! You've visited % times today. Your score is %/% (%%).",
name, visits, score, maxScore, score/maxScore * 100, "%"
);
is much easier to read than this horrific monstrosity:
"Hello " + name + "! You've visited " + visits + "% times today. " +
"Your score is " + score + "/" + maxScore + " (" + (score/maxScore * 100) +
"%).",
edit: I'm pleased to point out that I made in error in the above snippet, which in my opinion is a great demonstration of how error-prone this method of string building is.
visits + "% times today"
^ whoops
It's a good demonstration because the entire reason I made that error, and didn't notice it for as long as I did(n't), is because the code is bloody hard to read.
Always surround the arguments of your ternary expressions with parens. It aids readability and prevents bugs.
I borrow this rule from the best practices surrounding C preprocessor macros. But I don't really need to explain this one; see for yourself:
let myValue = someValue < maxValue ? someValue * 2 : 0;
let myValue = (someValue < maxValue) ? (someValue * 2) : (0);
I don't care how well you think you understand your language's syntax, the latter will ALWAYS be easier to read than the former, and readability is the the only argument that is necessary. You read thousands of times more code than you write. Don't be a jerk to your future self long-term just so you can pat yourself on the back for being clever in the short term.
Deleting a pointer in C++
- You are trying to delete a variable allocated on the stack. You can not do this
- Deleting a pointer does not destruct a pointer actually, just the memory occupied is given back to the OS. You can access it untill the memory is used for another variable, or otherwise manipulated. So it is good practice to set a pointer to NULL (0) after deleting.
- Deleting a NULL pointer does not delete anything.
Serialize Property as Xml Attribute in Element
Kind of, use the XmlAttribute
instead of XmlElement
, but it won't look like what you want. It will look like the following:
<SomeModel SomeStringElementName="testData">
</SomeModel>
The only way I can think of to achieve what you want (natively) would be to have properties pointing to objects named SomeStringElementName and SomeInfoElementName where the class contained a single getter named "value". You could take this one step further and use DataContractSerializer so that the wrapper classes can be private. XmlSerializer won't read private properties.
// TODO: make the class generic so that an int or string can be used.
[Serializable]
public class SerializationClass
{
public SerializationClass(string value)
{
this.Value = value;
}
[XmlAttribute("value")]
public string Value { get; }
}
[Serializable]
public class SomeModel
{
[XmlIgnore]
public string SomeString { get; set; }
[XmlIgnore]
public int SomeInfo { get; set; }
[XmlElement]
public SerializationClass SomeStringElementName
{
get { return new SerializationClass(this.SomeString); }
}
}
Where should I put <script> tags in HTML markup?
If you are using JQuery then put the javascript wherever you find it best and use $(document).ready()
to ensure that things are loaded properly before executing any functions.
On a side note: I like all my script tags in the <head>
section as that seems to be the cleanest place.
How do I print colored output with Python 3?
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def colour_print(text,colour):
if colour == 'OKBLUE':
string = bcolors.OKBLUE + text + bcolors.ENDC
print(string)
elif colour == 'HEADER':
string = bcolors.HEADER + text + bcolors.ENDC
print(string)
elif colour == 'OKCYAN':
string = bcolors.OKCYAN + text + bcolors.ENDC
print(string)
elif colour == 'OKGREEN':
string = bcolors.OKGREEN + text + bcolors.ENDC
print(string)
elif colour == 'WARNING':
string = bcolors.WARNING + text + bcolors.ENDC
print(string)
elif colour == 'FAIL':
string = bcolors.HEADER + text + bcolors.ENDC
print(string)
elif colour == 'BOLD':
string = bcolors.BOLD + text + bcolors.ENDC
print(string)
elif colour == 'UNDERLINE':
string = bcolors.UNDERLINE + text + bcolors.ENDC
print(string)
just copy the above code.
just call them easily
colour_print('Hello world','OKBLUE')
colour_print('easy one','OKCYAN')
colour_print('copy and paste','OKGREEN')
colour_print('done','OKBLUE')
Hope it would help
Convert NaN to 0 in javascript
How about a regex?
function getNum(str) {
return /[-+]?[0-9]*\.?[0-9]+/.test(str)?parseFloat(str):0;
}
The code below will ignore NaN to allow a calculation of properly entered numbers
_x000D_
_x000D_
function getNum(str) {_x000D_
return /[-+]?[0-9]*\.?[0-9]+/.test(str)?parseFloat(str):0;_x000D_
}_x000D_
var inputsArray = document.getElementsByTagName('input');_x000D_
_x000D_
function computeTotal() {_x000D_
var tot = 0;_x000D_
tot += getNum(inputsArray[0].value);_x000D_
tot += getNum(inputsArray[1].value);_x000D_
tot += getNum(inputsArray[2].value);_x000D_
inputsArray[3].value = tot;_x000D_
}
_x000D_
<input type="text"></input>_x000D_
<input type="text"></input>_x000D_
<input type="text"></input>_x000D_
<input type="text" disabled></input>_x000D_
<button type="button" onclick="computeTotal()">Calculate</button>
_x000D_
_x000D_
_x000D_
How to prevent gcc optimizing some statements in C?
Turning off optimization fixes the problem, but it is unnecessary. A safer alternative is to make it illegal for the compiler to optimize out the store by using the volatile
type qualifier.
// Assuming pageptr is unsigned char * already...
unsigned char *pageptr = ...;
((unsigned char volatile *)pageptr)[0] = pageptr[0];
The volatile
type qualifier instructs the compiler to be strict about memory stores and loads. One purpose of volatile
is to let the compiler know that the memory access has side effects, and therefore must be preserved. In this case, the store has the side effect of causing a page fault, and you want the compiler to preserve the page fault.
This way, the surrounding code can still be optimized, and your code is portable to other compilers which don't understand GCC's #pragma
or __attribute__
syntax.
How can I send large messages with Kafka (over 15MB)?
You need to adjust three (or four) properties:
- Consumer side:
fetch.message.max.bytes
- this will determine the largest size of a message that can be fetched by the consumer.
- Broker side:
replica.fetch.max.bytes
- this will allow for the replicas in the brokers to send messages within the cluster and make sure the messages are replicated correctly. If this is too small, then the message will never be replicated, and therefore, the consumer will never see the message because the message will never be committed (fully replicated).
- Broker side:
message.max.bytes
- this is the largest size of the message that can be received by the broker from a producer.
- Broker side (per topic):
max.message.bytes
- this is the largest size of the message the broker will allow to be appended to the topic. This size is validated pre-compression. (Defaults to broker's message.max.bytes
.)
I found out the hard way about number 2 - you don't get ANY exceptions, messages, or warnings from Kafka, so be sure to consider this when you are sending large messages.
Break out of a While...Wend loop
The best way is to use an And
clause in your While
statement
Dim count as Integer
count =0
While True And count <= 10
count=count+1
Debug.Print(count)
Wend
JS: Failed to execute 'getComputedStyle' on 'Window': parameter is not of type 'Element'
I had the same error on my Angular6 project. none of those solutions seemed to work out for me. turned out that the problem was due to an element which was specified as dropdown
but it didn't have dropdown options in it. take a look at code below:
<span class="nav-link" id="navbarDropdownMenuLink" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
<i class="material-icons "
style="font-size: 2rem">notifications</i>
<span class="notification"></span>
<p>
<span class="d-lg-none d-md-block">Some Actions</span>
</p>
</span>
<div class="dropdown-menu dropdown-menu-left"
*ngIf="global.localStorageItem('isInSadHich')"
aria-labelledby="navbarDropdownMenuLink">
<a class="dropdown-item" href="#">You have 5 new tasks</a>
<a class="dropdown-item" href="#">You're now friend with Andrew</a>
<a class="dropdown-item" href="#">Another Notification</a>
<a class="dropdown-item" href="#">Another One</a>
</div>
removing the code data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"
solved the problem.
I myself think that by each click on the first span element, the scope expected to set style for dropdown children which did not existed in the parent span, so it threw error.
PHP - remove <img> tag from string
simply use the form_validation class of codeigniter:
strip_image_tags($str).
$this->load->library('form_validation');
$this->form_validation->set_rules('nombre_campo', 'label', 'strip_image_tags');
Sprintf equivalent in Java
Strings are immutable types. You cannot modify them, only return new string instances.
Because of that, formatting with an instance method makes little sense, as it would have to be called like:
String formatted = "%s: %s".format(key, value);
The original Java authors (and .NET authors) decided that a static method made more sense in this situation, as you are not modifying the target, but instead calling a format method and passing in an input string.
Here is an example of why format()
would be dumb as an instance method. In .NET (and probably in Java), Replace()
is an instance method.
You can do this:
"I Like Wine".Replace("Wine","Beer");
However, nothing happens, because strings are immutable. Replace()
tries to return a new string, but it is assigned to nothing.
This causes lots of common rookie mistakes like:
inputText.Replace(" ", "%20");
Again, nothing happens, instead you have to do:
inputText = inputText.Replace(" ","%20");
Now, if you understand that strings are immutable, that makes perfect sense. If you don't, then you are just confused. The proper place for Replace()
would be where format()
is, as a static method of String
:
inputText = String.Replace(inputText, " ", "%20");
Now there is no question as to what's going on.
The real question is, why did the authors of these frameworks decide that one should be an instance method, and the other static? In my opinion, both are more elegantly expressed as static methods.
Regardless of your opinion, the truth is that you are less prone to make a mistake using the static version, and the code is easier to understand (No Hidden Gotchas).
Of course there are some methods that are perfect as instance methods, take String.Length()
int length = "123".Length();
In this situation, it's obvious we are not trying to modify "123", we are just inspecting it, and returning its length. This is a perfect candidate for an instance method.
My simple rules for Instance Methods on Immutable Objects:
- If you need to return a new instance of the same type, use a static method.
- Otherwise, use an instance method.
How to extract the file name from URI returned from Intent.ACTION_GET_CONTENT?
This actually worked for me:
private String uri2filename() {
String ret;
String scheme = uri.getScheme();
if (scheme.equals("file")) {
ret = uri.getLastPathSegment();
}
else if (scheme.equals("content")) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
ret = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
}
return ret;
}
Solve error javax.mail.AuthenticationFailedException
If you are logging in to your gmail account from a new application or device, Google might be blocking that device. Try following these steps:
To protect your account, Google might make it harder to sign in to your account if we suspect it isn’t you. For example, Google might ask for additional information besides your username and password if you are traveling or if you try to sign in to your account from a new device.
Go to https://g.co/allowaccess from a different device you have previously used to access your Google account and follow the instructions.
Try signing in again from the blocked app.
Can I install Python 3.x and 2.x on the same Windows computer?
Before I courageously installed both simultaneously, I had so many questions. If I give python will it go to py3 when i want py2? pip/virtualenv will happen under py2/3?
It seems to be very simple now.
Just blindly install both of them. Make sure you get the right type(x64/x32).
While/after installing make sure you add to the path to your environment variables.
[ENVIRONMENT]::SETENVIRONMENTVARIABLE("PATH", "$ENV:PATH;C:\PYTHONx", "USER")
Replace the x in the command above to set the path.
Then go to both the folders.
Navigate to
python3.6/Scripts/
and rename pip to pip3.
If pip3 already exists delete the pip. This will make sure that just pip will run under python2. You can verify by:
pip --version
In case you want to use pip with python3 then just use
pip3 install
You can similarly do the same to python file and others.
Cheers!
HTML how to clear input using javascript?
You could use a placeholder because it does it for you, but for old browsers that don't support placeholder, try this:
<script>
function clearThis(target) {
if (target.value == "[email protected]") {
target.value = "";
}
}
function replace(target) {
if (target.value == "" || target.value == null) {
target.value == "[email protected]";
}
}
</script>
<input type="text" name="email" value="[email protected]" size="x" onfocus="clearThis(this)" onblur="replace(this)" />
CODE EXPLAINED: When the text box has focus, clear the value. When text box is not focused AND when the box is blank, replace the value.
I hope that works, I have been having the same issue, but then I tried this and it worked for me.
Redirecting a page using Javascript, like PHP's Header->Location
You cannot mix JS and PHP that way, PHP is rendered before the page is sent to the browser (i.e. before the JS is run)
You can use window.location to change your current page.
$('.entry a:first').click(function() {
window.location = "http://google.ca";
});