For bootstrap 4
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" integrity="sha384-9gVQ4dYFwwWSjIDZnLEWnxCjeSWFphJiwGPXr1jddIhOegiu1FwO5qRGvFXOdJZ4" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.0/umd/popper.min.js" integrity="sha384-cs/chFZiN24E4KMATLdqdvsezGxaGsi4hLGOzlXwp5UZB1LY//20VyM2taTB4QvJ" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js" integrity="sha384-uefMccjFJAIv6A+rW+L4AHf99KvxDjWSu1z9VI8SKNVmz4sk7buKt/6v9KI65qnm" crossorigin="anonymous"></script>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<form class="form-inline my-2 my-lg-0">
<div class="input-group">
<input class="form-control" type="search" placeholder="Search">
<div class="input-group-append">
<div class="input-group-text"><i class="fa fa-search"></i></div>
</div>
</div>
</form>
Go to "Target" -> "Build Phases", select your target, select the “Build Phases” tab, click “Add Build Phase”, and select “Add Copy Files”. Change the destination to “Products Directory”. Drag your file into the “Add files” section.
You can use .closest()
to get up to the current <tr>
parent, like this:
$('input[type=button]' ).click(function() {
var bid = this.id; // button ID
var trid = $(this).closest('tr').attr('id'); // table row ID
});
This work as a charm...
import csv
with open("data.csv", 'r') as f:
data = list(csv.reader(f, delimiter=";"))
import numpy as np
data = np.array(data, dtype=np.float)
In addition to answer by Dinesh Prajapati, Use
adb -d logcat <your package name>:<log level>
where -d is for device and you may also choose -e instead for emulator log and log level is a/d/i/v/e/w etc.
Now your command goes like:
adb -d logcat com.example.example:V > logfileName_WithPath.txt
If you want the biggest pt value for a subject, you could simply use:
pt_max = as.data.frame(aggregate(pt~Subject, group, max))
In general, x
and y
must satisfy (x - center_x)^2 + (y - center_y)^2 < radius^2
.
Please note that points that satisfy the above equation with <
replaced by ==
are considered the points on the circle, and the points that satisfy the above equation with <
replaced by >
are considered the outside the circle.
when you are in El Capitan, will get error: ln: /usr/lib/libmysqlclient.18.dylib: Operation not permitted
need to close the "System Integrity Protection".
first, reboot and hold on cmd + R to enter the Recovery mode, then launch the terminal and type the command: csrutil disable
, now you can reboot and try again.
An interesting collection library is https://github.com/mgesmundo/smart-collection. Allows you to watch arrays and add views to them as well. Not sure about the performance as I am testing it out myself. Will update this post soon.
Update for Swift 3:
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
I do this:
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
let hour = components.hour
let minutes = components.minute
See the same question in objective-c How do I get hour and minutes from NSDate?
Compared to Nate’s answer, you’ll get numbers with this one, not strings… pick your choice!
I think you will want to use ThreadSafeClientConnManager.
You can see how it works here: http://foo.jasonhudgins.com/2009/08/http-connection-reuse-in-android.html
Or in the AndroidHttpClient
which uses it internally.
You can create extension method like:
public static IEnumerable<TResult> LeftOuterJoin<TSource, TInner, TKey, TResult>(this IEnumerable<TSource> source, IEnumerable<TInner> other, Func<TSource, TKey> func, Func<TInner, TKey> innerkey, Func<TSource, TInner, TResult> res)
{
return from f in source
join b in other on func.Invoke(f) equals innerkey.Invoke(b) into g
from result in g.DefaultIfEmpty()
select res.Invoke(f, result);
}
I think you are not configured properly,
if you are using XAMPP then you can easily send mail from localhost.
for example you can configure C:\xampp\php\php.ini
and c:\xampp\sendmail\sendmail.ini
for gmail to send mail.
in C:\xampp\php\php.ini
find extension=php_openssl.dll
and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.
in php.ini file find [mail function]
and change
SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"
(use the above send mail path only and it will work)
Now Open C:\xampp\sendmail\sendmail.ini
. Replace all the existing code in sendmail.ini with following code
[sendmail]
smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]
Now you have done!! create php file with mail function and send mail from localhost.
Update
First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()
).
You can set the following settings in your PHP.ini:
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
"
is shown as \"
in the debugger, but the data is correct in the string, and you don't need to replace anything. Try to dump your string to a file and you will note that the string is correct.
STRING=(one two three four)
echo "${STRING[n]}"
New Note: You probably don't want or need to do this. What you probably want to do is just put those types of command dependencies for build/test etc. in the devDependencies
section of your package.json. Anytime you use something from scripts
in package.json your devDependencies commands (in node_modules/.bin) act as if they are in your path.
For example:
npm i --save-dev mocha # Install test runner locally
npm i --save-dev babel # Install current babel locally
Then in package.json:
// devDependencies has mocha and babel now
"scripts": {
"test": "mocha",
"build": "babel -d lib src",
"prepublish": "babel -d lib src"
}
Then at your command prompt you can run:
npm run build # finds babel
npm test # finds mocha
npm publish # will run babel first
But if you really want to install globally, you can add a preinstall in the scripts section of the package.json:
"scripts": {
"preinstall": "npm i -g themodule"
}
So actually my npm install executes npm install again .. which is weird but seems to work.
Note: you might have issues if you are using the most common setup for npm
where global Node package installs required sudo
. One option is to change your npm
configuration so this isn't necessary:
npm config set prefix ~/npm
, add $HOME/npm/bin to $PATH by appending export PATH=$HOME/npm/bin:$PATH
to your ~/.bashrc
.
Policykit is a system daemon and policykit authentication agent is used to verify identity of the user before executing actions. The messages logged in /var/log/secure
show that an authentication agent is registered when user logs in and it gets unregistered when user logs out. These messages are harmless and can be safely ignored.
No, but you might consider using a set of functions (or macros) to approximate using default args:
// No default args
int foo3(int a, int b, int c)
{
return ...;
}
// Default 3rd arg
int foo2(int a, int b)
{
return foo3(a, b, 0); // default c
}
// Default 2nd and 3rd args
int foo1(int a)
{
return foo3(a, 1, 0); // default b and c
}
This might be impossible or at least very hard. The DLL's contents don't depend (a lot) on it being written in C++; it's all machine code. That code might have been optimized so a lot of information that was present in the original source code is simply gone.
That said, here is one article that goes through a lot of material about doing this.
The following code worked for me.
$('input[name="chkGender[]"]:checked').length;
Solution is to Add common-logging.x.x jar file
Probably the most definitive is Figure B.1(d) of the ggplot2 book, the appendices of which are available at http://ggplot2.org/book/appendices.pdf.
However, it is not quite that simple. hjust
and vjust
as described there are how it works in geom_text
and theme_text
(sometimes). One way to think of it is to think of a box around the text, and where the reference point is in relation to that box, in units relative to the size of the box (and thus different for texts of different size). An hjust
of 0.5 and a vjust
of 0.5 center the box on the reference point. Reducing hjust
moves the box right by an amount of the box width times 0.5-hjust
. Thus when hjust=0
, the left edge of the box is at the reference point. Increasing hjust
moves the box left by an amount of the box width times hjust-0.5
. When hjust=1
, the box is moved half a box width left from centered, which puts the right edge on the reference point. If hjust=2
, the right edge of the box is a box width left of the reference point (center is 2-0.5=1.5
box widths left of the reference point. For vertical, less is up and more is down. This is effectively what that Figure B.1(d) says, but it extrapolates beyond [0,1].
But, sometimes this doesn't work. For example
DF <- data.frame(x=c("a","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()
p + opts(axis.text.x=theme_text(vjust=0))
p + opts(axis.text.x=theme_text(vjust=1))
p + opts(axis.text.x=theme_text(vjust=2))
The three latter plots are identical. I don't know why that is. Also, if text is rotated, then it is more complicated. Consider
p + opts(axis.text.x=theme_text(hjust=0, angle=90))
p + opts(axis.text.x=theme_text(hjust=0.5 angle=90))
p + opts(axis.text.x=theme_text(hjust=1, angle=90))
p + opts(axis.text.x=theme_text(hjust=2, angle=90))
The first has the labels left justified (against the bottom), the second has them centered in some box so their centers line up, and the third has them right justified (so their right sides line up next to the axis). The last one, well, I can't explain in a coherent way. It has something to do with the size of the text, the size of the widest text, and I'm not sure what else.
I had the same issue when my server free disk space available was 0
You can use the command (there must be ample space for the mysql files)
REPAIR TABLE `<table name>`;
for repairing individual tables
Solution works for matplotlib 2.1+
There exists an axes method tick_params
that can change tick properties. It also exists as an axis method as set_tick_params
ax.tick_params(axis='x', rotation=45)
Or
ax.xaxis.set_tick_params(rotation=45)
As a side note, the current solution mixes the stateful interface (using pyplot) with the object-oriented interface by using the command plt.xticks(rotation=70)
. Since the code in the question uses the object-oriented approach, it's best to stick to that approach throughout. The solution does give a good explicit solution with plt.setp( axs[1].xaxis.get_majorticklabels(), rotation=70 )
You might be interested in the SciPy Stats package. It has the percentile function you're after and many other statistical goodies.
percentile()
is available in numpy
too.
import numpy as np
a = np.array([1,2,3,4,5])
p = np.percentile(a, 50) # return 50th percentile, e.g median.
print p
3.0
This ticket leads me to believe they won't be integrating percentile()
into numpy anytime soon.
I have created on time task in which the task which user wants to repeat, add in the Custom TimeTask run() method. it is successfully reoccurring.
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.app.Activity;
import android.content.Intent;
public class MainActivity extends Activity {
CheckBox optSingleShot;
Button btnStart, btnCancel;
TextView textCounter;
Timer timer;
MyTimerTask myTimerTask;
int tobeShown = 0 ;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
optSingleShot = (CheckBox)findViewById(R.id.singleshot);
btnStart = (Button)findViewById(R.id.start);
btnCancel = (Button)findViewById(R.id.cancel);
textCounter = (TextView)findViewById(R.id.counter);
tobeShown = 1;
if(timer != null){
timer.cancel();
}
//re-schedule timer here
//otherwise, IllegalStateException of
//"TimerTask is scheduled already"
//will be thrown
timer = new Timer();
myTimerTask = new MyTimerTask();
if(optSingleShot.isChecked()){
//singleshot delay 1000 ms
timer.schedule(myTimerTask, 1000);
}else{
//delay 1000ms, repeat in 5000ms
timer.schedule(myTimerTask, 1000, 1000);
}
btnStart.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
Intent i = new Intent(MainActivity.this, ActivityB.class);
startActivity(i);
/*if(timer != null){
timer.cancel();
}
//re-schedule timer here
//otherwise, IllegalStateException of
//"TimerTask is scheduled already"
//will be thrown
timer = new Timer();
myTimerTask = new MyTimerTask();
if(optSingleShot.isChecked()){
//singleshot delay 1000 ms
timer.schedule(myTimerTask, 1000);
}else{
//delay 1000ms, repeat in 5000ms
timer.schedule(myTimerTask, 1000, 1000);
}*/
}});
btnCancel.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
if (timer!=null){
timer.cancel();
timer = null;
}
}
});
}
@Override
protected void onResume() {
super.onResume();
if(timer != null){
timer.cancel();
}
//re-schedule timer here
//otherwise, IllegalStateException of
//"TimerTask is scheduled already"
//will be thrown
timer = new Timer();
myTimerTask = new MyTimerTask();
if(optSingleShot.isChecked()){
//singleshot delay 1000 ms
timer.schedule(myTimerTask, 1000);
}else{
//delay 1000ms, repeat in 5000ms
timer.schedule(myTimerTask, 1000, 1000);
}
}
@Override
protected void onPause() {
super.onPause();
if (timer!=null){
timer.cancel();
timer = null;
}
}
@Override
protected void onStop() {
super.onStop();
if (timer!=null){
timer.cancel();
timer = null;
}
}
class MyTimerTask extends TimerTask {
@Override
public void run() {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat simpleDateFormat =
new SimpleDateFormat("dd:MMMM:yyyy HH:mm:ss a");
final String strDate = simpleDateFormat.format(calendar.getTime());
runOnUiThread(new Runnable(){
@Override
public void run() {
textCounter.setText(strDate);
}});
}
}
}
@Html.TextBoxFor(m => m.EntryDate, new{ type = "date" })
or type = "time"
it will display a calendar
it will not work if you give @Html.EditorFor()
How about using name attribute for old browsers and id attribute to the new browsers. Both options will be used and fallback method will be implemented by default!!!
Steps for Window10:
https://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python
mysqlclient-1.4.2-cp37-cp37m-win32.whl
works for python3.7 and Intel CPU.pip install mysqlclient-1.4.2-cp37-cp37m-win32.whl
scrollHeight
is not only buggy, but doesn't work when your container has a hardcoded height (which is probably most cases, since you wanna get contents height without doing container.height()
itself)$('#outer')_x000D_
// Get children in array format, as we'll be reducing them into a single number_x000D_
.contents().toArray()_x000D_
// Filter out text and comment nodes, only allowing tags_x000D_
.filter(el => el.nodeType === 1)_x000D_
// Sum up all the children individual heights_x000D_
.reduce((accumulator, el) => $(el).outerHeight(true) + accumulator, 0);
_x000D_
Of course, this latter alternative only works when #outer
doesn't have immediate text childrens that take up space and you want to measure. Those are my 2 cents.
<div>
of which you can measure easily by doing $('#outer').children().height()
The default matcher for compiling files includes application.js, application.css and all non-JS/CSS files (this will include all image assets automatically) from app/assets folders including your gems:
If you have other manifests or individual stylesheets and JavaScript files to include, you can add them to the precompile array in config/initializers/assets.rb:
Rails.application.config.assets.precompile += ['admin.js', 'admin.css', 'swfObject.js']
http://guides.rubyonrails.org/asset_pipeline.html#precompiling-assets
In Angular2, this can help to get components name:
getName() {
let comp:any = this.constructor;
return comp.name;
}
comp:any is needed because TypeScript compiler will issue errors since Function initially does not have property name.
use .css
in Jquery like $('strong').css('background','red');
$('strong').css('background','red');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<strong> Example_x000D_
</strong>
_x000D_
I just tried doing this on Chrome:
var $sel = $('#sel'); $sel.find('option').hover(function(){$sel.attr('title',$(this).attr('title'));console.log($(this).attr('title'))}, function(){$sel.attr('title','');});
However, the hover enter never fires... So you wouldn't be able to do this at all using the standard select. You could achieve this though through some non standard ways:
I am not sure whether this will help anyone, I started working on a big project with lot of dependencies which threw me the same error. My colleague suggested me to install watchman
using brew and that fixed this problem for me.
brew update
brew install watchman
Edit on 26 June 2019: Github link to watchman
In order to do this your JavaScript file would need to be pre-processed on the server side. Essentially, it would have to become an ASP.NET View of some kind, and script
tags which reference the file would essentially be referencing a controller action which responds with that view.
That sounds like a can of worms you don't want to open.
Since JavaScript is client-side, why not just set the value to some client-side element and have the JavaScript interact with that. It's perhaps an additional step of indirection, but it sounds like much less of a headache than creating a JavaScript view.
Something like this:
<script type="text/javascript">
var someValue = @ViewBag.someValue
</script>
Then the external JavaScript file can reference the someValue
JavaScript variable within the scope of that document.
Or even:
<input type="hidden" id="someValue" value="@ViewBag.someValue" />
Then you can access that hidden input.
Unless you come up with some really slick way to actually make your JavaScript file usable as a view. It's certainly doable, and I can't readily think of any problems you'd have (other than really ugly view code since the view engine will get very confused as to what's JavaScript and what's Razor... so expect a ton of <text>
markup), so if you find a slick way to do it that would be pretty cool, albeit perhaps unintuitive to someone who needs to support the code later.
For Java (not php, not javascript, not anyother):
txt.replaceAll("\\p{javaSpaceChar}{2,}"," ")
You could also use eval()
but JSON.parse()
is safer and easier way, so why would you?
good and works
var yourJsonObject = JSON.parse(json_as_text);
I don't see any reason why would you prefer to use eval
. It only puts your application at risk.
That said - this is also possible.
bad - but also works
var yourJsonObject = eval(json_as_text);
Why is eval
a bad idea?
Consider the following example.
Some third party or user provided JSON string data.
var json = `
[{
"adjacencies": [
{
"nodeTo": function(){
return "delete server files - you have been hacked!";
}(),
"nodeFrom": "graphnode1",
"data": {
"$color": "#557EAA"
}
}
],
"data": {
"$color": "#EBB056",
"$type": "triangle",
"$dim": 9
},
"id": "graphnode1",
"name": "graphnode1"
},{
"adjacencies": [],
"data": {
"$color": "#EBB056",
"$type": "triangle",
"$dim": 9
},
"id": "graphnode2",
"name": "graphnode2"
}]
`;
Your server-side script processes that data.
Using JSON.parse
:
window.onload = function(){
var placeholder = document.getElementById('placeholder1');
placeholder.innerHTML = JSON.parse(json)[0].adjacencies[0].nodeTo;
}
will throw:
Uncaught SyntaxError: Unexpected token u in JSON at position X.
Function will not get executed.
You are safe.
Using eval()
:
window.onload = function(){
var placeholder = document.getElementById('placeholder1');
placeholder.innerHTML = eval(json)[0].adjacencies[0].nodeTo;
}
will execute the function and return the text.
If I replace that harmless function with one that removes files from your website folder you have been hacked. No errors/warnings will get thrown in this example.
You are NOT safe.
I was able to manipulate a JSON text string so it acts as a function which will execute on the server.
eval(JSON)[0].adjacencies[0].nodeTo
expects to process a JSON string but, in reality, we just executed a function on our server.
This could also be prevented if we server-side check all user-provided data before passing it to an eval()
function but why not just use the built-in tool for parsing JSON and avoid all this trouble and danger?
If you're using bootstrap 3 date time picker, try this:
$('.selector').datetimepicker({ maxDate: $.now() });
you must look for something called " dictionary in cursor "
i'm using mysql connector and i have to add this parameter to my cursor , so i can use my columns names instead of index's
db = mysql.connector.connect(
host=db_info['mysql_host'],
user=db_info['mysql_user'],
passwd=db_info['mysql_password'],
database=db_info['mysql_db'])
cur = db.cursor()
cur = db.cursor( buffered=True , dictionary=True)
Check out this page which has an example of how to do it.
You can't remove an element from the basic Java array. Take a look at various Collections and ArrayList instead.
Find out the web server user
open up terminal and type
lsof -i tcp:80
This will show you the user of the web server process Here is an example from a raspberry pi running debian:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
apache2 7478 www-data 3u IPv4 450666 0t0 TCP *:http (LISTEN)
apache2 7664 www-data 3u IPv4 450666 0t0 TCP *:http (LISTEN)
apache2 7794 www-data 3u IPv4 450666 0t0 TCP *:http (LISTEN)
The user is www-data
If you give ownership of the web files to the web server:
chown www-data:www-data -R /opt/lamp/htdocs
And chmod 755 for good measure:
chmod 755 -R /opt/lamp/htdocs
Let me know how you go, maybe you need to use 'sudo' before the command, i.e.
sudo chown www-data:www-data -R /opt/lamp/htdocs
if it doesn't work, please give us the output of:
ls -al /opt/lamp/htdocs
You should make the Builder class as static and also you should make the fields final and have getters to get those values. Don't provide setters to those values. In this way your class will be perfectly immutable.
public class NutritionalFacts {
private final int sodium;
private final int fat;
private final int carbo;
public int getSodium(){
return sodium;
}
public int getFat(){
return fat;
}
public int getCarbo(){
return carbo;
}
public static class Builder {
private int sodium;
private int fat;
private int carbo;
public Builder sodium(int s) {
this.sodium = s;
return this;
}
public Builder fat(int f) {
this.fat = f;
return this;
}
public Builder carbo(int c) {
this.carbo = c;
return this;
}
public NutritionalFacts build() {
return new NutritionalFacts(this);
}
}
private NutritionalFacts(Builder b) {
this.sodium = b.sodium;
this.fat = b.fat;
this.carbo = b.carbo;
}
}
And now you can set the properties as follows:
NutritionalFacts n = new NutritionalFacts.Builder().sodium(10).carbo(15).
fat(5).build();
Similar with @Michael-Neal.
I had named the controller as singular. app/controllers/product_controller.rb
When I renamed it as plural, error solved. app/controllers/products_controller.rb
It's an old question, but I don't see mentioned that, depending on the details, the sharey
option may be able to do all of this for you, instead of digging up axis limits, margins, etc. There's a demo in the docs that shows how to use sharex
, but the same can be done with y-axes.
The viewport is all that matters, but you likely want the entire website to stay darkened even while scrolling. For this, you want to use position:fixed
instead of position:absolute
. Fixed will keep the element static on the screen as you scroll, giving the impression that the entire body is darkened.
Example: http://jsbin.com/okabo3/edit
div.fadeMe {
opacity: 0.5;
background: #000;
width: 100%;
height: 100%;
z-index: 10;
top: 0;
left: 0;
position: fixed;
}
<body>
<div class="fadeMe"></div>
<p>A bunch of content here...</p>
</body>
Use a Linux Live cd/usb and boot an that to be able to directly connect to your wifi hardware or use linux as the main OS with direct access to the wifi card and then use windows as a guest os, I know that this maybe not the ideal way but it will work.
remap
is an option that makes mappings work recursively. By default it is on and I'd recommend you leave it that way. The rest are mapping commands, described below:
:map
and :noremap
are recursive and non-recursive versions of the various mapping commands. For example, if we run:
:map j gg (moves cursor to first line)
:map Q j (moves cursor to first line)
:noremap W j (moves cursor down one line)
Then:
j
will be mapped to gg
.Q
will also be mapped to gg
, because j
will be expanded for the recursive mapping.W
will be mapped to j
(and not to gg
) because j
will not be expanded for the non-recursive mapping.Now remember that Vim is a modal editor. It has a normal mode, visual mode and other modes.
For each of these sets of mappings, there is a mapping that works in normal, visual, select and operator modes (:map
and :noremap
), one that works in normal mode (:nmap
and :nnoremap
), one in visual mode (:vmap
and :vnoremap
) and so on.
For more guidance on this, see:
:help :map
:help :noremap
:help recursive_mapping
:help :map-modes
Your can use either of the following methods.
@Before("execution(* ong.customer.bo.CustomerBo.addCustomer(String))")
public void logBefore1(JoinPoint joinPoint) {
System.out.println(joinPoint.getArgs()[0]);
}
or
@Before("execution(* ong.customer.bo.CustomerBo.addCustomer(String)), && args(inputString)")
public void logBefore2(JoinPoint joinPoint, String inputString) {
System.out.println(inputString);
}
joinpoint.getArgs() returns object array. Since, input is single string, only one object is returned.
In the second approach, the name should be same in expression and input parameter in the advice method i.e. args(inputString)
and public void logBefore2(JoinPoint joinPoint, String inputString)
Here, addCustomer(String)
indicates the method with one String input parameter.
Thinking that manually setting up .gitmodules
is enough is WRONG
My local git version 2.22.0
as of this writing.
So I came to this thread wondering why wasn't git submodule init
working; I setup the .gitmodules
file and proceeded to do git submodule init
...
IMPORTANT
git submodule add company/project.git includes/project
is required (when adding the module for the first time), this will:
.git/config
.gitmodules
fileincludes/project
in this example).you must then git commit
after you have added the submodule, this will commit .gitmodules
and the tracked submodule location.
When the project is cloned again, it will have the .gitmodules
and the empty submodules directory (e.g. includes/project
in this example). At this point .git/config
does not have submodule config yet, until git submodule init
is run, and remember this only works because .gitmodules
AND includes/project
are tracked in the main git repo.
Also for reference see:
You can download the 32bit or 64bit version of "Express With Tools" or "SQL Server Management Studio Express" (SSMSE tools only) from:
This link is for SQL Server 2012 Express Service Pack 1 released 11/09/2012 (11.0.3000.00) The original RTM release was 11.0.2100.60 from March or May of 2012.
For those of you (like me) that wasted too much time from this error:
I had received the same error: "Could not find implementation of query Pattern for source type 'DbSet'" but the solution for me was fixing a mistake at the DbContext level.
When I created my context I had this:
public class ContactContext : DbContext
{
public ContactContext() : base() { }
public DbSet Contacts { get; set; }
}
And my Repository (I was following a Repository pattern in ASP.NET guide) looked like this:
public Contact FindById(int id)
{
var contact = from c in _db.Contacts where c.Id == id select c;
return contact;
}
My issue came from the initial setup of my DbContext, when I used DbSet as a generic instead of the type.
I changed public DbSet Contacts { get; set; }
to public DbSet<Contact> Contacts { get; set; }
and suddenly the query was recognized.
This is probably what k.m says in his answer, but since he mentioned IEnumerable<t>
and not DbSet<<YourDomainObject>>
I had to dig around in the code for a couple hours to find the line that caused this headache.
You can't call a constructor as if it was a normal method, you can only call it with new
to create a new object:
Kid newKid = new Kid(this.name, this.height, this.bDay);
But constructing a new object from your toString() method is not what you want to be doing.
In general, I use nohup CMD &
to run a nohup background process. However, when the command is in a form that nohup
won't accept then I run it through bash -c "..."
.
For example:
nohup bash -c "(time ./script arg1 arg2 > script.out) &> time_n_err.out" &
stdout from the script gets written to script.out
, while stderr and the output of time
goes into time_n_err.out
.
So, in your case:
nohup bash -c "(time bash executeScript 1 input fileOutput > scrOutput) &> timeUse.txt" &
git remote rm origin
git remote -v
It will not display any repository name
git remote add origin [email protected]:username/myapp.git
git push origin master
It will start the process and creating the new branch.
You can see your work is pushed to github.
in HTML:
<a class="main-item" (click)="onNavigate()">Go to URL</a>
OR
<button class="main-item" (click)="onNavigate()">Go to URL</button>
in TS file:
onNavigate(){
// your logic here.... like set the url
const url = 'https://www.google.com';
window.open(url, '_blank');
}
int x = 3;
if(ceil(x) == x) {
System.out.println("x is an integer");
} else {
System.out.println("x is not an integer");
}
I've put this answer on a similar question that was marked as a duplicate of this question. The answer has helped a decent amount of people so I thought I'd add it here too in just in case.
This doesn't exactly answer the question but for anyone using AngularJS trying to achieve this, the answer is slightly different. And actually the normal answer won't work (at least it didn't for me).
Your html will look pretty similar to the normal radio button:
<input type='radio' name='group' ng-model='mValue' value='first' />First
<input type='radio' name='group' ng-model='mValue' value='second' /> Second
In your controller you'll have declared the mValue
that is associated with the radio buttons. To have one of these radio buttons preselected, assign the $scope
variable associated with the group to the desired input's value:
$scope.mValue="second"
This makes the "second" radio button selected on loading the page.
Define an interface, and implement it in the class that will receive the callback.
Have attention to the multi-threading in your case.
Code example from http://cleancodedevelopment-qualityseal.blogspot.com.br/2012/10/understanding-callbacks-with-java.html
interface CallBack { //declare an interface with the callback methods, so you can use on more than one class and just refer to the interface
void methodToCallBack();
}
class CallBackImpl implements CallBack { //class that implements the method to callback defined in the interface
public void methodToCallBack() {
System.out.println("I've been called back");
}
}
class Caller {
public void register(CallBack callback) {
callback.methodToCallBack();
}
public static void main(String[] args) {
Caller caller = new Caller();
CallBack callBack = new CallBackImpl(); //because of the interface, the type is Callback even thought the new instance is the CallBackImpl class. This alows to pass different types of classes that have the implementation of CallBack interface
caller.register(callBack);
}
}
In your case, apart from multi-threading you could do like this:
interface ServerInterface {
void newSeverConnection(Socket socket);
}
public class Server implements ServerInterface {
public Server(int _address) {
System.out.println("Starting Server...");
serverConnectionHandler = new ServerConnections(_address, this);
workers.execute(serverConnectionHandler);
System.out.println("Do something else...");
}
void newServerConnection(Socket socket) {
System.out.println("A function of my child class was called.");
}
}
public class ServerConnections implements Runnable {
private ServerInterface serverInterface;
public ServerConnections(int _serverPort, ServerInterface _serverInterface) {
serverPort = _serverPort;
serverInterface = _serverInterface;
}
@Override
public void run() {
System.out.println("Starting Server Thread...");
if (serverInterface == null) {
System.out.println("Server Thread error: callback null");
}
try {
mainSocket = new ServerSocket(serverPort);
while (true) {
serverInterface.newServerConnection(mainSocket.accept());
}
} catch (IOException ex) {
Logger.getLogger(Server.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
Multi-threading
Remember this does not handle multi-threading, this is another topic and can have various solutions depending on the project.
The observer-pattern
The observer-pattern does nearly this, the major difference is the use of an ArrayList
for adding more than one listener. Where this is not needed, you get better performance with one reference.
I think the best way is to compare with blank string
BenchmarkStringCheck1 is checking with blank string
BenchmarkStringCheck2 is checking with len zero
I check with the empty and non-empty string checking. You can see that checking with a blank string is faster.
BenchmarkStringCheck1-4 2000000000 0.29 ns/op 0 B/op 0 allocs/op
BenchmarkStringCheck1-4 2000000000 0.30 ns/op 0 B/op 0 allocs/op
BenchmarkStringCheck2-4 2000000000 0.30 ns/op 0 B/op 0 allocs/op
BenchmarkStringCheck2-4 2000000000 0.31 ns/op 0 B/op 0 allocs/op
Code
func BenchmarkStringCheck1(b *testing.B) {
s := "Hello"
b.ResetTimer()
for n := 0; n < b.N; n++ {
if s == "" {
}
}
}
func BenchmarkStringCheck2(b *testing.B) {
s := "Hello"
b.ResetTimer()
for n := 0; n < b.N; n++ {
if len(s) == 0 {
}
}
}
strtok allows you to pass in multiple chars as delimiters. I bet if you passed in ">=" your example string would be split correctly (even though the > and = are counted as individual delimiters).
EDIT if you don't want to use c_str()
to convert from string to char*, you can use substr and find_first_of to tokenize.
string token, mystring("scott>=tiger");
while(token != mystring){
token = mystring.substr(0,mystring.find_first_of(">="));
mystring = mystring.substr(mystring.find_first_of(">=") + 1);
printf("%s ",token.c_str());
}
Yes, according to iTunes Connect Export Compliance Information screens, if you use built-in iOS or MacOS encryption (keychain, https), you are using encryption for purposes of US Government Export regulations. Whether you qualify for an export compliance exemption depends on what your app does and how it uses this encryption. Attached images show the iTunes Connect Export Compliance Screens to help you determine your export reporting obligations. In particular, it states:
If you are making use of ATS or making a call to HTTPS please note that you are required to submit a year-end self classification report to the US government. Learn more
The %#08X
conversion must precede the value with 0X
; that is required by the standard. There's no evidence in the standard that the #
should alter the behaviour of the 08
part of the specification except that the 0X
prefix is counted as part of the length (so you might want/need to use %#010X
. If, like me, you like your hex presented as 0x1234CDEF
, then you have to use 0x%08X
to achieve the desired result. You could use %#.8X
and that should also insert the leading zeroes.
Try variations on the following code:
#include <stdio.h>
int main(void)
{
int j = 0;
printf("0x%.8X = %#08X = %#.8X = %#010x\n", j, j, j, j);
for (int i = 0; i < 8; i++)
{
j = (j << 4) | (i + 6);
printf("0x%.8X = %#08X = %#.8X = %#010x\n", j, j, j, j);
}
return(0);
}
On an RHEL 5 machine, and also on Mac OS X (10.7.5), the output was:
0x00000000 = 00000000 = 00000000 = 0000000000
0x00000006 = 0X000006 = 0X00000006 = 0x00000006
0x00000067 = 0X000067 = 0X00000067 = 0x00000067
0x00000678 = 0X000678 = 0X00000678 = 0x00000678
0x00006789 = 0X006789 = 0X00006789 = 0x00006789
0x0006789A = 0X06789A = 0X0006789A = 0x0006789a
0x006789AB = 0X6789AB = 0X006789AB = 0x006789ab
0x06789ABC = 0X6789ABC = 0X06789ABC = 0x06789abc
0x6789ABCD = 0X6789ABCD = 0X6789ABCD = 0x6789abcd
I'm a little surprised at the treatment of 0; I'm not clear why the 0X
prefix is omitted, but with two separate systems doing it, it must be standard. It confirms my prejudices against the #
option.
The treatment of zero is according to the standard.
ISO/IEC 9899:2011 §7.21.6.1 The
fprintf
function¶6 The flag characters and their meanings are:
...
#
The result is converted to an "alternative form". ... Forx
(orX
) conversion, a nonzero result has0x
(or0X
) prefixed to it. ...
(Emphasis added.)
Note that using %#X
will use upper-case letters for the hex digits and 0X
as the prefix; using %#x
will use lower-case letters for the hex digits and 0x
as the prefix. If you prefer 0x
as the prefix and upper-case letters, you have to code the 0x
separately: 0x%X
. Other format modifiers can be added as needed, of course.
For printing addresses, use the <inttypes.h>
header and the uintptr_t
type and the PRIXPTR
format macro:
#include <inttypes.h>
#include <stdio.h>
int main(void)
{
void *address = &address; // &address has type void ** but it converts to void *
printf("Address 0x%.12" PRIXPTR "\n", (uintptr_t)address);
return 0;
}
Example output:
Address 0x7FFEE5B29428
Choose your poison on the length — I find that a precision of 12 works well for addresses on a Mac running macOS. Combined with the .
to specify the minimum precision (digits), it formats addresses reliably. If you set the precision to 16, the extra 4 digits are always 0 in my experience on the Mac, but there's certainly a case to be made for using 16 instead of 12 in portable 64-bit code (but you'd use 8 for 32-bit code).
ROW_NUMBER()
returns a unique number for each row starting with 1. You can easily use this by simply writing:
ROW_NUMBER() OVER (ORDER BY 'Column_Name' DESC) as ROW_NUMBER
If you image is in document directory, Add this URL extension:
extension URL {
func compressedImageURL(quality: CGFloat = 0.3) throws -> URL? {
let imageData = try Data(contentsOf: self)
debugPrint("Image file size before compression: \(imageData.count) bytes")
let compressedURL = NSURL.fileURL(withPath: NSTemporaryDirectory() + NSUUID().uuidString + ".jpg")
guard let actualImage = UIImage(data: imageData) else { return nil }
guard let compressedImageData = UIImageJPEGRepresentation(actualImage, quality) else {
return nil
}
debugPrint("Image file size after compression: \(compressedImageData.count) bytes")
do {
try compressedImageData.write(to: compressedURL)
return compressedURL
} catch {
return nil
}
}
}
Usage:
guard let localImageURL = URL(string: "< LocalImagePath.jpg >") else {
return
}
//Here you will get URL of compressed image
guard let compressedImageURL = try localImageURL.compressedImageURL() else {
return
}
debugPrint("compressedImageURL: \(compressedImageURL.absoluteString)")
Note:- Change < LocalImagePath.jpg > with your local jpg image path.
You need to use anchors to match the beginning of the string ^
and the end of the string $
^[0-9]{2}$
Remove from File > File Structure > Dependencies > - button. Then if it is stull there you can remove the module by going to the settings.gradle file and removing it from the include line.
For more clarity refer below image
For me in PgAdmin 4 on Mac OS High Sierra, Clicking the PostrgreSQL10 database under Servers in the left column, then the Properties tab, showed 5433 as the port under Connection. (I don't know why, because I chose 5432 during install). Anyway, I clicked the Edit icon under the Properties tab, change that to 5432, saved, and that solved the problem. Go figure.
<style>
body{
max-width: 1180px;
width: 98%;
margin: 0px auto;
text-align: left;
}
</style>
Just apply this style before applying any CSS. You can change width as per your need.
I had the same problem. Make sure you include assembly name in Factory
property in your .svc
file. Maybe you need to clean IIS cache if you had renamed project assembly name.
MessageBox.Show(
"your message",
"window title",
MessageBoxButtons.OK,
MessageBoxIcon.Asterisk //For Info Asterisk
MessageBoxIcon.Exclamation //For triangle Warning
)
Social.class.getSimpleName()
getSimpleName() : Returns the simple name of the underlying class as given in the source code. Returns an empty string if the underlying class is anonymous. The simple name of an array is the simple name of the component type with "[]" appended. In particular the simple name of an array whose component type is anonymous is "[]".
Passable for getting multiple values with scanf()
int r,m,v,i,e,k;
scanf("%d%d%d%d%d%d",&r,&m,&v,&i,&e,&k);
I know this is an old topic. I had the same problem. I tested all the answers about this topic. And nothing worked here... but i found another solution.
Go to pom->overview and add these to you properties:
and
Now do a maven update.
The accepted answer was correct up until July 2011. To get the latest version, including the Service Pack you should find the latest version as described here:
For example, if you check the SP2 CTP and SP1, you'll find the latest version of SQL Server Management Studio under SP1:
Download the 32-bit (x86) or 64-bit (x64) version of the SQLManagementStudio*.exe files as appropriate and install it. You can find out whether your system is 32-bit or 64-bit by right clicking Computer, selecting Properties and looking at the System Type.
Although you could apply the service pack to the base version that results from following the accepted answer, it's easier to just download the latest version of SQL Server Management Studio and simply install it in one step.
"john f. kennedy".replace(/\b\S/g, t => t.toUpperCase())
right click on console.. click save as.. its this simple.. you'll get an output text file
The return
statement exits a function from anywhere within the function:
function something(x)
{
if (x >= 10)
// this leaves the function if x is at least 10.
return;
// this message displays only if x is less than 10.
alert ("x is less than 10!");
}
Eclipse 3.5 has an option to package required libraries into the runnable jar. File -> Export... Choose runnable jar and click next. The runnable jar export window has a radio button where you can choose to package the required libraries into the jar.
the field=value
syntax in queries is a shorthand for field__exact=value
. That is to say that Django puts query operators on query fields in the identifiers. Django supports the following operators:
exact
iexact
contains
icontains
in
gt
gte
lt
lte
startswith
istartswith
endswith
iendswith
range
date
year
iso_year
month
day
week
week_day
iso_week_day
quarter
time
hour
minute
second
isnull
regex
iregex
I'm sure by combining these with the Q objects as Dave Vogt suggests and using filter()
or exclude()
as Jason Baker suggests you'll get exactly what you need for just about any possible query.
Same issue with mine.
New to Flutter. I'm using VS build-in terminal to do flutter run
, to run the app in iPhone. It gives me error Error when reading 'lib/student_model.dart': No such file...
, which is an old code version in my code. I have changed it to lib/model/student_model.dart
.
And I search this line 'lib/student_model.dart'in the project, it appears file
kernel_snapshot.d` containing it. So, it build the project with old code version.
For me, Flutter clean
is not working. Restart VS fix the issue, not sure the problem is due to Flutter or VS?
And I'm wondering if there is some command to just build flutter project without run?
a) the method/function only reads the array argument => implicit (internal) reference
b) the method/function modifies the array argument => value
c) the method/function array argument is explicitly marked as a reference (with an ampersand) => explicit (user-land) reference
Or this:
- non-ampersand array param: passed by reference; the writing operations alter a new copy of the array, copy which is created on the first write;
- ampersand array param: passed by reference; the writing operations alter the original array.
Remember - PHP does a value-copy the moment you write to the non-ampersand array param. That's what copy-on-write
means. I'd love to show you the C source of this behaviour, but it's scary in there. Better use xdebug_debug_zval().
Pascal MARTIN was right. Kosta Kontos was even more so.
It depends.
I think I'm writing this down for myself. I should have a blog or something...
Whenever people talk of references (or pointers, for that matter), they usually end up in a logomachy (just look at this thread!).
PHP being a venerable language, I thought I should add up to the confusion (even though this a summary of the above answers). Because, although two people can be right at the same time, you're better off just cracking their heads together into one answer.
First off, you should know that you're not a pedant if you don't answer in a black-and-white manner. Things are more complicated than "yes/no".
As you will see, the whole by-value/by-reference thing is very much related to what exactly are you doing with that array in your method/function scope: reading it or modifying it?
The manual says this (emphasis mine):
By default, function arguments are passed by value (so that if the value of the argument within the function is changed, it does not get changed outside of the function). To allow a function to modify its arguments, they must be passed by reference.
To have an argument to a function always passed by reference, prepend an ampersand (&) to the argument name in the function definition
As far as I can tell, when big, serious, honest-to-God programmers talk about references, they usually talk about altering the value of that reference. And that's exactly what the manual talks about: hey, if you want to CHANGE the value in a function, consider that PHP's doing "pass-by-value"
.
There's another case that they don't mention, though: what if I don't change anything - just read?
What if you pass an array to a method which doesn't explicitly marks a reference, and we don't change that array in the function scope? E.g.:
<?php
function readAndDoStuffWithAnArray($array)
{
return $array[0] + $array[1] + $array[2];
}
$x = array(1, 2, 3);
echo readAndDoStuffWithAnArray($x);
Read on, my fellow traveller.
The same big and serious programmers, when they get even more serious, they talk about "memory optimizations" in regards to references. So does PHP. Because PHP is a dynamic, loosely typed language, that uses copy-on-write and reference counting
, that's why.
It wouldn't be ideal to pass HUGE arrays to various functions, and PHP to make copies of them (that's what "pass-by-value" does, after all):
<?php
// filling an array with 10000 elements of int 1
// let's say it grabs 3 mb from your RAM
$x = array_fill(0, 10000, 1);
// pass by value, right? RIGHT?
function readArray($arr) { // <-- a new symbol (variable) gets created here
echo count($arr); // let's just read the array
}
readArray($x);
Well now, if this actually was pass-by-value, we'd have some 3mb+ RAM gone, because there are two copies of that array, right?
Wrong. As long as we don't change the $arr
variable, that's a reference, memory-wise. You just don't see it. That's why PHP mentions user-land references when talking about &$someVar
, to distinguish between internal and explicit (with ampersand) ones.
So, when an array is passed as an argument to a method or function is it passed by reference?
I came up with three (yeah, three) cases:
a) the method/function only reads the array argument
b) the method/function modifies the array argument
c) the method/function array argument is explicitly marked as a reference (with an ampersand)
Firstly, let's see how much memory that array actually eats (run here):
<?php
$start_memory = memory_get_usage();
$x = array_fill(0, 10000, 1);
echo memory_get_usage() - $start_memory; // 1331840
That many bytes. Great.
Now let's make a function which only reads the said array as an argument and we'll see how much memory the reading logic takes:
<?php
function printUsedMemory($arr)
{
$start_memory = memory_get_usage();
count($arr); // read
$x = $arr[0]; // read (+ minor assignment)
$arr[0] - $arr[1]; // read
echo memory_get_usage() - $start_memory; // let's see the memory used whilst reading
}
$x = array_fill(0, 10000, 1); // this is 1331840 bytes
printUsedMemory($x);
Wanna guess? I get 80! See for yourself. This is the part that the PHP manual omits. If the $arr
param was actually passed-by-value, you'd see something similar to 1331840
bytes. It seems that $arr
behaves like a reference, doesn't it? That's because it is a references - an internal one.
Now, let's write to that param, instead of reading from it:
<?php
function printUsedMemory($arr)
{
$start_memory = memory_get_usage();
$arr[0] = 1; // WRITE!
echo memory_get_usage() - $start_memory; // let's see the memory used whilst reading
}
$x = array_fill(0, 10000, 1);
printUsedMemory($x);
Again, see for yourself, but, for me, that's pretty close to being 1331840. So in this case, the array is actually being copied to $arr
.
Now let's see how much memory a write operation to an explicit reference takes (run here) - note the ampersand in the function signature:
<?php
function printUsedMemory(&$arr) // <----- explicit, user-land, pass-by-reference
{
$start_memory = memory_get_usage();
$arr[0] = 1; // WRITE!
echo memory_get_usage() - $start_memory; // let's see the memory used whilst reading
}
$x = array_fill(0, 10000, 1);
printUsedMemory($x);
My bet is that you get 200 max! So this eats approximately as much memory as reading from a non-ampersand param.
According to this blog post, this function should do it:
String.prototype.splitCSV = function(sep) {
for (var foo = this.split(sep = sep || ","), x = foo.length - 1, tl; x >= 0; x--) {
if (foo[x].replace(/'\s+$/, "'").charAt(foo[x].length - 1) == "'") {
if ((tl = foo[x].replace(/^\s+'/, "'")).length > 1 && tl.charAt(0) == "'") {
foo[x] = foo[x].replace(/^\s*'|'\s*$/g, '').replace(/''/g, "'");
} else if (x) {
foo.splice(x - 1, 2, [foo[x - 1], foo[x]].join(sep));
} else foo = foo.shift().split(sep).concat(foo);
} else foo[x].replace(/''/g, "'");
} return foo;
};
You would call it like so:
var string = "'string, duppi, du', 23, lala";
var parsed = string.splitCSV();
alert(parsed.join("|"));
This jsfiddle kind of works, but it looks like some of the elements have spaces before them.
It looks like you can say
Convert.ToInt64(value, 16)
to get the decimal from hexdecimal.
The other way around is:
otherVar.ToString("X");
Well, the <head>
tag has nothing to do with the <header>
tag. In the head
comes all the metadata and stuff, while the header
is just a layout component.
And layout comes into body
. So I disagree with you.
Using float does not work.
DECLARE @t1 datetime, @t2 datetime
SELECT @t1 = '19000101 23:55:00', @t2 = '20001102 23:55:00'
SELECT CAST(@t1 as float) - floor(CAST(@t1 as float)), CAST(@t2 as float) - floor(CAST(@t2 as float))
You'll see that the values are not the same (SQL Server 2005). I wanted to use this method to check for times around midnight (the full method has more detail) in which I was comparing the current time for being between 23:55:00 and 00:05:00.
PS> I posted this answer on a related question. Here's how I got round the issue of my async ajax request losing the trusted context:
I opened the popup directly on the users click, directed the url to about:blank
and got a handle on that window. You could probably direct the popup to a 'loading' url while your ajax request is made
var myWindow = window.open("about:blank",'name','height=500,width=550');
Then, when my request is successful, I open my callback url in the window
function showWindow(win, url) {
win.open(url,'name','height=500,width=550');
}
I had a similar problem getting scrollTop to work after reload of div content. The content scrolled to top each time the procedure below was run. I found that a little delay before setting the new scrolltop solved the issue.
This is cut from wdCalendar where I modified this procedure:
function BuildDaysAndWeekView(startday, l, events, config)
....
var scrollpos = $("#dvtec").scrollTop();
gridcontainer.html(html.join(""));
setTimeout(function() {
$("#dvtec").scrollTop(scrollpos);
}, 25);
....
Without the delay, it simply did not work.
.c : 'C' source code
.h : Header file
Usually, the .c
files contain the implementation, and .h
files contain the "interface" of an implementation.
While I understand that this is not a major differentiating factor, I noticed today that StringBuffer(and StringBuilder) provides some interesting methods that String doesn't.
INSERT INTO target( userid, rightid, count )
SELECT userid, rightid, count
FROM batch
WHERE NOT EXISTS (
SELECT * FROM target t2, batch b2
WHERE t2.userid = b2.userid
-- ... other keyfields ...
)
;
BTW: if you want the whole batch to fail in case of a duplicate, then (given a primary key constraint)
INSERT INTO target( userid, rightid, count )
SELECT userid, rightid, count
FROM batch
;
will do exactly what you want: either it succeeds, or it fails.
In ASP.NET web api 2 , CORS support has been added . Please check the link [ http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api ]
cURL is a way you can hit a URL from your code to get a html response from it. cURL means client URL which allows you to connect with other URLs and use their responses in your code.
To get the value of a pointer, just de-reference the pointer.
int *ptr;
int value;
*ptr = 9;
value = *ptr;
value is now 9.
I suggest you read more about pointers, this is their base functionality.
The following simply returns 4 as an answer. When you replace the add expressions for strings it returns the first string.
Function StartingMain {
$a = 1 + 3
$b = 2 + 5
$c = 3 + 7
Return $a
}
Function StartingEnd($b) {
Write-Host $b
}
StartingEnd(StartingMain)
This can also be done for an array. The example below will return "Text 2"
Function StartingMain {
$a = ,@("Text 1","Text 2","Text 3")
Return $a
}
Function StartingEnd($b) {
Write-Host $b[1]
}
StartingEnd(StartingMain)
Note that you have to call the function below the function itself. Otherwise, the first time it runs it will return an error that it doesn't know what "StartingMain" is.
If you have python installed you could try:
python -c 'import sys;f=open(sys.argv[1]);print len(f.readline().split("|"))' \
stores.dat
The Log class:
API for sending log output.
Generally, use the
Log.v()
Log.d()
Log.i()
Log.w()
andLog.e()
methods.The order in terms of verbosity, from least to most is
ERROR
,WARN
,INFO
,DEBUG
,VERBOSE
. Verbose should never be compiled into an application except during development. Debug logs are compiled in but stripped at runtime. Error, warning and info logs are always kept.
Outside of Android, System.out.println(String msg)
is used.
Here's what's usually sufficient for me:
I create a serialization mixin which I use with my models. The serialization function basically fetches whatever attributes the SQLAlchemy inspector exposes and puts it in a dict.
from sqlalchemy.inspection import inspect
class Serializer(object):
def serialize(self):
return {c: getattr(self, c) for c in inspect(self).attrs.keys()}
@staticmethod
def serialize_list(l):
return [m.serialize() for m in l]
All that's needed now is to extend the SQLAlchemy model with the Serializer
mixin class.
If there are fields you do not wish to expose, or that need special formatting, simply override the serialize()
function in the model subclass.
class User(db.Model, Serializer):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String)
password = db.Column(db.String)
# ...
def serialize(self):
d = Serializer.serialize(self)
del d['password']
return d
In your controllers, all you have to do is to call the serialize()
function (or serialize_list(l)
if the query results in a list) on the results:
def get_user(id):
user = User.query.get(id)
return json.dumps(user.serialize())
def get_users():
users = User.query.all()
return json.dumps(User.serialize_list(users))
IT returns number of objects are updated in table.
update_counts = ModelClass.objects.filter(name='bar').update(name="foo")
You can refer this link to get more information on bulk update and create. Bulk update and Create
Error:(30, 13) Failed to resolve: com.google.firebase:firebase-auth:9.6.1
If you ever get this error and you are using Android studio 2.2 that comes with firebase component integrated in it which has libraries version 9.6.0 by default and you are adding the latest dependencies like 9.6.1 . You might need to downgrade com.google.firebase:firebase-auth:9.6.1
to com.google.firebase:firebase-auth:9.6.0
Or check the library version of your pre-installed firebase and make sure it is of the same version with the new library you are trying to add or added to your project.
Actually I had used (what else ;-) ) Vim for this: it has a 2html "plugin". See the docs here.
So as I edit my code, I just convert it to HTML and paste the results to Blogger's HTML editor.
Note: it's not so beautiful HTML (embeded css would be better), but it just works.
Oh: and it has syntax files for several languages which makes it pretty useful.
I've had success forcing the view to be ordered using
SELECT TOP 9999999 ... ORDER BY something
Unfortunately using SELECT TOP 100 PERCENT
does not work due the issue here.
check it
const mq = window.matchMedia( "(min-width: 500px)" );
if (mq.matches) {
// window width is at least 500px
} else {
// window width is less than 500px
}
https://developer.mozilla.org/en-US/docs/Web/API/Window/matchMedia
These are much much better references than w3schools (the most awful web reference ever made):
Examples derived from these references:
// sets the cookie cookie1
document.cookie = 'cookie1=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'
// sets the cookie cookie2 (cookie1 is *not* overwritten)
document.cookie = 'cookie2=test; expires=Sun, 1 Jan 2023 00:00:00 UTC; path=/'
// remove cookie2
document.cookie = 'cookie2=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/'
The Mozilla reference even has a nice cookie library you can use.
You can do it with 2 ways. In template and in Controller. In template you can set your filtered array to another variable, then use it like you want. Here is how to do it:
<ul>
<li data-ng-repeat="user in usersList = (users | gender:filterGender)" data-ng-bind="user.name"></li>
</ul>
....
<span>{{ usersList.length | number }}</span>
If you need examples, see the AngularJs filtered count examples/demos
So I know this is a rapidly changing field but (as of 2015-09-08) I found the following in the Docker Registry HTTP API V2:
GET /v2/_catalog
GET /v2/<name>/tags/list
Based on that the following worked for me on a local registry (registry:2 IMAGE ID 1e847b14150e365a95d76a9cc6b71cd67ca89905e3a0400fa44381ecf00890e1 created on 2015-08-25T07:55:17.072):
$ curl -X GET http://localhost:5000/v2/_catalog
{"repositories":["ubuntu"]}
$ curl -X GET http://localhost:5000/v2/ubuntu/tags/list
{"name":"ubuntu","tags":["latest"]}
Use grep to match any line that has nothing between the start anchor (^
) and the end anchor ($
):
grep -v '^$' infile.txt > outfile.txt
If you want to remove lines with only whitespace, you can still use grep. I am using Perl regular expressions in this example, but here are other ways:
grep -P -v '^\s*$' infile.txt > outfile.txt
or, without Perl regular expressions:
grep -v '^[[:space:]]*$' infile.txt > outfile.txt
Dependency Walker tells all(well almost). http://www.dependencywalker.com/
It does not "install" -just get it, extract it and run the exec. It works for any x32 or x64 windows module|application.
As I recall it is fairly straightforward to see all dependencies, i.e. the dll modules, and since the appl. is a sum of the dependencies one can ascertain if it is full x64, x32(x86) or a bit of each.
Type of CPU that the module was built for is in the "CPU" column. Most 64-bit aps are still a bit of each but 32-bit ap w/b all x86.
Beautiful program for geeks/programmers and it is free...
3rd approach is most common way to share data between components. you may inject the item service which you want to use in related component.
import { Injectable } from '@angular/core';
import { Predicate } from '../interfaces'
import * as _ from 'lodash';
@Injectable()
export class ItemsService {
constructor() { }
removeItemFromArray<T>(array: Array<T>, item: any) {
_.remove(array, function (current) {
//console.log(current);
return JSON.stringify(current) === JSON.stringify(item);
});
}
removeItems<T>(array: Array<T>, predicate: Predicate<T>) {
_.remove(array, predicate);
}
setItem<T>(array: Array<T>, predicate: Predicate<T>, item: T) {
var _oldItem = _.find(array, predicate);
if(_oldItem){
var index = _.indexOf(array, _oldItem);
array.splice(index, 1, item);
} else {
array.push(item);
}
}
addItemToStart<T>(array: Array<T>, item: any) {
array.splice(0, 0, item);
}
getPropertyValues<T, R>(array: Array<T>, property : string) : R
{
var result = _.map(array, property);
return <R><any>result;
}
getSerialized<T>(arg: any): T {
return <T>JSON.parse(JSON.stringify(arg));
}
}
export interface Predicate<T> {
(item: T): boolean
}
.container {
display: inline-block;
padding: 5px; /*included padding to see background when img apacity is 100%*/
background-color: black;
opacity: 1;
}
.container:hover {
background-color: red;
}
img {
opacity: 1;
}
img:hover {
opacity: 0.7;
}
.transition {
transition: all .25s ease-in-out;
-moz-transition: all .25s ease-in-out;
-webkit-transition: all .25s ease-in-out;
}
None of these solutions worked for me. I needed to know the server port while constructing a Swagger configuration bean. Using ServerProperties worked for me:
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import javax.ws.rs.ApplicationPath;
import io.swagger.jaxrs.config.BeanConfig;
import io.swagger.jaxrs.listing.ApiListingResource;
import io.swagger.jaxrs.listing.SwaggerSerializers;
import org.glassfish.jersey.server.ResourceConfig;
import org.springframework.stereotype.Component;
@Component
@ApplicationPath("api")
public class JerseyConfig extends ResourceConfig
{
@Inject
private org.springframework.boot.autoconfigure.web.ServerProperties serverProperties;
public JerseyConfig()
{
property(org.glassfish.jersey.server.ServerProperties.BV_SEND_ERROR_IN_RESPONSE, true);
}
@PostConstruct
protected void postConstruct()
{
// register application endpoints
registerAndConfigureSwaggerUi();
}
private void registerAndConfigureSwaggerUi()
{
register(ApiListingResource.class);
register(SwaggerSerializers.class);
final BeanConfig config = new BeanConfig();
// set other properties
config.setHost("localhost:" + serverProperties.getPort()); // gets server.port from application.properties file
}
}
This example uses Spring Boot auto configuration and JAX-RS (not Spring MVC).
Try nerfing the local source declaration in your @font-face
directives.
There's a known bug in either Firefox or the Google Font API that prevents the variants of fonts to be used if the font is installed locally, and matches the defined local name:
http://code.google.com/p/googlefontdirectory/issues/detail?id=13
To effectively nerf the local declaration, just make your local source string some nonsense. The generally accepted convention for this is to use a the smiley unicode character ("?"
). Why? Paul Irish has a great explanation up on his blog:
Okay, most things should be clear so far... the tricky part is the SQL: if it is not in reality running in another thread or process in it’s entirety, the SQL-execution has to be broken down into individual steps (by an SQL processor made for asynchronous execution!), where the non-blocking ones are executed, and the blocking ones (e.g. the sleep) actually can be transferred to the kernel (as an alarm interrupt/event) and put on the event list for the main loop.
That means, e.g. the interpretation of the SQL, etc. is done immediately, but during the wait (stored as an event to come in the future by the kernel in some kqueue, epoll, ... structure; together with the other IO operations) the main loop can do other things and eventually check if something happened of those IOs and waits.
So, to rephrase it again: the program is never (allowed to get) stuck, sleeping calls are never executed. Their duty is done by the kernel (write something, wait for something to come over the network, waiting for time to elapse) or another thread or process. – The Node process checks if at least one of those duties is finished by the kernel in the only blocking call to the OS once in each event-loop-cycle. That point is reached, when everything non-blocking is done.
Clear? :-)
I don’t know Node. But where does the c.query come from?
Clear your cache and your website will be work well.
Here's a more recent and in depth analysis of Appcelerator and PhoneGap: http://savagelook.com/blog/portfolio/a-deeper-look-at-appcelerator-and-phonegap
And here's even more detail on how they differ programmatically: http://savagelook.com/blog/portfolio/phonegap-is-web-based-appcelerator-is-pure-javascript
Stored Procedure.........
CREATE PROCEDURE usp_InsertContract
@ContractNumber varchar(7)
AS
BEGIN
INSERT into [dbo].[Contracts] (ContractNumber)
VALUES (@ContractNumber)
SELECT SCOPE_IDENTITY() AS [SCOPE_IDENTITY]
END
C#
pvCommand.CommandType = CommandType.StoredProcedure;
pvCommand.Parameters.Clear();
pvCommand.Parameters.Add(new SqlParameter("@ContractNumber", contractNumber));
object uniqueId;
int id;
try
{
uniqueId = pvCommand.ExecuteScalar();
id = Convert.ToInt32(uniqueId);
}
catch (Exception e)
{
Debug.Print(" Message: {0}", e.Message);
}
}
EDIT: "I still get back a DBNull value....Object cannot be cast from DBNull to other types. I'll take this up again tomorrow. I'm off to my other job,"
I believe the Id column in your SQL Table isn't a identity column.
Update: This answer has led to the development of ng2-completer
an Angular2 autocomplete component.
This is the list of existing autocomplete components for Angular2:
Credit goes to @dan-cancro for coming up with the idea
Keeping the original answer for those who wish to create their own directive:
To display autocomplete list we first need an attribute directive that will return the list of suggestions based on the input text and then display them in a dropdown. The directive has 2 options to display the list:
It looks to me that 2nd way is a better choice as it uses angular 2 core mechanisms instead of bypassing them by working directly with the DOM and therefore I'll use this method.
This is the directive code:
"use strict";
import {Directive, DynamicComponentLoader, Input, ComponentRef, Output, EventEmitter, OnInit, ViewContainerRef} from "@angular/core";
import {Promise} from "es6-promise";
import {AutocompleteList} from "./autocomplete-list";
@Directive({
selector: "[ng2-autocomplete]", // The attribute for the template that uses this directive
host: {
"(keyup)": "onKey($event)" // Liten to keyup events on the host component
}
})
export class AutocompleteDirective implements OnInit {
// The search function should be passed as an input
@Input("ng2-autocomplete") public search: (term: string) => Promise<Array<{ text: string, data: any }>>;
// The directive emits ng2AutocompleteOnSelect event when an item from the list is selected
@Output("ng2AutocompleteOnSelect") public selected = new EventEmitter();
private term = "";
private listCmp: ComponentRef<AutocompleteList> = undefined;
private refreshTimer: any = undefined;
private searchInProgress = false;
private searchRequired = false;
constructor( private viewRef: ViewContainerRef, private dcl: DynamicComponentLoader) { }
/**
* On key event is triggered when a key is released on the host component
* the event starts a timer to prevent concurrent requests
*/
public onKey(event: any) {
if (!this.refreshTimer) {
this.refreshTimer = setTimeout(
() => {
if (!this.searchInProgress) {
this.doSearch();
} else {
// If a request is in progress mark that a new search is required
this.searchRequired = true;
}
},
200);
}
this.term = event.target.value;
if (this.term === "" && this.listCmp) {
// clean the list if the search term is empty
this.removeList();
}
}
public ngOnInit() {
// When an item is selected remove the list
this.selected.subscribe(() => {
this.removeList();
});
}
/**
* Call the search function and handle the results
*/
private doSearch() {
this.refreshTimer = undefined;
// if we have a search function and a valid search term call the search
if (this.search && this.term !== "") {
this.searchInProgress = true;
this.search(this.term)
.then((res) => {
this.searchInProgress = false;
// if the term has changed during our search do another search
if (this.searchRequired) {
this.searchRequired = false;
this.doSearch();
} else {
// display the list of results
this.displayList(res);
}
})
.catch(err => {
console.log("search error:", err);
this.removeList();
});
}
}
/**
* Display the list of results
* Dynamically load the list component if it doesn't exist yet and update the suggestions list
*/
private displayList(list: Array<{ text: string, data: any }>) {
if (!this.listCmp) {
this.dcl.loadNextToLocation(AutocompleteList, this.viewRef)
.then(cmp => {
// The component is loaded
this.listCmp = cmp;
this.updateList(list);
// Emit the selectd event when the component fires its selected event
(<AutocompleteList>(this.listCmp.instance)).selected
.subscribe(selectedItem => {
this.selected.emit(selectedItem);
});
});
} else {
this.updateList(list);
}
}
/**
* Update the suggestions list in the list component
*/
private updateList(list: Array<{ text: string, data: any }>) {
if (this.listCmp) {
(<AutocompleteList>(this.listCmp.instance)).list = list;
}
}
/**
* remove the list component
*/
private removeList() {
this.searchInProgress = false;
this.searchRequired = false;
if (this.listCmp) {
this.listCmp.destroy();
this.listCmp = undefined;
}
}
}
The directive dynamically loads a dropdown component, this is a sample of such a component using bootstrap 4:
"use strict";
import {Component, Output, EventEmitter} from "@angular/core";
@Component({
selector: "autocomplete-list",
template: `<div class="dropdown-menu search-results">
<a *ngFor="let item of list" class="dropdown-item" (click)="onClick(item)">{{item.text}}</a>
</div>`, // Use a bootstrap 4 dropdown-menu to display the list
styles: [".search-results { position: relative; right: 0; display: block; padding: 0; overflow: hidden; font-size: .9rem;}"]
})
export class AutocompleteList {
// Emit a selected event when an item in the list is selected
@Output() public selected = new EventEmitter();
public list;
/**
* Listen for a click event on the list
*/
public onClick(item: {text: string, data: any}) {
this.selected.emit(item);
}
}
To use the directive in another component you need to import the directive, include it in the components directives and provide it with a search function and event handler for the selection:
"use strict";
import {Component} from "@angular/core";
import {AutocompleteDirective} from "../component/ng2-autocomplete/autocomplete";
@Component({
selector: "my-cmp",
directives: [AutocompleteDirective],
template: `<input class="form-control" type="text" [ng2-autocomplete]="search()" (ng2AutocompleteOnSelect)="onItemSelected($event)" autocomplete="off">`
})
export class MyComponent {
/**
* generate a search function that returns a Promise that resolves to array of text and optionally additional data
*/
public search() {
return (filter: string): Promise<Array<{ text: string, data: any }>> => {
// do the search
resolve({text: "one item", data: null});
};
}
/**
* handle item selection
*/
public onItemSelected(selected: { text: string, data: any }) {
console.log("selected: ", selected.text);
}
}
Update: code compatible with angular2 rc.1
Remember, you can only add a cookie for the current domain.
If you want to add a cookie for your Google account, do
browser.get('http://google.com')
for cookie in cookies:
browser.add_cookie(cookie)
Here are some options for using AJAX to upload files:
AjaxFileUpload - Requires a form element on the page, but uploads the file without reloading the page. See the Demo.
Uploadify - A Flash-based method of uploading files.
Ten Examples of AJAX File Upload - This was posted this year.
UPDATE: Here is a JQuery plug-in for Multiple File Uploading.
45 characters.
You might expect an address to be
0000:0000:0000:0000:0000:0000:0000:0000
8 * 4 + 7 = 39
8 groups of 4 digits with 7 :
between them.
But if you have an IPv4-mapped IPv6 address, the last two groups can be written in base 10 separated by .
, eg. [::ffff:192.168.100.228]
. Written out fully:
0000:0000:0000:0000:0000:ffff:192.168.100.228
(6 * 4 + 5) + 1 + (4 * 3 + 3) = 29 + 1 + 15 = 45
Note, this is an input/display convention - it's still a 128 bit address and for storage it would probably be best to standardise on the raw colon separated format, i.e. [0000:0000:0000:0000:0000:ffff:c0a8:64e4]
for the address above.
You can use the entry set and iterate over the entries which allows you to access both, key and value, directly.
for (Entry<String, ArrayList<String>> entry : test1.entrySet() {
System.out.println(entry.getKey() + "/" + entry.getValue());
}
I tried this but get only returns string
Why do you think so? The method get
returns the type E
for which the generic type parameter was chosen, in your case ArrayList<String>
.
You can actually provide implementations of pure virtual functions in C++. The only difference is all pure virtual functions must be implemented by derived classes before the class can be instantiated.
Vincent Povirk's answer won't work completely;
import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgfile = archive.open('img_01.png')
...
You have to change it in:
import zipfile
archive = zipfile.ZipFile('images.zip', 'r')
imgdata = archive.read('img_01.png')
...
For details read the ZipFile
docs here.
If you're dealing with natural language text and need to replace a word, not just part of a string, you have to add a pinch of regular expressions to your gsub as a plain text substitution can lead to disastrous results:
'mislocated cat, vindicating'.gsub('cat', 'dog')
=> "mislodoged dog, vindidoging"
Regular expressions have word boundaries, such as \b
which matches start or end of a word. Thus,
'mislocated cat, vindicating'.gsub(/\bcat\b/, 'dog')
=> "mislocated dog, vindicating"
In Ruby, unlike some other languages like Javascript, word boundaries are UTF-8-compatible, so you can use it for languages with non-Latin or extended Latin alphabets:
'???? ? ??????, ??? ??????'.gsub(/\b????\b/, '?????')
=> "????? ? ??????, ??? ??????"
Here's another way that might be faster, in terms of compute time, than iterating. Not sure. The idea is to convert the array to a string, truncate it, and get the size of the new array.
For example, to find the index of 'd':
arr=(a b c d)
temp=`echo ${arr[@]}`
temp=( ${temp%%d*} )
index=${#temp[@]}
You could turn this into a function like:
get-index() {
Item=$1
Array="$2[@]"
ArgArray=( ${!Array} )
NewArray=( ${!Array%%${Item}*} )
Index=${#NewArray[@]}
[[ ${#ArgArray[@]} == ${#NewArray[@]} ]] && echo -1 || echo $Index
}
You could then call:
get-index d arr
and it would echo back 3, which would be assignable with:
index=`get-index d arr`
Okay, I was blind:
e.which
will contain the ASCII code of the key.
See https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which
Just in case somebody finds it usefull.
I had a problem with the KEYCODE_DPAD_UP it belongs to the trackBall. to solve this change your avdfolder/config.ini hw.trackBall=yes and push DEL or F6
After @SedatKapanoglu comment, I am adding all my approach that works, because he was right, just using the fluent API does not work.
1- Create custom code generator and override Generate for a ColumnModel.
public class ExtendedMigrationCodeGenerator : CSharpMigrationCodeGenerator
{
protected override void Generate(ColumnModel column, IndentedTextWriter writer, bool emitName = false)
{
if (column.Annotations.Keys.Contains("Default"))
{
var value = Convert.ChangeType(column.Annotations["Default"].NewValue, column.ClrDefaultValue.GetType());
column.DefaultValue = value;
}
base.Generate(column, writer, emitName);
}
}
2- Assign the new code generator:
public sealed class Configuration : DbMigrationsConfiguration<Data.Context.EfSqlDbContext>
{
public Configuration()
{
CodeGenerator = new ExtendedMigrationCodeGenerator();
AutomaticMigrationsEnabled = false;
}
}
3- Use fluent api to created the Annotation:
public static void Configure(DbModelBuilder builder){
builder.Entity<Company>().Property(c => c.Status).HasColumnAnnotation("Default", 0);
}
Use SHFileOperation to remove the folder recursivelly
Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.
Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe
, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.
you can use ES5 some. Its pretty first by using callback
function findRestaurent(foodType) {
var restaurant;
restaurants.some(function (r) {
if (r.food === id) {
restaurant = r;
return true;
}
});
return restaurant;
}
Two ways
window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId')
OR
window.frames['myIFrame'].contentWindow.document.getElementById('myIFrameElemId')
You're not saying how exactly putdata()
is not behaving. I'm assuming you're doing
>>> pic.putdata(a)
Traceback (most recent call last):
File "...blablabla.../PIL/Image.py", line 1185, in putdata
self.im.putdata(data, scale, offset)
SystemError: new style getargs format but argument is not a tuple
This is because putdata
expects a sequence of tuples and you're giving it a numpy array. This
>>> data = list(tuple(pixel) for pixel in pix)
>>> pic.putdata(data)
will work but it is very slow.
As of PIL 1.1.6, the "proper" way to convert between images and numpy arrays is simply
>>> pix = numpy.array(pic)
although the resulting array is in a different format than yours (3-d array or rows/columns/rgb in this case).
Then, after you make your changes to the array, you should be able to do either pic.putdata(pix)
or create a new image with Image.fromarray(pix)
.
I had the same error after using the hibernate code generation
https://www.mkyong.com/hibernate/how-to-generate-code-with-hibernate-tools/
then the hibernate.cfg.xml
was created in /src/main/java
but without the connection parameters
after removing it - my problem was solved
If anyone is looking for a quick fix for this, here's how you do it.
while (array[i] != '\0') i++;
The variable i will hold the used length of the array, not the entire initialized array. I know it's a late post, but it may help someone.
You can use:
GLfloat coordinates[8] = {1.0f, ..., 0.0f};
but this is a compile-time initialisation - you can't use that method in the current standard to re-initialise (although I think there are ways to do it in the upcoming standard, which may not immediately help you).
The other two ways that spring to mind are to blat the contents if they're fixed:
GLfloat base_coordinates[8] = {1.0f, ..., 0.0f};
GLfloat coordinates[8];
:
memcpy (coordinates, base_coordinates, sizeof (coordinates));
or provide a function that looks like your initialisation code anyway:
void setCoords (float *p0, float p1, ..., float p8) {
p0[0] = p1; p0[1] = p2; p0[2] = p3; p0[3] = p4;
p0[4] = p5; p0[5] = p6; p0[6] = p7; p0[7] = p8;
}
:
setCoords (coordinates, 1.0f, ..., 0.0f);
keeping in mind those ellipses (...
) are placeholders, not things to literally insert in the code.
To get it on init
public innerWidth: any;
ngOnInit() {
this.innerWidth = window.innerWidth;
}
If you wanna keep it updated on resize:
@HostListener('window:resize', ['$event'])
onResize(event) {
this.innerWidth = window.innerWidth;
}
Nowadays at least with android it's relatively easy. Just use normal file input tag and when user clicks it the phone will ask if user wants to use camera (or file managers etc..) to upload a file. Just take a photo with the camera and it will automatically be added and uploaded.
No idea about iphone. Maybe someone can enlighten on that. EDIT: Iphone works similarly.
Sample of the input tag:
<input type="file" accept="image/*" capture="camera">
With a list comprehension:
a = [x - 13 for x in a]
as of Jan 2017, unfortunately @Adi's answer, while it seems like it should work, does not. (Google's API key process is buggy)
you'll need to click "get a key" from this link: https://developers.google.com/maps/documentation/javascript/get-api-key
also I strongly recommend you don't ever choose "secure key" until you are ready to switch to production. I did http referrer restrictions on a key and afterwards was unable to get it working with localhost, even after disabling security for the key. I had to create a new key for it to work again.
You can also use fpdf class available at: http://www.fpdf.org. It gives options for both outputting to a file and displaying on browser.
In Python the passing by reference or by value has to do with what are the actual objects you are passing.So,if you are passing a list for example,then you actually make this pass by reference,since the list is a mutable object.Thus,you are passing a pointer to the function and you can modify the object (list) in the function body.
When you are passing a string,this passing is done by value,so a new string object is being created and when the function terminates it is destroyed. So it all has to do with mutable and immutable objects.
The File
object has a length
method:
f = new File("your/file/name");
f.length();
You could implement your own exceptions and their handling for example like here:
// define exceptions "classes"
function NotNumberException() {}
function NotPositiveNumberException() {}
// try some code
try {
// some function/code that can throw
if (isNaN(value))
throw new NotNumberException();
else
if (value < 0)
throw new NotPositiveNumberException();
}
catch (e) {
if (e instanceof NotNumberException) {
alert("not a number");
}
else
if (e instanceof NotPositiveNumberException) {
alert("not a positive number");
}
}
There is another syntax for catching a typed exception, although this won't work in every browser (for example not in IE):
// define exceptions "classes"
function NotNumberException() {}
function NotPositiveNumberException() {}
// try some code
try {
// some function/code that can throw
if (isNaN(value))
throw new NotNumberException();
else
if (value < 0)
throw new NotPositiveNumberException();
}
catch (e if e instanceof NotNumberException) {
alert("not a number");
}
catch (e if e instanceof NotPositiveNumberException) {
alert("not a positive number");
}
DateTime.Today.ToString("MM/dd/yy")
Look at the docs for custom date and time format strings for more info.
(Oh, and I hope this app isn't destined for other cultures. That format could really confuse a lot of people... I've never understood the whole month/day/year thing, to be honest. It just seems weird to go "middle/low/high" in terms of scale like that.)
Delete .android folder cache files, Also delete the build folder manually from a directory and open android studio and run again.
To accomplish that, you can use the two events onfocus and onblur:
<input type="text" name="theName" value="DefaultValue"
onblur="if(this.value==''){ this.value='DefaultValue'; this.style.color='#BBB';}"
onfocus="if(this.value=='DefaultValue'){ this.value=''; this.style.color='#000';}"
style="color:#BBB;" />
New versions of excel have made old answers obsolete. It took a long time to make this, but it does a pretty good job. Note that the maximum image size is limited and the aspect ratio is ever so slightly off, as I was not able to perfectly optimize the reshaping math. Note that I've named one of my worksheets wsTMP, you can replace it with Sheet1 or the like. Takes about 1 second to print the screenshot to target path.
Option Explicit
Private Declare PtrSafe Sub keybd_event Lib "user32" (ByVal bVk As Byte, ByVal bScan As Byte, ByVal dwFlags As Long, ByVal dwExtraInfo As Long)
Sub weGucciFam()
Dim tmp As Variant, str As String, h As Double, w As Double
Application.PrintCommunication = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
If Application.StatusBar = False Then Application.StatusBar = "EVENTS DISABLED"
keybd_event vbKeyMenu, 0, 0, 0 'these do just active window
keybd_event vbKeySnapshot, 0, 0, 0
keybd_event vbKeySnapshot, 0, 2, 0
keybd_event vbKeyMenu, 0, 2, 0 'sendkeys alt+printscreen doesn't work
wsTMP.Paste
DoEvents
Const dw As Double = 1186.56
Const dh As Double = 755.28
str = "C:\Users\YOURUSERNAMEHERE\Desktop\Screenshot.jpeg"
w = wsTMP.Shapes(1).Width
h = wsTMP.Shapes(1).Height
Application.DisplayAlerts = False
Set tmp = Charts.Add
On Error Resume Next
With tmp
.PageSetup.PaperSize = xlPaper11x17
.PageSetup.TopMargin = IIf(w > dw, dh - dw * h / w, dh - h) + 28
.PageSetup.BottomMargin = 0
.PageSetup.RightMargin = IIf(h > dh, dw - dh * w / h, dw - w) + 36
.PageSetup.LeftMargin = 0
.PageSetup.HeaderMargin = 0
.PageSetup.FooterMargin = 0
.SeriesCollection(1).Delete
DoEvents
.Paste
DoEvents
.Export Filename:=str, Filtername:="jpeg"
.Delete
End With
On Error GoTo 0
Do Until wsTMP.Shapes.Count < 1
wsTMP.Shapes(1).Delete
Loop
Application.PrintCommunication = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.StatusBar = False
End Sub
you can also use:
var path = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/myfile.txt")
if
var path = Server.MapPath("~/App_Data");
var fullpath = Path.Combine(path , "myfile.txt");
is inaccessible
This works well:
function test(el){
el.childNodes.item("child").style.display = "none";
}
If the argument of item() function is an integer, the function will treat it as an index. If the argument is a string, then the function searches for name or ID of element.
One way to fix it is by modifying the assembly redirect in the web.config file.
Modify the following:
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
to
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="4.0.0.0" />
</dependentAssembly>
So the oldVersion attribute should change from "...-4.0.0.0" to "...-5.2.3.0".
WordUtils.capitalizeFully(str)
from apache commons-lang has the exact semantics as required.
Python lists
translate to JSON arrays
. What it is giving you is a perfectly valid JSON string that could be used in a Javascript application. To get what you expected, you would need to use a dict
:
>>> json.dumps({'apple': 'cat', 'banana':'dog', 'pear':'fish'})
'{"pear": "fish", "apple": "cat", "banana": "dog"}'
import pyautogui
import keyboard
import time
import os
import pyperclip
os.chdir("target directory")
# get the current directory
cwd=os.getcwd()
files=[]
for i in os.walk(cwd):
for j in i[2]:
files.append(os.path.abspath(j))
os.startfile("C:\Program Files (x86)\Adobe\Acrobat 11.0\Acrobat\Acrobat.exe")
time.sleep(1)
for i in files:
print(i)
pyperclip.copy(i)
keyboard.press('ctrl')
keyboard.press_and_release('o')
keyboard.release('ctrl')
time.sleep(1)
keyboard.press('ctrl')
keyboard.press_and_release('v')
keyboard.release('ctrl')
time.sleep(1)
keyboard.press_and_release('enter')
keyboard.press('ctrl')
keyboard.press_and_release('p')
keyboard.release('ctrl')
keyboard.press_and_release('enter')
time.sleep(3)
keyboard.press('ctrl')
keyboard.press_and_release('w')
keyboard.release('ctrl')
pyperclip.copy('')
I had a similar issues fresh install and same error surprising. Finally I figured out it was a problem with browser cookies...
Try cleaning your browser cookies and see it helps to resolve this issue, before even trying any configuration changes.
Try using XAMPP Control panel "Admin" button instead of usual http://localhost
or http://localhost/phpmyadmin
Try direct link: http://localhost/phpmyadmin/main.php
or http://127.0.0.1/phpmyadmin/main.php
Finally try this: http://localhost/phpmyadmin/index.php?db=phpmyadmin&server=1&target=db_structure.php
Somehow if you have old installation and you upgraded to new version it keeps track of your old settings through cookies.
If this solution helped let me know.
int64_t
is guaranteed by the C99 standard to be exactly 64 bits wide on platforms that implement it, there's no such guarantee for a long
which is at least 32 bits so it could be more.
§7.18.1.3 Exact-width integer types 1 The typedef name intN_t designates a signed integer type with width N , no padding bits, and a two’s complement representation. Thus, int8_t denotes a signed integer type with a width of exactly 8 bits.
new_data <- data %>% filter_all(any_vars(is.na(.)))
This should create a new data frame (new_data
) with only the missing values in it.
Works best to keep a track of values that you might later drop because they had some columns with missing observations (NA).
It looks like there are a couple of release distro for MinGW. Which one did you try? For the record, I ran into the exact same problem as the OP and the distro I got was from TDM-GCC 4.5.1.
I found the MinGW distro here seems to work far better and sets things up correctly. So for anyone running into this retarded 'createprocess-no-such-file-or-directory' error and can't get things to work, uninstall your existing MinGW and try the one I linked instead.
As Mitch mentioned, backing data up is the best method.
However, it maybe possible to extract the lost data partially depending on the situation or DB server used. For most part, you are out of luck if you don't have any backup.
SELECT * FROM user_cons_columns WHERE table_name = 'table_name';
Use ng-disabled or a special CSS class with ng-class
<input data-ng-model="userInf.username"
class="span12 editEmail"
type="text"
placeholder="[email protected]"
pattern="[^@]+@[^@]+\.[a-zA-Z]{2,6}"
required
ng-disabled="{expression or condition}"
/>
This type of query worked for me:
db.events.aggregate({$group: {_id : "$date", number: { $sum : 1} }} )
See http://docs.mongodb.org/manual/tutorial/aggregation-with-user-preference-data/
Use the AddWithValue
method:
comm.Parameters.AddWithValue("@person", "Myname");
comm.Parameters.AddWithValue("@address", "Myaddress");
the complete information one that I got from askTom-Oracle. I hope it helps you
select *
from v$sql
where buffer_gets > 1000000
or disk_reads > 100000
or executions > 50000
I've found Max Lambertini's answer very helpful, but have modified his HandleTextChanged method as such:
//I like min length set to 3, to not give too many options
//after the first character or two the user types
public Int32 AutoCompleteMinLength {get; set;}
private void HandleTextChanged() {
var txt = comboBox.Text;
if (txt.Length < AutoCompleteMinLength)
return;
//The GetMatches method can be whatever you need to filter
//table rows or some other data source based on the typed text.
var matches = GetMatches(comboBox.Text.ToUpper());
if (matches.Count() > 0) {
//The inside of this if block has been changed to allow
//users to continue typing after the auto-complete results
//are found.
comboBox.Items.Clear();
comboBox.Items.AddRange(matches);
comboBox.DroppedDown = true;
Cursor.Current = Cursors.Default;
comboBox.Select(txt.Length, 0);
return;
}
else {
comboBox.DroppedDown = false;
comboBox.SelectionStart = txt.Length;
}
}
If its money use:
NumberFormat.getNumberInstance(java.util.Locale.US).format(bd)
Similar to Lea Hayes above, but here's how I did it:
div {_x000D_
background: #999;_x000D_
height: 100px;_x000D_
width: 200px;_x000D_
border: #999 solid 1px;_x000D_
border-radius: 10px;_x000D_
margin: 15px;_x000D_
box-shadow: 0px 0px 0px 1px #fff inset;_x000D_
}
_x000D_
<div></div>
_x000D_
No nesting of DIVs or jQuery necessary, Altho for brevity I have left out the -moz and -webkit variants of some of the CSS. You can see the result above
I don't know what they're trying to say with this "React Context" stuff - they're talking Greek, to me, but here's how I did it:
Carrying values between functions, on the same page
In your constructor, bind your setter:
this.setSomeVariable = this.setSomeVariable.bind(this);
Then declare a function just below your constructor:
setSomeVariable(propertyTextToAdd) {
this.setState({
myProperty: propertyTextToAdd
});
}
When you want to set it, call this.setSomeVariable("some value");
(You might even be able to get away with this.state.myProperty = "some value";
)
When you want to get it, call var myProp = this.state.myProperty;
Using alert(myProp);
should give you some value
.
Extra scaffolding method to carry values across pages/components
You can assign a model to this
(technically this.stores
), so you can then reference it with this.state
:
import Reflux from 'reflux'
import Actions from '~/actions/actions`
class YourForm extends Reflux.Store
{
constructor()
{
super();
this.state = {
someGlobalVariable: '',
};
this.listenables = Actions;
this.baseState = {
someGlobalVariable: '',
};
}
onUpdateFields(name, value) {
this.setState({
[name]: value,
});
}
onResetFields() {
this.setState({
someGlobalVariable: '',
});
}
}
const reqformdata = new YourForm
export default reqformdata
Save this to a folder called stores
as yourForm.jsx
.
Then you can do this in another page:
import React from 'react'
import Reflux from 'reflux'
import {Form} from 'reactstrap'
import YourForm from '~/stores/yourForm.jsx'
Reflux.defineReact(React)
class SomePage extends Reflux.Component {
constructor(props) {
super(props);
this.state = {
someLocalVariable: '',
}
this.stores = [
YourForm,
]
}
render() {
const myVar = this.state.someGlobalVariable;
return (
<Form>
<div>{myVar}</div>
</Form>
)
}
}
export default SomePage
If you had set this.state.someGlobalVariable
in another component using a function like:
setSomeVariable(propertyTextToAdd) {
this.setState({
myGlobalVariable: propertyTextToAdd
});
}
that you bind in the constructor with:
this.setSomeVariable = this.setSomeVariable.bind(this);
the value in propertyTextToAdd
would be displayed in SomePage
using the code shown above.
Here is quick and dirty color generator in C# (using 'RYB approach' described in this article). It's a rewrite from JavaScript.
Use:
List<Color> ColorPalette = ColorGenerator.Generate(30).ToList();
First two colors tend to be white and a shade of black. I often skip them like this (using Linq):
List<Color> ColorsPalette = ColorGenerator
.Generate(30)
.Skip(2) // skip white and black
.ToList();
Implementation:
public static class ColorGenerator
{
// RYB color space
private static class RYB
{
private static readonly double[] White = { 1, 1, 1 };
private static readonly double[] Red = { 1, 0, 0 };
private static readonly double[] Yellow = { 1, 1, 0 };
private static readonly double[] Blue = { 0.163, 0.373, 0.6 };
private static readonly double[] Violet = { 0.5, 0, 0.5 };
private static readonly double[] Green = { 0, 0.66, 0.2 };
private static readonly double[] Orange = { 1, 0.5, 0 };
private static readonly double[] Black = { 0.2, 0.094, 0.0 };
public static double[] ToRgb(double r, double y, double b)
{
var rgb = new double[3];
for (int i = 0; i < 3; i++)
{
rgb[i] = White[i] * (1.0 - r) * (1.0 - b) * (1.0 - y) +
Red[i] * r * (1.0 - b) * (1.0 - y) +
Blue[i] * (1.0 - r) * b * (1.0 - y) +
Violet[i] * r * b * (1.0 - y) +
Yellow[i] * (1.0 - r) * (1.0 - b) * y +
Orange[i] * r * (1.0 - b) * y +
Green[i] * (1.0 - r) * b * y +
Black[i] * r * b * y;
}
return rgb;
}
}
private class Points : IEnumerable<double[]>
{
private readonly int pointsCount;
private double[] picked;
private int pickedCount;
private readonly List<double[]> points = new List<double[]>();
public Points(int count)
{
pointsCount = count;
}
private void Generate()
{
points.Clear();
var numBase = (int)Math.Ceiling(Math.Pow(pointsCount, 1.0 / 3.0));
var ceil = (int)Math.Pow(numBase, 3.0);
for (int i = 0; i < ceil; i++)
{
points.Add(new[]
{
Math.Floor(i/(double)(numBase*numBase))/ (numBase - 1.0),
Math.Floor((i/(double)numBase) % numBase)/ (numBase - 1.0),
Math.Floor((double)(i % numBase))/ (numBase - 1.0),
});
}
}
private double Distance(double[] p1)
{
double distance = 0;
for (int i = 0; i < 3; i++)
{
distance += Math.Pow(p1[i] - picked[i], 2.0);
}
return distance;
}
private double[] Pick()
{
if (picked == null)
{
picked = points[0];
points.RemoveAt(0);
pickedCount = 1;
return picked;
}
var d1 = Distance(points[0]);
int i1 = 0, i2 = 0;
foreach (var point in points)
{
var d2 = Distance(point);
if (d1 < d2)
{
i1 = i2;
d1 = d2;
}
i2 += 1;
}
var pick = points[i1];
points.RemoveAt(i1);
for (int i = 0; i < 3; i++)
{
picked[i] = (pickedCount * picked[i] + pick[i]) / (pickedCount + 1.0);
}
pickedCount += 1;
return pick;
}
public IEnumerator<double[]> GetEnumerator()
{
Generate();
for (int i = 0; i < pointsCount; i++)
{
yield return Pick();
}
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
public static IEnumerable<Color> Generate(int numOfColors)
{
var points = new Points(numOfColors);
foreach (var point in points)
{
var rgb = RYB.ToRgb(point[0], point[1], point[2]);
yield return Color.FromArgb(
(int)Math.Floor(255 * rgb[0]),
(int)Math.Floor(255 * rgb[1]),
(int)Math.Floor(255 * rgb[2]));
}
}
}
SELECT DISTINCT Col1,Col2 FROM Table GROUP BY Col1 HAVING COUNT( DISTINCT Col1 ) = 1
I noticed this post was old but it appears top on google and this kind of solution was never offered so I decided to post it anyway.
You can just disable cursor-events and enable them again later via css. It is supported on all major browsers and may prove useful in some situations.
$("#button_id").click(function() {
$("#button_id").css("pointer-events", "none");
//do something
$("#button_id").css("pointer-events", "auto");
}
If you have an option of file formats I suggest using .ini and Python's ConfigParser as mentioned. If you need compatibility with Java .properties files I have written a library for it called jprops. We were using pyjavaproperties, but after encountering various limitations I ended up implementing my own. It has full support for the .properties format, including unicode support and better support for escape sequences. Jprops can also parse any file-like object while pyjavaproperties only works with real files on disk.
it can be done by using this command: tcptraceroute -p destination port destination IP
. like: tcptraceroute -p 9100 10.0.0.50
but don't forget to install tcptraceroute package on your system. tcpdump and nc by default installed on the system. regards
An unusual but pretty way of doing it
Without index:
each _ in Array(5)
= 'a'
Will print: aaaaa
With index:
each _, i in Array(5)
= i
Will print: 01234
Notes: In the examples above, I have assigned the val
parameter of jade's each
iteration syntax to _
because it is required, but will always return undefined
.
I'm very sorry for necro-threading but I wanted to provide a solution without converting the integer to a string. Also I wanted to work with more computer-like thinking so that's why the answer from Chris Mueller wasn't good enough for me.
So without further ado,
import math
def count_number(number):
counter = 0
counter_number = number
while counter_number > 0:
counter_number //= 10
counter += 1
return counter
def digit_selector(number, selected_digit, total):
total_counter = total
calculated_select = total_counter - selected_digit
number_selected = int(number / math.pow(10, calculated_select))
while number_selected > 10:
number_selected -= 10
return number_selected
def main():
x = 1548731588
total_digits = count_number(x)
digit_2 = digit_selector(x, 2, total_digits)
return print(digit_2)
if __name__ == '__main__':
main()
which will print:
5
Hopefully someone else might need this specific kind of code. Would love to have feedback on this aswell!
This should find any digit in a integer.
Flaws:
Works pretty ok but if you use this for long numbers then it'll take more and more time. I think that it would be possible to see if there are multiple thousands etc and then substract those from number_selected but that's maybe for another time ;)
Usage:
You need every line from 1-21. Then you can call first count_number to make it count your integer.
x = 1548731588
total_digits = count_number(x)
Then read/use the digit_selector function as follows:
digit_selector('insert your integer here', 'which digit do you want to have? (starting from the most left digit as 1)', 'How many digits are there in total?')
If we have 1234567890, and we need 4 selected, that is the 4th digit counting from left so we type '4'.
We know how many digits there are due to using total_digits. So that's pretty easy.
Hope that explains everything!
Han
PS: Special thanks for CodeVsColor for providing the count_number function. I used this link: https://www.codevscolor.com/count-number-digits-number-python to help me make the digit_selector work.
Quick way to enable MySQL General Query Log without restarting.
mysql> SET GLOBAL general_log = 'ON';
mysql> SET GLOBAL general_log_file = '/var/www/nanhe/log/all.log';
I have installed mysql through homebrew, mysql version : mysql Ver 14.14 Distrib 5.7.15, for osx10.11 (x86_64) using EditLine wrapper
Use extern keyword in another .c file.
Use numpy.full
. Here's a Python that creates a gray, blue, green and red image and shows in a 2x2 grid.
import cv2
import numpy as np
gray_img = np.full((100, 100, 3), 127, np.uint8)
blue_img = np.full((100, 100, 3), 0, np.uint8)
green_img = np.full((100, 100, 3), 0, np.uint8)
red_img = np.full((100, 100, 3), 0, np.uint8)
full_layer = np.full((100, 100), 255, np.uint8)
# OpenCV goes in blue, green, red order
blue_img[:, :, 0] = full_layer
green_img[:, :, 1] = full_layer
red_img[:, :, 2] = full_layer
cv2.imshow('2x2_grid', np.vstack([
np.hstack([gray_img, blue_img]),
np.hstack([green_img, red_img])
]))
cv2.waitKey(0)
cv2.destroyWindow('2x2_grid')
32-bit JVMs which expect to have a single large chunk of memory and use raw pointers cannot use more than 4 Gb (since that is the 32 bit limit which also applies to pointers). This includes Sun and - I'm pretty sure - also IBM implementations. I do not know if e.g. JRockit or others have a large memory option with their 32-bit implementations.
If you expect to be hitting this limit you should strongly consider starting a parallel track validating a 64-bit JVM for your production environment so you have that ready for when the 32-bit environment breaks down. Otherwise you will have to do that work under pressure, which is never nice.
Edit 2014-05-15: Oracle FAQ:
The maximum theoretical heap limit for the 32-bit JVM is 4G. Due to various additional constraints such as available swap, kernel address space usage, memory fragmentation, and VM overhead, in practice the limit can be much lower. On most modern 32-bit Windows systems the maximum heap size will range from 1.4G to 1.6G. On 32-bit Solaris kernels the address space is limited to 2G. On 64-bit operating systems running the 32-bit VM, the max heap size can be higher, approaching 4G on many Solaris systems.
(http://www.oracle.com/technetwork/java/hotspotfaq-138619.html#gc_heap_32bit)
My setup:
/api/ws
As mentioned above by @Basj, make sure a2enmod proxy and ws_tunnel are enabled.
This is a screenshot of the Apache config file that solved my problem:
The relevant part as text:
<VirtualHost *:80>
ServerName *******
ServerAlias *******
ProxyPass / http://localhost:3000/
ProxyPassReverse / http://localhost:3000/
<Location "/api/ws">
ProxyPass "ws://localhost:3000/api/ws"
</Location>
</VirtualHost>
Hope that helps.
No. But what you can do is have your Active Directory admin enable LDAP so that users can maintain one set of credentials
The alignment-baseline
property is what you're looking for it can take the following values
auto | baseline | before-edge | text-before-edge |
middle | central | after-edge | text-after-edge |
ideographic | alphabetic | hanging | mathematical |
inherit
Description from w3c
This property specifies how an object is aligned with respect to its parent. This property specifies which baseline of this element is to be aligned with the corresponding baseline of the parent. For example, this allows alphabetic baselines in Roman text to stay aligned across font size changes. It defaults to the baseline with the same name as the computed value of the alignment-baseline property. That is, the position of "ideographic" alignment-point in the block-progression-direction is the position of the "ideographic" baseline in the baseline-table of the object being aligned.
Unfortunately, although this is the "correct" way of achieving what you're after it would appear Firefox have not implemented a lot of the presentation attributes for the SVG Text Module ('SVG in Firefox' MDN Documentation)
Yes, you need the full path.
log = open(os.path.join(root, f), 'r')
Is the quick fix. As the comment pointed out, os.walk
decends into subdirs so you do need to use the current directory root rather than indir
as the base for the path join.
In Weblogic 9.2 the configuration via console is as follows:
I believe the default value was 60
.
Remember to use Release Configuration
button after you edit the field.
There is not only 1 %SystemRoot%\System32
on Windows x64. There are 2 such directories.
The real %SystemRoot%\System32
directory is for 64-bit applications. This directory contains a 64-bit cmd.exe
.
But there is also %SystemRoot%\SysWOW64
for 32-bit applications. This directory is used if a 32-bit application accesses %SystemRoot%\System32
. It contains a 32-bit cmd.exe
.
32-bit applications can access %SystemRoot%\System32
for 64-bit applications by using the alias %SystemRoot%\Sysnative
in path.
For more details see the Microsoft documentation about File System Redirector.
So the subdirectory run
was created either in %SystemRoot%\System32
for 64-bit applications and 32-bit cmd
is run for which this directory does not exist because there is no subdirectory run
in %SystemRoot%\SysWOW64
which is %SystemRoot%\System32
for 32-bit cmd.exe
or the subdirectory run
was created in %SystemRoot%\System32
for 32-bit applications and 64-bit cmd
is run for which this directory does not exist because there is no subdirectory run
in %SystemRoot%\System32
as this subdirectory exists only in %SystemRoot%\SysWOW64
.
The following code could be used at top of the batch file in case of subdirectory run
is in %SystemRoot%\System32
for 64-bit applications:
@echo off
set "SystemPath=%SystemRoot%\System32"
if not "%ProgramFiles(x86)%" == "" if exist %SystemRoot%\Sysnative\* set "SystemPath=%SystemRoot%\Sysnative"
Every console application in System32\run
directory must be executed with %SystemPath%
in the batch file, for example %SystemPath%\run\YourApp.exe
.
How it works?
There is no environment variable ProgramFiles(x86) on Windows x86 and therefore there is really only one %SystemRoot%\System32
as defined at top.
But there is defined the environment variable ProgramFiles(x86) with a value on Windows x64. So it is additionally checked on Windows x64 if there are files in %SystemRoot%\Sysnative
. In this case the batch file is processed currently by 32-bit cmd.exe
and only in this case %SystemRoot%\Sysnative
needs to be used at all. Otherwise %SystemRoot%\System32
can be used also on Windows x64 as when the batch file is processed by 64-bit cmd.exe
, this is the directory containing the 64-bit console applications (and the subdirectory run
).
Note: %SystemRoot%\Sysnative
is not a directory! It is not possible to cd
to %SystemRoot%\Sysnative
or use if exist %SystemRoot%\Sysnative
or if exist %SystemRoot%\Sysnative\
. It is a special alias existing only for 32-bit executables and therefore it is necessary to check if one or more files exist on using this path by using if exist %SystemRoot%\Sysnative\cmd.exe
or more general if exist %SystemRoot%\Sysnative\*
.
If you want a true validator that does not rely on jquery and handles server side validation as well ( and you should. server side validation is the most important part) then here is a control
public class RequiredCheckBoxValidator : System.Web.UI.WebControls.BaseValidator
{
private System.Web.UI.WebControls.CheckBox _ctrlToValidate = null;
protected System.Web.UI.WebControls.CheckBox CheckBoxToValidate
{
get
{
if (_ctrlToValidate == null)
_ctrlToValidate = FindControl(this.ControlToValidate) as System.Web.UI.WebControls.CheckBox;
return _ctrlToValidate;
}
}
protected override bool ControlPropertiesValid()
{
if (this.ControlToValidate.Length == 0)
throw new System.Web.HttpException(string.Format("The ControlToValidate property of '{0}' is required.", this.ID));
if (this.CheckBoxToValidate == null)
throw new System.Web.HttpException(string.Format("This control can only validate CheckBox."));
return true;
}
protected override bool EvaluateIsValid()
{
return CheckBoxToValidate.Checked;
}
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (this.Visible && this.Enabled)
{
System.Web.UI.ClientScriptManager cs = this.Page.ClientScript;
if (this.DetermineRenderUplevel() && this.EnableClientScript)
{
cs.RegisterExpandoAttribute(this.ClientID, "evaluationfunction", "cb_verify", false);
}
if (!this.Page.ClientScript.IsClientScriptBlockRegistered(this.GetType().FullName))
{
cs.RegisterClientScriptBlock(this.GetType(), this.GetType().FullName, GetClientSideScript());
}
}
}
private string GetClientSideScript()
{
return @"<script language=""javascript"">function cb_verify(sender) {var cntrl = document.getElementById(sender.controltovalidate);return cntrl.checked;}</script>";
}
}
Use proper escaping: string.split("\\|")
Or, in Java 5+, use the helper Pattern.quote()
which has been created for exactly this purpose:
string.split(Pattern.quote("|"))
which works with arbitrary input strings. Very useful when you need to quote / escape user input.
I would solve this in this way:
from pyspark.sql import SparkSession
df_1.createOrReplaceTempView("tab_1")
df_2.createOrReplaceTempView("tab_2")
df_concat=spark.sql("select tab_1.id,tab_1.uniform,tab_1.normal,tab_2.normal_2 from tab_1 tab_1 left join tab_2 tab_2 on tab_1.uniform=tab_2.uniform\
union\
select tab_2.id,tab_2.uniform,tab_1.normal,tab_2.normal_2 from tab_2 tab_2 left join tab_1 tab_1 on tab_1.uniform=tab_2.uniform")
df_concat.show()
Well, you may try this '.*[0-9]'
Take a look at CIFS (http://www.samba.org/cifs/). It is a virtual file system you can run on your linux machine that will allow you to mount folders on your linux machine in windows using SMB.
CIFS on linux information can be found here: http://linux-cifs.samba.org/
always use 'r' to get a raw string when you want to avoid escape.
test_file=open(r'c:\Python27\test.txt','r')
If you don't want to repeat the list twice (as per @J W's answer), then put the updates in a table variable and use a JOIN
in the UPDATE
:
declare @ToDo table (FromName varchar(10), ToName varchar(10))
insert into @ToDo(FromName,ToName) values
('AAA','BBB'),
('CCC','DDD'),
('EEE','FFF')
update ts set LastName = ToName
from dbo.TestStudents ts
inner join
@ToDo t
on
ts.LastName = t.FromName
I think you should count the results with FOUND_ROWS() and SQL_CALC_FOUND_ROWS. You'll need two queries: select
, group_by
, etc. You'll add a plus select: SQL_CALC_FOUND_ROWS user_id
. After this query run a query: SELECT FOUND_ROWS()
. This will return the desired number.
The default sort is stable, so we sort twice: First by the minor key, then by the major key
rum1 <- rum[order(rum$I2, decreasing = FALSE),]
rum2 <- rum1[order(rum1$I1, decreasing = TRUE),]
to Make it look nice you can use little bootstrap help
@if(count($errors) > 0 )
<div class="alert alert-danger alert-dismissible fade show" role="alert">
<button type="button" class="close" data-dismiss="alert" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<ul class="p-0 m-0" style="list-style: none;">
@foreach($errors->all() as $error)
<li>{{$error}}</li>
@endforeach
</ul>
</div>
@endif
$(document).ready(function() {
$("#raaagh").click(function() {
$.ajax({
url: 'ajax.php', //This is the current doc
type: "POST",
data: ({name: 145}),
success: function(data) {
console.log(data);
$.ajax({
url:'ajax.php',
data: data,
dataType:'json',
success:function(data1) {
var y1=data1;
console.log(data1);
}
});
}
});
});
});
Use like this, first make a ajax call to get data, then your php function will return u the result which u wil get in data and pass that data to the new ajax call