In python generally “with” statement is used to open a file, process the data present in the file, and also to close the file without calling a close() method. “with” statement makes the exception handling simpler by providing cleanup activities.
General form of with:
with open(“file name”, “mode”) as file-var:
processing statements
note: no need to close the file by calling close() upon file-var.close()
With the latest versions of mock, you can use the really useful mock_open helper:
mock_open(mock=None, read_data=None)
A helper function to create a mock to replace the use of open. It works for open called directly or used as a context manager.
The mock argument is the mock object to configure. If None (the default) then a MagicMock will be created for you, with the API limited to methods or attributes available on standard file handles.
read_data is a string for the read method of the file handle to return. This is an empty string by default.
>>> from mock import mock_open, patch
>>> m = mock_open()
>>> with patch('{}.open'.format(__name__), m, create=True):
... with open('foo', 'w') as h:
... h.write('some stuff')
>>> m.assert_called_once_with('foo', 'w')
>>> handle = m()
>>> handle.write.assert_called_once_with('some stuff')
Like this:
{% if age > 18 %}
{% with patient as p %}
<my html here>
{% endwith %}
{% else %}
{% with patient.parent as p %}
<my html here>
{% endwith %}
{% endif %}
If the html is too big and you don't want to repeat it, then the logic would better be placed in the view. You set this variable and pass it to the template's context:
p = (age > 18 && patient) or patient.parent
and then just use {{ p }} in the template.
In Python 3.1+ you can specify multiple context expressions, and they will be processed as if multiple with
statements were nested:
with A() as a, B() as b:
suite
is equivalent to
with A() as a:
with B() as b:
suite
This also means that you can use the alias from the first expression in the second (useful when working with db connections/cursors):
with get_conn() as conn, conn.cursor() as cursor:
cursor.execute(sql)
Using these magic methods (__enter__
, __exit__
) allows you to implement objects which can be used easily with the with
statement.
The idea is that it makes it easy to build code which needs some 'cleandown' code executed (think of it as a try-finally
block). Some more explanation here.
A useful example could be a database connection object (which then automagically closes the connection once the corresponding 'with'-statement goes out of scope):
class DatabaseConnection(object):
def __enter__(self):
# make a database connection and return it
...
return self.dbconn
def __exit__(self, exc_type, exc_val, exc_tb):
# make sure the dbconnection gets closed
self.dbconn.close()
...
As explained above, use this object with the with
statement (you may need to do from __future__ import with_statement
at the top of the file if you're on Python 2.5).
with DatabaseConnection() as mydbconn:
# do stuff
PEP343 -- The 'with' statement' has a nice writeup as well.
As you're passing true as the second parameter to json_decode
, in the above example you can retrieve data doing something similar to:
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
var_dump(json_decode($json, true));
?>
Cookies are Client-side and cannot be tested properly using PHP. That's the baseline and every solution is a wrap-around for this problem.
Meaning if you are looking a solution for your cookie problem, you are on the wrong way. Don'y use PHP, use a client language like Javascript.
Can you use cookies using PHP? Yes, but you have to reload to make the settings to PHP 'visible'.
For instance: Is a test possible to see if the browser can set Cookies with plain PHP'. The only correct answer is 'NO'.
Can you read an already set Cookie: 'YES' use the predefined $_COOKIE (A copy of the settings before you started PHP-App).
also if you need to select a sibling with a name rather than the class, you could use the following
var $sibling = $(this).siblings('input[name=bidbutton]');
I tried all the possible commands listed above and none of them worked for me, Check if Package.json contain "@angular-devkit/build-angular" if not just install it using(in my case version 0.803.19 worked)
npm i @angular-devkit/[email protected]
Or checkout at npm website repositories for version selection
If the set of colors is more or less fixed, the most efficient and also most readable way would be to use string constants in your app and then use MySQL's SET
type with FIND_IN_SET('red',colors)
in your queries. When using the SET
type with FIND_IN_SET, MySQL uses one integer to store all values and uses binary "and"
operation to check for presence of values which is way more efficient than scanning a comma-separated string.
In SET('red','blue','green')
, 'red'
would be stored internally as 1
, 'blue'
would be stored internally as 2
and 'green'
would be stored internally as 4
. The value 'red,blue'
would be stored as 3
(1|2
) and 'red,green'
as 5
(1|4
).
I have tried opening the .gitignore
file in my vscode, windows 10
. There you can see, some previously added ignore files (if any).
To create a new rule to ignore a file with (.js)
extension, append the extension of the file like this:
*.js
This will ignore all .js
files in your git
repository.
To exclude certain type of file from a particular directory, you can add this:
**/foo/*.js
This will ignore all .js files inside only /foo/ directory.
For a detailed learning you can visit: about git-ignore
I found this approach useful in some cases:
page.onConsoleMessage(function(msg) {
// do something e.g. page.render
});
Than if you own the page put some script inside:
<script>
window.onload = function(){
console.log('page loaded');
}
</script>
The simplest solution would be:
let str = '\t\n\r this \n \t \r is \r a \n test \t \r \n';
str.replace(/\s+/g, ' ').trim();
console.log(str); // logs: "this is a test"
.replace()
with /\s+/g
regexp is changing all groups of white-spaces characters to a single space in the whole string then we .trim()
the result to remove all exceeding white-spaces before and after the text.
Are considered as white-spaces characters:
[ \f\n\r\t\v?\u00a0\u1680?\u2000?-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]
You can avoid compilation errors if you remove the method definitions from the header files and let the classes contain only the method declarations and variable declarations/definitions. The method definitions should be placed in a .cpp file (just like a best practice guideline says).
The down side of the following solution is (assuming that you had placed the methods in the header file to inline them) that the methods are no longer inlined by the compiler and trying to use the inline keyword produces linker errors.
//A.h
#ifndef A_H
#define A_H
class B;
class A
{
int _val;
B* _b;
public:
A(int val);
void SetB(B *b);
void Print();
};
#endif
//B.h
#ifndef B_H
#define B_H
class A;
class B
{
double _val;
A* _a;
public:
B(double val);
void SetA(A *a);
void Print();
};
#endif
//A.cpp
#include "A.h"
#include "B.h"
#include <iostream>
using namespace std;
A::A(int val)
:_val(val)
{
}
void A::SetB(B *b)
{
_b = b;
cout<<"Inside SetB()"<<endl;
_b->Print();
}
void A::Print()
{
cout<<"Type:A val="<<_val<<endl;
}
//B.cpp
#include "B.h"
#include "A.h"
#include <iostream>
using namespace std;
B::B(double val)
:_val(val)
{
}
void B::SetA(A *a)
{
_a = a;
cout<<"Inside SetA()"<<endl;
_a->Print();
}
void B::Print()
{
cout<<"Type:B val="<<_val<<endl;
}
//main.cpp
#include "A.h"
#include "B.h"
int main(int argc, char* argv[])
{
A a(10);
B b(3.14);
a.Print();
a.SetB(&b);
b.Print();
b.SetA(&a);
return 0;
}
Reading the comments, it seems that these solutions are not consistent across browsers. Decided then to think how I would have done this 10 years ago before the advent of jQuery and event function binding.
So here is my retro hipster solution:
<script type="text/javascript">
var _formConfirm_submitted = false;
</script>
<form name="frmConfirm" onsubmit="if( _formConfirm_submitted == false ){ _formConfirm_submitted = true;return true }else{ alert('your request is being processed!'); return false; }" action="" method="GET">
<input type="submit" value="submit - but only once!"/>
</form>
The main point of difference is that I am relying on the ability to stop a form submitting through returning false on the submit handler, and I am using a global flag variable - which will make me go straight to hell!
But on the plus side, I cannot imagine any browser compatibility issues - hey, it would probably even work in Netscape!
Everyone forgot http_build_url?
http_build_url($_SERVER['REQUEST_URI']);
When no parameters are passed to http_build_url
it will automatically assume the current URL. I would expect REQUEST_URI
to be included as well, though it seems to be required in order to include the GET parameters.
The above example will return full URL.
Run
cat ~/.bash_profile
to check if anaconda is there. If not you should add its path there. If conda is there copy the entire row that you see the Anaconda there from "export" to the end of line. like this:
export PATH=~/anaconda3/bin:$PATH
Run this in your terminal. Then run
conda --version
to see if it is exported and running!
From the React documentation: The event handlers below are triggered by an event in the bubbling phase. To register an event handler for the capture phase, append Capture. (emphasis added)
If you have a click event listener in your React code and you don't want it to bubble up, I think what you want to do is use onClickCapture
instead of onClick
. Then you would pass the event to the handler and do event.nativeEvent.stopPropagation()
to keep the native event from bubbling up to a vanilla JS event listener (or anything that's not react).
How to total up used memory by process name:
Sometimes even looking at the biggest single processes there is still a lot of used memory unaccounted for. To check if there are a lot of the same smaller processes using the memory you can use a command like the following which uses awk to sum up the total memory used by processes of the same name:
ps -e -orss=,args= |awk '{print $1 " " $2 }'| awk '{tot[$2]+=$1;count[$2]++} END {for (i in tot) {print tot[i],i,count[i]}}' | sort -n
e.g. output
9344 docker 1
9948 nginx: 4
22500 /usr/sbin/NetworkManager 1
24704 sleep 69
26436 /usr/sbin/sshd 15
34828 -bash 19
39268 sshd: 10
58384 /bin/su 28
59876 /bin/ksh 29
73408 /usr/bin/python 2
78176 /usr/bin/dockerd 1
134396 /bin/sh 84
5407132 bin/naughty_small_proc 1432
28061916 /usr/local/jdk/bin/java 7
Adding to C2H5OH's answer, in Python 3.6+ you can use format strings to make it a bit cleaner:
s = "something about cupcakes"
print(f"L{s}LL")
You can change set orientation of linearlayout programmatically by:
LinearLayout linearLayout =new linearLayout(this);//just to give the clarity
linearLayout.setOrientation(LinearLayout.VERTICAL);
This :
mail.To = "[email protected]";
Should be:
mail.To.Add(new MailAddress("[email protected]"));
Since the question is about "how it works", some readers may want to see more nuts and bolts. Specifically, the method in question is the __missing__(key)
method. See: https://docs.python.org/2/library/collections.html#defaultdict-objects .
More concretely, this answer shows how to make use of __missing__(key)
in a practical way:
https://stackoverflow.com/a/17956989/1593924
To clarify what 'callable' means, here's an interactive session (from 2.7.6 but should work in v3 too):
>>> x = int
>>> x
<type 'int'>
>>> y = int(5)
>>> y
5
>>> z = x(5)
>>> z
5
>>> from collections import defaultdict
>>> dd = defaultdict(int)
>>> dd
defaultdict(<type 'int'>, {})
>>> dd = defaultdict(x)
>>> dd
defaultdict(<type 'int'>, {})
>>> dd['a']
0
>>> dd
defaultdict(<type 'int'>, {'a': 0})
That was the most typical use of defaultdict (except for the pointless use of the x variable). You can do the same thing with 0 as the explicit default value, but not with a simple value:
>>> dd2 = defaultdict(0)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
dd2 = defaultdict(0)
TypeError: first argument must be callable
Instead, the following works because it passes in a simple function (it creates on the fly a nameless function which takes no arguments and always returns 0):
>>> dd2 = defaultdict(lambda: 0)
>>> dd2
defaultdict(<function <lambda> at 0x02C4C130>, {})
>>> dd2['a']
0
>>> dd2
defaultdict(<function <lambda> at 0x02C4C130>, {'a': 0})
>>>
And with a different default value:
>>> dd3 = defaultdict(lambda: 1)
>>> dd3
defaultdict(<function <lambda> at 0x02C4C170>, {})
>>> dd3['a']
1
>>> dd3
defaultdict(<function <lambda> at 0x02C4C170>, {'a': 1})
>>>
I faced with same problem. Solution that worked for me. If you use v7.Toolbar you must use theme extended from Theme.AppCompat.* You can't use theme extended from android:Theme.Material.* because they have different style attributes.
Hope it will helpful.
Here, the paragraph is printed only 'isValid' is true / it contains any value
<p *ngIf="isValid ? true : false">Paragraph</p>
First, you should know now the android.support.v4.app.ActionBarDrawerToggle
is deprecated.
You must replace that with android.support.v7.app.ActionBarDrawerToggle
.
Here is my example and I use the new Toolbar
to replace the ActionBar
.
MainActivity.java
public class MainActivity extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
this, mDrawerLayout, mToolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close
);
mDrawerLayout.setDrawerListener(mDrawerToggle);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mDrawerToggle.syncState();
}
styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light">
<item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>
<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
<item name="spinBars">true</item>
<item name="color">@android:color/white</item>
</style>
You can read the documents on AndroidDocument#DrawerArrowToggle_spinBars
This attribute is the key to implement the menu-to-arrow animation.
public static int DrawerArrowToggle_spinBars
Whether bars should rotate or not during transition
Must be a boolean value, either "true" or "false".
So, you set this: <item name="spinBars">true</item>
.
Then the animation can be presented.
Hope this can help you.
Note: Just reposting John Zwinck's comment as answer.
One issue might be that you are using a older version of Node (for the moment, I cannot upgrade, codebase struck with v4.3.1
). Simple solution here is, using the deprecated way:
new Buffer(bufferStr)
Note #2: This is for people struck in older version, for whom Buffer.from
does not work
I recommend the answer found here: How do I concatenate two arrays in C#?
e.g.
var z = new int[x.Length + y.Length];
x.CopyTo(z, 0);
y.CopyTo(z, x.Length);
I liked PostMan
, it was the main reason why I kept using Chrome, now I'm good with HttpRequester
https://addons.mozilla.org/En-us/firefox/addon/httprequester/?src=search
You need to create new TextNodes as well as td nodes for each column, not reuse them among all of the columns as your code is doing.
Edit: Revise your code like so:
for (var i = 1; i < 4; i++)
{
tr[i] = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
td1.appendChild(document.createTextNode('Text1'));
td2.appendChild(document.createTextNode('Text2'));
tr[i].appendChild(td1);
tr[i].appendChild(td2);
table.appendChild(tr[i]);
}
Changing col-md-offset-*
to offset-md-*
worked for me
Here is the solution provided by MySQL: http://dev.mysql.com/doc/refman/5.5/en/forcing-innodb-recovery.html
My problem turned out to be that I was assigning as document.getElementById("myinput").Value = '1';
Notice the capital V in Value? Once I changed it to small case, i.e., value, the data started posting. Odd as it was not giving any JavaScript errors either.
The solution
func scrollViewDidScroll(scrollView: UIScrollView) {
if(scrollView.panGestureRecognizer.translationInView(scrollView.superview).y > 0)
{
print("up")
}
else
{
print("down")
}
}
You need to create Object
for the class.
$obj = new Functions();
$var = $obj->filter($_GET['params']);
Why :not just use two :not
:
input:not([type="radio"]):not([type="checkbox"])
Yes, it is intentional
If you are converting to HTML, you can set the size of the image using HTML syntax using:
<img src="path/to/image" height="400px" width="300px" />
or whatever height and width you would want to give.
RUN: Can be many, and it is used in build process, e.g. install multiple libraries
CMD: Can only have 1, which is your execute start point (e.g. ["npm", "start"]
, ["node", "app.js"]
)
Based on answer by @Cici I give here a more generic solution:
=SUM(INDIRECT(CONCATENATE(B1,C1)):INDIRECT(CONCATENATE(B2,C2)))
In Italian version of Excel:
=SOMMA(INDIRETTO(CONCATENA(B1;C1)):INDIRETTO(CONCATENA(B2;C2)))
Where B1-C2 cells hold these values:
You can change these valuese to change the final range at wish.
Splitting the formula in parts:
Hence:
=SUM(INDIRECT(CONCATENATE(B1,C1)):INDIRECT(CONCATENATE(B2,C2)))
results in
=SUM(A1:A5)
I'll write down here a couple of SEO keywords for Italian users:
Con la formula indicata qui sopra basta scrivere nelle caselle da B1 a C2 gli estremi dell'intervallo per vedelo cambiare dentro la formula stessa.
Maybe you need "sys." before:
select * from sys.registry$history;
The structures as well as all other symbols in Core Graphics and other APIs have become cleaner and also include parameter names. https://developer.apple.com/reference/coregraphics#symbols
CGRect(x: Int, y: Int, width: Int, height: Int)
CGVector(dx: Int, dy: Int)
CGPoint(x: Double, y: Double)
CGSize(width: Int, height: Int)
CGPoint Example:
let newPoint = stackMid.convert(CGPoint(x: -10, y: 10), to: self)
CGVector Example:
self.physicsWorld.gravity = CGVector(dx: 0, dy: gravity)
CGSize Example:
hero.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: 16, height: 18))
CGRect Example:
let back = SKShapeNode(rect: CGRect(x: 0-120, y: 1024-200-30, width: 240, height: 140), cornerRadius: 20)
Apple Blog
Swift syntax and API renaming changes in Swift 3 make the language feel more natural, and provide an even more Swift-y experience when calling Cocoa frameworks. Popular frameworks Core Graphics and Grand Central Dispatch have new, much cleaner interfaces in Swift.
Actually you can just push query like this: this.$router.push({query: {plan: 'private'}})
PowerShell features a Restart-Service
cmdlet, which either starts or restarts the service as appropriate.
The
Restart-Service
cmdlet sends a stop message and then a start message to the Windows Service Controller for a specified service. If a service was already stopped, it is started without notifying you of an error.You can specify the services by their service names or display names, or you can use the
InputObject
parameter to pass an object that represents each service that you want to restart.
It is a little more foolproof than running two separate commands.
The easiest way to use it just pass either the service name or the display name directly:
Restart-Service 'Service Name'
It can be used directly from the standard cmd prompt with a command like:
powershell -command "Restart-Service 'Service Name'"
self.view.backgroundColor = UIColor.redColor()
In Swift 3:
self.view.backgroundColor = UIColor.red
You could try using UpdateVersion by Matt Griffith. It's quite old now, but works well. To use it, you simply need to setup a pre-build event which points at your AssemblyInfo.cs file, and the application will update the version numbers accordingly, as per the command line arguments.
As the application is open-source, I've also created a version to increment the version number using the format (Major version).(Minor version).([year][dayofyear]).(increment). I've put the code for my modified version of the UpdateVersion application on GitHub: https://github.com/munr/UpdateVersion
To solve this problem.
cd projectName
npm update
ng serve -o
Vue
allows for you to specify a default prop
value and type
directly, by making props an object (see: https://vuejs.org/guide/components.html#Prop-Validation):
props: {
year: {
default: 2016,
type: Number
}
}
If the wrong type is passed then it throws an error and logs it in the console, here's the fiddle:
value = value.setScale(2, RoundingMode.CEILING)
If in your XML you have layout with id "root" It`s problem, just change id name
Hello. I always have had some issues with the solutions above (and on other sites).
I, as a developer, am programming a addon for a API. The API prevents the use of any external libraries or 3rd party tools. The setup also consists of a mixture of code in jar or zip files and class files located directly in some directories. So my code had to be able to work arround every setup. After a lot of research I have come up with a method that will work in at least 95% of all possible setups.
The following code is basically the overkill method that will always work.
This code scans a given package for all classes that are included in it. It will only work for all classes in the current ClassLoader
.
/**
* Private helper method
*
* @param directory
* The directory to start with
* @param pckgname
* The package name to search for. Will be needed for getting the
* Class object.
* @param classes
* if a file isn't loaded but still is in the directory
* @throws ClassNotFoundException
*/
private static void checkDirectory(File directory, String pckgname,
ArrayList<Class<?>> classes) throws ClassNotFoundException {
File tmpDirectory;
if (directory.exists() && directory.isDirectory()) {
final String[] files = directory.list();
for (final String file : files) {
if (file.endsWith(".class")) {
try {
classes.add(Class.forName(pckgname + '.'
+ file.substring(0, file.length() - 6)));
} catch (final NoClassDefFoundError e) {
// do nothing. this class hasn't been found by the
// loader, and we don't care.
}
} else if ((tmpDirectory = new File(directory, file))
.isDirectory()) {
checkDirectory(tmpDirectory, pckgname + "." + file, classes);
}
}
}
}
/**
* Private helper method.
*
* @param connection
* the connection to the jar
* @param pckgname
* the package name to search for
* @param classes
* the current ArrayList of all classes. This method will simply
* add new classes.
* @throws ClassNotFoundException
* if a file isn't loaded but still is in the jar file
* @throws IOException
* if it can't correctly read from the jar file.
*/
private static void checkJarFile(JarURLConnection connection,
String pckgname, ArrayList<Class<?>> classes)
throws ClassNotFoundException, IOException {
final JarFile jarFile = connection.getJarFile();
final Enumeration<JarEntry> entries = jarFile.entries();
String name;
for (JarEntry jarEntry = null; entries.hasMoreElements()
&& ((jarEntry = entries.nextElement()) != null);) {
name = jarEntry.getName();
if (name.contains(".class")) {
name = name.substring(0, name.length() - 6).replace('/', '.');
if (name.contains(pckgname)) {
classes.add(Class.forName(name));
}
}
}
}
/**
* Attempts to list all the classes in the specified package as determined
* by the context class loader
*
* @param pckgname
* the package name to search
* @return a list of classes that exist within that package
* @throws ClassNotFoundException
* if something went wrong
*/
public static ArrayList<Class<?>> getClassesForPackage(String pckgname)
throws ClassNotFoundException {
final ArrayList<Class<?>> classes = new ArrayList<Class<?>>();
try {
final ClassLoader cld = Thread.currentThread()
.getContextClassLoader();
if (cld == null)
throw new ClassNotFoundException("Can't get class loader.");
final Enumeration<URL> resources = cld.getResources(pckgname
.replace('.', '/'));
URLConnection connection;
for (URL url = null; resources.hasMoreElements()
&& ((url = resources.nextElement()) != null);) {
try {
connection = url.openConnection();
if (connection instanceof JarURLConnection) {
checkJarFile((JarURLConnection) connection, pckgname,
classes);
} else if (connection instanceof FileURLConnection) {
try {
checkDirectory(
new File(URLDecoder.decode(url.getPath(),
"UTF-8")), pckgname, classes);
} catch (final UnsupportedEncodingException ex) {
throw new ClassNotFoundException(
pckgname
+ " does not appear to be a valid package (Unsupported encoding)",
ex);
}
} else
throw new ClassNotFoundException(pckgname + " ("
+ url.getPath()
+ ") does not appear to be a valid package");
} catch (final IOException ioex) {
throw new ClassNotFoundException(
"IOException was thrown when trying to get all resources for "
+ pckgname, ioex);
}
}
} catch (final NullPointerException ex) {
throw new ClassNotFoundException(
pckgname
+ " does not appear to be a valid package (Null pointer exception)",
ex);
} catch (final IOException ioex) {
throw new ClassNotFoundException(
"IOException was thrown when trying to get all resources for "
+ pckgname, ioex);
}
return classes;
}
These three methods provide you with the ability to find all classes in a given package.
You use it like this:
getClassesForPackage("package.your.classes.are.in");
The method first gets the current ClassLoader
. It then fetches all resources that contain said package and iterates of these URL
s. It then creates a URLConnection
and determines what type of URl we have. It can either be a directory (FileURLConnection
) or a directory inside a jar or zip file (JarURLConnection
). Depending on what type of connection we have two different methods will be called.
First lets see what happens if it is a FileURLConnection
.
It first checks if the passed File exists and is a directory. If that's the case it checks if it is a class file. If so a Class
object will be created and put in the ArrayList
. If it is not a class file but is a directory, we simply iterate into it and do the same thing. All other cases/files will be ignored.
If the URLConnection
is a JarURLConnection
the other private helper method will be called. This method iterates over all Entries in the zip/jar archive. If one entry is a class file and is inside of the package a Class
object will be created and stored in the ArrayList
.
After all resources have been parsed it (the main method) returns the ArrayList
containig all classes in the given package, that the current ClassLoader
knows about.
If the process fails at any point a ClassNotFoundException
will be thrown containg detailed information about the exact cause.
To build on Paul Lammertsma's answer, this command will print the names and signatures of all APKs in the current dir (I'm using sh because later I need to pipe the output to grep):
find . -name "*.apk" -exec echo "APK: {}" \; -exec sh -c 'keytool -printcert -jarfile "{}"' \;
Sample output:
APK: ./com.google.android.youtube-10.39.54-107954130-minAPI15.apk
Signer #1:
Signature:
Owner: CN=Unknown, OU="Google, Inc", O="Google, Inc", L=Mountain View, ST=CA, C=US
Issuer: CN=Unknown, OU="Google, Inc", O="Google, Inc", L=Mountain View, ST=CA, C=US
Serial number: 4934987e
Valid from: Mon Dec 01 18:07:58 PST 2008 until: Fri Apr 18 19:07:58 PDT 2036
Certificate fingerprints:
MD5: D0:46:FC:5D:1F:C3:CD:0E:57:C5:44:40:97:CD:54:49
SHA1: 24:BB:24:C0:5E:47:E0:AE:FA:68:A5:8A:76:61:79:D9:B6:13:A6:00
SHA256: 3D:7A:12:23:01:9A:A3:9D:9E:A0:E3:43:6A:B7:C0:89:6B:FB:4F:B6:79:F4:DE:5F:E7:C2:3F:32:6C:8F:99:4A
Signature algorithm name: MD5withRSA
Version: 1
APK: ./com.google.android.youtube_10.40.56-108056134_minAPI15_maxAPI22(armeabi-v7a)(480dpi).apk
Signer #1:
Signature:
Owner: CN=Unknown, OU="Google, Inc", O="Google, Inc", L=Mountain View, ST=CA, C=US
Issuer: CN=Unknown, OU="Google, Inc", O="Google, Inc", L=Mountain View, ST=CA, C=US
Serial number: 4934987e
Valid from: Mon Dec 01 18:07:58 PST 2008 until: Fri Apr 18 19:07:58 PDT 2036
Certificate fingerprints:
MD5: D0:46:FC:5D:1F:C3:CD:0E:57:C5:44:40:97:CD:54:49
SHA1: 24:BB:24:C0:5E:47:E0:AE:FA:68:A5:8A:76:61:79:D9:B6:13:A6:00
SHA256: 3D:7A:12:23:01:9A:A3:9D:9E:A0:E3:43:6A:B7:C0:89:6B:FB:4F:B6:79:F4:DE:5F:E7:C2:3F:32:6C:8F:99:4A
Signature algorithm name: MD5withRSA
Version: 1
Or if you just care about SHA1:
find . -name "*.apk" -exec echo "APK: {}" \; -exec sh -c 'keytool -printcert -jarfile "{}" | grep SHA1' \;
Sample output:
APK: ./com.google.android.youtube-10.39.54-107954130-minAPI15.apk
SHA1: 24:BB:24:C0:5E:47:E0:AE:FA:68:A5:8A:76:61:79:D9:B6:13:A6:00
APK: ./com.google.android.youtube_10.40.56-108056134_minAPI15_maxAPI22(armeabi-v7a)(480dpi).apk
SHA1: 24:BB:24:C0:5E:47:E0:AE:FA:68:A5:8A:76:61:79:D9:B6:13:A6:00
Depending on what you're wanting, you can use…
rake db:create
…to build the database from scratch from config/database.yml
, or…
rake db:schema:load
…to build the database from scratch from your schema.rb
file.
mysqli:query()
returns a mysqli_result
object, which cannot be serialized into a string.
You need to fetch the results from the object. Here's how to do it.
Fetch a single row from the result and then access column index 0 or using an associative key. Use the null-coalescing operator in case no rows are present in the result.
$result = $con->query($tourquery); // or mysqli_query($con, $tourquery);
$tourresult = $result->fetch_array()[0] ?? '';
// OR
$tourresult = $result->fetch_array()['roomprice'] ?? '';
echo '<strong>Per room amount: </strong>'.$tourresult;
Use foreach
loop to iterate over the result and fetch each row one by one. You can access each column using the column name as an array index.
$result = $con->query($tourquery); // or mysqli_query($con, $tourquery);
foreach($result as $row) {
echo '<strong>Per room amount: </strong>'.$row['roomprice'];
}
Difference between UTF-8 and UTF-16? Why do we need these?
There have been at least a couple of security vulnerabilities in implementations of UTF-16. See Wikipedia for details.
WHATWG and W3C have now declared that only UTF-8 is to be used on the Web.
The [security] problems outlined here go away when exclusively using UTF-8, which is one of the many reasons that is now the mandatory encoding for all things.
Other groups are saying the same.
So while UTF-16 may continue being used internally by some systems such as Java and Windows, what little use of UTF-16 you may have seen in the past for data files, data exchange, and such, will likely fade away entirely.
object["property"] = value;
or
object.property = value;
Object and Array in JavaScript are different in terms of usage. Its best if you understand them:
You simply can't do that in SQL. You have to explicitly list the fields and concat each one:
SELECT CONCAT(field1, '/'), CONCAT(field2, '/'), ... FROM `socials` WHERE 1
If you are using an app, you can use SQL to read the column names, and then use your app to construct a query like above. See this stackoverflow question to find the column names: Get table column names in mysql?
function removeLocationHash(){
var noHashURL = window.location.href.replace(/#.*$/, '');
window.history.replaceState('', document.title, noHashURL)
}
window.addEventListener("load", function(){
removeLocationHash();
});
// find the first select and bind a click handler
$('#column_select').bind('click', function(){
// retrieve the selected value
var value = $(this).val(),
// build a regular expression that does a head-match
expression = new RegExp('^' + value),
// find the second select
$select = $('#layout_select);
// hide all children (<option>s) of the second select,
// check each element's value agains the regular expression built from the first select's value
// show elements that match the expression
$select.children().hide().filter(function(){
return !!$(this).val().match(expression);
}).show();
});
(this is far from perfect, but should get you there…)
Not sure about how other people solve this problem or whether Bootstrap has any configuration for this.
I found this thread that provides a solution:
https://github.com/twbs/bootstrap/issues/1411
One of the post suggests the use of
<ul class="dropdown-menu" style="right: 0; left: auto;">
I tested and it works.
Hope to know whether Bootstrap provides config for doing this, not via the above css.
Cheers.
In my application I have set
grid.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
grid.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
Also, I have set the
grid.AllowUserToOrderColumns = true;
grid.AllowUserToResizeColumns = true;
Now the column widths can be changed and the columns can be rearranged by the user. That works pretty well for me.
Maybe that will work for you.
BSTR
to std::wstring
:
// given BSTR bs
assert(bs != nullptr);
std::wstring ws(bs, SysStringLen(bs));
std::wstring
to BSTR
:
// given std::wstring ws
assert(!ws.empty());
BSTR bs = SysAllocStringLen(ws.data(), ws.size());
Doc refs:
This is more a footnote to a number of the answers above which suggest the use of ON DUPLICATE KEY UPDATE
, BEWARE that this is NOT always replication safe, so if you ever plan on growing beyond a single server, you'll want to avoid this and use two queries, one to verify the existence, and then a second to either UPDATE
when a row exists, or INSERT
when it does not.
It seems like you installed a zip version of sbt, which is fine. But I suggest you install the native debian package if you are on Ubuntu. That is how I managed to install it on my Ubuntu 12.04. Check it out here: http://www.scala-sbt.org/release/docs/Installing-sbt-on-Linux.html Or simply directly download it from here.
The line height of the <br>
can be different from the line height of the rest of the text inside a <p>
. You can control the line height of your <br>
tags independently of the rest of the text by enclosing two of them in a <span>
that is styled. Use the line-height
css property, as others have suggested.
<p class="normalLineHeight">
Lots of text here which will display on several lines with normal line height if you put it in a narrow container...
<span class="customLineHeight"><br><br></span>
After a custom break, this text will again display on several lines with normal line height...
</p>
The libs are located in
/u01/app/oracle/product/11.2.0/xe/lib
(For Oracle XE) or similar.
You should add this path to /etc/ld.so.conf
or if this file shows only an include location, as in a separate file in the /etc/ld.so.conf.d
directory
I have oracle.conf in /etc/ld.so.conf.d
, just one file with the path. Nothing else.
Of course don't forget to run ldconfig as a last step.
Attach onchange
event to the checkbox:
<input class="coupon_question" type="checkbox" name="coupon_question" value="1" onchange="valueChanged()"/>
<script type="text/javascript">
function valueChanged()
{
if($('.coupon_question').is(":checked"))
$(".answer").show();
else
$(".answer").hide();
}
</script>
I searched now over 2h to find a nicely way how to find duplicates in a list and how to remove them. Here is the simplest answer:
//Copy the string array with the filtered data of the analytics db into an list
// a list should be easier to use
List<string> list_filtered_data = new List<string>(analytics_db_filtered_data);
// Get distinct elements and convert into a list again.
List<string> distinct = list_filtered_data.Distinct().ToList();
The Output will look like this: Duplicated Elements will be removed in the new list called distinct!
using System.IO;
using System.Text;
using (StreamWriter sw = new StreamWriter(File.Open(myfilename, FileMode.Create), Encoding.WhateverYouWant))
{
sw.WriteLine("my text...");
}
An alternate way of getting your encoding:
using System.IO;
using System.Text;
using (var sw = new StreamWriter(File.Open(@"c:\myfile.txt", FileMode.CreateNew), Encoding.GetEncoding("iso-8859-1"))) {
sw.WriteLine("my text...");
}
Check out the docs for the StreamWriter constructor.
Use FirstOrDefault. First will never return null - if it can't find a matching element it throws the exception you're seeing.
_dsACL.Documents.FirstOrDefault(o => o.ID == id);
I think we do need preprocess(maybe NOT call the compile) the head file. Because from my understanding, during the compile stage, the head file should be included in c file. For example, in test.h we have
typedef enum{
a,
b,
c
}test_t
and in test.c we have
void foo()
{
test_t test;
...
}
during the compile, i think the compiler will put the code in head file and c file together and code in head file will be pre-processed and substitute the code in c file. Meanwhile, we'd better to define the include path in makefile.
You need to store the psftp script (lines from open
to bye
) into a separate file and pass that to psftp
using -b
switch:
cd "C:\Program Files (x86)\PuTTY"
psftp -b "C:\path\to\script\script.txt"
Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-option-b
EDIT: For username+password: As you cannot use psftp
commands in a batch file, for the same reason, you cannot specify the username and the password as psftp
commands. These are inputs to the open
command. While you can specify the username with the open
command (open <user>@<IP>
), you cannot specify the password this way. This can be done on a psftp
command line only. Then it's probably cleaner to do all on the command-line:
cd "C:\Program Files (x86)\PuTTY"
psftp -b script.txt <user>@<IP> -pw <PW>
And remove the open
, <user>
and <PW>
lines from your script.txt
.
Reference:
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter6.html#psftp-starting
https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-pw
What you are doing atm is that you run psftp
without any parameter or commands. Once you exit it (like by typing bye
), your batch file continues trying to run open
command (and others), what Windows shell obviously does not understand.
If you really want to keep everything in one file (the batch file), you can write commands to psftp standard input, like:
(
echo cd ...
echo lcd ...
echo put log.sh
) | psftp -b script.txt <user>@<IP> -pw <PW>
You should also make sure that the ports WAMP uses aren't already in use.
That can be done by typing the following command into the command prompt:
netstat –o
From what I know, respond_to is a method attached to the ActionController, so you can use it in every single controller, because all of them inherits from the ActionController. Here is the Rails respond_to method:
def respond_to(&block)
responder = Responder.new(self)
block.call(responder)
responder.respond
end
You are passing it a block, like I show here:
respond_to <<**BEGINNING OF THE BLOCK**>> do |format|
format.html
format.xml { render :xml => @whatever }
end <<**END OF THE BLOCK**>>
The |format| part is the argument that the block is expecting, so inside the respond_to method we can use that. How?
Well, if you notice we pass the block with a prefixed & in the respond_to method, and we do that to treat that block as a Proc. Since the argument has the ".xml", ".html" we can use that as methods to be called.
What we basically do in the respond_to class is call methods ".html, .xml, .json" to an instance of a Responder class.
Put sleep. It will work. I have tried. The reason is that the page wasn't loaded yet. Check this question to know how to wait for load - Wait for page load in Selenium
Here is an alternate solution to reduce For/ForEach looping, this would reduce looping time and updates quickly :)
dt.Columns.Add("MyRow", typeof(System.Int32));
dt.Columns["MyRow"].Expression = "'0'";
If time_created is a unix timestamp (int), you should be able to use something like this:
DELETE FROM locks WHERE time_created < (UNIX_TIMESTAMP() - 600);
(600 seconds = 10 minutes - obviously)
Otherwise (if time_created is mysql timestamp), you could try this:
DELETE FROM locks WHERE time_created < (NOW() - INTERVAL 10 MINUTE)
Use these libraries:
import java.util.LinkedHashMap;
import java.util.Map;
The code:
public static String RomanNumerals(int Int) {
LinkedHashMap<String, Integer> roman_numerals = new LinkedHashMap<String, Integer>();
roman_numerals.put("M", 1000);
roman_numerals.put("CM", 900);
roman_numerals.put("D", 500);
roman_numerals.put("CD", 400);
roman_numerals.put("C", 100);
roman_numerals.put("XC", 90);
roman_numerals.put("L", 50);
roman_numerals.put("XL", 40);
roman_numerals.put("X", 10);
roman_numerals.put("IX", 9);
roman_numerals.put("V", 5);
roman_numerals.put("IV", 4);
roman_numerals.put("I", 1);
String res = "";
for(Map.Entry<String, Integer> entry : roman_numerals.entrySet()){
int matches = Int/entry.getValue();
res += repeat(entry.getKey(), matches);
Int = Int % entry.getValue();
}
return res;
}
public static String repeat(String s, int n) {
if(s == null) {
return null;
}
final StringBuilder sb = new StringBuilder();
for(int i = 0; i < n; i++) {
sb.append(s);
}
return sb.toString();
}
Testing the code:
for (int i = 1;i<256;i++) {
System.out.println("i="+i+" -> "+RomanNumerals(i));
}
The output:
i=1 -> I
i=2 -> II
i=3 -> III
i=4 -> IV
i=5 -> V
i=6 -> VI
i=7 -> VII
i=8 -> VIII
i=9 -> IX
i=10 -> X
i=11 -> XI
i=12 -> XII
i=13 -> XIII
i=14 -> XIV
i=15 -> XV
i=16 -> XVI
i=17 -> XVII
i=18 -> XVIII
i=19 -> XIX
i=20 -> XX
i=21 -> XXI
i=22 -> XXII
i=23 -> XXIII
i=24 -> XXIV
i=25 -> XXV
i=26 -> XXVI
i=27 -> XXVII
i=28 -> XXVIII
i=29 -> XXIX
i=30 -> XXX
i=31 -> XXXI
i=32 -> XXXII
i=33 -> XXXIII
i=34 -> XXXIV
i=35 -> XXXV
i=36 -> XXXVI
i=37 -> XXXVII
i=38 -> XXXVIII
i=39 -> XXXIX
i=40 -> XL
i=41 -> XLI
i=42 -> XLII
i=43 -> XLIII
i=44 -> XLIV
i=45 -> XLV
i=46 -> XLVI
i=47 -> XLVII
i=48 -> XLVIII
i=49 -> XLIX
i=50 -> L
i=51 -> LI
i=52 -> LII
i=53 -> LIII
i=54 -> LIV
i=55 -> LV
i=56 -> LVI
i=57 -> LVII
i=58 -> LVIII
i=59 -> LIX
i=60 -> LX
i=61 -> LXI
i=62 -> LXII
i=63 -> LXIII
i=64 -> LXIV
i=65 -> LXV
i=66 -> LXVI
i=67 -> LXVII
i=68 -> LXVIII
i=69 -> LXIX
i=70 -> LXX
i=71 -> LXXI
i=72 -> LXXII
i=73 -> LXXIII
i=74 -> LXXIV
i=75 -> LXXV
i=76 -> LXXVI
i=77 -> LXXVII
i=78 -> LXXVIII
i=79 -> LXXIX
i=80 -> LXXX
i=81 -> LXXXI
i=82 -> LXXXII
i=83 -> LXXXIII
i=84 -> LXXXIV
i=85 -> LXXXV
i=86 -> LXXXVI
i=87 -> LXXXVII
i=88 -> LXXXVIII
i=89 -> LXXXIX
i=90 -> XC
i=91 -> XCI
i=92 -> XCII
i=93 -> XCIII
i=94 -> XCIV
i=95 -> XCV
i=96 -> XCVI
i=97 -> XCVII
i=98 -> XCVIII
i=99 -> XCIX
i=100 -> C
i=101 -> CI
i=102 -> CII
i=103 -> CIII
i=104 -> CIV
i=105 -> CV
i=106 -> CVI
i=107 -> CVII
i=108 -> CVIII
i=109 -> CIX
i=110 -> CX
i=111 -> CXI
i=112 -> CXII
i=113 -> CXIII
i=114 -> CXIV
i=115 -> CXV
i=116 -> CXVI
i=117 -> CXVII
i=118 -> CXVIII
i=119 -> CXIX
i=120 -> CXX
i=121 -> CXXI
i=122 -> CXXII
i=123 -> CXXIII
i=124 -> CXXIV
i=125 -> CXXV
i=126 -> CXXVI
i=127 -> CXXVII
i=128 -> CXXVIII
i=129 -> CXXIX
i=130 -> CXXX
i=131 -> CXXXI
i=132 -> CXXXII
i=133 -> CXXXIII
i=134 -> CXXXIV
i=135 -> CXXXV
i=136 -> CXXXVI
i=137 -> CXXXVII
i=138 -> CXXXVIII
i=139 -> CXXXIX
i=140 -> CXL
i=141 -> CXLI
i=142 -> CXLII
i=143 -> CXLIII
i=144 -> CXLIV
i=145 -> CXLV
i=146 -> CXLVI
i=147 -> CXLVII
i=148 -> CXLVIII
i=149 -> CXLIX
i=150 -> CL
i=151 -> CLI
i=152 -> CLII
i=153 -> CLIII
i=154 -> CLIV
i=155 -> CLV
i=156 -> CLVI
i=157 -> CLVII
i=158 -> CLVIII
i=159 -> CLIX
i=160 -> CLX
i=161 -> CLXI
i=162 -> CLXII
i=163 -> CLXIII
i=164 -> CLXIV
i=165 -> CLXV
i=166 -> CLXVI
i=167 -> CLXVII
i=168 -> CLXVIII
i=169 -> CLXIX
i=170 -> CLXX
i=171 -> CLXXI
i=172 -> CLXXII
i=173 -> CLXXIII
i=174 -> CLXXIV
i=175 -> CLXXV
i=176 -> CLXXVI
i=177 -> CLXXVII
i=178 -> CLXXVIII
i=179 -> CLXXIX
i=180 -> CLXXX
i=181 -> CLXXXI
i=182 -> CLXXXII
i=183 -> CLXXXIII
i=184 -> CLXXXIV
i=185 -> CLXXXV
i=186 -> CLXXXVI
i=187 -> CLXXXVII
i=188 -> CLXXXVIII
i=189 -> CLXXXIX
i=190 -> CXC
i=191 -> CXCI
i=192 -> CXCII
i=193 -> CXCIII
i=194 -> CXCIV
i=195 -> CXCV
i=196 -> CXCVI
i=197 -> CXCVII
i=198 -> CXCVIII
i=199 -> CXCIX
i=200 -> CC
i=201 -> CCI
i=202 -> CCII
i=203 -> CCIII
i=204 -> CCIV
i=205 -> CCV
i=206 -> CCVI
i=207 -> CCVII
i=208 -> CCVIII
i=209 -> CCIX
i=210 -> CCX
i=211 -> CCXI
i=212 -> CCXII
i=213 -> CCXIII
i=214 -> CCXIV
i=215 -> CCXV
i=216 -> CCXVI
i=217 -> CCXVII
i=218 -> CCXVIII
i=219 -> CCXIX
i=220 -> CCXX
i=221 -> CCXXI
i=222 -> CCXXII
i=223 -> CCXXIII
i=224 -> CCXXIV
i=225 -> CCXXV
i=226 -> CCXXVI
i=227 -> CCXXVII
i=228 -> CCXXVIII
i=229 -> CCXXIX
i=230 -> CCXXX
i=231 -> CCXXXI
i=232 -> CCXXXII
i=233 -> CCXXXIII
i=234 -> CCXXXIV
i=235 -> CCXXXV
i=236 -> CCXXXVI
i=237 -> CCXXXVII
i=238 -> CCXXXVIII
i=239 -> CCXXXIX
i=240 -> CCXL
i=241 -> CCXLI
i=242 -> CCXLII
i=243 -> CCXLIII
i=244 -> CCXLIV
i=245 -> CCXLV
i=246 -> CCXLVI
i=247 -> CCXLVII
i=248 -> CCXLVIII
i=249 -> CCXLIX
i=250 -> CCL
i=251 -> CCLI
i=252 -> CCLII
i=253 -> CCLIII
i=254 -> CCLIV
i=255 -> CCLV
I had this edge case, where I checked out a previous version of the code in which my file directory structure was different:
git checkout 1.87.1
warning: unable to unlink web/sites/default/default.settings.php: Permission denied
... other warnings ...
Note: checking out '1.87.1'.
You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.
If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again.
Example:
git checkout -b <new-branch-name>
HEAD is now at 50a7153d7... Merge branch 'hotfix/1.87.1'
In a case like this you may need to use --force (when you know that going back to the original branch and discarding changes is a safe thing to do).
git checkout master
did not work:
$ git checkout master
error: The following untracked working tree files would be overwritten by checkout:
web/sites/default/default.settings.php
... other files ...
git checkout master --force
(or git checkout master -f
) worked:
git checkout master -f
Previous HEAD position was 50a7153d7... Merge branch 'hotfix/1.87.1'
Switched to branch 'master'
Your branch is up-to-date with 'origin/master'.
From Go 1.10 there is a strings.Builder
type, please take a look at this answer for more detail.
Use the bytes
package. It has a Buffer
type which implements io.Writer
.
package main
import (
"bytes"
"fmt"
)
func main() {
var buffer bytes.Buffer
for i := 0; i < 1000; i++ {
buffer.WriteString("a")
}
fmt.Println(buffer.String())
}
This does it in O(n) time.
I got this on Firefox (FF58). I fixed this with:
dom.moduleScripts.enabled
in about:config
Source: Import page on mozilla (See Browser compatibility)
type="module"
to your script tag where you import the js file<script type="module" src="appthatimports.js"></script>
./
, /
, ../
or http://
before)import * from "./mylib.js"
For more examples, this blog post is good.
You go around making your webpage, and keep on putting {{data bindings}} whenever you feel you would have dynamic data. Angular will then provide you a $scope handler, which you can populate (statically or through calls to the web server).
This is a good understanding of data-binding. I think you've got that down.
For simple DOM manipulation, which doesnot involve data manipulation (eg: color changes on mousehover, hiding/showing elements on click), jQuery or old-school js is sufficient and cleaner. This assumes that the model in angular's mvc is anything that reflects data on the page, and hence, css properties like color, display/hide, etc changes dont affect the model.
I can see your point here about "simple" DOM manipulation being cleaner, but only rarely and it would have to be really "simple". I think DOM manipulation is one the areas, just like data-binding, where Angular really shines. Understanding this will also help you see how Angular considers its views.
I'll start by comparing the Angular way with a vanilla js approach to DOM manipulation. Traditionally, we think of HTML as not "doing" anything and write it as such. So, inline js, like "onclick", etc are bad practice because they put the "doing" in the context of HTML, which doesn't "do". Angular flips that concept on its head. As you're writing your view, you think of HTML as being able to "do" lots of things. This capability is abstracted away in angular directives, but if they already exist or you have written them, you don't have to consider "how" it is done, you just use the power made available to you in this "augmented" HTML that angular allows you to use. This also means that ALL of your view logic is truly contained in the view, not in your javascript files. Again, the reasoning is that the directives written in your javascript files could be considered to be increasing the capability of HTML, so you let the DOM worry about manipulating itself (so to speak). I'll demonstrate with a simple example.
<div rotate-on-click="45"></div>
First, I'd just like to comment that if we've given our HTML this functionality via a custom Angular Directive, we're already done. That's a breath of fresh air. More on that in a moment.
function rotate(deg, elem) {
$(elem).css({
webkitTransform: 'rotate('+deg+'deg)',
mozTransform: 'rotate('+deg+'deg)',
msTransform: 'rotate('+deg+'deg)',
oTransform: 'rotate('+deg+'deg)',
transform: 'rotate('+deg+'deg)'
});
}
function addRotateOnClick($elems) {
$elems.each(function(i, elem) {
var deg = 0;
$(elem).click(function() {
deg+= parseInt($(this).attr('rotate-on-click'), 10);
rotate(deg, this);
});
});
}
addRotateOnClick($('[rotate-on-click]'));
app.directive('rotateOnClick', function() {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var deg = 0;
element.bind('click', function() {
deg+= parseInt(attrs.rotateOnClick, 10);
element.css({
webkitTransform: 'rotate('+deg+'deg)',
mozTransform: 'rotate('+deg+'deg)',
msTransform: 'rotate('+deg+'deg)',
oTransform: 'rotate('+deg+'deg)',
transform: 'rotate('+deg+'deg)'
});
});
}
};
});
Pretty light, VERY clean and that's just a simple manipulation! In my opinion, the angular approach wins in all regards, especially how the functionality is abstracted away and the dom manipulation is declared in the DOM. The functionality is hooked onto the element via an html attribute, so there is no need to query the DOM via a selector, and we've got two nice closures - one closure for the directive factory where variables are shared across all usages of the directive, and one closure for each usage of the directive in the link
function (or compile
function).
Two-way data binding and directives for DOM manipulation are only the start of what makes Angular awesome. Angular promotes all code being modular, reusable, and easily testable and also includes a single-page app routing system. It is important to note that jQuery is a library of commonly needed convenience/cross-browser methods, but Angular is a full featured framework for creating single page apps. The angular script actually includes its own "lite" version of jQuery so that some of the most essential methods are available. Therefore, you could argue that using Angular IS using jQuery (lightly), but Angular provides much more "magic" to help you in the process of creating apps.
This is a great post for more related information: How do I “think in AngularJS” if I have a jQuery background?
The above points are aimed at the OP's specific concerns. I'll also give an overview of the other important differences. I suggest doing additional reading about each topic as well.
Angular is a framework, jQuery is a library. Frameworks have their place and libraries have their place. However, there is no question that a good framework has more power in writing an application than a library. That's exactly the point of a framework. You're welcome to write your code in plain JS, or you can add in a library of common functions, or you can add a framework to drastically reduce the code you need to accomplish most things. Therefore, a more appropriate question is:
Good frameworks can help architect your code so that it is modular (therefore reusable), DRY, readable, performant and secure. jQuery is not a framework, so it doesn't help in these regards. We've all seen the typical walls of jQuery spaghetti code. This isn't jQuery's fault - it's the fault of developers that don't know how to architect code. However, if the devs did know how to architect code, they would end up writing some kind of minimal "framework" to provide the foundation (achitecture, etc) I discussed a moment ago, or they would add something in. For example, you might add RequireJS to act as part of your framework for writing good code.
Here are some things that modern frameworks are providing:
Before I further discuss Angular, I'd like to point out that Angular isn't the only one of its kind. Durandal, for example, is a framework built on top of jQuery, Knockout, and RequireJS. Again, jQuery cannot, by itself, provide what Knockout, RequireJS, and the whole framework built on top them can. It's just not comparable.
If you need to destroy a planet and you have a Death Star, use the Death star.
Building on my previous points about what frameworks provide, I'd like to commend the way that Angular provides them and try to clarify why this is matter of factually superior to jQuery alone.
In my above example, it is just absolutely unavoidable that jQuery has to hook onto the DOM in order to provide functionality. That means that the view (html) is concerned about functionality (because it is labeled with some kind of identifier - like "image slider") and JavaScript is concerned about providing that functionality. Angular eliminates that concept via abstraction. Properly written code with Angular means that the view is able to declare its own behavior. If I want to display a clock:
<clock></clock>
Done.
Yes, we need to go to JavaScript to make that mean something, but we're doing this in the opposite way of the jQuery approach. Our Angular directive (which is in it's own little world) has "augumented" the html and the html hooks the functionality into itself.
Angular gives you a straightforward way to structure your code. View things belong in the view (html), augmented view functionality belongs in directives, other logic (like ajax calls) and functions belong in services, and the connection of services and logic to the view belongs in controllers. There are some other angular components as well that help deal with configuration and modification of services, etc. Any functionality you create is automatically available anywhere you need it via the Injector subsystem which takes care of Dependency Injection throughout the application. When writing an application (module), I break it up into other reusable modules, each with their own reusable components, and then include them in the bigger project. Once you solve a problem with Angular, you've automatically solved it in a way that is useful and structured for reuse in the future and easily included in the next project. A HUGE bonus to all of this is that your code will be much easier to test.
THANK GOODNESS. The aforementioned jQuery spaghetti code resulted from a dev that made something "work" and then moved on. You can write bad Angular code, but it's much more difficult to do so, because Angular will fight you about it. This means that you have to take advantage (at least somewhat) to the clean architecture it provides. In other words, it's harder to write bad code with Angular, but more convenient to write clean code.
Angular is far from perfect. The web development world is always growing and changing and there are new and better ways being put forth to solve problems. Facebook's React and Flux, for example, have some great advantages over Angular, but come with their own drawbacks. Nothing's perfect, but Angular has been and is still awesome for now. Just as jQuery once helped the web world move forward, so has Angular, and so will many to come.
I think the selected answer is not correct, as the original question is "how to add a new validator after create the formControl".
As far as I know, that's not possible. The only thing you can do, is create the array of validators dynamicaly.
But what we miss is to have a function addValidator() to not override the validators already added to the formControl. If anybody has an answer for that requirement, would be nice to be posted here.
COLUMN()
and ROW()
won't work this way because they are applied to the cell that is calling them. In conditional formatting, you will have to be explicit instead of implicit.
For instance, if you want to use this conditional formating on a range begining on cell A1
, you can try:
`COLUMN(A1)` and `ROW(A1)`
Excel will automatically adapt the conditional formating to the current cell.
I personally use this function to create CSV content from any array.
function array2csv(array &$array)
{
if (count($array) == 0) {
return null;
}
ob_start();
$df = fopen("php://output", 'w');
fputcsv($df, array_keys(reset($array)));
foreach ($array as $row) {
fputcsv($df, $row);
}
fclose($df);
return ob_get_clean();
}
Then you can make your user download that file using something like:
function download_send_headers($filename) {
// disable caching
$now = gmdate("D, d M Y H:i:s");
header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
header("Last-Modified: {$now} GMT");
// force download
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/download");
// disposition / encoding on response body
header("Content-Disposition: attachment;filename={$filename}");
header("Content-Transfer-Encoding: binary");
}
Usage example:
download_send_headers("data_export_" . date("Y-m-d") . ".csv");
echo array2csv($array);
die();
The database is a MySQL database, not a phpMyAdmin database. phpMyAdmin is only PHP code that connects to the DB.
mysql_connect('localhost', 'username', 'password') or die (mysql_error());
mysql_select_database('db_name') or die (mysql_error());
// now you are connected
There are multiple reasons for this error.
One of the reason where i encountered this error is while building for linux and windows.
I have a filename with caps BaseClass.h SubClass.h Unix maintains has case-sensitive filenaming convention and windows is case-insensitive.
C++ why people don't use uppercase in name of header files?
Try compiling clean build using gmake clean if you are using gmake
Some text editors has default settings to ignore case-sensitive filenames. This could also lead to the same error.
import React, { Component } from 'react';
class Result extends Component {
render() {
if(this.props.resultsfood.status=='found'){
var foodlist = this.props.resultsfood.items.map(name=>{
return (
<div className="row" key={name.id} >
<div className="list-group">
<a href="#" className="list-group-item list-group-item-action disabled">
<span className="badge badge-info"><h6> {name.item}</h6></span>
<span className="badge badge-danger"><h6> Rs.{name.price}/=</h6></span>
</a>
<a href="#" className="list-group-item list-group-item-action disabled">
<div className="alert alert-dismissible alert-secondary">
<strong>{name.description}</strong>
</div>
</a>
<div className="form-group">
<label className="col-form-label col-form-label-sm" htmlFor="inputSmall">Quantitiy</label>
<input className="form-control form-control-sm" placeholder="unit/kg" type="text" ref="qty"/>
<div> <button type="button" className="btn btn-success"
onClick={()=>{this.props.savelist(name.item,name.price);
this.props.pricelist(name.price);
this.props.quntylist(this.refs.qty.value);
}
}>ADD Cart</button>
</div>
<br/>
</div>
</div>
</div>
)
})
}
return (
<ul>
{foodlist}
</ul>
)
}
}
export default Result;
My opinions on these are:
1) No, table names should be singular.
While it appears to make sense for the simple selection (select * from Orders
) it makes less sense for the OO equivalent (Orders x = new Orders
).
A table in a DB is really the set of that entity, it makes more sense once you're using set-logic:
select Orders.*
from Orders inner join Products
on Orders.Key = Products.Key
That last line, the actual logic of the join, looks confusing with plural table names.
I'm not sure about always using an alias (as Matt suggests) clears that up.
2) They should be singular as they only hold 1 property
3) Never, if the column name is ambiguous (as above where they both have a column called [Key]) the name of the table (or its alias) can distinguish them well enough. You want queries to be quick to type and simple - prefixes add unnecessary complexity.
4) Whatever you want, I'd suggest CapitalCase
I don't think there's one set of absolute guidelines on any of these.
As long as whatever you pick is consistent across the application or DB I don't think it really matters.
Two things you can do:
git checkout -b sillyname
git commit -am "silly message"
git checkout -
or
git stash -u
git branch sillyname stash@{0}
(git checkout -
<-- the dash is a shortcut for the previous branch you were on )
(git stash -u
<-- the -u
means that it also takes unstaged changes )
Use Apache's mod_dumpio. Be careful for obvious reasons.
Note that mod_dumpio stops logging binary payloads at the first null character. For example a multipart/form-data
upload of a gzip'd file will probably only show the first few bytes with mod_dumpio.
Also note that Apache might not mention this module in httpd.conf
even when it's present in the /modules
folder. Just manually adding LoadModule
will work fine.
You may want to take your argument a step further and talk about design patterns - and you can find out why he'd want to bother trying to inherit from multiple classes in c# if he even could
Always, always, always put disposable objects inside of using statements. I can't see how you've instantiated your DataReader but you should do it like this:
using (Connection c = ...)
{
using (DataReader dr = ...)
{
//Work with dr in here.
}
}
//Now the connection and reader have been closed and disposed.
Now, to answer your question, the reader is using the same connection as the command you're trying to ExecuteNonQuery
on. You need to use a separate connection since the DataReader keeps the connection open and reads data as you need it.
In command mode (press Esc if you are not sure) you can use:
In the Macros explorer under samples/accessibility there is an IncreaseTextEditorFontSize and a DecreaseTextEditorFontSize. Bind those to some keyboard shortcuts.
Like has been repeated, functors are classes that can be treated as functions (overload operator ()).
They are most useful for situations in which you need to associate some data with repeated or delayed calls to a function.
For example, a linked-list of functors could be used to implement a basic low-overhead synchronous coroutine system, a task dispatcher, or interruptable file parsing. Examples:
/* prints "this is a very simple and poorly used task queue" */
class Functor
{
public:
std::string output;
Functor(const std::string& out): output(out){}
operator()() const
{
std::cout << output << " ";
}
};
int main(int argc, char **argv)
{
std::list<Functor> taskQueue;
taskQueue.push_back(Functor("this"));
taskQueue.push_back(Functor("is a"));
taskQueue.push_back(Functor("very simple"));
taskQueue.push_back(Functor("and poorly used"));
taskQueue.push_back(Functor("task queue"));
for(std::list<Functor>::iterator it = taskQueue.begin();
it != taskQueue.end(); ++it)
{
*it();
}
return 0;
}
/* prints the value stored in "i", then asks you if you want to increment it */
int i;
bool should_increment;
int doSomeWork()
{
std::cout << "i = " << i << std::endl;
std::cout << "increment? (enter the number 1 to increment, 0 otherwise" << std::endl;
std::cin >> should_increment;
return 2;
}
void doSensitiveWork()
{
++i;
should_increment = false;
}
class BaseCoroutine
{
public:
BaseCoroutine(int stat): status(stat), waiting(false){}
void operator()(){ status = perform(); }
int getStatus() const { return status; }
protected:
int status;
bool waiting;
virtual int perform() = 0;
bool await_status(BaseCoroutine& other, int stat, int change)
{
if(!waiting)
{
waiting = true;
}
if(other.getStatus() == stat)
{
status = change;
waiting = false;
}
return !waiting;
}
}
class MyCoroutine1: public BaseCoroutine
{
public:
MyCoroutine1(BaseCoroutine& other): BaseCoroutine(1), partner(other){}
protected:
BaseCoroutine& partner;
virtual int perform()
{
if(getStatus() == 1)
return doSomeWork();
if(getStatus() == 2)
{
if(await_status(partner, 1))
return 1;
else if(i == 100)
return 0;
else
return 2;
}
}
};
class MyCoroutine2: public BaseCoroutine
{
public:
MyCoroutine2(bool& work_signal): BaseCoroutine(1), ready(work_signal) {}
protected:
bool& work_signal;
virtual int perform()
{
if(i == 100)
return 0;
if(work_signal)
{
doSensitiveWork();
return 2;
}
return 1;
}
};
int main()
{
std::list<BaseCoroutine* > coroutineList;
MyCoroutine2 *incrementer = new MyCoroutine2(should_increment);
MyCoroutine1 *printer = new MyCoroutine1(incrementer);
while(coroutineList.size())
{
for(std::list<BaseCoroutine *>::iterator it = coroutineList.begin();
it != coroutineList.end(); ++it)
{
*it();
if(*it.getStatus() == 0)
{
coroutineList.erase(it);
}
}
}
delete printer;
delete incrementer;
return 0;
}
Of course, these examples aren't that useful in themselves. They only show how functors can be useful, the functors themselves are very basic and inflexible and this makes them less useful than, for example, what boost provides.
Is the Config/setup.php
file actually in /test/content/home/
or is in your document root? it is best to make all references relative to your document root.
include $_SERVER['DOCUMENT_ROOT'] . "Config/setup.php";
Your current code assumes that the location of setup.php
is in /text/content/home/Config/setup.php
, is this correct?
If anyone is wondering you can use the 'pip show' command.
pip show [options] <package>
This will list the install directory of the given package.
I know I'm joining late to the discussion, but I think this can be useful to others.
I wanted to avoid deprecated stuff and after a lot of fiddling I found a simple way to send to servers requiring Implicit SSL: use NuGet and add the MailKit package to the project. (I used VS2017 targetting .NET 4.6.2 but it should work on lower .NET versions...)
Then you'll only need to do something like this:
using MailKit.Net.Smtp;
using MimeKit;
var client = new SmtpClient();
client.Connect("server.name", 465, true);
// Note: since we don't have an OAuth2 token, disable the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove ("XOAUTH2");
if (needsUserAndPwd)
{
// Note: only needed if the SMTP server requires authentication
client.Authenticate (user, pwd);
}
var msg = new MimeMessage();
msg.From.Add(new MailboxAddress("[email protected]"));
msg.To .Add(new MailboxAddress("[email protected]"));
msg.Subject = "This is a test subject";
msg.Body = new TextPart("plain") {
Text = "This is a sample message body"
};
client.Send(msg);
client.Disconnect(true);
Of course you can also tweak it to use Explicit SSL or no transport security at all.
Making a small adjustment to Tor Valamo's solution to fix the problem noticed by Dominic Rodger, you could use:
// Remove anything which isn't a word, whitespace, number
// or any of the following caracters -_~,;[]().
// If you don't need to handle multi-byte characters
// you can use preg_replace rather than mb_ereg_replace
// Thanks @Lukasz Rysiak!
$file = mb_ereg_replace("([^\w\s\d\-_~,;\[\]\(\).])", '', $file);
// Remove any runs of periods (thanks falstro!)
$file = mb_ereg_replace("([\.]{2,})", '', $file);
So a recent question prompted me to notice a selector set hack for excluding IE 8 only.
.selector, #excludeIE8::before {}
will cause IE 8 to throw out the entire selector set, while 5-7 and 9-11 will read it just fine. Any of the ::
selectors (::first-line, ::before, ::first-letter, ::selection
) will work, I've merely chosen ::before
so the line reads accurately. Note that the goal of the fake ::before
selector is to be fake, so be sure to change it to something else if you actually have an element with the ID excludeIE8
Interestingly enough, in modern browsers (FF 45-52, GC 49-57, Edge 25/13) a bad ::
selector eats the entire selector set (dabblet demo). It seems that the last Windows version of Safari (and LTE IE 7, lol) doesn't have this behavior while still understanding ::before
. Additionally, I can't find anything in the spec to indicate that this is intended behavior, and since it would cause breakage on any selector set containing: ::future-legitimate-pseudoelement
... I'm inclined to say this is a bug- and one that'll nibble our rears in the future.
However, if you only want something at the property level (rather than the rule level), Ziga above had the best solution via appending \9
(the space is key; do NOT copypaste that inline as it uses an nbsp):
/*property-level hacks:*/
/*Standards, Edge*/
prop:val;
/*lte ie 11*/
prop:val\9;
/*lte ie 8*/
prop:val \9;
/*lte ie 7*/
*prop:val;
/*lte ie 6*/
_prop:val;
/*other direction...*/
/*gte ie 8, NOT Edge*/
prop:val\0;
Side note, I feel like a dirty necromancer- but I wanted somewhere to document the exclude-IE8-only selector set hack I found today, and this seemed to be the most fitting place.
If you only want to have glyphicons icons without any additional css you can create a css file and put the code below and include it into main css file.
I have to create this extra file as link below was messing with my site styles too.
//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css
Instead to using it directly I created a css file bootstrap-glyphicons.css
@font-face{font-family:'Glyphicons Halflings';src:url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot');src:url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'),url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.woff') format('woff'),url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.ttf') format('truetype'),url('http://netdna.bootstrapcdn.com/bootstrap/3.0.0/fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');}.glyphicon{position:relative;top:1px;display:inline-block;font-family:'Glyphicons Halflings';font-style:normal;font-weight:normal;line-height:1;-webkit-font-smoothing:antialiased;}_x000D_
.glyphicon-asterisk:before{content:"\2a";}_x000D_
.glyphicon-plus:before{content:"\2b";}_x000D_
.glyphicon-euro:before{content:"\20ac";}_x000D_
.glyphicon-minus:before{content:"\2212";}_x000D_
.glyphicon-cloud:before{content:"\2601";}_x000D_
.glyphicon-envelope:before{content:"\2709";}_x000D_
.glyphicon-pencil:before{content:"\270f";}_x000D_
.glyphicon-glass:before{content:"\e001";}_x000D_
.glyphicon-music:before{content:"\e002";}_x000D_
.glyphicon-search:before{content:"\e003";}_x000D_
.glyphicon-heart:before{content:"\e005";}_x000D_
.glyphicon-star:before{content:"\e006";}_x000D_
.glyphicon-star-empty:before{content:"\e007";}_x000D_
.glyphicon-user:before{content:"\e008";}_x000D_
.glyphicon-film:before{content:"\e009";}_x000D_
.glyphicon-th-large:before{content:"\e010";}_x000D_
.glyphicon-th:before{content:"\e011";}_x000D_
.glyphicon-th-list:before{content:"\e012";}_x000D_
.glyphicon-ok:before{content:"\e013";}_x000D_
.glyphicon-remove:before{content:"\e014";}_x000D_
.glyphicon-zoom-in:before{content:"\e015";}_x000D_
.glyphicon-zoom-out:before{content:"\e016";}_x000D_
.glyphicon-off:before{content:"\e017";}_x000D_
.glyphicon-signal:before{content:"\e018";}_x000D_
.glyphicon-cog:before{content:"\e019";}_x000D_
.glyphicon-trash:before{content:"\e020";}_x000D_
.glyphicon-home:before{content:"\e021";}_x000D_
.glyphicon-file:before{content:"\e022";}_x000D_
.glyphicon-time:before{content:"\e023";}_x000D_
.glyphicon-road:before{content:"\e024";}_x000D_
.glyphicon-download-alt:before{content:"\e025";}_x000D_
.glyphicon-download:before{content:"\e026";}_x000D_
.glyphicon-upload:before{content:"\e027";}_x000D_
.glyphicon-inbox:before{content:"\e028";}_x000D_
.glyphicon-play-circle:before{content:"\e029";}_x000D_
.glyphicon-repeat:before{content:"\e030";}_x000D_
.glyphicon-refresh:before{content:"\e031";}_x000D_
.glyphicon-list-alt:before{content:"\e032";}_x000D_
.glyphicon-flag:before{content:"\e034";}_x000D_
.glyphicon-headphones:before{content:"\e035";}_x000D_
.glyphicon-volume-off:before{content:"\e036";}_x000D_
.glyphicon-volume-down:before{content:"\e037";}_x000D_
.glyphicon-volume-up:before{content:"\e038";}_x000D_
.glyphicon-qrcode:before{content:"\e039";}_x000D_
.glyphicon-barcode:before{content:"\e040";}_x000D_
.glyphicon-tag:before{content:"\e041";}_x000D_
.glyphicon-tags:before{content:"\e042";}_x000D_
.glyphicon-book:before{content:"\e043";}_x000D_
.glyphicon-print:before{content:"\e045";}_x000D_
.glyphicon-font:before{content:"\e047";}_x000D_
.glyphicon-bold:before{content:"\e048";}_x000D_
.glyphicon-italic:before{content:"\e049";}_x000D_
.glyphicon-text-height:before{content:"\e050";}_x000D_
.glyphicon-text-width:before{content:"\e051";}_x000D_
.glyphicon-align-left:before{content:"\e052";}_x000D_
.glyphicon-align-center:before{content:"\e053";}_x000D_
.glyphicon-align-right:before{content:"\e054";}_x000D_
.glyphicon-align-justify:before{content:"\e055";}_x000D_
.glyphicon-list:before{content:"\e056";}_x000D_
.glyphicon-indent-left:before{content:"\e057";}_x000D_
.glyphicon-indent-right:before{content:"\e058";}_x000D_
.glyphicon-facetime-video:before{content:"\e059";}_x000D_
.glyphicon-picture:before{content:"\e060";}_x000D_
.glyphicon-map-marker:before{content:"\e062";}_x000D_
.glyphicon-adjust:before{content:"\e063";}_x000D_
.glyphicon-tint:before{content:"\e064";}_x000D_
.glyphicon-edit:before{content:"\e065";}_x000D_
.glyphicon-share:before{content:"\e066";}_x000D_
.glyphicon-check:before{content:"\e067";}_x000D_
.glyphicon-move:before{content:"\e068";}_x000D_
.glyphicon-step-backward:before{content:"\e069";}_x000D_
.glyphicon-fast-backward:before{content:"\e070";}_x000D_
.glyphicon-backward:before{content:"\e071";}_x000D_
.glyphicon-play:before{content:"\e072";}_x000D_
.glyphicon-pause:before{content:"\e073";}_x000D_
.glyphicon-stop:before{content:"\e074";}_x000D_
.glyphicon-forward:before{content:"\e075";}_x000D_
.glyphicon-fast-forward:before{content:"\e076";}_x000D_
.glyphicon-step-forward:before{content:"\e077";}_x000D_
.glyphicon-eject:before{content:"\e078";}_x000D_
.glyphicon-chevron-left:before{content:"\e079";}_x000D_
.glyphicon-chevron-right:before{content:"\e080";}_x000D_
.glyphicon-plus-sign:before{content:"\e081";}_x000D_
.glyphicon-minus-sign:before{content:"\e082";}_x000D_
.glyphicon-remove-sign:before{content:"\e083";}_x000D_
.glyphicon-ok-sign:before{content:"\e084";}_x000D_
.glyphicon-question-sign:before{content:"\e085";}_x000D_
.glyphicon-info-sign:before{content:"\e086";}_x000D_
.glyphicon-screenshot:before{content:"\e087";}_x000D_
.glyphicon-remove-circle:before{content:"\e088";}_x000D_
.glyphicon-ok-circle:before{content:"\e089";}_x000D_
.glyphicon-ban-circle:before{content:"\e090";}_x000D_
.glyphicon-arrow-left:before{content:"\e091";}_x000D_
.glyphicon-arrow-right:before{content:"\e092";}_x000D_
.glyphicon-arrow-up:before{content:"\e093";}_x000D_
.glyphicon-arrow-down:before{content:"\e094";}_x000D_
.glyphicon-share-alt:before{content:"\e095";}_x000D_
.glyphicon-resize-full:before{content:"\e096";}_x000D_
.glyphicon-resize-small:before{content:"\e097";}_x000D_
.glyphicon-exclamation-sign:before{content:"\e101";}_x000D_
.glyphicon-gift:before{content:"\e102";}_x000D_
.glyphicon-leaf:before{content:"\e103";}_x000D_
.glyphicon-eye-open:before{content:"\e105";}_x000D_
.glyphicon-eye-close:before{content:"\e106";}_x000D_
.glyphicon-warning-sign:before{content:"\e107";}_x000D_
.glyphicon-plane:before{content:"\e108";}_x000D_
.glyphicon-random:before{content:"\e110";}_x000D_
.glyphicon-comment:before{content:"\e111";}_x000D_
.glyphicon-magnet:before{content:"\e112";}_x000D_
.glyphicon-chevron-up:before{content:"\e113";}_x000D_
.glyphicon-chevron-down:before{content:"\e114";}_x000D_
.glyphicon-retweet:before{content:"\e115";}_x000D_
.glyphicon-shopping-cart:before{content:"\e116";}_x000D_
.glyphicon-folder-close:before{content:"\e117";}_x000D_
.glyphicon-folder-open:before{content:"\e118";}_x000D_
.glyphicon-resize-vertical:before{content:"\e119";}_x000D_
.glyphicon-resize-horizontal:before{content:"\e120";}_x000D_
.glyphicon-hdd:before{content:"\e121";}_x000D_
.glyphicon-bullhorn:before{content:"\e122";}_x000D_
.glyphicon-certificate:before{content:"\e124";}_x000D_
.glyphicon-thumbs-up:before{content:"\e125";}_x000D_
.glyphicon-thumbs-down:before{content:"\e126";}_x000D_
.glyphicon-hand-right:before{content:"\e127";}_x000D_
.glyphicon-hand-left:before{content:"\e128";}_x000D_
.glyphicon-hand-up:before{content:"\e129";}_x000D_
.glyphicon-hand-down:before{content:"\e130";}_x000D_
.glyphicon-circle-arrow-right:before{content:"\e131";}_x000D_
.glyphicon-circle-arrow-left:before{content:"\e132";}_x000D_
.glyphicon-circle-arrow-up:before{content:"\e133";}_x000D_
.glyphicon-circle-arrow-down:before{content:"\e134";}_x000D_
.glyphicon-globe:before{content:"\e135";}_x000D_
.glyphicon-tasks:before{content:"\e137";}_x000D_
.glyphicon-filter:before{content:"\e138";}_x000D_
.glyphicon-fullscreen:before{content:"\e140";}_x000D_
.glyphicon-dashboard:before{content:"\e141";}_x000D_
.glyphicon-heart-empty:before{content:"\e143";}_x000D_
.glyphicon-link:before{content:"\e144";}_x000D_
.glyphicon-phone:before{content:"\e145";}_x000D_
.glyphicon-usd:before{content:"\e148";}_x000D_
.glyphicon-gbp:before{content:"\e149";}_x000D_
.glyphicon-sort:before{content:"\e150";}_x000D_
.glyphicon-sort-by-alphabet:before{content:"\e151";}_x000D_
.glyphicon-sort-by-alphabet-alt:before{content:"\e152";}_x000D_
.glyphicon-sort-by-order:before{content:"\e153";}_x000D_
.glyphicon-sort-by-order-alt:before{content:"\e154";}_x000D_
.glyphicon-sort-by-attributes:before{content:"\e155";}_x000D_
.glyphicon-sort-by-attributes-alt:before{content:"\e156";}_x000D_
.glyphicon-unchecked:before{content:"\e157";}_x000D_
.glyphicon-expand:before{content:"\e158";}_x000D_
.glyphicon-collapse-down:before{content:"\e159";}_x000D_
.glyphicon-collapse-up:before{content:"\e160";}_x000D_
.glyphicon-log-in:before{content:"\e161";}_x000D_
.glyphicon-flash:before{content:"\e162";}_x000D_
.glyphicon-log-out:before{content:"\e163";}_x000D_
.glyphicon-new-window:before{content:"\e164";}_x000D_
.glyphicon-record:before{content:"\e165";}_x000D_
.glyphicon-save:before{content:"\e166";}_x000D_
.glyphicon-open:before{content:"\e167";}_x000D_
.glyphicon-saved:before{content:"\e168";}_x000D_
.glyphicon-import:before{content:"\e169";}_x000D_
.glyphicon-export:before{content:"\e170";}_x000D_
.glyphicon-send:before{content:"\e171";}_x000D_
.glyphicon-floppy-disk:before{content:"\e172";}_x000D_
.glyphicon-floppy-saved:before{content:"\e173";}_x000D_
.glyphicon-floppy-remove:before{content:"\e174";}_x000D_
.glyphicon-floppy-save:before{content:"\e175";}_x000D_
.glyphicon-floppy-open:before{content:"\e176";}_x000D_
.glyphicon-credit-card:before{content:"\e177";}_x000D_
.glyphicon-transfer:before{content:"\e178";}_x000D_
.glyphicon-cutlery:before{content:"\e179";}_x000D_
.glyphicon-header:before{content:"\e180";}_x000D_
.glyphicon-compressed:before{content:"\e181";}_x000D_
.glyphicon-earphone:before{content:"\e182";}_x000D_
.glyphicon-phone-alt:before{content:"\e183";}_x000D_
.glyphicon-tower:before{content:"\e184";}_x000D_
.glyphicon-stats:before{content:"\e185";}_x000D_
.glyphicon-sd-video:before{content:"\e186";}_x000D_
.glyphicon-hd-video:before{content:"\e187";}_x000D_
.glyphicon-subtitles:before{content:"\e188";}_x000D_
.glyphicon-sound-stereo:before{content:"\e189";}_x000D_
.glyphicon-sound-dolby:before{content:"\e190";}_x000D_
.glyphicon-sound-5-1:before{content:"\e191";}_x000D_
.glyphicon-sound-6-1:before{content:"\e192";}_x000D_
.glyphicon-sound-7-1:before{content:"\e193";}_x000D_
.glyphicon-copyright-mark:before{content:"\e194";}_x000D_
.glyphicon-registration-mark:before{content:"\e195";}_x000D_
.glyphicon-cloud-download:before{content:"\e197";}_x000D_
.glyphicon-cloud-upload:before{content:"\e198";}_x000D_
.glyphicon-tree-conifer:before{content:"\e199";}_x000D_
.glyphicon-tree-deciduous:before{content:"\e200";}_x000D_
.glyphicon-briefcase:before{content:"\1f4bc";}_x000D_
.glyphicon-calendar:before{content:"\1f4c5";}_x000D_
.glyphicon-pushpin:before{content:"\1f4cc";}_x000D_
.glyphicon-paperclip:before{content:"\1f4ce";}_x000D_
.glyphicon-camera:before{content:"\1f4f7";}_x000D_
.glyphicon-lock:before{content:"\1f512";}_x000D_
.glyphicon-bell:before{content:"\1f514";}_x000D_
.glyphicon-bookmark:before{content:"\1f516";}_x000D_
.glyphicon-fire:before{content:"\1f525";}_x000D_
.glyphicon-wrench:before{content:"\1f527";}
_x000D_
And imported the created css file into my main css file which enable me to just import the glyphicons only. Hope this help
@import url("bootstrap-glyphicons.css");
This error occurs because VMware has a bug that uses the absolute path of the disk file in certain situations.
If you look at the top of that small *.vmdk file you'll likely see an incorrect absolute path to the original VMDK file that needs to be corrected.
You can use ViewChild
<child-tag #varName></child-tag>
@ViewChild('varName') someElement;
ngAfterViewInit() {
someElement...
}
where varName
is a template variable added to the element. Alternatively, you can query by component or directive type.
There are alternatives like ViewChildren
, ContentChild
, ContentChildren
.
@ViewChildren
can also be used in the constructor.
constructor(@ViewChildren('var1,var2,var3') childQuery:QueryList)
The advantage is that the result is available earlier.
See also http://www.bennadel.com/blog/3041-constructor-vs-property-querylist-injection-in-angular-2-beta-8.htm for some advantages/disadvantages of using the constructor or a field.
Note: @Query()
is the deprecated predecessor of @ContentChildren()
Update
Query
is currently just an abstract base class. I haven't found if it is used at all https://github.com/angular/angular/blob/2.1.x/modules/@angular/core/src/metadata/di.ts#L145
Nope. C++ does not throw an exception when you do something bad, that would incur a performance hit. Things like access violations or division by zero errors are more like "machine" exceptions, rather than language-level things that you can catch.
CGI is an interface which tells the webserver how to pass data to and from an application. More specifically, it describes how request information is passed in environment variables (such as request type, remote IP address), how the request body is passed in via standard input, and how the response is passed out via standard output. You can refer to the CGI specification for details.
To use your image:
user (client) request for page ---> webserver ---[CGI]----> Server side Program ---> MySQL Server.
Most if not all, webservers can be configured to execute a program as a 'CGI'. This means that the webserver, upon receiving a request, will forward the data to a specific program, setting some environment variables and marshalling the parameters via standard input and standard output so the program can know where and what to look for.
The main benefit is that you can run ANY executable code from the web, given that both the webserver and the program know how CGI works. That's why you could write web programs in C or Bash with a regular CGI-enabled webserver. That, and that most programming environments can easily use standard input, standard output and environment variables.
In your case you most likely used another, specific for PHP, means of communication between your scripts and the webserver, this, as you well mention in your question, is an embedded interpreter called mod_php.
So, answering your questions:
What exactly is CGI?
See above.
Whats the big deal with /cgi-bin/*.cgi? Whats up with this? I don't know what is this cgi-bin directory on the server for. I don't know why they have *.cgi extensions.
That's the traditional place for cgi programs, many webservers come with this directory pre configured to execute all binaries there as CGI programs. The .cgi extension denotes an executable that is expected to work through the CGI.
Why does Perl always comes in the way. CGI & Perl (language). I also don't know whats up with these two. Almost all the time I keep hearing these two in combination "CGI & Perl". This book is another great example CGI Programming with Perl Why not "CGI Programming with PHP/JSP/ASP". I never saw such things.
Because Perl is ancient (older than PHP, JSP and ASP which all came to being when CGI was already old, Perl existed when CGI was new) and became fairly famous for being a very good language to serve dynamic webpages via the CGI. Nowadays there are other alternatives to run Perl in a webserver, mainly mod_perl.
CGI Programming in C this confuses me a lot. in C?? Seriously?? I don't know what to say. I"m just confused. "in C"?? This changes everything. Program needs to be compiled and executed. This entirely changes my view of web programming. When do I compile? How does the program gets executed (because it will be a machine code, so it must execute as a independent process). How does it communicate with the web server? IPC? and interfacing with all the servers (in my example MATLAB & MySQL) using socket programming? I'm lost!!
You compile the executable once, the webserver executes the program and passes the data in the request to the program and outputs the received response. CGI specifies that one program instance will be launched per each request. This is why CGI is inefficient and kind of obsolete nowadays.
They say that CGI is deprecated. Its no more in use. Is it so? What is its latest update?
CGI is still used when performance is not paramount and a simple means of executing code is required. It is inefficient for the previously stated reasons and there are more modern means of executing any program in a web enviroment. Currently the most famous is FastCGI.
Nothing, they are synonymous (Response.Write
is simply a shorter way to express the act of writing to the response output).
If you are curious, the implementation of HttpResponse.Write
looks like this:
public void Write(string s)
{
this._writer.Write(s);
}
And the implementation of HttpResponse.Output
is this:
public TextWriter Output
{
get
{
return this._writer;
}
}
So as you can see, Response.Write
and Response.Output.Write
are truly synonymous expressions.
TimeSpan can be added to a fresh DateTime to achieve this.
TimeSpan ts="XXX";
DateTime dt = new DateTime() + ts;
But as mentioned before, it is not strictly logical without a valid start date. I have encountered a use-case where i required only the time aspect. will work fine as long as the logic is correct.
you can also covert int to str first and assign index to it then again convert it to int like this:
int(str(x)[n]) //where x is an integer value
It is now possible to create command line launcher automatically from JetBrains Toolbox. This is how you do it:
Generate shell scripts
;Shell script location
textbox with the location where you want the launchers to reside. You have to do this manually it will not fill automatically at this time!On Mac the location could be /usr/local/bin
. For the novices, you can use any path inside the PATH variable or add a new path to the PATH variable in your bash profile. Use echo $PATH
to see which paths are there.
Note! It did not work right away for me, I had to fiddle around a little before the scripts were generated. You can go to the gearbox of the IDEA (PyCharm for example) and see/change the launcher name. So for PyCharm, the default name is pycharm
but you can change this to whatever you prefer.
If you do not use the toolbox you can still use my original answer.
~~For some reason, the Create Command Line Launcher
is not available anymore in 2019.1.~~ Because it is now part of JetBrains Toolbox
This is how you can create the script yourself:
If you already used the charm command before use type -a charm
to find the script. Change the pycharm version in the file paths. Note that the numbering in the first variable RUN_PATH
is different. You will have to look this up in the dir yourself.
RUN_PATH = u'/Users/boatfolder/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/191.6183.50/PyCharm.app'
CONFIG_PATH = u'/Users/boatfolder/Library/Preferences/PyCharm2019.1'
SYSTEM_PATH = u'/Users/boatfolder/Library/Caches/PyCharm2019.1'
If you did not use the charm command before, you will have to create it.
Create the charm file somewhere like this: /usr/local/bin/charm
Then add this code (change version number to your version as explained above):
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import socket
import struct
import sys
import os
import time
# see com.intellij.idea.SocketLock for the server side of this interface
RUN_PATH = u'/Users/boatfolder/Library/Application Support/JetBrains/Toolbox/apps/PyCharm-P/ch-0/191.6183.50/PyCharm.app'
CONFIG_PATH = u'/Users/boatfolder/Library/Preferences/PyCharm2019.1'
SYSTEM_PATH = u'/Users/boatfolder/Library/Caches/PyCharm2019.1'
def print_usage(cmd):
print(('Usage:\n' +
' {0} -h | -? | --help\n' +
' {0} [project_dir]\n' +
' {0} [-l|--line line] [project_dir|--temp-project] file[:line]\n' +
' {0} diff <left> <right>\n' +
' {0} merge <local> <remote> [base] <merged>').format(cmd))
def process_args(argv):
args = []
skip_next = False
for i, arg in enumerate(argv[1:]):
if arg == '-h' or arg == '-?' or arg == '--help':
print_usage(argv[0])
exit(0)
elif i == 0 and (arg == 'diff' or arg == 'merge' or arg == '--temp-project'):
args.append(arg)
elif arg == '-l' or arg == '--line':
args.append(arg)
skip_next = True
elif skip_next:
args.append(arg)
skip_next = False
else:
path = arg
if ':' in arg:
file_path, line_number = arg.rsplit(':', 1)
if line_number.isdigit():
args.append('-l')
args.append(line_number)
path = file_path
args.append(os.path.abspath(path))
return args
def try_activate_instance(args):
port_path = os.path.join(CONFIG_PATH, 'port')
token_path = os.path.join(SYSTEM_PATH, 'token')
if not (os.path.exists(port_path) and os.path.exists(token_path)):
return False
try:
with open(port_path) as pf:
port = int(pf.read())
with open(token_path) as tf:
token = tf.read()
except (ValueError):
return False
s = socket.socket()
s.settimeout(0.3)
try:
s.connect(('127.0.0.1', port))
except (socket.error, IOError):
return False
found = False
while True:
try:
path_len = struct.unpack('>h', s.recv(2))[0]
path = s.recv(path_len).decode('utf-8')
if os.path.abspath(path) == os.path.abspath(CONFIG_PATH):
found = True
break
except (socket.error, IOError):
return False
if found:
cmd = 'activate ' + token + '\0' + os.getcwd() + '\0' + '\0'.join(args)
if sys.version_info.major >= 3: cmd = cmd.encode('utf-8')
encoded = struct.pack('>h', len(cmd)) + cmd
s.send(encoded)
time.sleep(0.5) # don't close the socket immediately
return True
return False
def start_new_instance(args):
if sys.platform == 'darwin':
if len(args) > 0:
args.insert(0, '--args')
os.execvp('/usr/bin/open', ['-a', RUN_PATH] + args)
else:
bin_file = os.path.split(RUN_PATH)[1]
os.execv(RUN_PATH, [bin_file] + args)
ide_args = process_args(sys.argv)
if not try_activate_instance(ide_args):
start_new_instance(ide_args)
If you are building a windows app try to build as x64 instead of Any CPU. It should work fine.
I just had to do this myself, you need to do it the other way around.
<div>
<span class="icon icon-2x icon-camera" style=" vertical-align: middle;"></span>
<span class="my-text">hello world</span>
</div>
Of course you could not use inline styles and target it with your own css class. But this works in a copy paste fashion.
See here: Vertical alignment of text and icon in button
If it were up to me however, I would not use the icon-2x. And simply specify the font-size myself, as in the following
<div class='my-fancy-container'>
<span class='my-icon icon-file-text'></span>
<span class='my-text'>Hello World</span>
</div>
.my-icon {
vertical-align: middle;
font-size: 40px;
}
.my-text {
font-family: "Courier-new";
}
.my-fancy-container {
border: 1px solid #ccc;
border-radius: 6px;
display: inline-block;
margin: 60px;
padding: 10px;
}
for a working example, please see JsFiddle
That error means that jQuery has not yet loaded on the page. Using $(document).ready(...)
or any variant thereof will do no good, as $
is the jQuery function.
Using window.onload
should work here. Note that only one function can be assigned to window.onload
. To avoid losing the original onload logic, you can decorate the original function like so:
originalOnload = window.onload;
window.onload = function() {
if (originalOnload) {
originalOnload();
}
// YOUR JQUERY
};
This will execute the function that was originally assigned to window.onload
, and then will execute // YOUR JQUERY
.
See https://en.wikipedia.org/wiki/Decorator_pattern for more detail about the decorator pattern.
This is a place in which C++ has a strange rule. Before being able to compile a call to a function the compiler must know the function name, return value and all parameters.
This can be done by adding a "prototype". In your case this simply means adding before main
the following line:
int writeFile();
this tells the compiler that there exist a function named writeFile
that will be defined somewhere, that returns an int
and that accepts no parameters.
Alternatively you can define first the function writeFile
and then main
because in this case when the compiler gets to main
already knows your function.
Note that this requirement of knowing in advance the functions being called is not always applied. For example for class members defined inline it's not required...
struct Foo {
void bar() {
if (baz() != 99) {
std::cout << "Hey!";
}
}
int baz() {
return 42;
}
};
In this case the compiler has no problem analyzing the definition of bar
even if it depends on a function baz
that is declared later in the source code.
One simple thing you could do is abstract the test inside a function.
local function isempty(s)
return s == nil or s == ''
end
if isempty(foo) then
foo = "default value"
end
using System;
using System.Data;
using System.Data.SqlClient;
namespace InsertingData
{
class sqlinsertdata
{
static void Main(string[] args)
{
try
{
SqlConnection conn = new SqlConnection("Data source=USER-PC; Database=Emp123;User Id=sa;Password=sa123");
conn.Open();
SqlCommand cmd = new SqlCommand("insert into <Table Name>values(1,'nagendra',10000);",conn);
cmd.ExecuteNonQuery();
Console.WriteLine("Inserting Data Successfully");
conn.Close();
}
catch(Exception e)
{
Console.WriteLine("Exception Occre while creating table:" + e.Message + "\t" + e.GetType());
}
Console.ReadKey();
}
}
}
Great answers. I also had a problem with NULLS and managed to solve it by including a COALESCE inside of the GROUP_CONCAT. Example as follows:
SELECT id, GROUP_CONCAT(COALESCE(name,'') SEPARATOR ' ')
FROM table
GROUP BY id;
Hope this helps someone else
I was getting the above mentioned error message when I tried to push my current branch foobar
:
git checkout foobar
git push origin foo
It turns out I had two local branches tracking the same remote branch:
foo -> origin/foo (some old branch)
foobar -> origin/foo (my current working branch)
It worked for me to push my current branch by using:
git push origin foobar:foo
... and to cleanup with git branch -d
Verbose, but copied from the HTTP 1.1 method specification at http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity in the response and not the source text of the process, unless that text happens to be the output of the process.
The semantics of the GET method change to a "conditional GET" if the request message includes an If-Modified-Since, If-Unmodified-Since, If-Match, If-None-Match, or If-Range header field. A conditional GET method requests that the entity be transferred only under the circumstances described by the conditional header field(s). The conditional GET method is intended to reduce unnecessary network usage by allowing cached entities to be refreshed without requiring multiple requests or transferring data already held by the client.
The semantics of the GET method change to a "partial GET" if the request message includes a Range header field. A partial GET requests that only part of the entity be transferred, as described in section 14.35. The partial GET method is intended to reduce unnecessary network usage by allowing partially-retrieved entities to be completed without transferring data already held by the client.
The response to a GET request is cacheable if and only if it meets the requirements for HTTP caching described in section 13.
See section 15.1.3 for security considerations when used for forms.
The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions:
- Annotation of existing resources;
- Posting a message to a bulletin board, newsgroup, mailing list,
or similar group of articles;
- Providing a block of data, such as the result of submitting a
form, to a data-handling process;
- Extending a database through an append operation.
The actual function performed by the POST method is determined by the server and is usually dependent on the Request-URI. The posted entity is subordinate to that URI in the same way that a file is subordinate to a directory containing it, a news article is subordinate to a newsgroup to which it is posted, or a record is subordinate to a database.
The action performed by the POST method might not result in a resource that can be identified by a URI. In this case, either 200 (OK) or 204 (No Content) is the appropriate response status, depending on whether or not the response includes an entity that describes the result.
If a resource has been created on the origin server, the response SHOULD be 201 (Created) and contain an entity which describes the status of the request and refers to the new resource, and a Location header (see section 14.30).
Responses to this method are not cacheable, unless the response includes appropriate Cache-Control or Expires header fields. However, the 303 (See Other) response can be used to direct the user agent to retrieve a cacheable resource.
POST requests MUST obey the message transmission requirements set out in section 8.2.
See section 15.1.3 for security considerations.
The PUT method requests that the enclosed entity be stored under the supplied Request-URI. If the Request-URI refers to an already existing resource, the enclosed entity SHOULD be considered as a modified version of the one residing on the origin server. If the Request-URI does not point to an existing resource, and that URI is capable of being defined as a new resource by the requesting user agent, the origin server can create the resource with that URI. If a new resource is created, the origin server MUST inform the user agent via the 201 (Created) response. If an existing resource is modified, either the 200 (OK) or 204 (No Content) response codes SHOULD be sent to indicate successful completion of the request. If the resource could not be created or modified with the Request-URI, an appropriate error response SHOULD be given that reflects the nature of the problem. The recipient of the entity MUST NOT ignore any Content-* (e.g. Content-Range) headers that it does not understand or implement and MUST return a 501 (Not Implemented) response in such cases.
If the request passes through a cache and the Request-URI identifies one or more currently cached entities, those entries SHOULD be treated as stale. Responses to this method are not cacheable.
The fundamental difference between the POST and PUT requests is reflected in the different meaning of the Request-URI. The URI in a POST request identifies the resource that will handle the enclosed entity. That resource might be a data-accepting process, a gateway to some other protocol, or a separate entity that accepts annotations. In contrast, the URI in a PUT request identifies the entity enclosed with the request -- the user agent knows what URI is intended and the server MUST NOT attempt to apply the request to some other resource. If the server desires that the request be applied to a different URI,
it MUST send a 301 (Moved Permanently) response; the user agent MAY then make its own decision regarding whether or not to redirect the request.
A single resource MAY be identified by many different URIs. For example, an article might have a URI for identifying "the current version" which is separate from the URI identifying each particular version. In this case, a PUT request on a general URI might result in several other URIs being defined by the origin server.
HTTP/1.1 does not define how a PUT method affects the state of an origin server.
PUT requests MUST obey the message transmission requirements set out in section 8.2.
Unless otherwise specified for a particular entity-header, the entity-headers in the PUT request SHOULD be applied to the resource created or modified by the PUT.
The DELETE method requests that the origin server delete the resource identified by the Request-URI. This method MAY be overridden by human intervention (or other means) on the origin server. The client cannot be guaranteed that the operation has been carried out, even if the status code returned from the origin server indicates that the action has been completed successfully. However, the server SHOULD NOT indicate success unless, at the time the response is given, it intends to delete the resource or move it to an inaccessible location.
A successful response SHOULD be 200 (OK) if the response includes an entity describing the status, 202 (Accepted) if the action has not yet been enacted, or 204 (No Content) if the action has been enacted but the response does not include an entity.
If the request passes through a cache and the Request-URI identifies one or more currently cached entities, those entries SHOULD be treated as stale. Responses to this method are not cacheable.
Select * from table
where CONTAINS([Column], '"A00*"')
will act as % same as
where [Column] Like 'A00%'
As SYS:
startup force;
Brutal, yet elegant.
If you want to look for all commits by filename
and not by filepath
, use:
git log --all -- '*.wmv'
It's a shortened "N-tuple
" (like in quadruple
, quintuple
etc.)
It's a row of a rowset taken as a whole.
If you issue:
SELECT col1, col2
FROM mytable
, whole result will be a ROWSET
, and each pair of col1, col2
will be a tuple
.
Some databases can work with a tuple as a whole.
Like, you can do this:
SELECT col1, col2
FROM mytable
WHERE (col1, col2) =
(
SELECT col3, col4
FROM othertable
)
, which checks that a whole tuple
from one rowset
matches a whole tuple
from another rowset
.
A simple solution is encapsulate code of button event in a function, and call it when you add TRs too:
var i = 1;
$("#addbutton").click(function() {
$("table tr:first").clone().find("input").each(function() {
$(this).val('').attr({
'id': function(_, id) {return id + i },
'name': function(_, name) { return name + i },
'value': ''
});
}).end().appendTo("table");
i++;
applyRemoveEvent();
});
function applyRemoveEvent(){
$('button.removebutton').on('click',function() {
alert("aa");
$(this).closest( 'tr').remove();
return false;
});
};
applyRemoveEvent();
Try:
//Difference in days
var diff = Math.floor(( start - end ) / 86400000);
alert(diff);
KEY
is normally a synonym for INDEX
. The key attribute PRIMARY KEY
can also be specified as just KEY
when given in a column definition. This was implemented for compatibility with other database systems.
column_definition:
data_type [NOT NULL | NULL] [DEFAULT default_value]
[AUTO_INCREMENT] [UNIQUE [KEY] | [PRIMARY] KEY]
...
Ref: http://dev.mysql.com/doc/refman/5.1/en/create-table.html
I had the same issue today.While searching here for solution,I have did silly mistake that is instead of importing
import org.springframework.transaction.annotation.Transactional;
unknowingly i have imported
import javax.transaction.Transactional;
Afer changing it everything worked fine.
So thought of sharing,If somebody does same mistake .
private Session.StatusCallback statusCallback = new SessionStatusCallback();
logout.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Session.openActiveSession(this, true, statusCallback);
}
});
private class SessionStatusCallback implements Session.StatusCallback {
@Override
public void call(Session session, SessionState state,
Exception exception) {
session.closeAndClearTokenInformation();
}
}
Now in Python >= 3.3 you can just call the timestamp() method to get the timestamp as a float.
import datetime
current_time = datetime.datetime.now(datetime.timezone.utc)
unix_timestamp = current_time.timestamp() # works if Python >= 3.3
unix_timestamp_plus_5_min = unix_timestamp + (5 * 60) # 5 min * 60 seconds
Note that the if $myVar; then ... ;fi
construct has a security problem you might want to avoid with
case $myvar in
(true) echo "is true";;
(false) echo "is false";;
(rm -rf*) echo "I just dodged a bullet";;
esac
You might also want to rethink why if [ "$myvar" = "true" ]
appears awkward to you. It's a shell string comparison that beats possibly forking a process just to obtain an exit status. A fork is a heavy and expensive operation, while a string comparison is dead cheap. Think a few CPU cycles versus several thousand. My case
solution is also handled without forks.
GNU linker, in my case companion of GCC 8.1.0, well detects not re-declared pure virtual methods, but above certain complexity of class design it fails to identify missing implementation of methods and answers with a flat "V-Table Missing",
or even tends to report missing implementation, in spite it is there.
The only solution then is to verify consistency of declaration of implementation manually, method by method.
I've not looked into this but shooting from the hip I'd say that they dropped command line support in the portable. The reason people don't do much command line stuff in portable applications is that the OS (windows in your case) requires that executables be added to the %path% inclusion list.
If that requirement is not met using command line utilities is rather tedious.
7z -a .
would be
d:\portable\z7\z7 -a c:\to\archive\folder*.*
Typing that out for everything is why GUI's make sense with things like portable apps it (the app) can remember it's own location and handle that stuff for you and if you can't run it you know it's not attached.
If you really want the portable app to contain that though you can always install the full version and pull the required 7z.exe out and put it into the portable folder making sure it's in with the required dll's.
You'll have to set your path when you hit the shell after making sure it's attached.
http://www.redfernplace.com/software-projects/patheditor/ -- a good path editor (down) usefull if you have lots of path information 20+ get's hard to read.
http://www.softpedia.com/get/System/System-Miscellaneous/Path-Editor.shtml -- alternet source for path editor
It's not advisable to modify your system path for temproary "portable" drives though manualy do that by:
set path=%path%;"d:\portable\z7\";
when you run dos cmd.exe or http://sourceforge.net/p/conemu/home/Home/
The other answers address other problems better I'm not going to try..
http://www.codejacked.com/zip-up-files-from-the-command-line/ -- good reference for command line usage of z7 and z7a.
PS: sorry for the necro but I figured it needed a more direct answer to why (even if it's just speculative).
On Debian I needed the following packages to fix this
sudo apt install libcurl4-openssl-dev libssl-dev
The top answer only works for Python 2.x
For Python 3.x, use this:
activate_this_file = "/path/to/virtualenv/bin/activate_this.py"
exec(compile(open(activate_this_file, "rb").read(), activate_this_file, 'exec'), dict(__file__=activate_this_file))
public enum Gender {
MALE,
FEMALE
}
For people just finding this post, you should know that in newer versions (not sure on the exact version since official docs are slim on this topic) the default behavior of the InvokeCommandAction, if no CommandParameter is specified, is to pass the args of the event it's attached to as the CommandParameter. So the originals poster's XAML could be simply written as:
<i:Interaction.Triggers>
<i:EventTrigger EventName="Navigated">
<i:InvokeCommandAction Command="{Binding NavigatedEvent}"/>
</i:EventTrigger>
</i:Interaction.Triggers>
Then in your command, you can accept a parameter of type NavigationEventArgs
(or whatever event args type is appropriate) and it will automatically be provided.
you can have a variable
DEBUG = 0
then you can use a conditional statement
ifeq ($(DEBUG),1)
else
endif
There are a few answers mentioning the functions dplyr::rename_with
and rlang::set_names
already. By they are separate. this answer illustrates the differences between the two and the use of functions and formulas to rename columns.
rename_with
from the dplyr
package can use either a function or a formula
to rename a selection of columns given as the .cols
argument. For example passing the function name toupper
:
library(dplyr)
rename_with(head(iris), toupper, starts_with("Petal"))
Is equivalent to passing the formula ~ toupper(.x)
:
rename_with(head(iris), ~ toupper(.x), starts_with("Petal"))
When renaming all columns, you can also use set_names
from the rlang package. To make a different example, let's use paste0
as a renaming function. pasteO
takes 2 arguments, as a result there are different ways to pass the second argument depending on whether we use a function or a formula.
rlang::set_names(head(iris), paste0, "_hi")
rlang::set_names(head(iris), ~ paste0(.x, "_hi"))
The same can be achieved with rename_with
by passing the data frame as first
argument .data
, the function as second argument .fn
, all columns as third
argument .cols=everything()
and the function parameters as the fourth
argument ...
. Alternatively you can place the second, third and fourth
arguments in a formula given as the second argument.
rename_with(head(iris), paste0, everything(), "_hi")
rename_with(head(iris), ~ paste0(.x, "_hi"))
rename_with
only works with data frames. set_names
is more generic and can
also perform vector renaming
rlang::set_names(1:4, c("a", "b", "c", "d"))
As other folks have mentioned, Java, ActiveX, Silverlight, Browser Helper Objects (BHOs) and other plugins are not supported in Microsoft Edge. Most modern browsers are moving away from plugins and toward standard HTML5 controls and technologies.
If you must continue to use the Java plugin in a corporate web app, consider adding the site to an Enterprise Mode site list. This will automatically prompt the user to open in IE.
Instead of the bulky DateTime object .. just use the core date() function
function isValidDate($date, $format= 'Y-m-d'){
return $date == date($format, strtotime($date));
}
solution is easy:
replace
mask = (50 < df['heart rate'] < 101 &
140 < df['systolic blood pressure'] < 160 &
90 < df['dyastolic blood pressure'] < 100 &
35 < df['temperature'] < 39 &
11 < df['respiratory rate'] < 19 &
95 < df['pulse oximetry'] < 100
, "excellent", "critical")
by
mask = ((50 < df['heart rate'] < 101) &
(140 < df['systolic blood pressure'] < 160) &
(90 < df['dyastolic blood pressure'] < 100) &
(35 < df['temperature'] < 39) &
(11 < df['respiratory rate'] < 19) &
(95 < df['pulse oximetry'] < 100)
, "excellent", "critical")
What I like about it is that it aligns the unit-of-work (as the user sees it - i.e. a page submit) with the unit-of-work in the ORM sense.
Therefore, you can make the entire page submission transactional, which you could not do if you were exposing CRUD methods with each creating a new context.
You can simply place a forward declaration of your second()
function in your main.cpp
above main()
. If your second.cpp
has more than one function and you want all of it in main()
, put all the forward declarations of your functions in second.cpp
into a header file and #include
it in main.cpp
.
Like this-
Second.h:
void second();
int third();
double fourth();
main.cpp:
#include <iostream>
#include "second.h"
int main()
{
//.....
return 0;
}
second.cpp:
void second()
{
//...
}
int third()
{
//...
return foo;
}
double fourth()
{
//...
return f;
}
Note that: it is not necessary to #include "second.h"
in second.cpp
. All your compiler need is forward declarations and your linker will do the job of searching the definitions of those declarations in the other files.
Using custom exception class you can return different HTTP status code and dto object.
@PostMapping("/save")
public ResponseEntity<UserDto> saveUser(@RequestBody UserDto userDto) {
if(userDto.getId() != null) {
throw new UserNotFoundException("A new user cannot already have an ID");
}
return ResponseEntity.ok(userService.saveUser(userDto));
}
Exception class
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;
@ResponseStatus(value = HttpStatus.NOT_FOUND, reason = "user not found")
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
I can't give you graphics, but maybe I can give a clear explanation.
Suppose we have an information channel, such as a light that flashes once every day either red or green. How much information does it convey? The first guess might be one bit per day. But what if we add blue, so that the sender has three options? We would like to have a measure of information that can handle things other than powers of two, but still be additive (the way that multiplying the number of possible messages by two adds one bit). We could do this by taking log2(number of possible messages), but it turns out there's a more general way.
Suppose we're back to red/green, but the red bulb has burned out (this is common knowledge) so that the lamp must always flash green. The channel is now useless, we know what the next flash will be so the flashes convey no information, no news. Now we repair the bulb but impose a rule that the red bulb may not flash twice in a row. When the lamp flashes red, we know what the next flash will be. If you try to send a bit stream by this channel, you'll find that you must encode it with more flashes than you have bits (50% more, in fact). And if you want to describe a sequence of flashes, you can do so with fewer bits. The same applies if each flash is independent (context-free), but green flashes are more common than red: the more skewed the probability the fewer bits you need to describe the sequence, and the less information it contains, all the way to the all-green, bulb-burnt-out limit.
It turns out there's a way to measure the amount of information in a signal, based on the the probabilities of the different symbols. If the probability of receiving symbol xi is pi, then consider the quantity
-log pi
The smaller pi, the larger this value. If xi becomes twice as unlikely, this value increases by a fixed amount (log(2)). This should remind you of adding one bit to a message.
If we don't know what the symbol will be (but we know the probabilities) then we can calculate the average of this value, how much we will get, by summing over the different possibilities:
I = -Σ pi log(pi)
This is the information content in one flash.
Red bulb burnt out: pred = 0, pgreen=1, I = -(0 + 0) = 0 Red and green equiprobable: pred = 1/2, pgreen = 1/2, I = -(2 * 1/2 * log(1/2)) = log(2) Three colors, equiprobable: pi=1/3, I = -(3 * 1/3 * log(1/3)) = log(3) Green and red, green twice as likely: pred=1/3, pgreen=2/3, I = -(1/3 log(1/3) + 2/3 log(2/3)) = log(3) - 2/3 log(2)
This is the information content, or entropy, of the message. It is maximal when the different symbols are equiprobable. If you're a physicist you use the natural log, if you're a computer scientist you use log2 and get bits.
Example: Read json from file
/* test.json */
{
"appDesc": {
"description": "SomeDescription",
"message": "SomeMessage"
},
"appName": {
"description": "Home",
"message": "Welcome",
"imp":["awesome","best","good"]
}
}
void readJson()
{
QString val;
QFile file;
file.setFileName("test.json");
file.open(QIODevice::ReadOnly | QIODevice::Text);
val = file.readAll();
file.close();
qWarning() << val;
QJsonDocument d = QJsonDocument::fromJson(val.toUtf8());
QJsonObject sett2 = d.object();
QJsonValue value = sett2.value(QString("appName"));
qWarning() << value;
QJsonObject item = value.toObject();
qWarning() << tr("QJsonObject of description: ") << item;
/* in case of string value get value and convert into string*/
qWarning() << tr("QJsonObject[appName] of description: ") << item["description"];
QJsonValue subobj = item["description"];
qWarning() << subobj.toString();
/* in case of array get array and convert into string*/
qWarning() << tr("QJsonObject[appName] of value: ") << item["imp"];
QJsonArray test = item["imp"].toArray();
qWarning() << test[1].toString();
}
OUTPUT
QJsonValue(object, QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) )
"QJsonObject of description: " QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"})
"QJsonObject[appName] of description: " QJsonValue(string, "Home")
"Home"
"QJsonObject[appName] of value: " QJsonValue(array, QJsonArray(["awesome","best","good"]) )
"best"
Example: Read json from string
Assign json to string as below and use the readJson()
function shown before:
val =
' {
"appDesc": {
"description": "SomeDescription",
"message": "SomeMessage"
},
"appName": {
"description": "Home",
"message": "Welcome",
"imp":["awesome","best","good"]
}
}';
OUTPUT
QJsonValue(object, QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"}) )
"QJsonObject of description: " QJsonObject({"description": "Home","imp": ["awesome","best","good"],"message": "YouTube"})
"QJsonObject[appName] of description: " QJsonValue(string, "Home")
"Home"
"QJsonObject[appName] of value: " QJsonValue(array, QJsonArray(["awesome","best","good"]) )
"best"
You can also like this:
$ nvm alias default lts/fermium
If you are using phpmyadmin to add new routine then don't forget to wrap your code between BEGIN and END
There is a tool usually used in MS Servers (as far as I can remember) called forfiles:
The link above contains help as well as a link to the microsoft download page.
I also had the same problem. I used next way:
1.Added settings.xml file (~/.m2/settings.xml) with next content
<proxies>
<proxy>
<active>true</active>
<protocol>http</protocol>
<host>qq-proxya</host>
<port>8080</port>
<username>user</username>
<password>passw</password>
<nonProxyHosts>www.google.com|*.example.com</nonProxyHosts>
</proxy>
</proxies>
3. Using cmd go to folder with my project and wrote mvn clean and after that mvn install !
P.S. after that, when I add new dependency to my project I have to compile project using cmd(mvn compile). Because if I do it using eclipse plugin, I get error connecting with proxy connection.
For TRUE
localStorage.infiniteScrollEnabled = 1;
FOR FALSE
localStorage.removeItem("infiniteScrollEnabled")
CHECK EXISTANCE
if (localStorage[""infiniteScrollEnabled""]) {
//CODE IF ENABLED
}
jQuery:
$(function(){
// your code...this will run when DOM is ready
});
If you want to run your code after all page resources including images/frames/DOM have loaded, you need to use load
event:
$(window).load(function(){
// your code...
});
JavaScript:
window.onload = function(){
// your code...
};
To accomplish what you're describing will take two steps...
Step 1: To add the file to the source tarball, include it in the MANIFEST
Create a MANIFEST template in the folder that contains setup.py
The MANIFEST is basically a text file with a list of all the files that will be included in the source tarball.
Here's what the MANIFEST for my project look like:
Note: While sdist does add some files automatically, I prefer to explicitly specify them to be sure instead of predicting what it does and doesn't.
Step 2: To install the data file to the source folder, modify setup.py
Since you're looking to add a data file (LICENSE.txt) to the source install folder you need to modify the data install path to match the source install path. This is necessary because, by default, data files are installed to a different location than source files.
To modify the data install dir to match the source install dir...
Pull the install dir info from distutils with:
from distutils.command.install import INSTALL_SCHEMES
Modify the data install dir to match the source install dir:
for scheme in INSTALL_SCHEMES.values():
scheme['data'] = scheme['purelib']
And, add the data file and location to setup():
data_files=[('', ['LICENSE.txt'])]
Note: The steps above should accomplish exactly what you described in a standard manner without requiring any extension libraries.
I had this problem today using any of concat, append or merge, and I got around it by adding a helper column sequentially numbered and then doing an outer join
helper=1
for i in df1.index:
df1.loc[i,'helper']=helper
helper=helper+1
for i in df2.index:
df2.loc[i,'helper']=helper
helper=helper+1
df1.merge(df2,on='helper',how='outer')
From the DOCS
Formats a number as text. Group sizing and separator and other locale-specific configurations are based on the active locale.
SYNTAX:
number_expression | number[:digitInfo[:locale]]
where expression
is a number:
digitInfo
is a string which has a following format:
{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
This article can provide a lot of insight here: http://redis.io/topics/memory-optimization
There are many ways to store an array of Objects in Redis (spoiler: I like option 1 for most use cases):
Store the entire object as JSON-encoded string in a single key and keep track of all Objects using a set (or list, if more appropriate). For example:
INCR id:users
SET user:{id} '{"name":"Fred","age":25}'
SADD users {id}
Generally speaking, this is probably the best method in most cases. If there are a lot of fields in the Object, your Objects are not nested with other Objects, and you tend to only access a small subset of fields at a time, it might be better to go with option 2.
Advantages: considered a "good practice." Each Object is a full-blown Redis key. JSON parsing is fast, especially when you need to access many fields for this Object at once. Disadvantages: slower when you only need to access a single field.
Store each Object's properties in a Redis hash.
INCR id:users
HMSET user:{id} name "Fred" age 25
SADD users {id}
Advantages: considered a "good practice." Each Object is a full-blown Redis key. No need to parse JSON strings. Disadvantages: possibly slower when you need to access all/most of the fields in an Object. Also, nested Objects (Objects within Objects) cannot be easily stored.
Store each Object as a JSON string in a Redis hash.
INCR id:users
HMSET users {id} '{"name":"Fred","age":25}'
This allows you to consolidate a bit and only use two keys instead of lots of keys. The obvious disadvantage is that you can't set the TTL (and other stuff) on each user Object, since it is merely a field in the Redis hash and not a full-blown Redis key.
Advantages: JSON parsing is fast, especially when you need to access many fields for this Object at once. Less "polluting" of the main key namespace. Disadvantages: About same memory usage as #1 when you have a lot of Objects. Slower than #2 when you only need to access a single field. Probably not considered a "good practice."
Store each property of each Object in a dedicated key.
INCR id:users
SET user:{id}:name "Fred"
SET user:{id}:age 25
SADD users {id}
According to the article above, this option is almost never preferred (unless the property of the Object needs to have specific TTL or something).
Advantages: Object properties are full-blown Redis keys, which might not be overkill for your app. Disadvantages: slow, uses more memory, and not considered "best practice." Lots of polluting of the main key namespace.
Option 4 is generally not preferred. Options 1 and 2 are very similar, and they are both pretty common. I prefer option 1 (generally speaking) because it allows you to store more complicated Objects (with multiple layers of nesting, etc.) Option 3 is used when you really care about not polluting the main key namespace (i.e. you don't want there to be a lot of keys in your database and you don't care about things like TTL, key sharding, or whatever).
If I got something wrong here, please consider leaving a comment and allowing me to revise the answer before downvoting. Thanks! :)
Please check the permissions on the the ca certificates installed on server.
I am old to the party but may be this will help some one. Thanks to @paperclip
In Windows 10:
Step 1: Go to This PC
> Right click Properties
step 2: Click Advanced System Settings
and click Environment Variables
Step 3: Under System Variables
create new variable called HOME
and input the value as %USERPROFILE%
like below
Step 4: Important You must restart your PC to take effect
Step 5: Install Git for Windows
now and optional Tortoise Git for windows
if you prefer.
Make a git clone request or try pushing something in to your repo. Magic it will work. All should work fine now.
From manual: s[i:j:k] slice of s from i to j with step k
li = range(100)
sub = li[0::10]
>>> sub
[0, 10, 20, 30, 40, 50, 60, 70, 80, 90]
There's a bunch of functions to trim strings in go.
See them there : Trim
Here's an example, adapted from the documentation, removing leading and trailing white spaces :
fmt.Printf("[%q]", strings.Trim(" Achtung ", " "))
AHHH!!! This looks so wrong it hurts my head. Try something more like this...
<?php
include('db.php');
$result = mysql_query('SELECT `id`, `name`, `description`, `icon` FROM `staff` ORDER BY `id` DESC LIMIT 20') or die(mysql_error());
$rows = array();
while($row = mysql_fetch_assoc($result)){
$rows[] = $row;
}
echo json_encode($rows);
?>
mysql_num_rows
you should use <
not <=
. You should also cache this value (save it to a variable) instead of having it re-count every loop. Who knows what it's doing under the hood... (might be efficient, I'm not really sure)mysql_fetch_array
returns the values both by key
and by int
. You not using the indices, so don't fetch em.If this really is a problem with json_encode
, then might I suggest replacing the body of the loop with something like
$rows[] = array_map('htmlentities',$row);
Perhpas there are some special chars in there that are mucking things up...
As pprakash mentions above, copying the table.frm files AND the ibdata1 file was what worked for me.
In short:
After that, all was well. (Don't forget to backup if you have success!)
var lastDayOfMonth = DateTime.DaysInMonth(date.Year, date.Month);
We can create a simple directive and disable the button until all the mandatory fields are filled.
angular.module('sampleapp').directive('disableBtn',
function() {
return {
restrict : 'A',
link : function(scope, element, attrs) {
var $el = $(element);
var submitBtn = $el.find('button[type="submit"]');
var _name = attrs.name;
scope.$watch(_name + '.$valid', function(val) {
if (val) {
submitBtn.removeAttr('disabled');
} else {
submitBtn.attr('disabled', 'disabled');
}
});
}
};
}
);
Unable to process Jar entry [module-info.class] from Jar [jar:file:/xxxxxxxx/lombok-1.18.4.jar!/] for annotations
org.apache.tomcat.util.bcel.classfile.ClassFormatException: Invalid byte tag in constant pool: 19
1.update and append below argument in <root or instance tomcat folder>/conf/catalina.properties
org.apache.catalina.startup.ContextConfig.jarsToSkip=...,lombok-1.18.4.jar
2.clean and deploy the to-be-pulish project.
A nice code for the push_back and emplace_back is shown here.
http://en.cppreference.com/w/cpp/container/vector/emplace_back
You can see the move operation on push_back and not on emplace_back.
Since both projects are under the same solution, there's a simpler way for the include files and linker as described in https://docs.microsoft.com/en-us/cpp/build/adding-references-in-visual-cpp-projects?view=vs-2019 :
#include "../libProject/libHeader.h"
).The easiest way now is to add it as a module
This will create a new module containing the aar file, so you just need to include that module as a dependency afterwards
No, absolutely positioning does not conflict with flex containers. Making an element be a flex container only affects its inner layout model, that is, the way in which its contents are laid out. Positioning affects the element itself, and can alter its outer role for flow layout.
That means that
If you add absolute positioning to an element with display: inline-flex
, it will become block-level (like display: flex
), but will still generate a flex formatting context.
If you add absolute positioning to an element with display: flex
, it will be sized using the shrink-to-fit algorithm (typical of inline-level containers) instead of the fill-available one.
That said, absolutely positioning conflicts with flex children.
As it is out-of-flow, an absolutely-positioned child of a flex container does not participate in flex layout.
If you want to authenticate against a user name and password and without an authorization cookie, the MVC4 Authorize attribute won't work out of the box. However, you can add the following helper method to your controller to accept basic authentication headers. Call it from the beginning of your controller's methods.
void EnsureAuthenticated(string role)
{
string[] parts = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(Request.Headers.Authorization.Parameter)).Split(':');
if (parts.Length != 2 || !Membership.ValidateUser(parts[0], parts[1]))
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "No account with that username and password"));
if (role != null && !Roles.IsUserInRole(parts[0], role))
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "An administrator account is required"));
}
From the client side, this helper creates a HttpClient
with the authentication header in place:
static HttpClient CreateBasicAuthenticationHttpClient(string userName, string password)
{
var client = new HttpClient();
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(userName + ':' + password)));
return client;
}
Dynamic Array Example:
Console.WriteLine("Define Array Size? ");
int number = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Enter numbers:\n");
int[] arr = new int[number];
for (int i = 0; i < number; i++)
{
arr[i] = Convert.ToInt32(Console.ReadLine());
}
for (int i = 0; i < arr.Length; i++ )
{
Console.WriteLine("Array Index: "+i + " AND Array Item: " + arr[i].ToString());
}
Console.ReadKey();
In case you do not want to use Asset Catalog, you can add an iOS 7 icon for an old app by creating a 120x120 .png image. Name it Icon-120.png
and drag in to the project.
Under TARGET > Your App > Info > Icon files, add one more entry in the Target Properties:
I tested on Xcode 5 and an app was submitted without the missing retina icon warning.
Note that if variable is list of lists, some approaches would fail. For example:
v1 = [[range(3)] for x in range(4)]
v2 = v1[:3]+v1[4:] # this fails
v2
For the general case, use
removed_index = 1
v1 = [[range(3)] for x in range(4)]
v2 = [x for i,x in enumerate(v1) if x!=removed_index]
v2
Hendry's answer is 100% correct. I had the same problem with my application, where there is repository project dealing with database with use of methods encapsulating EF db context operation. Other projects use this repository, and I don't want to reference EF in those projects. Somehow I don't feel it's proper, I need EF only in repository project. Anyway, copying EntityFramework.SqlServer.dll to other project output directory solves the problem. To avoid problems, when you forget to copy this dll, you can change repository build directory. Go to repository project's properties, select Build tab, and in output section you can set output directory to other project's build directory. Sure, it's just workaround. Maybe the hack, mentioned in some placec, is better:
var instance = System.Data.Entity.SqlServer.SqlProviderServices.Instance;
Still, for development purposes it is enough. Later, when preparing install or publish, you can add this file to package.
I'm quite new to EF. Is there any better method to solve this issue? I don't like "hack" - it makes me feel that there is something that is "not secure".
@bku_drytt's solution didn't do it for me.
I solved it by additionally changing every occurence of 14.0
to 12.0
and v140
to v120
manually in the .vcxproj files.
Then it compiled!
You can also check out dateparser
dateparser
provides modules to easily parse localized dates in almost any string formats commonly found on web pages.
Install:
$ pip install dateparser
This is, I think, the easiest way you can parse dates.
The most straightforward way is to use the
dateparser.parse
function, that wraps around most of the functionality in the module.
Sample Code:
import dateparser
t1 = 'Jun 1 2005 1:33PM'
t2 = 'Aug 28 1999 12:00AM'
dt1 = dateparser.parse(t1)
dt2 = dateparser.parse(t2)
print(dt1)
print(dt2)
Output:
2005-06-01 13:33:00
1999-08-28 00:00:00
A CDATA section is required if you need your document to parse as XML (e.g. when an XHTML page is interpreted as XML) and you want to be able to write literal i<10
and a && b
instead of i<10
and a && b
, as XHTML will parse the JavaScript code as parsed character data as opposed to character data by default. This is not an issue with scripts that are stored in external source files, but for any inline JavaScript in XHTML you will probably want to use a CDATA section.
Note that many XHTML pages were never intended to be parsed as XML in which case this will not be an issue.
For a good writeup on the subject, see https://web.archive.org/web/20140304083226/http://javascript.about.com/library/blxhtml.htm
Disabling pyright worked perfectly for me on VS.
You can either use:
[x / 10.0 for x in range(5, 50, 15)]
or use lambda / map:
map(lambda x: x/10.0, range(5, 50, 15))
One of the major changes it seems is that with Android Studio the test application is integrated into the application project.
I'm not sure if this helps your specific problem, but I found a guide on making tests with a Gradle project. Android Gradle user Guide
You need to encode Unicode explicitly before writing to a file, otherwise Python does it for you with the default ASCII codec.
Pick an encoding and stick with it:
f.write(printinfo.encode('utf8') + '\n')
or use io.open()
to create a file object that'll encode for you as you write to the file:
import io
f = io.open(filename, 'w', encoding='utf8')
You may want to read:
Pragmatic Unicode by Ned Batchelder
The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) by Joel Spolsky
before continuing.
To filter a list of dicts you can use the selectattr filter together with the equalto test:
network.addresses.private_man | selectattr("type", "equalto", "fixed")
The above requires Jinja2 v2.8 or later (regardless of Ansible version).
Ansible also has the tests match
and search
, which take regular expressions:
match
will require a complete match in the string, whilesearch
will require a match inside of the string.
network.addresses.private_man | selectattr("type", "match", "^fixed$")
To reduce the list of dicts to a list of strings, so you only get a list of the addr
fields, you can use the map filter:
... | map(attribute='addr') | list
Or if you want a comma separated string:
... | map(attribute='addr') | join(',')
Combined, it would look like this.
- debug: msg={{ network.addresses.private_man | selectattr("type", "equalto", "fixed") | map(attribute='addr') | join(',') }}
Since None of the above solutions worked for my usecase, here I provide a solution using None
(pun!) which can be adapted to a wide variety of scenarios.
Here is a sample piece of code that produces cluttered ticks on both X
and Y
axes.
# Note the super cluttered ticks on both X and Y axis.
# inputs
x = np.arange(1, 101)
y = x * np.log(x)
fig = plt.figure() # create figure
ax = fig.add_subplot(111)
ax.plot(x, y)
ax.set_xticks(x) # set xtick values
ax.set_yticks(y) # set ytick values
plt.show()
Now, we clean up the clutter with a new plot that shows only a sparse set of values on both x and y axes as ticks.
# inputs
x = np.arange(1, 101)
y = x * np.log(x)
fig = plt.figure() # create figure
ax = fig.add_subplot(111)
ax.plot(x, y)
ax.set_xticks(x)
ax.set_yticks(y)
# which values need to be shown?
# here, we show every third value from `x` and `y`
show_every = 3
sparse_xticks = [None] * x.shape[0]
sparse_xticks[::show_every] = x[::show_every]
sparse_yticks = [None] * y.shape[0]
sparse_yticks[::show_every] = y[::show_every]
ax.set_xticklabels(sparse_xticks, fontsize=6) # set sparse xtick values
ax.set_yticklabels(sparse_yticks, fontsize=6) # set sparse ytick values
plt.show()
Depending on the usecase, one can adapt the above code simply by changing show_every
and using that for sampling tick values for X or Y or both the axes.
If this stepsize based solution doesn't fit, then one can also populate the values of sparse_xticks
or sparse_yticks
at irregular intervals, if that is what is desired.
If you want to make it shorter, you could write :
import matplolib.pyplot as plt
for i in range(4):
plt.subplot(2,2,i+1).set_title('Subplot n°{}' .format(i+1))
plt.show()
It makes it maybe less clear but you don't need more lines or variables
Everything in Java is passed by value. In case of an array (which is nothing but an Object), the array reference is passed by value (just like an object reference is passed by value).
When you pass an array to other method, actually the reference to that array is copied.
See this post: Is Java "pass-by-reference" or "pass-by-value"?
See this working example:
public static void changeContent(int[] arr) {
// If we change the content of arr.
arr[0] = 10; // Will change the content of array in main()
}
public static void changeRef(int[] arr) {
// If we change the reference
arr = new int[2]; // Will not change the array in main()
arr[0] = 15;
}
public static void main(String[] args) {
int [] arr = new int[2];
arr[0] = 4;
arr[1] = 5;
changeContent(arr);
System.out.println(arr[0]); // Will print 10..
changeRef(arr);
System.out.println(arr[0]); // Will still print 10..
// Change the reference doesn't reflect change here..
}
Here's an example:
package foo;
public class Test
{
public static void main(String[] args)
{
ClassLoader loader = Test.class.getClassLoader();
System.out.println(loader.getResource("foo/Test.class"));
}
}
This printed out:
file:/C:/Users/Jon/Test/foo/Test.class
I know this has been answered, but here's mine just because I think case is an under-appreciated tool. (Maybe because people think it is slow, but it's at least as fast as an if, sometimes faster.)
case "$1" in
0|1) xinput set-prop 12 "Device Enabled" $1 ;;
*) echo "This script requires a 1 or 0 as first parameter." ;;
esac
It could be some other line as well. PHP is not always that exact.
Probably you are just missing a semicolon on previous line.
How to reproduce this error, put this in a file called a.php
:
<?php
$a = 5
$b = 7; // Error happens here.
print $b;
?>
Run it:
eric@dev ~ $ php a.php
PHP Parse error: syntax error, unexpected T_VARIABLE in
/home/el/code/a.php on line 3
Explanation:
The PHP parser converts your program to a series of tokens. A T_VARIABLE
is a Token of type VARIABLE. When the parser processes tokens, it tries to make sense of them, and throws errors if it receives a variable where none is allowed.
In the simple case above with variable $b
, the parser tried to process this:
$a = 5 $b = 7;
The PHP parser looks at the $b after the 5 and says "that is unexpected".
You could use event delegation on the parent div. Or use the closest method to find the parent of the button.
The easiest of the two is probably the closest.
var id = $("button").closest("div").prop("id");
new File(fileName).getName();
or
int idx = fileName.replaceAll("\\\\", "/").lastIndexOf("/");
return idx >= 0 ? fileName.substring(idx + 1) : fileName;
Notice that the first solution is system dependent. It only takes the system's path separator character into account. So if your code runs on a Unix system and receives a Windows path, it won't work. This is the case when processing file uploads being sent by Internet Explorer.
You'll find a great tutorial here: bootstrap-3-grid-introduction and answer for your question is <div class="container-fluid"> ... </div>
import java.io.*;
class Initials {
public static void main(String args[]) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s;
char x;
int l;
System.out.print("Enter any sentence: ");
s = br.readLine();
s = " " + s; //adding a space infront of the inputted sentence or a name
s = s.toUpperCase(); //converting the sentence into Upper Case (Capital Letters)
l = s.length(); //finding the length of the sentence
System.out.print("Output = ");
for (int i = 0; i < l; i++) {
x = s.charAt(i); //taking out one character at a time from the sentence
if (x == ' ') //if the character is a space, printing the next Character along with a fullstop
System.out.print(s.charAt(i + 1) + ".");
}
}
}
Simply in windows
ctrl + @ (the button 2 in the upper horizontal row of numbers in keyboard)
neater:
function BlockID() {
return {
"s":"Images/Block_01.png",
"g":"Images/Block_02.png",
"C":"Images/Block_03.png",
"d":"Images/Block_04.png"
}
}
or just
var images = {
"s":"Images/Block_01.png",
"g":"Images/Block_02.png",
"C":"Images/Block_03.png",
"d":"Images/Block_04.png"
}
You're looking for Select
which can be used to transform\project the input sequence:
IEnumerable<string> strings = integers.Select(i => i.ToString());
Example:
select Table_name as [Table] , column_name as [Column] , Table_catalog as [Database], table_schema as [Schema] from information_schema.columns
where table_schema = 'dbo'
order by Table_name,COLUMN_NAME
Just my code
I'm not sure what problem you are solving, but when I have two side by side containers that need to be the same height, I run a little javascript on page load that finds the maximum height of the two and explicitly sets the other to the same height. It seems to me that height: 100% might just mean "make it the size needed to fully contain the content" when what you really want is "make both the size of the largest content."
Note: you'll need to resize them again if anything happens on the page to change their height -- like a validation summary being made visible or a collapsible menu opening.
You can just CAST your CLOB value into a VARCHAR value and make your querie like a
With parent::$bb;
you try to retrieve the static constant defined with the value of $bb
.
Instead, do:
echo $this->bb;
Note: you don't need to call parent::_construct
if B is the only class that calls it. Simply don't declare __construct in B class.
This code will work on all android versions:
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
//Automatic popping up keyboard on start Activity
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
or
//avoid automatically appear android keyboard when activity start
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
The service :
import 'rxjs/add/operator/map';
import { Http } from '@angular/http';
import { Observable } from "rxjs/Rx"
import { Injectable } from '@angular/core';
@Injectable()
export class ItemService {
private api = "your_api_url";
constructor(private http: Http) {
}
toSaveItem(item) {
return new Promise((resolve, reject) => {
this.http
.post(this.api + '/items', { item: item })
.map(res => res.json())
// This catch is very powerfull, it can catch all errors
.catch((err: Response) => {
// The err.statusText is empty if server down (err.type === 3)
console.log((err.statusText || "Can't join the server."));
// Really usefull. The app can't catch this in "(err)" closure
reject((err.statusText || "Can't join the server."));
// This return is required to compile but unuseable in your app
return Observable.throw(err);
})
// The (err) => {} param on subscribe can't catch server down error so I keep only the catch
.subscribe(data => { resolve(data) })
})
}
}
In the app :
this.itemService.toSaveItem(item).then(
(res) => { console.log('success', res) },
(err) => { console.log('error', err) }
)
I too have tried invalidate(), invalidateViews(), notifyDataSetChanged(). They all might work in some particular contexts but it did not do the job in my case.
In my case, I had to add some new rows to the list and it just does not work. Creating a new adapter solved the issue.
While debugging, I realized that the data was there but just not rendered. If invalidate() or invalidateViews() does not render (which it is supposed to), I don't know what would.
Creating a new Adapter object to refresh modified data does not seem to be a bad idea. It definitely works. The only downside could be the time consumed in allocating new memory for your adapter but that should be OK assuming the Android system is smart enough and takes care of that to keep it efficient.
If you take this out of the equation, the flow is almost same as to calling notifyDataSetChanged. In the sense, the same set of adapter functions are called in either case.
So we are not losing much but gaining a lot.
It don't create normally; you need to add it by yourself.
After adding Global.asax
by
You need to add a class
Inherit the newly generated by System.Web.HttpApplication
and copy all the method created Global.asax
to Global.cs
and also add an inherit attribute to the Global.asax file.
Your Global.asax will look like this: -
<%@ Application Language="C#" Inherits="Global" %>
Your Global.cs in App_Code
will look like this: -
public class Global : System.Web.HttpApplication
{
public Global()
{
//
// TODO: Add constructor logic here
//
}
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
}
/// Many other events like begin request...e.t.c, e.t.c
}
If all you're trying to do is select the first blank cell in a given column, you can give this a try:
Range("A1").End(xlDown).Offset(1, 0).Select
If you're using it relative to a column you've selected this works:
Selection.End(xlDown).Offset(1, 0).Select