If you're going to access your local computer (or any computer) using UNC, you'll need to setup a share. If you haven't already setup a share, you could use the default administrative shares. Example:
\\localhost\c$\my_dir
... accesses a folder called "my_dir" via UNC on your C: drive. By default all the hard drives on your machine are shared with hidden shares like c$, d$, etc.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
getWindow().setStatusBarColor(getResources().getColor(R.color.actionbar));
}
Put this code in your Activity's onCreate
method. This helped me.
In Spring Data you simply define an update query if you have the ID
@Repository
public interface CustomerRepository extends JpaRepository<Customer , Long> {
@Query("update Customer c set c.name = :name WHERE c.id = :customerId")
void setCustomerName(@Param("customerId") Long id, @Param("name") String name);
}
Some solutions claim to use Spring data and do JPA oldschool (even in a manner with lost updates) instead.
In the accepted answer you get annoying spacing between the visible rows when the expandable row is hidden. You can get rid of that by adding this to css:
.collapse-row.collapsed + tr {
display: none;
}
'+' is adjacent sibling selector, so if you want your expandable row to be the next row, this selects the next tr following tr named collapse-row.
Here is updated fiddle: http://jsfiddle.net/Nb7wy/2372/
Using Fourier transformation and the convolution theorem
The time complexicity is N*log(N)
def autocorr1(x):
r2=np.fft.ifft(np.abs(np.fft.fft(x))**2).real
return r2[:len(x)//2]
Here is a normalized and unbiased version, it is also N*log(N)
def autocorr2(x):
r2=np.fft.ifft(np.abs(np.fft.fft(x))**2).real
c=(r2/x.shape-np.mean(x)**2)/np.std(x)**2
return c[:len(x)//2]
The method provided by A. Levy works, but I tested it in my PC, its time complexicity seems to be N*N
def autocorr(x):
result = numpy.correlate(x, x, mode='full')
return result[result.size/2:]
If you want exactly 40 spaces before the string then you should just do:
printf(" %s\n", myStr );
If that is too dirty, you can do (but it will be slower than manually typing the 40 spaces):
printf("%40s%s", "", myStr );
If you want the string to be lined up at column 40 (that is, have up to 39 spaces proceeding it such that the right most character is in column 40) then do this:
printf("%40s", myStr);
You can also put "up to" 40 spaces AfTER the string by doing:
printf("%-40s", myStr);
simply you can use "novalidate" for < form > tag
With default Github repository import it is possible, but just make sure the two factor authentication is not enabled in Gitlab.
Thanks
This repo on github seems to do the job quite well:
https://github.com/blackspikeltd/Xaml-Spinners-WPF
The spinners are all light weight and can easily be placed wherever needed. There is a sample project included in the repo that shows how to use them.
No nasty code-behinds with a bunch of logic either. If MVVM support is needed, one can just take these and throw them in a Grid with a Visibility binding.
Simply put inside your script :
source FILE
Or
. FILE # POSIX compliant
$ LANG=C help source
source: source filename [arguments]
Execute commands from a file in the current shell.
Read and execute commands from FILENAME in the current shell. The
entries in $PATH are used to find the directory containing FILENAME.
If any ARGUMENTS are supplied, they become the positional parameters
when FILENAME is executed.
Exit Status:
Returns the status of the last command executed in FILENAME; fails if
FILENAME cannot be read.
You can try with Angular-Tree-DnD sample with Angular-Ui-Tree, but i edited, compatibility with table, grid, list.
As of TypeScript 1.6, properties in object literals that do not have a corresponding property in the type they're being assigned to are flagged as errors.
Usually this error means you have a bug (typically a typo) in your code, or in the definition file. The right fix in this case would be to fix the typo. In the question, the property callbackOnLoactionHash
is incorrect and should have been callbackOnLocationHash
(note the mis-spelling of "Location").
This change also required some updates in definition files, so you should get the latest version of the .d.ts for any libraries you're using.
Example:
interface TextOptions {
alignment?: string;
color?: string;
padding?: number;
}
function drawText(opts: TextOptions) { ... }
drawText({ align: 'center' }); // Error, no property 'align' in 'TextOptions'
There are a few cases where you may have intended to have extra properties in your object. Depending on what you're doing, there are several appropriate fixes
Sometimes you want to make sure a few things are present and of the correct type, but intend to have extra properties for whatever reason. Type assertions (<T>v
or v as T
) do not check for extra properties, so you can use them in place of a type annotation:
interface Options {
x?: string;
y?: number;
}
// Error, no property 'z' in 'Options'
let q1: Options = { x: 'foo', y: 32, z: 100 };
// OK
let q2 = { x: 'foo', y: 32, z: 100 } as Options;
// Still an error (good):
let q3 = { x: 100, y: 32, z: 100 } as Options;
Some APIs take an object and dynamically iterate over its keys, but have 'special' keys that need to be of a certain type. Adding a string indexer to the type will disable extra property checking
Before
interface Model {
name: string;
}
function createModel(x: Model) { ... }
// Error
createModel({name: 'hello', length: 100});
After
interface Model {
name: string;
[others: string]: any;
}
function createModel(x: Model) { ... }
// OK
createModel({name: 'hello', length: 100});
interface Animal { move; }
interface Dog extends Animal { woof; }
interface Cat extends Animal { meow; }
interface Horse extends Animal { neigh; }
let x: Animal;
if(...) {
x = { move: 'doggy paddle', woof: 'bark' };
} else if(...) {
x = { move: 'catwalk', meow: 'mrar' };
} else {
x = { move: 'gallop', neigh: 'wilbur' };
}
Two good solutions come to mind here
Specify a closed set for x
// Removes all errors
let x: Dog|Cat|Horse;
or Type assert each thing
// For each initialization
x = { move: 'doggy paddle', woof: 'bark' } as Dog;
A clean solution to the "data model" problem using intersection types:
interface DataModelOptions {
name?: string;
id?: number;
}
interface UserProperties {
[key: string]: any;
}
function createDataModel(model: DataModelOptions & UserProperties) {
/* ... */
}
// findDataModel can only look up by name or id
function findDataModel(model: DataModelOptions) {
/* ... */
}
// OK
createDataModel({name: 'my model', favoriteAnimal: 'cat' });
// Error, 'ID' is not correct (should be 'id')
findDataModel({ ID: 32 });
See also https://github.com/Microsoft/TypeScript/issues/3755
Since Guava 15.0 (released September 2013) there's EvictingQueue:
A non-blocking queue which automatically evicts elements from the head of the queue when attempting to add new elements onto the queue and it is full. An evicting queue must be configured with a maximum size. Each time an element is added to a full queue, the queue automatically removes its head element. This is different from conventional bounded queues, which either block or reject new elements when full.
This class is not thread-safe, and does not accept null elements.
Example use:
EvictingQueue<String> queue = EvictingQueue.create(2);
queue.add("a");
queue.add("b");
queue.add("c");
queue.add("d");
System.out.print(queue); //outputs [c, d]
Here is a very simple way (3 lines of code) using the Fullscreen API and RequestFullscreen method that I used, which is compatible across all popular browsers:
var elem = document.getElementsByTagName('video')[0];_x000D_
var fullscreen = elem.webkitRequestFullscreen || elem.mozRequestFullScreen || elem.msRequestFullscreen;_x000D_
fullscreen.call(elem); // bind the 'this' from the video object and instantiate the correct fullscreen method.
_x000D_
sizeof
tells you the size of a thing, not the number of elements in it. A more C++11 way to do what you are doing would be:
#include <array>
#include <string>
#include <iostream>
int main()
{
std::array<std::string, 3> texts { "Apple", "Banana", "Orange" };
for (auto& text : texts) {
std::cout << text << '\n';
}
return 0;
}
ideone demo: http://ideone.com/6xmSrn
I used the construction of $.each (data [i], function (key, value)
But you must pre-match the names of the selection fields with the names of the form elements. Then, in the loop after "success", autocomplete elements from the "data" array. Did this: autocomplete form with ajax success
I had the same problem and my first <p>
element which was at the top of the page and also had a browser webkit default margin. This was pushing my entire div down which had the same effect you were talking about so watch out for any text-based elements that are at the very top of the page.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Website</title>
</head>
<body style="margin:0;">
<div id="image" style="background: url(pixabay-cleaning-kids-720.jpg)
no-repeat; width: 100%; background-size: 100%;height:100vh">
<p>Text in Paragraph</p>
</div>
</div>
</body>
</html>
So just remember to check all child elements not only the html and body tags.
There are several way to approach globals:
Webpack evaluates modules only once, so your instance remains global and carries changes through from module to module. So if you create something like a globals.js
and export an object of all your globals then you can import './globals'
and read/write to these globals. You can import into one module, make changes to the object from a function and import into another module and read those changes in a function. Also remember the order things happen. Webpack will first take all the imports and load them up in order starting in your entry.js
. Then it will execute entry.js
. So where you read/write to globals is important. Is it from the root scope of a module or in a function called later?
config.js
export default {
FOO: 'bar'
}
somefile.js
import CONFIG from './config.js'
console.log(`FOO: ${CONFIG.FOO}`)
Note: If you want the instance to be new
each time, then use an ES6 class. Traditionally in JS you would capitalize classes (as opposed to the lowercase for objects) like
import FooBar from './foo-bar' // <-- Usage: myFooBar = new FooBar()
Here's how you can do it using Webpack's ProvidePlugin (which makes a module available as a variable in every module and only those modules where you actually use it). This is useful when you don't want to keep typing import Bar from 'foo'
again and again. Or you can bring in a package like jQuery or lodash as global here (although you might take a look at Webpack's Externals).
Step 1) Create any module. For example, a global set of utilities would be handy:
utils.js
export function sayHello () {
console.log('hello')
}
Step 2) Alias the module and add to ProvidePlugin:
webpack.config.js
var webpack = require("webpack");
var path = require("path");
// ...
module.exports = {
// ...
resolve: {
extensions: ['', '.js'],
alias: {
'utils': path.resolve(__dirname, './utils') // <-- When you build or restart dev-server, you'll get an error if the path to your utils.js file is incorrect.
}
},
plugins: [
// ...
new webpack.ProvidePlugin({
'utils': 'utils'
})
]
}
Now just call utils.sayHello()
in any js file and it should work. Make sure you restart your dev-server if you are using that with Webpack.
Note: Don't forget to tell your linter about the global, so it won't complain. For example, see my answer for ESLint here.
If you just want to use const with string values for your globals, then you can add this plugin to your list of Webpack plugins:
new webpack.DefinePlugin({
PRODUCTION: JSON.stringify(true),
VERSION: JSON.stringify("5fa3b9"),
BROWSER_SUPPORTS_HTML5: true,
TWO: "1+1",
"typeof window": JSON.stringify("object")
})
Use it like:
console.log("Running App version " + VERSION);
if(!BROWSER_SUPPORTS_HTML5) require("html5shiv");
window.foo = 'bar' // For SPA's, browser environment.
global.foo = 'bar' // Webpack will automatically convert this to window if your project is targeted for web (default), read more here: https://webpack.js.org/configuration/node/
You'll see this commonly used for polyfills, for example: window.Promise = Bluebird
(For server side projects) The dotenv package will take a local configuration file (which you could add to your .gitignore if there are any keys/credentials) and adds your configuration variables to Node's process.env object.
// As early as possible in your application, require and configure dotenv.
require('dotenv').config()
Create a .env
file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE
. For example:
DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3
That's it.
process.env
now has the keys and values you defined in your .env
file.
var db = require('db')
db.connect({
host: process.env.DB_HOST,
username: process.env.DB_USER,
password: process.env.DB_PASS
})
Regarding Webpack's Externals, use it if you want to exclude some modules from being included in your built bundle. Webpack will make the module globally available but won't put it in your bundle. This is handy for big libraries like jQuery (because tree shaking external packages doesn't work in Webpack) where you have these loaded on your page already in separate script tags (perhaps from a CDN).
This issue occurs if the server sends a "Cache-control:no-store" header or sends a "Cache-control:no-cache" header.
I'd probably use an ImageIcon and set it on a JLabel which I'd add to the JPanel.
Here's Sun's docs on the subject matter.
many of the answer here are how to find unused items.
I wanted to remove them automatically.
Install this node project.
$ npm install -g typescript tslint tslint-etc
At the root dir, add a new file tslint-imports.json
{
"extends": [
"tslint-etc"
],
"rules": {
"no-unused-declaration": true
}
}
Run this at your own risk, make a backup :)
$ tslint --config tslint-imports.json --fix --project .
The conflict message:
CONFLICT (delete/modify): res/layout/dialog_item.xml deleted in dialog and modified in HEAD
means that res/layout/dialog_item.xml
was deleted in the 'dialog' branch you are merging, but was modified in HEAD (in the branch you are merging to).
So you have to decide whether
git rm res/layout/dialog_item.xml
"or
git add res/layout/dialog_item.xml
"Then you finalize merge with "git commit
".
Note that git will warn you that you are creating a merge commit, in the (rare) case where it is something you don't want. Probably remains from the days where said case was less rare.
This link has more information:
https://en.wikipedia.org/wiki/Magic_number_(programming)#Debug_values
* 0xABABABAB : Used by Microsoft's HeapAlloc() to mark "no man's land" guard bytes after allocated heap memory * 0xABADCAFE : A startup to this value to initialize all free memory to catch errant pointers * 0xBAADF00D : Used by Microsoft's LocalAlloc(LMEM_FIXED) to mark uninitialised allocated heap memory * 0xBADCAB1E : Error Code returned to the Microsoft eVC debugger when connection is severed to the debugger * 0xBEEFCACE : Used by Microsoft .NET as a magic number in resource files * 0xCCCCCCCC : Used by Microsoft's C++ debugging runtime library to mark uninitialised stack memory * 0xCDCDCDCD : Used by Microsoft's C++ debugging runtime library to mark uninitialised heap memory * 0xDDDDDDDD : Used by Microsoft's C++ debugging heap to mark freed heap memory * 0xDEADDEAD : A Microsoft Windows STOP Error code used when the user manually initiates the crash. * 0xFDFDFDFD : Used by Microsoft's C++ debugging heap to mark "no man's land" guard bytes before and after allocated heap memory * 0xFEEEFEEE : Used by Microsoft's HeapFree() to mark freed heap memory
Note that Git 2.5 (Q2 2015) a future Git might try to make that scenario impossible.
See commit ed178ef by Jeff King (peff
), 22 Apr 2015.
(Merged by Junio C Hamano -- gitster
-- in commit 05c3967, 19 May 2015)
Note: This has been reverted. See below.
stash
: require a clean index to apply/pop
If you have staged contents in your index and run "
stash apply/pop
", we may hit a conflict and put new entries into the index.
Recovering to your original state is difficult at that point, because tools like "git reset --keep" will blow away anything staged.
In other words:
"
git stash pop/apply
" forgot to make sure that not just the working tree is clean but also the index is clean.
The latter is important as a stash application can conflict and the index will be used for conflict resolution.
We can make this safer by refusing to apply when there are staged changes.
That means if there were merges before because of applying a stash on modified files (added but not committed), now they would not be any merges because the stash apply/pop would stop immediately with:
Cannot apply stash: Your index contains uncommitted changes.
Forcing you to commit the changes means that, in case of merges, you can easily restore the initial state( before
git stash apply/pop
) with agit reset --hard
.
See commit 1937610 (15 Jun 2015), and commit ed178ef (22 Apr 2015) by Jeff King (peff
).
(Merged by Junio C Hamano -- gitster
-- in commit bfb539b, 24 Jun 2015)
That commit was an attempt to improve the safety of applying a stash, because the application process may create conflicted index entries, after which it is hard to restore the original index state.
Unfortunately, this hurts some common workflows around "
git stash -k
", like:
git add -p ;# (1) stage set of proposed changes
git stash -k ;# (2) get rid of everything else
make test ;# (3) make sure proposal is reasonable
git stash apply ;# (4) restore original working tree
If you "git commit" between steps (3) and (4), then this just works. However, if these steps are part of a pre-commit hook, you don't have that opportunity (you have to restore the original state regardless of whether the tests passed or failed).
Here is a more user-friendly answer that still uses streaming.
Just define these functions and call getImage()
. It will use the same file name as the url and write to the current directory by default, but both can be changed.
import requests
from StringIO import StringIO
from PIL import Image
def createFilename(url, name, folder):
dotSplit = url.split('.')
if name == None:
# use the same as the url
slashSplit = dotSplit[-2].split('/')
name = slashSplit[-1]
ext = dotSplit[-1]
file = '{}{}.{}'.format(folder, name, ext)
return file
def getImage(url, name=None, folder='./'):
file = createFilename(url, name, folder)
with open(file, 'wb') as f:
r = requests.get(url, stream=True)
for block in r.iter_content(1024):
if not block:
break
f.write(block)
def getImageFast(url, name=None, folder='./'):
file = createFilename(url, name, folder)
r = requests.get(url)
i = Image.open(StringIO(r.content))
i.save(file)
if __name__ == '__main__':
# Uses Less Memory
getImage('http://www.example.com/image.jpg')
# Faster
getImageFast('http://www.example.com/image.jpg')
The request
guts of getImage()
are based on the answer here and the guts of getImageFast()
are based on the answer above.
htaccess files affect the directory they are placed in and all sub-directories, that is an htaccess file located in your root directory (yoursite.com) would affect yoursite.com/content, yoursite.com/content/contents, etc.
SELECT group,subGroup,COUNT(*) FROM tablename GROUP BY group,subgroup
Cracked it. Basically, what's happening is that when you set the z-index to the negative, it actually ignores the parent element, whether it is positioned or not, and sits behind the next positioned element, which in your case was your main container. Therefore, you have to put your parent element in another, positioned div, and your child div will sit behind that.
Working that out was a life saver for me, as my parent element specifically couldn't be positioned, in order for my code to work.
I found all this incredibly useful to achieve the effect that's instructed on here: Using only CSS, show div on hover over <a>
Have a look at the following code snippet. You have mentioned Most files will be 30-40 MB
. This claims to read 180 MB in 1.4 seconds on an Intel Quad Core:
private int _bufferSize = 16384;
private void ReadFile(string filename)
{
StringBuilder stringBuilder = new StringBuilder();
FileStream fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read);
using (StreamReader streamReader = new StreamReader(fileStream))
{
char[] fileContents = new char[_bufferSize];
int charsRead = streamReader.Read(fileContents, 0, _bufferSize);
// Can't do much with 0 bytes
if (charsRead == 0)
throw new Exception("File is 0 bytes");
while (charsRead > 0)
{
stringBuilder.Append(fileContents);
charsRead = streamReader.Read(fileContents, 0, _bufferSize);
}
}
}
Portability between Linux and Windows is a big headache, since Linux is a POSIX-conformant system with - generally - a proper, high quality toolchain for C, whereas Windows doesn't even provide a lot of functions in the C standard library.
However, if you want to stick to the standard, you can write something like this:
#include <stdio.h>
#include <stdlib.h>
FILE *f = fopen("textfile.txt", "rb");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET); /* same as rewind(f); */
char *string = malloc(fsize + 1);
fread(string, 1, fsize, f);
fclose(f);
string[fsize] = 0;
Here string
will contain the contents of the text file as a properly 0-terminated C string. This code is just standard C, it's not POSIX-specific (although that it doesn't guarantee it will work/compile on Windows...)
##Generated signed apk from commandline
#variables
APP_NAME=THE_APP_NAME
APK_LOCATION=./
APP_HOME=/path/to/THE_APP
APP_KEY=/path/to/Android_key
APP_KEY_ALIAS=the_alias
APP_KEY_PASSWORD=123456789
zipalign=$ANDROID_HOME/build-tools/28.0.3/zipalign
#the logic
cd $APP_HOME
cordova build --release android
cd platforms/android/app/build/outputs/apk/release
jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore $APP_KEY ./app-release-unsigned.apk $APP_KEY_ALIAS <<< $APP_KEY_PASSWORD
rm -rf "$APK_LOCATION/$APP_NAME.apk"
$zipalign -v 4 ./app-release-unsigned.apk "$APK_LOCATION/$APP_NAME.apk"
open $APK_LOCATION
#the end
String blogName = "how to do in java . com";
String nameWithProperSpacing = blogName.replaceAll("\\\s+", " ");
You can write
std::list<item*>::iterator i = items.begin();
while (i != items.end())
{
bool isActive = (*i)->update();
if (!isActive) {
i = items.erase(i);
} else {
other_code_involving(*i);
i++;
}
}
You can write equivalent code with std::list::remove_if
, which is less verbose and more explicit
items.remove_if([] (item*i) {
bool isActive = (*i)->update();
if (!isActive)
return true;
other_code_involving(*i);
return false;
});
The std::vector::erase
std::remove_if
idiom should be used when items is a vector instead of a list to keep compexity at O(n) - or in case you write generic code and items might be a container with no effective way to erase single items (like a vector)
items.erase(std::remove_if(begin(items), end(items), [] (item*i) {
bool isActive = (*i)->update();
if (!isActive)
return true;
other_code_involving(*i);
return false;
}));
In str's answer, value 'undefined' will be returned instead of the set default value if the property is undefined. This sometimes can cause bugs. The following will make sure the defaultVal will always be returned when either the property or the object is undefined.
const temp = {};
console.log(getSafe(()=>temp.prop, '0'));
function getSafe(fn, defaultVal) {
try {
if (fn() === undefined) {
return defaultVal
} else {
return fn();
}
} catch (e) {
return defaultVal;
}
}
Based on twitter scroll trouble (http://ejohn.org/blog/learning-from-twitter/).
Here is my solution, throttling the js scroll event (usefull for mobile devices)
JS:
$(function() {
var $document, didScroll, offset;
offset = $('.menu').position().top;
$document = $(document);
didScroll = false;
$(window).on('scroll touchmove', function() {
return didScroll = true;
});
return setInterval(function() {
if (didScroll) {
$('.menu').toggleClass('fixed', $document.scrollTop() > offset);
return didScroll = false;
}
}, 250);
});
CSS:
.menu {
background: pink;
top: 5px;
}
.fixed {
width: 100%;
position: fixed;
top: 0;
}
HTML:
<div class="menu">MENU FIXED ON TOP</div>
I had this same problem and none of the suggested fixes worked for me. So even though this is an old thread, I figure I might as well post my solution in case someone else finds this thread through Google(like I did).
For me, I had to uninstall MinGW/delete the MinGW folder, and re-install. After re-installing it works like a charm.
I received the same error after installing android studio and trying to run hello world. I think you need to use the SDK Manager inside Android Studio to install some things first.
Open up Android Studio, and click on the SDK Manager in the toolbar.
Now install the SDK tools you need.
For each Android release you are targeting, hit the appropriate Android X.X folder and select (at a minimum):
The SDK Manager will run (this can take a while) and download and install the various SDKs.
Inside Android Studio, File->Project Structure will show you where your Android sdks are installed. As you can see mine is c:\users\Joe\AppData\Local\Android\sdk1.
If I navigate to C:\Users\Joe\AppData\Local\Android\sdk1\sources you can see the various Android SDKs installed there...
I got this error when using Delphi with the LiteDAC components. Turned out it only happened while running my app from the Delphi IDE if the Connected property was set True for the SQLite connection component (in this case TLiteConnection).
For Symfony projects, be sure to check files in the project'es app/logs
More details available on this post :
How to debug 500 Error in Symfony 2
Btw, other frameworks or CMS share this kind of behaviour.
Use urllib2 in combination with the brilliant BeautifulSoup library:
import urllib2
from BeautifulSoup import BeautifulSoup
# or if you're using BeautifulSoup4:
# from bs4 import BeautifulSoup
soup = BeautifulSoup(urllib2.urlopen('http://example.com').read())
for row in soup('table', {'class': 'spad'})[0].tbody('tr'):
tds = row('td')
print tds[0].string, tds[1].string
# will print date and sunrise
There is no such feature in PostgreSQL. You can do it only in pl/PgSQL (or other pl/*), but not in plain SQL.
An exception is WITH ()
query which can work as a variable, or even tuple
of variables. It allows you to return a table of temporary values.
WITH master_user AS (
SELECT
login,
registration_date
FROM users
WHERE ...
)
SELECT *
FROM users
WHERE master_login = (SELECT login
FROM master_user)
AND (SELECT registration_date
FROM master_user) > ...;
To Start Tomcat7 Service :
Open cmd, go to bin directory within "Apache Tomcat 7" folder. You will see some this like C:\..\bin>
Enter above command to start the service: C:\..\bin>service.bat install
. The service will get started now.
Enter above command to start tomcat7w monitory service. If you have issue with starting the tomcat7 service then remove the service with command : C:\..\bin>tomcat7 //DS//Tomcat7
Now the service will no longer exist. Try the install command again, now the service will get installed and started: C:\..\bin>tomcat7w \\MS\tomcat7w
You will see the tomcat 7 icon in the system tray. Now, the tomcat7 service and tomcat7w will start automatically when the windows get start.
The answer shared by @mockinterface is correct. Although I would like to add my 2 cents to it.
If someone is using frameworks like scrapy
the you will have to use /html/body//a[contains(@href,'com')][2]/@href
along with get() like this:
response.xpath('//a[contains(@href,'com')][2]/@href').get()
Java is a verbose language.
If you are only 3 days in, and this is already bothering you, maybe you'd be better off learning a different language like Scala:
scala> println("Hello World")
Hello World
In a loose sense, this would qualify as using a "library" to enable shorter expressions ;)
I was facing same problem on Ubuntu machine so I removed this error by following some steps. Switch to postgres user
$ sudo su - postgres
it will ask for password and by default password is postgres
After switch the user to postgres, open psql console
$ psql
so check the version of postgres if multiple versions are available
psql=# select VERSION();
PostgreSQL 9.1.13 on x86_64-unk.... # so version is 9.1
Now Open postgres user
vim /etc/postgresql/9.1/main/pg_hba.conf
9.1
is version return form upper command
and replace
local all postgres peer
to
local all postgres md5
Restart the service
sudo service postgresql restart
I write steps on my blog also
http://tarungarg402.blogspot.in/2014/10/set-up-postgresql-on-ubuntu.html
Since none for these solutions support the latest version of PDFMiner I wrote a simple solution that will return text of a pdf using PDFMiner. This will work for those who are getting import errors with process_pdf
import sys
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.converter import XMLConverter, HTMLConverter, TextConverter
from pdfminer.layout import LAParams
from cStringIO import StringIO
def pdfparser(data):
fp = file(data, 'rb')
rsrcmgr = PDFResourceManager()
retstr = StringIO()
codec = 'utf-8'
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
# Create a PDF interpreter object.
interpreter = PDFPageInterpreter(rsrcmgr, device)
# Process each page contained in the document.
for page in PDFPage.get_pages(fp):
interpreter.process_page(page)
data = retstr.getvalue()
print data
if __name__ == '__main__':
pdfparser(sys.argv[1])
See below code that works for Python 3:
import sys
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.converter import XMLConverter, HTMLConverter, TextConverter
from pdfminer.layout import LAParams
import io
def pdfparser(data):
fp = open(data, 'rb')
rsrcmgr = PDFResourceManager()
retstr = io.StringIO()
codec = 'utf-8'
laparams = LAParams()
device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
# Create a PDF interpreter object.
interpreter = PDFPageInterpreter(rsrcmgr, device)
# Process each page contained in the document.
for page in PDFPage.get_pages(fp):
interpreter.process_page(page)
data = retstr.getvalue()
print(data)
if __name__ == '__main__':
pdfparser(sys.argv[1])
The only way is to go an underlying level to the JVM.
df.col._jc.toString().encode('utf8')
This is also how it is converted to a str
in the pyspark code itself.
From pyspark/sql/column.py:
def __repr__(self):
return 'Column<%s>' % self._jc.toString().encode('utf8')
Bringing my answer from another question.
From the C specification, section 6.7.2:
— unsigned, or unsigned int
Meaning that unsigned
, when not specified the type, shall default to unsigned int
. So writing unsigned a
is the same as unsigned int a
.
The issue was resolved as I was having a JDK pointing to 1.7 and JRE pointing to 1.8. Check in the command prompt by typing
java -version
and
javac -version
Both should be same.
I tried a lot of methods on Chrome but the only thing that worked for me was "Clear browsing data"
Had to do the "advanced" version because standard didn't work. I suspect it was "Content Settings" that was doing it.
I think you have to allocate a new array and put the values into the new array. For example:
int[] array1and2 = new int[array1.length + array2.length];
int currentPosition = 0;
for( int i = 0; i < array1.length; i++) {
array1and2[currentPosition] = array1[i];
currentPosition++;
}
for( int j = 0; j < array2.length; j++) {
array1and2[currentPosition] = array2[j];
currentPosition++;
}
As far as I can tell just looking at it, this code should work.
Simple and effective alternative:
public class ClassName
{
public List<dynamic> MyProperty { get; set; }
}
or
public class ClassName
{
public List<object> MyProperty { get; set; }
}
For differences see this post: List<Object> vs List<dynamic>
close you project then open xcode go to file -> open search your project and open it . this worked for me
def valid = pointAddress.findAll { a ->
validPointTypes.any { a.contains(it) }
}
Should do it
Using a custom attribute (implemented with a directive) is perhaps the cleanest way. Here's my version, based on @Josh and @sean's suggestions.
angular.module('mymodule', [])
// Click to navigate
// similar to <a href="#/partial"> but hash is not required,
// e.g. <div click-link="/partial">
.directive('clickLink', ['$location', function($location) {
return {
link: function(scope, element, attrs) {
element.on('click', function() {
scope.$apply(function() {
$location.path(attrs.clickLink);
});
});
}
}
}]);
It has some useful features, but I'm new to Angular so there's probably room for improvement.
Try:
openssl pkcs12 -in path.p12 -out newfile.crt.pem -clcerts -nokeys
openssl pkcs12 -in path.p12 -out newfile.key.pem -nocerts -nodes
After that you have:
To put the certificate and key in the same file without a password, use the following, as an empty password will cause the key to not be exported:
openssl pkcs12 -in path.p12 -out newfile.pem -nodes
Or, if you want to provide a password for the private key, omit -nodes
and input a password:
openssl pkcs12 -in path.p12 -out newfile.pem
If you need to input the PKCS#12 password directly from the command line (e.g. a script), just add -passin pass:${PASSWORD}
:
openssl pkcs12 -in path.p12 -out newfile.crt.pem -clcerts -nokeys -passin 'pass:P@s5w0rD'
realpath <path to the symlink file>
should do the trick.
I'm not a fan of any of these solutions. I use this instead:
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.google.com/recaptcha/api/siteverify");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'secret' => $privatekey,
'response' => $_POST['g-recaptcha-response'],
'remoteip' => $_SERVER['REMOTE_ADDR']
]);
$resp = json_decode(curl_exec($ch));
curl_close($ch);
if ($resp->success) {
// Success
} else {
// failure
}
I'd argue that this is superior because you ensure it is being POSTed to the server and it's not making an awkward 'file_get_contents' call. This is compatible with recaptcha 2.0 described here: https://developers.google.com/recaptcha/docs/verify
I find this cleaner. I see most solutions are file_get_contents, when I feel curl would suffice.
Here's a demo of the above:https://jsfiddle.net/sajadweb/mjnyLm0q/11
new Vue({_x000D_
el: '#app',_x000D_
data: {_x000D_
users: [{ name: 'sajadweb',email:'[email protected]' }] _x000D_
},_x000D_
methods: {_x000D_
addUser: function () {_x000D_
this.users.push({ name: '',email:'' });_x000D_
},_x000D_
deleteUser: function (index) {_x000D_
console.log(index);_x000D_
console.log(this.finds);_x000D_
this.users.splice(index, 1);_x000D_
if(index===0)_x000D_
this.addUser()_x000D_
}_x000D_
}_x000D_
});
_x000D_
<script src="https://unpkg.com/vue/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
<h1>Add user</h1>_x000D_
<div v-for="(user, index) in users">_x000D_
<input v-model="user.name">_x000D_
<input v-model="user.email">_x000D_
<button @click="deleteUser(index)">_x000D_
delete_x000D_
</button>_x000D_
</div>_x000D_
_x000D_
<button @click="addUser">_x000D_
New User_x000D_
</button>_x000D_
_x000D_
<pre>{{ $data }}</pre>_x000D_
</div>
_x000D_
I set CurrentCulture
and CurrentUICulture
my custom base controller
protected override void Initialize(RequestContext requestContext)
{
base.Initialize(requestContext);
Thread.CurrentThread.CurrentCulture = CultureInfo.GetCultureInfo("en-GB");
Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-GB");
}
I came up with this while trying to figure out how to display currency ('$' to left, number to right) in table cells:
<div class="currency">20.34</div>
.currency {
text-align: right;
}
.currency:before {
content: "$";
float: left;
padding-right: 4px;
}
This may be overkill for a simple breadcrumb, but it's worth a shot. I remember having this issue a long time ago when I first started, but I never really solved it. That is, until I just decided to write this up now. :)
I have documented as best I can inline, at the bottom are 3 possible use cases. Enjoy! (feel free to ask any questions you may have)
<?php
// This function will take $_SERVER['REQUEST_URI'] and build a breadcrumb based on the user's current path
function breadcrumbs($separator = ' » ', $home = 'Home') {
// This gets the REQUEST_URI (/path/to/file.php), splits the string (using '/') into an array, and then filters out any empty values
$path = array_filter(explode('/', parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)));
// This will build our "base URL" ... Also accounts for HTTPS :)
$base = ($_SERVER['HTTPS'] ? 'https' : 'http') . '://' . $_SERVER['HTTP_HOST'] . '/';
// Initialize a temporary array with our breadcrumbs. (starting with our home page, which I'm assuming will be the base URL)
$breadcrumbs = Array("<a href=\"$base\">$home</a>");
// Find out the index for the last value in our path array
$last = end(array_keys($path));
// Build the rest of the breadcrumbs
foreach ($path AS $x => $crumb) {
// Our "title" is the text that will be displayed (strip out .php and turn '_' into a space)
$title = ucwords(str_replace(Array('.php', '_'), Array('', ' '), $crumb));
// If we are not on the last index, then display an <a> tag
if ($x != $last)
$breadcrumbs[] = "<a href=\"$base$crumb\">$title</a>";
// Otherwise, just display the title (minus)
else
$breadcrumbs[] = $title;
}
// Build our temporary array (pieces of bread) into one big string :)
return implode($separator, $breadcrumbs);
}
?>
<p><?= breadcrumbs() ?></p>
<p><?= breadcrumbs(' > ') ?></p>
<p><?= breadcrumbs(' ^^ ', 'Index') ?></p>
Execute this on the file:
awk 'ORS=NR%3?" ":"\n"' filename
and you'll get what you're looking for.
Try this
var s = {name: "raul", age: "22", gender: "Male"}
var keys = [];
for(var k in s) keys.push(k);
Here keys array will return your keys ["name", "age", "gender"]
Can JAX-RS do Asynchronous Request like JAX-WS?
Yes, it can surely do use @Async
Can JAX-RS access a web service that is not running on the Java platform, and vice versa?
Yes, it can Do
What does it mean by "REST is particularly useful for limited-profile devices, such as PDAs and mobile phones"?
It is mainly use for public apis it depends on which approach you want to use.
What does it mean by "JAX-RS do not require XML messages or WSDL service–API definitions?
It has its own standards WADL(Web application Development Language) it has http request by which you can access resources they are altogether created by different mindset,In case in Jax-Rs you have to think of exposing resources
There are a couple things going on with your example. You have a list containing a string of numbers and newline characters:
list = ['350882 348521 350166\r\n']
And you are trying to find a number ID within this list:
id = 348521
if id not in list:
...
Your first conditional is always going to pass, because it will be looking for integer 348521
in list
which has one element at index list[0]
with the string value of '350882 348521 350166\r\n'
, so integer 348521 will be added to that list, making it a list of two elements: a string and an integer, as your output shows.
To reiterate: list is searched for id, not the string in list's first element.
If you were trying to find if the string representation of '348521'
was contained within the larger string contained within your list, you could do the following, noting that you would need to do this for each element in list
:
if str(id) not in list[0]: # list[0]: '350882 348521 350166\r\n'
... # ^^^^^^
However be aware that you would need to wrap str(id)
with whitespace for the search, otherwise it would also match:
2348521999
^^^^^^
It is unclear whether you want your "list" to be a "string of integers separated by whitespace" or if you really want a list of integers.
If all you are trying to accomplish is to have a list of IDs, and to add IDs to that list only if they are not already contained, (and if the order of the elements in the list is not important,) then a set would be the best data structure to use.
ids = set(
[int(id) for id in '350882 348521 350166\r\n'.strip().split(' ')]
)
# Adding an ID already in the set has no effect
ids.add(348521)
If the ordering of the IDs in the string is important then I would keep your IDs in a standard list and use your conditional check:
ids = [int(id) for id in '350882 348521 350166\r\n'.strip().split(' ')]
if 348521 not in ids:
...
if ("one" !== 1 )
would evaluate as true
, the string "one"
is not equal to the number 1
In "model overview" or "diagram" just right-click on the table and you have the folowing options: "Copy Insert to clipboard" OR "Copy SQL to clipboard"
You can manage selecting those elements without any form of regex as the previous answers show, but to answer the question directly, yes you can use a form of regex in selectors:
#sections div[id^='s'] {
color: red;
}
That says select any div elements inside the #sections div that have an ID starting with the letter 's'.
See fiddle here.
By using the .. operator, you've have duplicated the folder path - and will get something like this : /wp-content/themes/wp-content/themes/twentysixteen/fonts/
.
Use the console in your browser to see for this error.
For Mysql You can use this Query
UPDATE table1 a, table2 b SET a.coloumn = b.coloumn WHERE a.id= b.id
As mentioned in the earlier comment, stacked bar chart does the trick, though the data needs to be setup differently.(See image below)
Duration column = End - Start
If you want to do it via setAttribute
you would change the style
attribute like so:
element.setAttribute('style','transform:rotate(90deg); -webkit-transform: rotate(90deg)') //etc
This would be helpful if you want to reset all other inline style and only set your needed style properties' values again, BUT in most cases you may not want that. That's why everybody advised to use this:
element.style.transform = 'rotate(90deg)';
element.style.webkitTransform = 'rotate(90deg)';
The above is equivalent to
element.style['transform'] = 'rotate(90deg)';
element.style['-webkit-transform'] = 'rotate(90deg)';
If you are looking to serialize the inputs on an event. Here's a pure JavaScript approach I use.
// serialize form
var data = {};
var inputs = [].slice.call(e.target.getElementsByTagName('input'));
inputs.forEach(input => {
data[input.name] = input.value;
});
Data will be a JavaScript object of the inputs.
If you think of import
as just syntax sugar for Node.js modules, objects, and destructuring, I find it's pretty intuitive.
// bar.js
module = {};
module.exports = {
functionA: () => {},
functionB: ()=> {}
};
// Really all that is is this:
var module = {
exports: {
functionA, functionB
}
};
// Then, over in foo.js
// The whole exported object:
var fump = require('./bar.js'); //= { functionA, functionB }
// Or
import fump from './bar' // The same thing - object functionA and functionB properties
// Just one property of the object
var fump = require('./bar.js').functionA;
// Same as this, right?
var fump = { functionA, functionB }.functionA;
// And if we use ES6 destructuring:
var { functionA } = { functionA, functionB };
// We get same result
// So, in import syntax:
import { functionA } from './bar';
Just to append to @pixeline's answer (tried to add a simple comment but the site said I needed 50 reputation).
If you are writing your plugin for the admin section then you should use:
add_action('admin_enqueue_scripts', "add_my_css_and_my_js_files");
The admin_enqueueu_scripts is the correct hook for the admin section, use wp_enqueue_scripts for the front end.
You can use a temporary variable:
boolean outerBreak = false;
for (Type type : types) {
if(outerBreak) break;
for (Type t : types2) {
if (some condition) {
// Do something and break...
outerBreak = true;
break; // Breaks out of the inner loop
}
}
}
Depending on your function, you can also exit/return from the inner loop:
for (Type type : types) {
for (Type t : types2) {
if (some condition) {
// Do something and break...
return;
}
}
}
This should work:
#!/bin/bash
echo "Enter your Path:"
read a
if [[ -d $a ]]; then
echo "$a is a Dir"
elif [[ -f $a ]]; then
echo "$a is the File"
else
echo "Invalid path"
fi
I had the same problem. It turns out that, compiling a project I got from someone else, I haven't set the correct StartUp project (right click on the desired startup project in the solution explorer and pick "set as StartUp Project"). Maybe this will help, cheers.
The layout for Switch widget is something like this.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:gravity="right"
android:text="All"
android:textStyle="bold"
android:textColor="@color/black"
android:textSize="20dp"
android:id="@+id/list_toggle" />
</LinearLayout>
In the Activity class, you can code by two ways. Depends on the use you can code.
First Way
public class ActivityClass extends Activity implements CompoundButton.OnCheckedChangeListener {
Switch list_toggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.return_vehicle);
list_toggle=(Switch)findViewById(R.id.list_toggle);
list_toggle.setOnCheckedChangeListener(this);
}
}
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(isChecked) {
list_toggle.setText("Only Today's"); //To change the text near to switch
Log.d("You are :", "Checked");
}
else {
list_toggle.setText("All List"); //To change the text near to switch
Log.d("You are :", " Not Checked");
}
}
Second way
public class ActivityClass extends Activity {
Switch list_toggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.return_vehicle);
list_toggle=(Switch)findViewById(R.id.list_toggle);
list_toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
list_toggle.setText("Only Today's"); //To change the text near to switch
Log.d("You are :", "Checked");
}
else {
list_toggle.setText("All List"); //To change the text near to switch
Log.d("You are :", " Not Checked");
}
}
});
}
}
If you really want to get the type by name you may use the following:
System.AppDomain.CurrentDomain.GetAssemblies().SelectMany(x => x.GetTypes()).First(x => x.Name == "theassembly");
Note that you can improve the performance of this drastically the more information you have about the type you're trying to load.
jQuery 3
As of jQuery 3, removeAttr
does not set the corresponding property to false
anymore:
Prior to jQuery 3.0, using
.removeAttr()
on a boolean attribute such aschecked
,selected
, orreadonly
would also set the corresponding named property tofalse
. This behavior was required for ancient versions of Internet Explorer but is not correct for modern browsers because the attribute represents the initial value and the property represents the current (dynamic) value.It is almost always a mistake to use
.removeAttr( "checked" )
on a DOM element. The only time it might be useful is if the DOM is later going to be serialized back to an HTML string. In all other cases,.prop( "checked", false )
should be used instead.
Hence only .prop('checked',false)
is correct way when using this version.
Original answer (from 2011):
For attributes which have underlying boolean properties (of which checked
is one), removeAttr
automatically sets the underlying property to false
. (Note that this is among the backwards-compatibility "fixes" added in jQuery 1.6.1).
So, either will work... but the second example you gave (using prop
) is the more correct of the two. If your goal is to uncheck the checkbox, you really do want to affect the property, not the attribute, and there's no need to go through removeAttr
to do that.
I would like to add a little more explanation to @user837048's answer. on my OSX Yosemite and Galaxy S3 which is rooted and using firmware CyanogenMod 11
and KitKat
I have done the below proceedings to Enable
and Disable
root prompt.
Please make ensure below
On your system
Android SDK
and you have set paths to binary files. type which adb
on your shell. It must give you somewhat result.
$ which adb
/Applications/Android Studio.app/sdk/platform-tools/adb
On your Mobile
ON
Apps and ADB
If you don't see Developer Options
in your settings, Goto Settings > About Phone. Scroll down to Build number
and tap there 7 times. I know its crazy. But believe me it works :D
Connect your phone via USB Cable.
type on your computer's
terminal
$ adb shell
you will see a prompt similiar, If any prompt has been shown on your mobile, to trust the connection, tap 'Always Trust' and 'OK'
shell@m0:/ $
now type
shell@m0:/ $ id
uid=2000(shell) gid=2000(shell) groups=1004(input),1007(log),1011(adb),1015(sdcard_rw),1028(sdcard_r),3001(net_bt_admin),3002(net_bt),3003(inet),3006(net_bw_stats) context=u:r:shell:s0
See you are not root
Now exit from shell, which will fall back to computer's prompt
shell@m0:/ $ exit
Now activate root
$adb shell
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
root@m0:/ #
Wow.. you are root
root@m0:/ # id
uid=0(root) gid=0(root) context=u:r:shell:s0
I tried many solutions to go back to normal non root prompt
. But didn't worked except @user837048's solution.
root@m0:/ # stop adbd && setprop service.adb.root 0 && start adbd &
[1] 32137
root@m0:/ #
$
This might exit you from Adb prompt
to normal prompt. Now connect again.
$ adb shell
shell@m0:/ $
Well.. You are Non root
In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
I had the same problem when I tried to use the icons directly from BootstrapCDN (the easiest way). Then I downloaded the CSS file and copied it to my site's CSS folder the CSS file (Described under the 'easy way' in font awesome documentation), and everything started working as they should.
Use the synaptic packet manager in order to install yacc / lex. If you are feeling more comfortable doing this on the console just do:
sudo apt-get install bison flex
There are some very nice articles on the net on how to get started with those tools. I found the article from CodeProject to be quite good and helpful (see here). But you should just try and search for "introduction to lex", there are plenty of good articles showing up.
My simple solution for SQLite (and probably MySQL):
SELECT *, MAX(age) FROM mytable GROUP BY `Group`;
However it doesn't work in PostgreSQL and maybe some other platforms.
In PostgreSQL you can use DISTINCT ON clause:
SELECT DISTINCT ON ("group") * FROM "mytable" ORDER BY "group", "age" DESC;
I see you already have a answer but here is another answer, maybe even faster A simple class to pass in a List of objects and retrieve either a csv or excel or password protected zip csv or excel. https://github.com/ernst223/spread-sheet-exporter
SpreadSheetExporter spreadSheetExporter = new SpreadSheetExporter(List<Object>, "Filename");
File fileCSV = spreadSheetExporter.getCSV();
what about using the official API?
According to the API doc:
DESTROY: Removes the datepicker functionality completely. This will return the element back to its pre-init state.
Use:
$("#txtSearch").datepicker("destroy");
to restore the input to its normal behaviour and
$("#txtSearch").datepicker(/*options*/);
again to show the datapicker again.
Using a decorator for measuring execution time for functions can be handy. There is an example at http://www.zopyx.com/blog/a-python-decorator-for-measuring-the-execution-time-of-methods.
Below I've shamelessly pasted the code from the site mentioned above so that the example exists at SO in case the site is wiped off the net.
import time
def timeit(method):
def timed(*args, **kw):
ts = time.time()
result = method(*args, **kw)
te = time.time()
print '%r (%r, %r) %2.2f sec' % \
(method.__name__, args, kw, te-ts)
return result
return timed
class Foo(object):
@timeit
def foo(self, a=2, b=3):
time.sleep(0.2)
@timeit
def f1():
time.sleep(1)
print 'f1'
@timeit
def f2(a):
time.sleep(2)
print 'f2',a
@timeit
def f3(a, *args, **kw):
time.sleep(0.3)
print 'f3', args, kw
f1()
f2(42)
f3(42, 43, foo=2)
Foo().foo()
// John
I'd do it like this:
sudo chown -R $USER:www-data laravel-project/
find laravel-project/ -type f -exec chmod 664 {} \;
find laravel-project/ -type d -exec chmod 775 {} \;
then finally, you need to give webserver permission to modify the storage
and bootstrap/cache
directories:
sudo chgrp -R www-data storage bootstrap/cache
sudo chmod -R ug+rwx storage bootstrap/cache
I am using this workaround with css:
/*** Angular 2 link without href ***/
a:not([href]){
cursor: pointer;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none
}
html
<a [routerLink]="/">My link</a>
Hope this helps
// Sort Array of Objects
// Data
var booksArray = [
{ first_nom: 'Lazslo', last_nom: 'Jamf' },
{ first_nom: 'Pig', last_nom: 'Bodine' },
{ first_nom: 'Pirate', last_nom: 'Prentice' }
];
// Property to Sort By
var args = "last_nom";
// Function to Sort the Data by given Property
function sortByProperty(property) {
return function (a, b) {
var sortStatus = 0,
aProp = a[property].toLowerCase(),
bProp = b[property].toLowerCase();
if (aProp < bProp) {
sortStatus = -1;
} else if (aProp > bProp) {
sortStatus = 1;
}
return sortStatus;
};
}
// Implementation
var sortedArray = booksArray.sort(sortByProperty(args));
console.log("sortedArray: " + JSON.stringify(sortedArray) );
Console log output:
"sortedArray:
[{"first_nom":"Pig","last_nom":"Bodine"},
{"first_nom":"Lazslo","last_nom":"Jamf"},
{"first_nom":"Pirate","last_nom":"Prentice"}]"
Adapted based on this source: http://www.levihackwith.com/code-snippet-how-to-sort-an-array-of-json-objects-by-property/
I've wrestled with this myself, trying to make it work from the server. Couldn't. Instead...
To clarify on @dnc253's answer, $window.open(URL)
is a method for having an Angular application open a given URL in another window. (It's really just a testable angular proxy for the universal window.open()
.) This is a great solution, preserves your history, and gets the file downloaded and possibly renders it in that fresh browser window if that's supported. But it often runs into popup blockers, which is a huge problem for reliability. Users often simply don't understand what's going on with them. So, if you don't mind immediately downloading the file with the current window, you can simply use the equally effective universal javascript method: location.href = "uriString"
, which works like a charm for me. Angular doesn't even realize anything has happened. I call it in a promise handler for once my POST/PUT operation has completed. If need be, have the POST/PUT return the URL to call, if you can't already infer it. You'll get the same behavior for the user as if it had downloaded in response to the PUT/POST. For example:
$http.post(url, payload).then(function(returnData){
var uriString = parseReturn(returnData);
location.href="uriString"
})
You can, in fact, download something directly from an XHR request, but it requires full support for the HTML5 file API and is usually more trouble than it's worth unless you need to perform local transformations upon the file before you make it available to the user. (Sadly, I lack the time to provide details on that but there are other SO posts about using it.)
Maybe you can try NetBeans IDE.
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.
Surprising to see nobody mentioned document.hasFocus
if (document.hasFocus()) console.log('Tab is active')
Using the standard mysql.createPool(), connections are lazily created by the pool. If you configure the pool to allow up to 100 connections, but only ever use 5 simultaneously, only 5 connections will be made. However if you configure it for 500 connections and use all 500 they will remain open for the durations of the process, even if they are idle!
This means if your MySQL Server max_connections is 510 your system will only have 10 mySQL connections available until your MySQL Server closes them (depends on what you have set your wait_timeout to) or your application closes! The only way to free them up is to manually close the connections via the pool instance or close the pool.
mysql-connection-pool-manager module was created to fix this issue and automatically scale the number of connections dependant on the load. Inactive connections are closed and idle connection pools are eventually closed if there has not been any activity.
// Load modules
const PoolManager = require('mysql-connection-pool-manager');
// Options
const options = {
...example settings
}
// Initialising the instance
const mySQL = PoolManager(options);
// Accessing mySQL directly
var connection = mySQL.raw.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
// Initialising connection
connection.connect();
// Performing query
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
// Ending connection
connection.end();
Ref: https://www.npmjs.com/package/mysql-connection-pool-manager
Switch to Branch2
git checkout Branch2
Apply the current (Branch2) changes on top of the Branch1 changes, staying in Branch2:
git rebase Branch1
Which would leave you with the desired result in Branch2:
a -- b -- c <-- Master
\
d -- e <-- Branch1
\
d -- e -- f' -- g' <-- Branch2
You can delete Branch1.
Just try encodeURI()
and encodeURIComponent()
yourself...
console.log(encodeURIComponent('@#$%^&*'));
_x000D_
Input: @#$%^&*
. Output: %40%23%24%25%5E%26*
. So, wait, what happened to *
? Why wasn't this converted? TLDR: You actually want fixedEncodeURIComponent()
and fixedEncodeURI()
. Long-story...
You should not be using encodeURIComponent()
or encodeURI()
. You should use fixedEncodeURIComponent()
and fixedEncodeURI()
, according to the MDN Documentation.
Regarding encodeURI()
...
If one wishes to follow the more recent RFC3986 for URLs, which makes square brackets reserved (for IPv6) and thus not encoded when forming something which could be part of a URL (such as a host), the following code snippet may help:
function fixedEncodeURI(str) { return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); }
Regarding encodeURIComponent()
...
To be more stringent in adhering to RFC 3986 (which reserves !, ', (, ), and *), even though these characters have no formalized URI delimiting uses, the following can be safely used:
function fixedEncodeURIComponent(str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16); }); }
So, what is the difference? fixedEncodeURI()
and fixedEncodeURIComponent()
convert the same set of values, but fixedEncodeURIComponent()
also converts this set: +@?=:*#;,$&
. This set is used in GET
parameters (&
, +
, etc.), anchor tags (#
), wildcard tags (*
), email/username parts (@
), etc..
For example -- If you use encodeURI()
, [email protected]/?email=me@home
will not properly send the second @
to the server, except for your browser handling the compatibility (as Chrome naturally does often).
You should be able to transfer the Application to another Username. You would need all your old user information to transfer it. The application would remove it's self from old account to new account. Also you could put a limit on how many times you where allowed to transfer it. If you transfer it to the application could expire after a year and force to buy update.
I assume that you haven't set the TableName
property of the DataTable, for example via constructor:
var tbl = new DataTable("dtImage");
If you don't provide a name, it will be automatically created with "Table1"
, the next table will get "Table2"
and so on.
Then the solution would be to provide the TableName
and then check with Contains(nameOfTable)
.
To clarify it: You'll get an ArgumentException
if that DataTable already belongs to the DataSet (the same reference). You'll get a DuplicateNameException
if there's already a DataTable in the DataSet with the same name(not case-sensitive).
Oh, dear. A few little problems...
As pointed out by others, you need to quote to protect against empty/space-containing entries, and use the !delayed_expansion! facility.
Two other matters of which you should be aware:
First, set/p
will assign a user-input value to a variable. That's not news - but the gotcha is that pressing enter
in response will leave the variable UNCHANGED - it will not ASSIGN a zero-length string to the variable (hence deleting the variable from the environment.) The safe method is:
set "var="
set /p var=
That is, of course, if you don't WANT enter
to repeat the existing value.
Another useful form is
set "var=default"
set /p var=
or
set "var=default"
set /p "var=[%var%]"
(which prompts with the default value; !var!
if in a block statement with delayedexpansion)
Second issue is that on some Windows versions (although W7 appears to "fix" this issue) ANY label - including a :: comment
(which is a broken-label) will terminate any 'block' - that is, parenthesised compound statement)
URL url = new URL(yourUrl, "/api/v1/status.xml");
According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:
URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");
Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html
redirect to ../
public String extractDigits(String src) {
StringBuilder builder = new StringBuilder();
for (int i = 0; i < src.length(); i++) {
char c = src.charAt(i);
if (Character.isDigit(c)) {
builder.append(c);
}
}
return builder.toString();
}
it should be enough to mark your aspect method like this:
@After("@annotation(com.marcot.CommitTransaction)")
public void after() {
have a look at this for a step by step guide on this.
Here is the example macro to convert the Excel worksheet to XML file.
#'vba code to convert excel to xml
Sub vba_code_to_convert_excel_to_xml()
Set wb = Workbooks.Open("C:\temp\testwb.xlsx")
wb.SaveAs fileName:="C:\temp\testX.xml", FileFormat:= _
xlXMLSpreadsheet, ReadOnlyRecommended:=False, CreateBackup:=False
End Sub
This macro will open an existing Excel workbook from the C drive and Convert the file into XML and Save the file with .xml extension in the specified Folder. We are using Workbook Open method to open a file. SaveAs method to Save the file into destination folder. This example will be help full, if you wan to convert all excel files in a directory into XML (xlXMLSpreadsheet format) file.
Just pass it as normal parameters and access it in PHP using the $argv
array.
php myfile.php daily
and in myfile.php
$type = $argv[1];
C++ is a standardized language. Visual C++ is a product that more or less implements that standard. You can write portable C++ using Visual C++, but you can also use Microsoft-only extensions that destroy your portability but enhance your productivity. This is a trade-off. You have to decide what appeals most to you.
I've maintained big desktop apps that were written in Visual C++, so that is perfectly feasible. From what I know of Visual Basic, the main advantage seems to be that the first part of the development cycle may be done faster than when using Visual C++, but as the complexity of a project increases, C++ programs tend to be more maintainable (If the programmers are striving for maintainability, that is).
the above solutions wont work on ipad-2
recently I had an safari browser crash issue while plotting the markers even if there are less number of markers. Initially I was using marker with label (markerwithlabel.js) library for plotting the marker , when i use google native marker it was working fine even with large number of markers but i want customized markers , so i refer the above solution given by jonathan but still the crashing issue is not resolved after doing lot of research i came to know about http://nickjohnson.com/b/google-maps-v3-how-to-quickly-add-many-markers this blog and now my map search is working smoothly on ipad-2 :)
You can use colorRampPalette
from base or RColorBrewer
package:
With colorRampPalette
, you can specify colours as follows:
colorRampPalette(c("red", "green"))(5)
# [1] "#FF0000" "#BF3F00" "#7F7F00" "#3FBF00" "#00FF00"
You can alternatively provide hex codes as well:
colorRampPalette(c("#3794bf", "#FFFFFF", "#df8640"))(5)
# [1] "#3794BF" "#9BC9DF" "#FFFFFF" "#EFC29F" "#DF8640"
# Note that the mid color is the mid value...
With RColorBrewer
you could use colors from pre-existing palettes:
require(RColorBrewer)
brewer.pal(9, "Set1")
# [1] "#E41A1C" "#377EB8" "#4DAF4A" "#984EA3" "#FF7F00" "#FFFF33" "#A65628" "#F781BF"
# [9] "#999999"
Look at RColorBrewer
package for other available palettes. Hope this helps.
Mby bootstrap img-responsive
class is you looking for.
$.get("/folder_name/filename.xml", function (xml) {_x000D_
var xmlInnerhtml = xml.documentElement.innerHTML;_x000D_
});
_x000D_
Update 2016/1/23
If you find this answer useful, you may be interested in a simple (~500 SLOC) password generation library I published:
Install-Package MlkPwgen
Then you can generate random strings just like in the answer below:
var str = PasswordGenerator.Generate(length: 10, allowed: Sets.Alphanumerics);
One advantage of the library is that the code is better factored out so you can use secure randomness for more than generating strings. Check out the project site for more details.
Since no one has provided secure code yet, I post the following in case anyone finds it useful.
string RandomString(int length, string allowedChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789") {
if (length < 0) throw new ArgumentOutOfRangeException("length", "length cannot be less than zero.");
if (string.IsNullOrEmpty(allowedChars)) throw new ArgumentException("allowedChars may not be empty.");
const int byteSize = 0x100;
var allowedCharSet = new HashSet<char>(allowedChars).ToArray();
if (byteSize < allowedCharSet.Length) throw new ArgumentException(String.Format("allowedChars may contain no more than {0} characters.", byteSize));
// Guid.NewGuid and System.Random are not particularly random. By using a
// cryptographically-secure random number generator, the caller is always
// protected, regardless of use.
using (var rng = System.Security.Cryptography.RandomNumberGenerator.Create()) {
var result = new StringBuilder();
var buf = new byte[128];
while (result.Length < length) {
rng.GetBytes(buf);
for (var i = 0; i < buf.Length && result.Length < length; ++i) {
// Divide the byte into allowedCharSet-sized groups. If the
// random value falls into the last group and the last group is
// too small to choose from the entire allowedCharSet, ignore
// the value in order to avoid biasing the result.
var outOfRangeStart = byteSize - (byteSize % allowedCharSet.Length);
if (outOfRangeStart <= buf[i]) continue;
result.Append(allowedCharSet[buf[i] % allowedCharSet.Length]);
}
}
return result.ToString();
}
}
Thanks to Ahmad for pointing out how to get the code working on .NET Core.
For those who Googled "disable a button" but may have more nuanced use cases:
Disable with visual effect: As others have said, this will prevent the button from being pressed and the system will automatically make it look disabled:
yourButton.isEnabled = false
Disable without visual effect: Are you using a button in a case where it should look normal but not behave likes button by reacting to touches? Try this!
yourButton.userInteractionEnabled = false
Hide without disabling: This approach hides the button without disabling it (invisible but can still be tapped):
yourButton.alpha = 0.0
Remove: This will remove the view entirely:
yourButton.removeFromSuperView()
Tap something behind a button: Have two buttons stacked and you want the top button to temporarily act like it's not there? If you won't need the top button again, remove it. If you will need it again, try condensing its height or width to 0!
function myfunction() {_x000D_
var first = document.getElementById("textbox1").value;_x000D_
var second = document.getElementById("textbox2").value;_x000D_
var answer = parseFloat(first) + parseFloat(second);_x000D_
_x000D_
var textbox3 = document.getElementById('textbox3');_x000D_
textbox3.value = answer;_x000D_
}
_x000D_
<input type="text" name="textbox1" id="textbox1" /> + <input type="text" name="textbox2" id="textbox2" />_x000D_
<input type="submit" name="button" id="button1" onclick="myfunction()" value="=" />_x000D_
<br/> Your answer is:--_x000D_
<input type="text" name="textbox3" id="textbox3" readonly="true" />
_x000D_
I you're happy with console emacs (emacs -nw), modern vterm implementations (like gnome-terminal) tend to have better font support. Plus if you get used to that, you can then use tmux, and so working with your full environment on remote servers becomes possible, even without X.
List Of Key codes:
a - z-> 29 - 54
"0" - "9"-> 7 - 16
BACK BUTTON - 4, MENU BUTTON - 82
UP-19, DOWN-20, LEFT-21, RIGHT-22
SELECT (MIDDLE) BUTTON - 23
SPACE - 62, SHIFT - 59, ENTER - 66, BACKSPACE - 67
To remove first Character of string in PHP,
$string = "abcdef";
$new_string = substr($string, 1);
echo $new_string;
Generates: "bcdef"
Is the Canvas crucial in your window? If not, try removing it and keep the Grid as the main panel. Canvas has no size unless specified, while a Grid normally takes up all available space. Inside the Canvas, the Grid will have no available space.
this metod delate all data from database
public void deleteAll()
{
SQLiteDatabase db = this.getWritableDatabase();
db.execSQL("delete from "+ TABLE_NAME);
db.close();
}
You may need to install or set the location of the Xcode Command Line Tools.
If you have Xcode downloaded you can run the following to set the path:
sudo xcode-select -s /Applications/Xcode.app
If the command line tools haven't been installed yet, you may need to run this first:
xcode-select --install
You may need to accept the Xcode license before installing command line tools:
sudo xcodebuild -license accept
Or adjust the Command Line Tools
setting via Xcode (Xcode > Preferences > Locations
):
This is very simple to understand :-
id is used when we have to apply CSS property to one attribute only.
class is used when we have to use CSS property in many locations within the same page or different.
General :- for unique structure like staring div and buttons layout we use id .
for same CSS throughout the page or project we use class
id is light and class is little heavy
I had a further issue that foxed me for a while when theming existing code from a CMS. I wanted to use flexbox with justify-content:space-between
but the left and right elements weren't flush.
In that system the items were floated and the container had a :before
and/or an :after
to clear floats at beginning or end. So setting those sneaky :before
and :after
elements to display:none
did the trick.
Just say: $("#divID").html($('').html($("#divID").html()));
Use Sessions.
Page1:
session_start();
$_SESSION['message'] = "Some message"
Page2:
session_start();
var_dump($_SESSION['message']);
From char*
to wstring
:
char* str = "hello worlddd";
wstring wstr (str, str+strlen(str));
From string
to wstring
:
string str = "hello worlddd";
wstring wstr (str.begin(), str.end());
Note this only works well if the string being converted contains only ASCII characters.
For small scripts an optional way to make it readable is to use a variable like this:
awk -v fmt="'%s'\n" '{printf fmt, $1}'
I found it conveninet in a case where I had to produce many times the single-quote character in the output and the \047 were making it totally unreadable
To help understand what do $#
, $0
and $1
, ..., $n
do, I use this script:
#!/bin/bash
for ((i=0; i<=$#; i++)); do
echo "parameter $i --> ${!i}"
done
Running it returns a representative output:
$ ./myparams.sh "hello" "how are you" "i am fine"
parameter 0 --> myparams.sh
parameter 1 --> hello
parameter 2 --> how are you
parameter 3 --> i am fine
You need to use jq 'keys[]'
. For example:
echo '{"example1" : 1, "example2" : 2, "example3" : 3}' | jq 'keys[]'
Will output a line separated list:
"example1"
"example2"
"example3"
#!/bin/bash
set -e
# Settings
user=xxx
pass=xxx
dir=xxx
repo_src=xxx
repo_trg=xxx
src_branch=xxx
repo_base_url=https://$user:[email protected]/$user
repo_src_url=$repo_base_url/$repo_src.git
repo_trg_url=$repo_base_url/$repo_trg.git
echo "Clone Source..."
git clone --depth 1 -b $src_branch $repo_src_url $dir
echo "CD"
cd ./$dir
echo "Remove GIT"
rm -rf .git
echo "Init GIT"
git init
git add .
git commit -m "Initial Commit"
git remote add origin $repo_trg_url
echo "Push..."
git push -u origin master
Here is how to create a DataFrame where each series is a row.
For a single Series (resulting in a single-row DataFrame):
series = pd.Series([1,2], index=['a','b'])
df = pd.DataFrame([series])
For multiple series with identical indices:
cols = ['a','b']
list_of_series = [pd.Series([1,2],index=cols), pd.Series([3,4],index=cols)]
df = pd.DataFrame(list_of_series, columns=cols)
For multiple series with possibly different indices:
list_of_series = [pd.Series([1,2],index=['a','b']), pd.Series([3,4],index=['a','c'])]
df = pd.concat(list_of_series, axis=1).transpose()
To create a DataFrame where each series is a column, see the answers by others. Alternatively, one can create a DataFrame where each series is a row, as above, and then use df.transpose()
. However, the latter approach is inefficient if the columns have different data types.
A solution would be to force the key files to be kept permanently, by adding them in your ~/.ssh/config
file:
IdentityFile ~/.ssh/gitHubKey
IdentityFile ~/.ssh/id_rsa_buhlServer
If you do not have a 'config' file in the ~/.ssh directory, then you should create one. It does not need root rights, so simply:
nano ~/.ssh/config
...and enter the lines above as per your requirements.
For this to work the file needs to have chmod 600. You can use the command chmod 600 ~/.ssh/config
.
If you want all users on the computer to use the key put these lines into /etc/ssh/ssh_config
and the key in a folder accessible to all.
Additionally if you want to set the key specific to one host, you can do the following in your ~/.ssh/config :
Host github.com
User git
IdentityFile ~/.ssh/githubKey
This has the advantage when you have many identities that a server doesn't reject you because you tried the wrong identities first. Only the specific identity will be tried.
Use Window.location.href to take the url in javascript. it's a property that will tell you the current URL location of the browser. Setting the property to something different will redirect the page.
if (window.location.href.indexOf("?added-to-cart=555") > -1) {
alert("found it");
}
I came across this method and I use it to make div IDs the slug name inside the loop:
<?php $slug = basename( get_permalink() ); echo $slug;?>
Demo: https://jsfiddle.net/kvxazhso/
Successfully pass equal values (keep same order). Flexible : handle ascendant (123) or descendant (321), works for numbers, letters, and unicodes. Works on all tested devices (Chrome, Android default browser, FF).
Given data such :
var people = [
{ 'myKey': 'A', 'status': 0 },
{ 'myKey': 'B', 'status': 3 },
{ 'myKey': 'C', 'status': 3 },
{ 'myKey': 'D', 'status': 2 },
{ 'myKey': 'E', 'status': 7 },
...
];
Sorting by ascending or reverse order:
function sortJSON(arr, key, way) {
return arr.sort(function(a, b) {
var x = a[key]; var y = b[key];
if (way === '123') { return ((x < y) ? -1 : ((x > y) ? 1 : 0)); }
if (way === '321') { return ((x > y) ? -1 : ((x < y) ? 1 : 0)); }
});
}
people2 = sortJSON(people,'status', '321'); // 123 or 321
alert("2. After processing (0 to x if 123; x to 0 if 321): "+JSON.stringify(people2));
I've been in same situation as well, and My case was because of the Korean letter in the path...
After I remove Korean letters from the folder name, it works.
OR put
[#-*- coding:utf-8 -*-]
(except [ ]
at the edge)
or something like that in the first line to make python understand Korean or your language or etc. then it will work even if there is some Koreans in the path in my case.
So the things is, it seems like there is something about path or the letter. People who answered are saying similar things. Hope you guys solve it!
Yet another approach - just set a flag on an element signaling which type of event should be handled:
function setRangeValueChangeHandler(rangeElement, handler) {
rangeElement.oninput = (event) => {
handler(event);
// Save flag that we are using onInput in current browser
event.target.onInputHasBeenCalled = true;
};
rangeElement.onchange = (event) => {
// Call only if we are not using onInput in current browser
if (!event.target.onInputHasBeenCalled) {
handler(event);
}
};
}
This is my version with the same number spaces. Hope you like it guys!
public String reverseWords(String text){
StringBuilder out = new StringBuilder();
for(String word : text.split(" ")){
out.append(new StringBuilder(word).reverse().toString());
out.append(" ");
}
return out.toString().substring(0, out.length() - 1);
}
I was able to absolutely position a right-floated element with one layer of nesting and a tricky margin:
function test() {_x000D_
document.getElementById("box").classList.toggle("hide");_x000D_
}
_x000D_
.right {_x000D_
float:right;_x000D_
}_x000D_
#box {_x000D_
position:absolute; background:#feb;_x000D_
width:20em; margin-left:-20em; padding:1ex;_x000D_
}_x000D_
#box.hide {_x000D_
display:none;_x000D_
}
_x000D_
<div>_x000D_
<div class="right">_x000D_
<button onclick="test()">box</button>_x000D_
<div id="box">Lorem ipsum dolor sit amet, consectetur adipiscing elit,_x000D_
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris_x000D_
nisi ut aliquip ex ea commodo consequat._x000D_
</div>_x000D_
</div>_x000D_
<p>_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit,_x000D_
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua._x000D_
Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris_x000D_
nisi ut aliquip ex ea commodo consequat._x000D_
</p>_x000D_
</div>
_x000D_
I decided to make this toggleable so you can see how it does not affect the flow of the surrounding text (run it and press the button to show/hide the floated absolute box).
This is an "old school solution", when MERGE command does not work (I think before version 10).
UPDATE TARGET_TABLE T
SET (T.VAL1, T.VAL2 ) =
(SELECT S.VAL1, S.VAL2
FROM SOURCE_TABLE S
WHERE T.KEY1 = S.KEY1 AND T.KEY2 = S.KEY2)
WHERE EXISTS
(SELECT 1
FROM SOURCE_TABLE S
WHERE T.KEY1 = S.KEY1 AND T.KEY2 = S.KEY2
AND (T.VAL1 <> S.VAL1 OR T.VAL2 <> S.VAL2));
The sum
function will add all numbers together to produce a single number, not a vector (well, at least not a vector of length greater than 1).
It looks as though at least one of your columns is a factor. You could convert them into numeric vectors by checking this
head(as.numeric(data$col1)) # make sure this gives you the right output
And if that looks right, do
data$col1 <- as.numeric(data$col1)
data$col2 <- as.numeric(data$col2)
You might have to convert them into characters first. In which case do
data$col1 <- as.numeric(as.character(data$col1))
data$col2 <- as.numeric(as.character(data$col2))
It's hard to tell which you should do without being able to see your data.
Once the columns are numeric, you just have to do
data$col3 <- data$col1 + data$col2
A more parsimonious way, rather than iterating through via a for loop you could also just print the original object containing all files inside your S3 bucket:
session = Session(aws_access_key_id=aws_access_key_id,aws_secret_access_key=aws_secret_access_key)
s3 = session.resource('s3')
bucket = s3.Bucket('bucket_name')
files_in_s3 = bucket.objects.all()
#you can print this iterable with print(list(files_in_s3))
Giving access to the IIS AppPool\YourAppPoolName user may be not enough with IIS default configurations.
In my case, I still had the error HTTP Error 401.3 - Unauthorized after adding the AppPool user and it was fixed only after adding permissions to the IUSR user.
This is necessary because, by default, Anonymous access is done using the IUSR. You can set another specific user, the Application Pool or continue using the IUSR, but don't forget to set the appropriate permissions.
Credits to this answer: HTTP Error 401.3 - Unauthorized
You can try with the following way,
<parent>
<groupId></groupId>
<artifactId></artifactId>
<version></version>
</parent>
So that the parent jar will be fetching from the repository.
nth-last-child
sounds like it was specifically designed to solve this problem, so I doubt whether there is a more compatible alternative. Support looks pretty decent, though.
For me, I didn't specify broker id for Kafka instance.
It will get a new id from zookeeper sometimes when it restarts in Docker environment.
If your broker id is greater than 1000, just specify the environment variable KAFKA_BROKER_ID
.
Use this to see brokers, topics and partitions.
brew install kafkacat
kafkacat -b [kafka_ip]:[kafka_poot] -L
Here's my take on this. I had to process the input string word by word, which could have been done by using space to count words but I felt it would be tedious and I should split the words into vectors.
#include<iostream>
#include<vector>
#include<string>
#include<stdio.h>
using namespace std;
int main()
{
char x = '\0';
string s = "";
vector<string> q;
x = getchar();
while(x != '\n')
{
if(x == ' ')
{
q.push_back(s);
s = "";
x = getchar();
continue;
}
s = s + x;
x = getchar();
}
q.push_back(s);
for(int i = 0; i<q.size(); i++)
cout<<q[i]<<" ";
return 0;
}
First I'd say you probably want to turn off persistent connections as they almost always do more harm than good.
Secondly I'd say you want to double check your MySQL users, just to make sure it's not possible for anyone to be connecting from a remote server. This is also a major security thing to check.
Thirdly I'd say you want to turn on the MySQL Slow Query Log to keep an eye on any queries that are taking a long time, and use that to make sure you don't have any queries locking up key tables for too long.
Some other things you can check would be to run the following query while the CPU load is high:
SHOW PROCESSLIST;
This will show you any queries that are currently running or in the queue to run, what the query is and what it's doing (this command will truncate the query if it's too long, you can use SHOW FULL PROCESSLIST to see the full query text).
You'll also want to keep an eye on things like your buffer sizes, table cache, query cache and innodb_buffer_pool_size (if you're using innodb tables) as all of these memory allocations can have an affect on query performance which can cause MySQL to eat up CPU.
You'll also probably want to give the following a read over as they contain some good information.
It's also a very good idea to use a profiler. Something you can turn on when you want that will show you what queries your application is running, if there's duplicate queries, how long they're taking, etc, etc. An example of something like this is one I've been working on called PHP Profiler but there are many out there. If you're using a piece of software like Drupal, Joomla or Wordpress you'll want to ask around within the community as there's probably modules available for them that allow you to get this information without needing to manually integrate anything.
you can try
$(function()
{
$(window).bind('load', function()
{
// INSERT YOUR CODE THAT WILL BE EXECUTED AFTER THE PAGE COMPLETELY LOADED...
});
});
i had the same problem and this code worked for me. how it works for you too!
As you are running on Linux I suspect you are running out of file descriptors. Check out ulimit. Here is an article that describes the problem: http://www.cyberciti.biz/faq/linux-increase-the-maximum-number-of-open-files/
If using adb devices on Mac OS X no device is displayed and, of course, you have enabled the USB debugging on your device (see http://developer.android.com/tools/device.html), then try with:
$ android update adb
adb has been updated. You must restart adb with the following commands
adb kill-server
adb start-server
Then:
$ adb kill-server
$ adb start-server
* daemon not running. starting it now on port ... *
* daemon started successfully *
And finally:
$ adb devices
List of devices attached
...... device
Your device should be now in the list.
I personally feel casting is the prettiest.
$iSomeVar = (int) $sSomeOtherVar;
Should a string like 'Hello' be sent, it will be cast to integer 0. For a string such as '22 years old', it will be cast to integer 22. Anything it can't parse to a number becomes 0.
If you really do NEED the speed, I guess the other suggestions here are correct in assuming that coercion is the fastest.
I think what you have missed here is this:
https://maven.apache.org/settings.html#Servers
The repositories for download and deployment are defined by the repositories and distributionManagement elements of the POM. However, certain settings such as username and password should not be distributed along with the pom.xml. This type of information should exist on the build server in the settings.xml.
This is the prefered way of using custom repos. So probably what is happening is that the url of this repo is in settings.xml of the build server.
Once you get hold of the url and credentials, you can put them in your machine here: ~/.m2/settings.xml
like this:
<settings ...>
.
.
.
<servers>
<server>
<id>internal-repository-group</id>
<username>YOUR-USERNAME-HERE</username>
<password>YOUR-PASSWORD-HERE</password>
</server>
</servers>
</settings>
EDIT:
You then need to refer this repository into project POM. The id internal-repository-group can be used in every project. You can setup multiple repos and credentials setting using different IDs in settings xml.
The advantage of this approach is that project can be shared without worrying about the credentials and don't have to mention the credentials in every project.
Following is a sample pom of a project using "internal-repository-group"
<repositories>
<repository>
<id>internal-repository-group</id>
<name>repo-name</name>
<url>http://project.com/yourrepourl/</url>
<layout>default</layout>
<releases>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</snapshots>
</repository>
</repositories>
If you want to apply the WHERE clause to the result of the UNION, then you have to embed the UNION in the FROM clause:
SELECT *
FROM (SELECT * FROM TableA
UNION
SELECT * FROM TableB
) AS U
WHERE U.Col1 = ...
I'm assuming TableA and TableB are union-compatible. You could also apply a WHERE clause to each of the individual SELECT statements in the UNION, of course.
In general error is which nobody can control or guess when it occurs.Exception can be guessed and can be handled. In Java Exception and Error are sub class of Throwable.It is differentiated based on the program control.Error such as OutOfMemory Error which no programmer can guess and can handle it.It depends on dynamically based on architectire,OS and server configuration.Where as Exception programmer can handle it and can avoid application's misbehavior.For example if your code is looking for a file which is not available then IOException is thrown.Such instances programmer can guess and can handle it.
If you need to specify options with flags, (like -h, --help, --number=42, etc) you can use the R package optparse (inspired from Python): http://cran.r-project.org/web/packages/optparse/vignettes/optparse.pdf.
At least this how I understand your question, because I found this post when looking for an equivalent of the bash getopt, or perl Getopt, or python argparse and optparse.
Synchronous Execution
My boss is a busy man. He tells me to write the code. I tell him: Fine. I get started and he's watching me like a vulture, standing behind me, off my shoulder. I'm like "Dude, WTF: why don't you go and do something while I finish this?"
he's like: "No, I'm waiting right here until you finish." This is synchronous.
Asynchronous Execution
The boss tells me to do it, and rather than waiting right there for my work, the boss goes off and does other tasks. When I finish my job I simply report to my boss and say: "I'm DONE!" This is Asynchronous Execution.
(Take my advice: NEVER work with the boss behind you.)
Merge a branch into new one (squash) and remove the files not needed:
git checkout master
git checkout -b <branch>
git merge --squash <source-branch-with-many-commits>
git reset HEAD <not-needed-file-1>
git checkout -- <not-needed-file-1>
git reset HEAD <not-needed-file-2>
git checkout -- <not-needed-file-2>
git commit
Change your meta tag to the one below and use placeholder attribute inside your HTML input tag.
<meta http-equiv="X-UA-Compatible" content="IE=edge" />_x000D_
<input type="text" placeholder="Placeholder text" />?
_x000D_
To expand on RiggsFolly’s answer—or for anyone who is facing the same issue but is using Apache 2.2 or below—this format should work well:
Order Deny,Allow
Deny from all
Allow from 127.0.0.1 ::1
Allow from localhost
Allow from 192.168
Allow from 10
Satisfy Any
For more details on the format changes for Apache 2.4, the official Upgrading to 2.2 from 2.4 page is pretty clear & concise. Key point being:
The old access control idioms should be replaced by the new authentication mechanisms, although for compatibility with old configurations, the new module
mod_access_compat
is provided.
Which means, system admins around the world don’t necessarily have to panic about changing Apache 2.2 configs to be 2.4 compliant just yet.
TL;DR: If you're just here for the most correct answer, you probably want my personal preference, find . -name '*.txt' -exec process {} \;
(see the bottom of this post). If you have time, read through the rest to see several different ways and the problems with most of them.
The full answer:
The best way depends on what you want to do, but here are a few options. As long as no file or folder in the subtree has whitespace in its name, you can just loop over the files:
for i in $x; do # Not recommended, will break on whitespace
process "$i"
done
Marginally better, cut out the temporary variable x
:
for i in $(find -name \*.txt); do # Not recommended, will break on whitespace
process "$i"
done
It is much better to glob when you can. White-space safe, for files in the current directory:
for i in *.txt; do # Whitespace-safe but not recursive.
process "$i"
done
By enabling the globstar
option, you can glob all matching files in this directory and all subdirectories:
# Make sure globstar is enabled
shopt -s globstar
for i in **/*.txt; do # Whitespace-safe and recursive
process "$i"
done
In some cases, e.g. if the file names are already in a file, you may need to use read
:
# IFS= makes sure it doesn't trim leading and trailing whitespace
# -r prevents interpretation of \ escapes.
while IFS= read -r line; do # Whitespace-safe EXCEPT newlines
process "$line"
done < filename
read
can be used safely in combination with find
by setting the delimiter appropriately:
find . -name '*.txt' -print0 |
while IFS= read -r -d '' line; do
process "$line"
done
For more complex searches, you will probably want to use find
, either with its -exec
option or with -print0 | xargs -0
:
# execute `process` once for each file
find . -name \*.txt -exec process {} \;
# execute `process` once with all the files as arguments*:
find . -name \*.txt -exec process {} +
# using xargs*
find . -name \*.txt -print0 | xargs -0 process
# using xargs with arguments after each filename (implies one run per filename)
find . -name \*.txt -print0 | xargs -0 -I{} process {} argument
find
can also cd into each file's directory before running a command by using -execdir
instead of -exec
, and can be made interactive (prompt before running the command for each file) using -ok
instead of -exec
(or -okdir
instead of -execdir
).
*: Technically, both find
and xargs
(by default) will run the command with as many arguments as they can fit on the command line, as many times as it takes to get through all the files. In practice, unless you have a very large number of files it won't matter, and if you exceed the length but need them all on the same command line, you're SOL find a different way.
You can extend TextView to set custom fonts as I learned here.
TextViewPlus.java:
package com.example;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.util.Log;
import android.widget.TextView;
public class TextViewPlus extends TextView {
private static final String TAG = "TextView";
public TextViewPlus(Context context) {
super(context);
}
public TextViewPlus(Context context, AttributeSet attrs) {
super(context, attrs);
setCustomFont(context, attrs);
}
public TextViewPlus(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
setCustomFont(context, attrs);
}
private void setCustomFont(Context ctx, AttributeSet attrs) {
TypedArray a = ctx.obtainStyledAttributes(attrs, R.styleable.TextViewPlus);
String customFont = a.getString(R.styleable.TextViewPlus_customFont);
setCustomFont(ctx, customFont);
a.recycle();
}
public boolean setCustomFont(Context ctx, String asset) {
Typeface tf = null;
try {
tf = Typeface.createFromAsset(ctx.getAssets(), asset);
} catch (Exception e) {
Log.e(TAG, "Could not get typeface: "+e.getMessage());
return false;
}
setTypeface(tf);
return true;
}
}
attrs.xml: (in res/values)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="TextViewPlus">
<attr name="customFont" format="string"/>
</declare-styleable>
</resources>
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:foo="http://schemas.android.com/apk/res/com.example"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<com.example.TextViewPlus
android:id="@+id/textViewPlus1"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:text="@string/showingOffTheNewTypeface"
foo:customFont="saxmono.ttf">
</com.example.TextViewPlus>
</LinearLayout>
You would put "saxmono.ttf" in the assets folder.
There are serious memory concerns with this method. See chedabob's comment below.
i was looking for changing second row html and you can do cascading selector
$('#tbox1 tr:nth-child(2) td').html(11111)
This is an improvement to a previous answer. It adds support for values with varying lengths and rows with a varying number of cells. For example:
+------------------------------------------------------------------------------+
¦Identifier¦ Type¦ Description¦ CPU Credit Use¦Hours¦Balance¦
+----------+---------+--------------------------+----------------+-----+-------+
¦ i-1234154¦ t2.small¦ This is an example.¦ 3263.75¦ 360¦
+----------+---------+--------------------------+----------------+-----+
¦ i-1231412¦ t2.small¦ This is another example.¦ 3089.93¦
+----------------------------------------------------------------+
Here is the code:
public class ArrayPrinter
{
const string TOP_LEFT_JOINT = "+";
const string TOP_RIGHT_JOINT = "+";
const string BOTTOM_LEFT_JOINT = "+";
const string BOTTOM_RIGHT_JOINT = "+";
const string TOP_JOINT = "-";
const string BOTTOM_JOINT = "-";
const string LEFT_JOINT = "+";
const string JOINT = "+";
const string RIGHT_JOINT = "¦";
const char HORIZONTAL_LINE = '-';
const char PADDING = ' ';
const string VERTICAL_LINE = "¦";
private static int[] GetMaxCellWidths(List<string[]> table)
{
int maximumCells = 0;
foreach (Array row in table)
{
if (row.Length > maximumCells)
maximumCells = row.Length;
}
int[] maximumCellWidths = new int[maximumCells];
for (int i = 0; i < maximumCellWidths.Length; i++)
maximumCellWidths[i] = 0;
foreach (Array row in table)
{
for (int i = 0; i < row.Length; i++)
{
if (row.GetValue(i).ToString().Length > maximumCellWidths[i])
maximumCellWidths[i] = row.GetValue(i).ToString().Length;
}
}
return maximumCellWidths;
}
public static string GetDataInTableFormat(List<string[]> table)
{
StringBuilder formattedTable = new StringBuilder();
Array nextRow = table.FirstOrDefault();
Array previousRow = table.FirstOrDefault();
if (table == null || nextRow == null)
return String.Empty;
// FIRST LINE:
int[] maximumCellWidths = GetMaxCellWidths(table);
for (int i = 0; i < nextRow.Length; i++)
{
if (i == 0 && i == nextRow.Length - 1)
formattedTable.Append(String.Format("{0}{1}{2}", TOP_LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), TOP_RIGHT_JOINT));
else if (i == 0)
formattedTable.Append(String.Format("{0}{1}", TOP_LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
else if (i == nextRow.Length - 1)
formattedTable.AppendLine(String.Format("{0}{1}{2}", TOP_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), TOP_RIGHT_JOINT));
else
formattedTable.Append(String.Format("{0}{1}", TOP_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
}
int rowIndex = 0;
int lastRowIndex = table.Count - 1;
foreach (Array thisRow in table)
{
// LINE WITH VALUES:
int cellIndex = 0;
int lastCellIndex = thisRow.Length - 1;
foreach (object thisCell in thisRow)
{
string thisValue = thisCell.ToString().PadLeft(maximumCellWidths[cellIndex], PADDING);
if (cellIndex == 0 && cellIndex == lastCellIndex)
formattedTable.AppendLine(String.Format("{0}{1}{2}", VERTICAL_LINE, thisValue, VERTICAL_LINE));
else if (cellIndex == 0)
formattedTable.Append(String.Format("{0}{1}", VERTICAL_LINE, thisValue));
else if (cellIndex == lastCellIndex)
formattedTable.AppendLine(String.Format("{0}{1}{2}", VERTICAL_LINE, thisValue, VERTICAL_LINE));
else
formattedTable.Append(String.Format("{0}{1}", VERTICAL_LINE, thisValue));
cellIndex++;
}
previousRow = thisRow;
// SEPARATING LINE:
if (rowIndex != lastRowIndex)
{
nextRow = table[rowIndex + 1];
int maximumCells = Math.Max(previousRow.Length, nextRow.Length);
for (int i = 0; i < maximumCells; i++)
{
if (i == 0 && i == maximumCells - 1)
{
formattedTable.Append(String.Format("{0}{1}{2}", LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), RIGHT_JOINT));
}
else if (i == 0)
{
formattedTable.Append(String.Format("{0}{1}", LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
}
else if (i == maximumCells - 1)
{
if (i > previousRow.Length)
formattedTable.AppendLine(String.Format("{0}{1}{2}", TOP_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), TOP_RIGHT_JOINT));
else if (i > nextRow.Length)
formattedTable.AppendLine(String.Format("{0}{1}{2}", BOTTOM_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), BOTTOM_RIGHT_JOINT));
else if (i > previousRow.Length - 1)
formattedTable.AppendLine(String.Format("{0}{1}{2}", JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), TOP_RIGHT_JOINT));
else if (i > nextRow.Length - 1)
formattedTable.AppendLine(String.Format("{0}{1}{2}", JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), BOTTOM_RIGHT_JOINT));
else
formattedTable.AppendLine(String.Format("{0}{1}{2}", JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), RIGHT_JOINT));
}
else
{
if (i > previousRow.Length)
formattedTable.Append(String.Format("{0}{1}", TOP_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
else if (i > nextRow.Length)
formattedTable.Append(String.Format("{0}{1}", BOTTOM_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
else
formattedTable.Append(String.Format("{0}{1}", JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
}
}
}
rowIndex++;
}
// LAST LINE:
for (int i = 0; i < previousRow.Length; i++)
{
if (i == 0)
formattedTable.Append(String.Format("{0}{1}", BOTTOM_LEFT_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
else if (i == previousRow.Length - 1)
formattedTable.AppendLine(String.Format("{0}{1}{2}", BOTTOM_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE), BOTTOM_RIGHT_JOINT));
else
formattedTable.Append(String.Format("{0}{1}", BOTTOM_JOINT, String.Empty.PadLeft(maximumCellWidths[i], HORIZONTAL_LINE)));
}
return formattedTable.ToString();
}
}
You need other headers, not only access-control-allow-origin. If your request have the "Access-Control-Allow-Origin" header, you must copy it into the response headers, If doesn't, you must check the "Origin" header and copy it into the response. If your request doesn't have Access-Control-Allow-Origin not Origin headers, you must return "*".
You can read the complete explanation here: http://www.html5rocks.com/en/tutorials/cors/#toc-adding-cors-support-to-the-server
and this is the function I'm using to write cross domain headers:
func writeCrossDomainHeaders(w http.ResponseWriter, req *http.Request) {
// Cross domain headers
if acrh, ok := req.Header["Access-Control-Request-Headers"]; ok {
w.Header().Set("Access-Control-Allow-Headers", acrh[0])
}
w.Header().Set("Access-Control-Allow-Credentials", "True")
if acao, ok := req.Header["Access-Control-Allow-Origin"]; ok {
w.Header().Set("Access-Control-Allow-Origin", acao[0])
} else {
if _, oko := req.Header["Origin"]; oko {
w.Header().Set("Access-Control-Allow-Origin", req.Header["Origin"][0])
} else {
w.Header().Set("Access-Control-Allow-Origin", "*")
}
}
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE")
w.Header().Set("Connection", "Close")
}
Most of the answers on this page are outdated.
Here's an updated python version to search google and get all results href's:
import urllib.parse
import re
from selenium import webdriver
driver.get("https://google.com/")
q = driver.find_element_by_name('q')
q.send_keys("always look on the bright side of life monty python")
q.submit();
sleep(1)
links= driver.find_elements_by_xpath("//h3[@class='r']//a")
for link in links:
url = urllib.parse.unquote(webElement.get_attribute("href")) # decode the url
url = re.sub("^.*?(?:url\?q=)(.*?)&sa.*", r"\1", url, 0, re.IGNORECASE) # get the clean url
Please note that the element id
/name
/class
(@class='r'
) ** will change depending on the user agent**.
The above code used PhantomJS default user agent.
This would restore focus to the previous application and exit the script if the answer was empty.
a=$(osascript -e 'try
tell app "SystemUIServer"
set answer to text returned of (display dialog "" default answer "")
end
end
activate app (path to frontmost application as text)
answer' | tr '\r' ' ')
[[ -z "$a" ]] && exit
If you told System Events to display the dialog, there would be a small delay if it wasn't running before.
For documentation about display dialog, open the dictionary of Standard Additions in AppleScript Editor or see the AppleScript Language Guide.
Blog post Serial RS232 connections in Python
import time
import serial
# configure the serial connections (the parameters differs on the device you are connecting to)
ser = serial.Serial(
port='/dev/ttyUSB1',
baudrate=9600,
parity=serial.PARITY_ODD,
stopbits=serial.STOPBITS_TWO,
bytesize=serial.SEVENBITS
)
ser.isOpen()
print 'Enter your commands below.\r\nInsert "exit" to leave the application.'
input=1
while 1 :
# get keyboard input
input = raw_input(">> ")
# Python 3 users
# input = input(">> ")
if input == 'exit':
ser.close()
exit()
else:
# send the character to the device
# (note that I happend a \r\n carriage return and line feed to the characters - this is requested by my device)
ser.write(input + '\r\n')
out = ''
# let's wait one second before reading output (let's give device time to answer)
time.sleep(1)
while ser.inWaiting() > 0:
out += ser.read(1)
if out != '':
print ">>" + out
public function index() {
$user = $this->session->userdata("username");
$file_path = "./images/" . $user . '/';
if (isset($_FILES['multipleUpload'])) {
if (!is_dir('images/' . $user)) {
mkdir('./images/' . $user, 0777, TRUE);
}
$files = $_FILES;
$cpt = count($_FILES ['multipleUpload'] ['name']);
for ($i = 0; $i < $cpt; $i ++) {
$name = time().$files ['multipleUpload'] ['name'] [$i];
$_FILES ['multipleUpload'] ['name'] = $name;
$_FILES ['multipleUpload'] ['type'] = $files ['multipleUpload'] ['type'] [$i];
$_FILES ['multipleUpload'] ['tmp_name'] = $files ['multipleUpload'] ['tmp_name'] [$i];
$_FILES ['multipleUpload'] ['error'] = $files ['multipleUpload'] ['error'] [$i];
$_FILES ['multipleUpload'] ['size'] = $files ['multipleUpload'] ['size'] [$i];
$this->upload->initialize($this->set_upload_options($file_path));
if(!($this->upload->do_upload('multipleUpload')) || $files ['multipleUpload'] ['error'] [$i] !=0)
{
print_r($this->upload->display_errors());
}
else
{
$this->load->model('uploadModel','um');
$this->um->insertRecord($user,$name);
}
}
} else {
$this->load->view('uploadForm');
}
}
public function set_upload_options($file_path) {
// upload an image options
$config = array();
$config ['upload_path'] = $file_path;
$config ['allowed_types'] = 'gif|jpg|png';
return $config;
}
I must clarify that no-cache
does not mean do not cache. In fact, it means "revalidate with server" before using any cached response you may have, on every request.
must-revalidate
, on the other hand, only needs to revalidate when the resource is considered stale.
If the server says that the resource is still valid then the cache can respond with its representation, thus alleviating the need for the server to resend the entire resource.
no-store
is effectively the full do not cache directive and is intended to prevent storage of the representation in any form of cache whatsoever.
I say whatsoever, but note this in the RFC 2616 HTTP spec:
History buffers MAY store such responses as part of their normal operation
But this is omitted from the newer RFC 7234 HTTP spec in potentially an attempt to make no-store
stronger, see:
According to the docs numpy.loadtxt
is
a fast reader for simply formatted files. The genfromtxt function provides more sophisticated handling of, e.g., lines with missing values.
so there are only a few options to handle more complicated files.
As mentioned numpy.genfromtxt
has more options. So as an example you could use
import numpy as np
data = np.genfromtxt('e:\dir1\datafile.csv', delimiter=',', skip_header=10,
skip_footer=10, names=['x', 'y', 'z'])
to read the data and assign names to the columns (or read a header line from the file with names=True
) and than plot it with
ax1.plot(data['x'], data['y'], color='r', label='the data')
I think numpy is quite well documented now. You can easily inspect the docstrings from within ipython
or by using an IDE like spider
if you prefer to read them rendered as HTML.
You could also consider to maven-dependency-plugin to your pom:
<plugins>
...
<plugin>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<phase>process-resources</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
</configuration>
</execution>
</executions>
</plugin>
...
</plugins>
Than you can run "mvn package" and maven will copy all needed dependencies to your_project_path/target/your_project_name/WEB-INF/lib/ directory. From there you can copy them to your project/lib dir and add as external jars (configuring your project settings buildpath)
Alan already gave you the right answer - use the sAMAccountName
to filter your user.
I would add a recommendation on your use of DirectorySearcher
- if you only want one or two pieces of information, add them into the "PropertiesToLoad"
collection of the DirectorySearcher
.
Instead of retrieving the whole big user object and then picking out one or two items, this will just return exactly those bits you need.
Sample:
adSearch.PropertiesToLoad.Add("sn"); // surname = last name
adSearch.PropertiesToLoad.Add("givenName"); // given (or first) name
adSearch.PropertiesToLoad.Add("mail"); // e-mail addresse
adSearch.PropertiesToLoad.Add("telephoneNumber"); // phone number
Those are just the usual AD/LDAP property names you need to specify.
In addition to @Jon Skeet's answer:
Traditionally Windows has used \r\n, Unix \n and Mac \r, however newer Macs use \n as they're unix based.
You were on the right track with response.getOutputStream()
, but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:
@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
// convert JSON to Employee
Employee emp = convertSomehow(json);
// generate the file
PdfUtil.showHelp(emp);
// retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
byte[] contents = (...);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
// Here you have to set the actual filename of your pdf
String filename = "output.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
return response;
}
Notes:
showHelp
is not a good ideabyte[]
: example hereshowHelp()
to avoid overwriting the file if two users send a request at the same timeOpen preferences windows (Command key + "," on Mac):
1.Tools
2.Python Integrated Tools
3.Default test runner
If you don't have an existing local branch, it is truly as simple as:
git fetch
git checkout <remote-branch-name>
For instance if you fetch and there is a new remote tracking branch called origin/feature/Main_Page
, just do this:
git checkout feature/Main_Page
This creates a local branch with the same name as the remote branch, tracking that remote branch. If you have multiple remotes with the same branch name, you can use the less ambiguous:
git checkout -t <remote>/<remote-branch-name>
If you already made the local branch and don't want to delete it, see How do you make an existing Git branch track a remote branch?.
you can easily resolve this problem by changing the port number of glassfish.
Go to glassfich configuration File domain.xml
which is located under GlassFish_Server\glassfish\domains\domain1\config
.
Open this file, then change the following line:
<network-listener port="8080" protocol="http-listener-1" transport="tcp"
name="http-listener-1" thread-pool="http-thread-pool"></network-listener>
replace 8080
by 9090
for example, then save file and run glassfish again.
it should nicely work.
You can always do the following:
const SomeCall = request.get(res => {
const Store = [];
Store.push(res.data);
Store.forEach(item => { DoSomethingNeat
});
});
To complete the above answers, I had the case using an XML mapping file where neither the @Transient
nor transient
worked...
I had to put the transient information in the xml file:
<attributes>
(...)
<transient name="field" />
</attributes>
There is an easier solution to this problem.
You just need to add a t
to the mode so it becomes wt
. This causes Python to open the file as a text file and not binary. Then everything will just work.
The complete program becomes this:
plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")
with gzip.open(filename + ".gz", "wt") as outfile:
outfile.write(plaintext)
Make use of using the Color and Backcolor Properties to write Expressions for your query. Add the following to the expression option for the color property that you want to cater for)
Example
=iif(fields!column.value = "Approved", "Green","<other color>")
iif
needs 3 values, first the relating Column, then the second is to handle the True and the third is to handle the False for the iif
statement
If you want to append two arrays -
var a = ['a', 'b'];
var b = ['c', 'd'];
then you could use:
var c = a.concat(b);
And if you want to add record g
to array (var a=[]
) then you could use:
a.push('g');
In simpler case (when html tags is the same):
<h2 th:text="${potentially_complex_expression} ? 'Hello' : 'Something else'">/h2>
use c methods
FILE *fp =fopen("filename","mode");
fclose(fp);
mode means a for appending r for reading ,w for writing
/ / using ofstream constructors.
#include <iostream>
#include <fstream>
std::string input="some text to write"
std::ofstream outfile ("test.txt");
outfile <<input << std::endl;
outfile.close();
In iOS 9.1 and lower, go to Settings - General - Profiles - tap on your Profile - tap on Trust button.
In iOS 9.2+ & iOS 11+ go to: Settings - General - Profiles & Device Management - tap on your Profile - tap on Trust button.
In iOS 10+, go to: Settings - General - Device Management - tap on your Profile - tap on Trust button.
In my case (multiple code ENOENT errno 34) problem was with ~/.npm/
directory access. Inside it there were some subdirs having root:root
rights, which were causing problems while I run commands as normal user (without sudo
). So I changed ownership of all subdirs and files inside ~/.npm/
dir into my local user and group. That did the trick on my Ubuntu (on Mac should work too).
$ sudo chown yourusername.yourgroupname ~/.npm/ -R
You should know your user name, right? If no then run $ whoami
and substitute your group name with it too, like this:
$ sudo chown johnb.johnb ~/.npm/ -R
EDIT:
Test case:
From my local account /home/johnb
I npm-installed globally some generator for yeoman
, like this:
$ sudo npm install -g generator-laravel
Problem nature:
Above action caused some dependencies being installed inside ~/.npm/
dir, having root:root
ownership (because of sudo ...
). Evidently npm does not run as local user (or change dependencies subdirs ownership afterwards) when pulling dependencies and writing them to a local user subdir ~/.npm/
.
As long as npm would be so careless against fundamental unix filesystem security issues the problem would reoccur.
Solution:
Continuosly check if ~/.npm/
contains subdirs with ownership (and/or permissions) other than your local user account, especially when you install or update something with sodo
(root). If so, change the ownership inside ~/.npm/
to a local user recursively.
Ask npm, bower, grunt, ...
community that they address this issue as I described it above.
ls -R | findstr ".mp3"
ls -R
=> lists subdirectories recursively
I am not sure is it the right way but this one works for me.
First import the component which contains the method you want to call in your component
import myComponent from './MyComponent'
and then call any method of MyCompenent
myComponent.methods.doSomething()
Logically OLAP functions are calculated after GROUP BY/HAVING, so you can only access columns in GROUP BY or columns with an aggregate function. Following looks strange, but is Standard SQL:
SELECT employee_number,
MAX(MAX(course_completion_date))
OVER (PARTITION BY course_code) AS max_course_date,
MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code
And as Teradata allows re-using an alias this also works:
SELECT employee_number,
MAX(max_date)
OVER (PARTITION BY course_code) AS max_course_date,
MAX(course_completion_date) AS max_date
FROM employee_course_completion
WHERE course_code IN ('M910303', 'M91301R', 'M91301P')
GROUP BY employee_number, course_code
Updated the list for further documentation.
socket.emit('message', "this is a test"); //sending to sender-client only
socket.broadcast.emit('message', "this is a test"); //sending to all clients except sender
socket.broadcast.to('game').emit('message', 'nice game'); //sending to all clients in 'game' room(channel) except sender
socket.to('game').emit('message', 'enjoy the game'); //sending to sender client, only if they are in 'game' room(channel)
socket.broadcast.to(socketid).emit('message', 'for your eyes only'); //sending to individual socketid
io.emit('message', "this is a test"); //sending to all clients, include sender
io.in('game').emit('message', 'cool game'); //sending to all clients in 'game' room(channel), include sender
io.of('myNamespace').emit('message', 'gg'); //sending to all clients in namespace 'myNamespace', include sender
socket.emit(); //send to all connected clients
socket.broadcast.emit(); //send to all connected clients except the one that sent the message
socket.on(); //event listener, can be called on client to execute on server
io.sockets.socket(); //for emiting to specific clients
io.sockets.emit(); //send to all connected clients (same as socket.emit)
io.sockets.on() ; //initial connection from a client.
Hope this helps.
An Apple way to do this is to use Segues. You need to use the prepareForSegue() function.
There are lots of great tutorials around, and here is one: Unleash Your Inner App Developer Part 21: Passing Data Between Controllers
Also, read up the Apple documentation on using segues: Using Segues
you can use this code for showing or print :
<byte_object>.decode("utf-8")
and you can use this for encode or saving :
<str_object>.encode('utf-8')
You can just use:
> names(LIST)
[1] "A" "B"
Obviously the names of the first element is just
> names(LIST)[1]
[1] "A"
Well, I believe it's an "Old but Gold" question. The answer is: "It depends!". The performances are such a delicate subject that it would be too much silly to say: "Never use subqueries, always join". In the following links, you'll find some basic best practices that I have found to be very helpful:
I have a table with 50000 elements, the result i was looking for was 739 elements.
My query at first was this:
SELECT p.id,
p.fixedId,
p.azienda_id,
p.categoria_id,
p.linea,
p.tipo,
p.nome
FROM prodotto p
WHERE p.azienda_id = 2699 AND p.anno = (
SELECT MAX(p2.anno)
FROM prodotto p2
WHERE p2.fixedId = p.fixedId
)
and it took 7.9s to execute.
My query at last is this:
SELECT p.id,
p.fixedId,
p.azienda_id,
p.categoria_id,
p.linea,
p.tipo,
p.nome
FROM prodotto p
WHERE p.azienda_id = 2699 AND (p.fixedId, p.anno) IN
(
SELECT p2.fixedId, MAX(p2.anno)
FROM prodotto p2
WHERE p.azienda_id = p2.azienda_id
GROUP BY p2.fixedId
)
and it took 0.0256s
Good SQL, good.
Have a look at C++11 Features (Modern C++)
and section "Quick Reference Guide to Visual C++ Version Numbers" ...
An alternative way of getting a feel of solutions provided by netters is to understand a little geometry implications.
Let pqr=[P,Q,R] are points that forms a plane that is divided into 2 sides by line [P,R]. We are to find out if two points on pqr plane, A,B, are on the same side.
Any point T on pqr plane can be represented with 2 vectors: v = P-Q and u = R-Q, as:
T' = T-Q = i * v + j * u
Now the geometry implications:
i+j: <0 0 <1 =1 >1
---------Q------[PR]--------- <== this is PQR plane
^
pr line
In general,
The other geometry significances of i and j (not related to this solution) are:
The value of i,j can be obtained by solving the equations:
i*vx + j*ux = T'x
i*vy + j*uy = T'y
i*vz + j*uz = T'z
So we are given 2 points, A,B on the plane:
A = a1 * v + a2 * u
B = b1 * v + b2 * u
If A,B are on the same side, this will be true:
sign(a1+a2-1) = sign(b1+b2-1)
Note that this applies also to the question: Are A,B in the same side of plane [P,Q,R], in which:
T = i * P + j * Q + k * R
and i+j+k=1 implies that T is on the plane [P,Q,R] and the sign of i+j+k-1 implies its sideness. From this we have:
A = a1 * P + a2 * Q + a3 * R
B = b1 * P + b2 * Q + b3 * R
and A,B are on the same side of plane [P,Q,R] if
sign(a1+a2+a3-1) = sign(b1+b2+b3-1)