To add a new file in SVN
svn add file_name
svn commit -m "text about changes..."
To add a new file in a directory in SVN
svn add directory_name/file_name
svn commit -m "text about changes"
To add all new files in a directory with some targets (files) are already versioned (added):
svn add directory_name/*
svn commit -m "text about changes"
Here is how I did it recently. Not perfect semantically, but gets the job done.
<div class="container" style="position: relative">
<img style="z-index: 32; left: 8px; position: relative;" alt="bottom image" src="images/bottom-image.jpg">
<div style="z-index: 100; left: 72px; position: absolute; top: 39px">
<img alt="top image" src="images/top-image.jpg"></div></div>
Simple way using lambda like so..
Thread t = new Thread(() => DoSomething("param1", "param2"));
t.Start();
OR you could even delegate
using ThreadStart
like so...
ThreadStart ts = delegate
{
bool moreWork = DoWork("param1", "param2", "param3");
if (moreWork)
{
DoMoreWork("param4", "param5");
}
};
new Thread(ts).Start();
OR using VS 2019 .NET 4.5+ even cleaner like so..
private void DoSomething(int param1, string param2)
{
//DO SOMETHING..
void ts()
{
if (param1 > 0) DoSomethingElse(param2, "param3");
}
new Thread(ts).Start();
//DO SOMETHING..
}
TEXT is a data-type for text based input. On the other hand, you have BLOB and CLOB which are more suitable for data storage (images, etc) due to their larger capacity limits (4GB for example).
As for the difference between BLOB and CLOB, I believe CLOB has character encoding associated with it, which implies it can be suited well for very large amounts of text.
BLOB and CLOB data can take a long time to retrieve, relative to how quick data from a TEXT field can be retrieved. So, use only what you need.
You need a table variable and it can be this simple.
declare @ID table (ID int)
insert into MyTable2(ID)
output inserted.ID into @ID
values (1)
You need to be careful with m/d/Y and m-d-Y formats. PHP considers /
to mean m/d/Y and -
to mean d-m-Y. I would explicitly describe the input format in this case:
$ymd = DateTime::createFromFormat('m-d-Y', '10-16-2003')->format('Y-m-d');
That way you are not at the whims of a certain interpretation.
final static String EXTRA_MESSAGE = "edit.list.message";
Context context;
public void onClick (View view)
{
Intent intent = new Intent(this,display.class);
RelativeLayout relativeLayout = (RelativeLayout) view.getParent();
TextView textView = (TextView) relativeLayout.findViewById(R.id.textView1);
String message = textView.getText().toString();
intent.putExtra(EXTRA_MESSAGE,message);
startActivity(intent);
}
Solution using pointers:
#include<stdio.h>
#include<stdlib.h>
#define n 3
struct body
{
double p[3];//position
double v[3];//velocity
double a[3];//acceleration
double radius;
double *mass;
};
int main()
{
struct body *bodies = (struct body*)malloc(n*sizeof(struct body));
int a, b;
for(a = 0; a < n; a++)
{
for(b = 0; b < 3; b++)
{
bodies[a].p[b] = 0;
bodies[a].v[b] = 0;
bodies[a].a[b] = 0;
}
bodies[a].mass = 0;
bodies[a].radius = 1.0;
}
return 0;
}
synchronized
is method level/block level access restriction modifier. It will make sure that one thread owns the lock for critical section. Only the thread,which own a lock can enter synchronized
block. If other threads are trying to access this critical section, they have to wait till current owner releases the lock.
volatile
is variable access modifier which forces all threads to get latest value of the variable from main memory. No locking is required to access volatile
variables. All threads can access volatile variable value at same time.
A good example to use volatile variable : Date
variable.
Assume that you have made Date variable volatile
. All the threads, which access this variable always get latest data from main memory so that all threads show real (actual) Date value. You don't need different threads showing different time for same variable. All threads should show right Date value.
Have a look at this article for better understanding of volatile
concept.
Lawrence Dol cleary explained your read-write-update query
.
Regarding your other queries
When is it more suitable to declare variables volatile than access them through synchronized?
You have to use volatile
if you think all threads should get actual value of the variable in real time like the example I have explained for Date variable.
Is it a good idea to use volatile for variables that depend on input?
Answer will be same as in first query.
Refer to this article for better understanding.
You can use strip() or split() to control the spaces values as in the following:
words = " first second "
# Remove end spaces
def remove_end_spaces(string):
return "".join(string.rstrip())
# Remove the first and end spaces
def remove_first_end_spaces(string):
return "".join(string.rstrip().lstrip())
# Remove all spaces
def remove_all_spaces(string):
return "".join(string.split())
# Show results
print(words)
print(remove_end_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))
Jscript is a .NET language similar to C#, with the same capabilities and access to all the .NET functions.
JavaScript is run on the ASP Classic server. Use Classic ASP to run the same JavaScript that you have on the Client (excluding HTML5 capabilities). I only have one set of code this way for most of my code.
I run .ASPX JScript when I require Image and Binary File functions, (among many others) that are not in Classic ASP. This code is unique for the server, but extremely powerful.
how about this:
string fullPath = ofd.FileName;
string fileName = ofd.SafeFileName;
string path = fullPath.Replace(fileName, "");
import os
os.path.getsize(fullpathhere) > 0
As other people said, there are many cases in which you should download a picture in the background thread without blocking the user interface
In this cases my favorite solution is to use a convenient method with blocks, like this one: (credit -> iOS: How To Download Images Asynchronously (And Make Your UITableView Scroll Fast))
- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue]
completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
if ( !error )
{
UIImage *image = [[UIImage alloc] initWithData:data];
completionBlock(YES,image);
} else{
completionBlock(NO,nil);
}
}];
}
And call it like
NSURL *imageUrl = //...
[[MyUtilManager sharedInstance] downloadImageWithURL:[NSURL URLWithString:imageURL] completionBlock:^(BOOL succeeded, UIImage *image) {
//Here you can save the image permanently, update UI and do what you want...
}];
Or have a function like:
def Print(s):
return sys.stdout.write(str(s))
Then now:
for i in range(10): # or `xrange` for python 2 version
Print(i)
Outputs:
0123456789
This works
@interface RGBComponents : NSObject {
float components[8];
}
@property(readonly) float * components;
- (float *) components {
return components;
}
You haven't specified the database. If it is one that allows analytical functions it may be faster to use this approach than the GROUP BY one(definitely faster in Oracle, most likely faster in the late SQL Server editions, don't know about others).
Syntax in SQL Server would be:
SELECT c.*, p.*
FROM customer c INNER JOIN
(SELECT RANK() OVER (PARTITION BY customer_id ORDER BY date DESC) r, *
FROM purchase) p
ON (c.id = p.customer_id)
WHERE p.r = 1
Well i know i am late to the party, but logging my answer here , incase, someone is facing similar issue as mine. I have faced this issue many times. 90% it gets solved by these two steps
project > properties > Build > Platform target > x64 (x32)
Test -> Test Settings > Default Processor Architecture > X64 (x32)
However i found one more common cause. The Solution files often change developer systems and they start pointing to wrong MSTest.TestAdapter. Especially if you are using custom path of nuget packages. I solved this issue by
Opening the .csproj file in notepad.
Manually correcting reference to MSTest.TestAdapter in import instructions like this.
You can try
Subject[] subjects = new Subject[2];
subjects[0] = new Subject{....};
subjects[1] = new Subject{....};
alternatively you can use List
List<Subject> subjects = new List<Subject>();
subjects.add(new Subject{....});
subjects.add(new Subject{....});
To dump:
pg_dump -Fc mydb > db.dump
To restore:
pg_restore --verbose --clean --no-acl --no-owner -h localhost -U myuser -d my_db db/latest.dump
you should do import Map from './Map'
React is just telling you it doesn't know where variable you are importing is.
$("#first").val(); // this will give you value of selected element. i.e. 1,2,3.
List<T>.Insert(0, item);
As far as I understand, the question is NOT about recursion. We can easily call main
method of another class in your class. Following example illustrates static and calling by object. Note omission of word static
in Class2
class Class1{
public static void main(String[] args) {
System.out.println("this is class 1");
}
}
class Class2{
public void main(String[] args) {
System.out.println("this is class 2");
}
}
class MyInvokerClass{
public static void main(String[] args) {
System.out.println("this is MyInvokerClass");
Class2 myClass2 = new Class2();
Class1.main(args);
myClass2.main(args);
}
}
Output Should be:
this is wrapper class
this is class 1
this is class 2
All the previous reviews were tested by me, but there was no solution. But I did not give up.
SOLUTION
Uncomment the following lines in my NGINX configuration
[/etc/nginx/site-avaible/{sitename}.conf]
The same code should follow in the site-enable folder
#fastcgi_param SCRIPT_FILENAME $ document_root $ fastcgi_script_name;
And comment this:
fastcgi_param SCRIPT_FILENAME / www / {namesite} / public_html $ fastcgi_script_name;
I changed several times from the original:
#fastcgi_pass unix: /var/php-nginx/9882989289032.sock;
Going back to this:
#fastcgi_pass 127.0.0.1:9007;
And finally I found what worked ...
fastcgi_pass localhost: 8004;
I also recommend these lines...
#fastcgi_index index.php;
#include fastcgi_params;
And even the FastCGI timeout (only to improve performance)
fastcgi_read_timeout 3000;
During the process, I checked the NGINX log for all modifications. (This is very important because it shows the wrong parameter.) In my case it is like this, but it depends on the configuration:
error_log/var/log/nginx/{site}_error_log;
Test the NGINX Configuration
nginx -t
Attention this is one of the options ... Well on the same server, what did not work on this site works on others ... So keep in mind that the settings depends on the platform.
In this case it was for Joomla CMS.
I used fake UserAgent.
How to use:
from fake_useragent import UserAgent
import requests
ua = UserAgent()
print(ua.chrome)
header = {'User-Agent':str(ua.chrome)}
print(header)
url = "https://www.hybrid-analysis.com/recent-submissions?filter=file&sort=^timestamp"
htmlContent = requests.get(url, headers=header)
print(htmlContent)
Output:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1309.0 Safari/537.17
{'User-Agent': 'Mozilla/5.0 (X11; OpenBSD i386) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/36.0.1985.125 Safari/537.36'}
<Response [200]>
Easier steps:
Simply apply aggregation function, Sum on your column
df.groupby('steps').sum().show()
Follow the Documentation http://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html
Check out this link also https://www.analyticsvidhya.com/blog/2016/10/spark-dataframe-and-operations/
2018 Update
In the current version of PowerShell (tested with v5.1 on Windows 10 1809) one can use the simpler Unix syntax rm -R .\DirName
to silently delete the directory .\DirName
with all subdirectories and files it may contain. In fact many common Unix commands work in the same way in PowerShell as in a Linux command line.
My experience with larger files sizes has been that java.nio
is faster than java.io
. Solidly faster. Like in the >250% range. That said, I am eliminating obvious bottlenecks, which I suggest your micro-benchmark might suffer from. Potential areas for investigating:
The buffer size. The algorithm you basically have is
My own experience has been that this buffer size is ripe for tuning. I've settled on 4KB for one part of my application, 256KB for another. I suspect your code is suffering with such a large buffer. Run some benchmarks with buffers of 1KB, 2KB, 4KB, 8KB, 16KB, 32KB and 64KB to prove it to yourself.
Don't perform java benchmarks that read and write to the same disk.
If you do, then you are really benchmarking the disk, and not Java. I would also suggest that if your CPU is not busy, then you are probably experiencing some other bottleneck.
Don't use a buffer if you don't need to.
Why copy to memory if your target is another disk or a NIC? With larger files, the latency incured is non-trivial.
Like other have said, use FileChannel.transferTo()
or FileChannel.transferFrom()
. The key advantage here is that the JVM uses the OS's access to DMA (Direct Memory Access), if present. (This is implementation dependent, but modern Sun and IBM versions on general purpose CPUs are good to go.) What happens is the data goes straight to/from disc, to the bus, and then to the destination... bypassing any circuit through RAM or the CPU.
The web app I spent my days and night working on is very IO heavy. I've done micro benchmarks and real-world benchmarks too. And the results are up on my blog, have a look-see:
Use production data and environments
Micro-benchmarks are prone to distortion. If you can, make the effort to gather data from exactly what you plan to do, with the load you expect, on the hardware you expect.
My benchmarks are solid and reliable because they took place on a production system, a beefy system, a system under load, gathered in logs. Not my notebook's 7200 RPM 2.5" SATA drive while I watched intensely as the JVM work my hard disc.
What are you running on? It matters.
Check syntax and execute one command at a time, then verify output.
mysqldump -u remoteusername -p remotepassword -h your.site.com databasename > dump.sql
mysql -u localusername -p localpassword databasename < dump.sql
Once you've matched all passwords, you can use pipe.
From the structure of your source Object, I would try:
containerObject= new JSONObject(container);
if(containerObject.has("LabelData")){
JSONObject innerObject = containerObject.getJSONObject("LabelData");
if(innerObject.has("video")){
//Do with video
}
}
One thing that I have observed is likely the email address you're providing is not a valid email address at the domain. like [email protected]. The email should be existing at Google Domain. I had alot of issues before figuring that out myself... Hope it helps.
Cleaning the Magento Logs using SSH :
login to shell(SSH) panel and go with root/shell
folder.
execute the below command inside the shell folder
php -f log.php clean
enter this command to view the log data's size
php -f log.php status
This method will help you to clean the log data's very easy way.
The best thing I have found (that seems to work in all browsers) for centering an image, or any element, horizontally is to create a CSS class and include the following parameters:
CSS
.center {
position: relative; /* where the next element will be automatically positioned */
display: inline-block; /* causes element width to shrink to fit content */
left: 50%; /* moves left side of image/element to center of parent element */
transform: translate(-50%); /* centers image/element on "left: 50%" position */
}
You can then apply the CSS class you created to your tag as follows:
HTML
<img class="center" src="image.jpg" />
You can also inline the CSS in your element(s) by doing the following:
<img style="position: relative; display: inline-block; left: 50%; transform: translate(-50%);" src ="image.jpg" />
...but I wouldn't recommend writing CSS inline because then you have to make multiple changes in all your tags using your centering CSS code if you ever want to change the style.
You can use Buffer.from()
to convert a string to buffer. More information on this can be found here
var buf = Buffer.from('some string', 'encoding');
for example
var buf = Buffer.from(bStr, 'utf-8');
If it helps to anyone, I currently use VMWare Workstation in my computer, and it also blocks Apache from starting, because VMWare Workstation listens for requests on port 443.
You can either comment out "listen 443" inside the "httpd-ssl.config" or you can disable "Shared VMs" from VMWare Workstation General Preferences.
You can't use $(this)
since jQuery doesn't know what it is there. You seem to be overcomplicating things. You can do $('#content h1.aktiv').hide()
. There's no reason to test to see if the class exists.
I have to disagree with the other answers: the built in json
library (in Python 2.7) is not necessarily slower than simplejson
. It also doesn't have this annoying unicode bug.
Here is a simple benchmark:
import json
import simplejson
from timeit import repeat
NUMBER = 100000
REPEAT = 10
def compare_json_and_simplejson(data):
"""Compare json and simplejson - dumps and loads"""
compare_json_and_simplejson.data = data
compare_json_and_simplejson.dump = json.dumps(data)
assert json.dumps(data) == simplejson.dumps(data)
result = min(repeat("json.dumps(compare_json_and_simplejson.data)", "from __main__ import json, compare_json_and_simplejson",
repeat = REPEAT, number = NUMBER))
print " json dumps {} seconds".format(result)
result = min(repeat("simplejson.dumps(compare_json_and_simplejson.data)", "from __main__ import simplejson, compare_json_and_simplejson",
repeat = REPEAT, number = NUMBER))
print "simplejson dumps {} seconds".format(result)
assert json.loads(compare_json_and_simplejson.dump) == data
result = min(repeat("json.loads(compare_json_and_simplejson.dump)", "from __main__ import json, compare_json_and_simplejson",
repeat = REPEAT, number = NUMBER))
print " json loads {} seconds".format(result)
result = min(repeat("simplejson.loads(compare_json_and_simplejson.dump)", "from __main__ import simplejson, compare_json_and_simplejson",
repeat = REPEAT, number = NUMBER))
print "simplejson loads {} seconds".format(result)
print "Complex real world data:"
COMPLEX_DATA = {'status': 1, 'timestamp': 1362323499.23, 'site_code': 'testing123', 'remote_address': '212.179.220.18', 'input_text': u'ny monday for less than \u20aa123', 'locale_value': 'UK', 'eva_version': 'v1.0.3286', 'message': 'Successful Parse', 'muuid1': '11e2-8414-a5e9e0fd-95a6-12313913cc26', 'api_reply': {"api_reply": {"Money": {"Currency": "ILS", "Amount": "123", "Restriction": "Less"}, "ProcessedText": "ny monday for less than \\u20aa123", "Locations": [{"Index": 0, "Derived From": "Default", "Home": "Default", "Departure": {"Date": "2013-03-04"}, "Next": 10}, {"Arrival": {"Date": "2013-03-04", "Calculated": True}, "Index": 10, "All Airports Code": "NYC", "Airports": "EWR,JFK,LGA,PHL", "Name": "New York City, New York, United States (GID=5128581)", "Latitude": 40.71427, "Country": "US", "Type": "City", "Geoid": 5128581, "Longitude": -74.00597}]}}}
compare_json_and_simplejson(COMPLEX_DATA)
print "\nSimple data:"
SIMPLE_DATA = [1, 2, 3, "asasd", {'a':'b'}]
compare_json_and_simplejson(SIMPLE_DATA)
And the results on my system (Python 2.7.4, Linux 64-bit):
Complex real world data:
json dumps 1.56666707993 seconds
simplejson dumps 2.25638604164 seconds
json loads 2.71256899834 seconds
simplejson loads 1.29233884811 secondsSimple data:
json dumps 0.370109081268 seconds
simplejson dumps 0.574181079865 seconds
json loads 0.422876119614 seconds
simplejson loads 0.270955085754 seconds
For dumping, json
is faster than simplejson
.
For loading, simplejson
is faster.
Since I am currently building a web service, dumps()
is more important—and using a standard library is always preferred.
Also, cjson
was not updated in the past 4 years, so I wouldn't touch it.
For people finding this post and using PHP5.5+, this might help.
I was finding the approach suggested by netcoder wasn't working. i.e. this didn't work:
$tmpfile = $_FILES['image']['tmp_name'];
$filename = basename($_FILES['image']['name']);
$data = array(
'uploaded_file' => '@'.$tmpfile.';filename='.$filename,
);
$ch = curl_init();
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
I would receive in the $_POST
var the 'uploaded_file'
field - and nothing in the $_FILES
var.
It turns out that for php5.5+ there is a new curl_file_create()
function you need to use. So the above would become:
$data = array(
'uploaded_file' => curl_file_create($tmpfile, $_FILES['image']['type'], $filename)
);
As the @
format is now deprecated.
ASP.NET Core 3.1
This is my implementation of the feature, it works on server side as well as with jquery validation unobtrusive with a custom error message just like any other attribute:
The attribute:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class MustBeIntegerAttribute : ValidationAttribute, IClientModelValidator
{
public void AddValidation(ClientModelValidationContext context)
{
MergeAttribute(context.Attributes, "data-val", "true");
var errorMsg = FormatErrorMessage(context.ModelMetadata.GetDisplayName());
MergeAttribute(context.Attributes, "data-val-mustbeinteger", errorMsg);
}
public override bool IsValid(object value)
{
return int.TryParse(value?.ToString() ?? "", out int newVal);
}
private bool MergeAttribute(
IDictionary<string, string> attributes,
string key,
string value)
{
if (attributes.ContainsKey(key))
{
return false;
}
attributes.Add(key, value);
return true;
}
}
Client side logic:
$.validator.addMethod("mustbeinteger",
function (value, element, parameters) {
return !isNaN(parseInt(value)) && isFinite(value);
});
$.validator.unobtrusive.adapters.add("mustbeinteger", [], function (options) {
options.rules.mustbeinteger = {};
options.messages["mustbeinteger"] = options.message;
});
And finally the Usage:
[MustBeInteger(ErrorMessage = "You must provide a valid number")]
public int SomeNumber { get; set; }
Big task, chances are you shouldn't reinvent the wheel rather using an existing wheel (such as paypal).
However, if you insist on continuing. Start small, you can use a credit card processing facility (Moneris, Authorize.NET) to process credit cards. Most providers have an API you can use. Be wary that you may need to use different providers depending on the card type (Discover, Visa, Amex, Mastercard) and Country (USA, Canada, UK). So build it so that you can communicate with multiple credit card processing APIs.
Security is essential if you are storing credit cards and payment details. Ensure that you are encrypting things properly.
Again, don't reinvent the wheel. You are better off using an existing provider and focussing your development attention on solving an problem that can't easily be purchase.
Only because there's a more base point to point out I'll add that you can simply test your string is null:
if [ "$1" ]; then
echo yes
else
echo no
fi
Likewise if you're expecting arg count just test your last:
if [ "$3" ]; then
echo has args correct or not
else
echo fixme
fi
and so on with any arg or var
System.Net.WebUtility
class is
available starting from .NET 4.0
(You don't need System.Web.dll dependency).
The difference between http and https is that https requests are sent over an ssl-encrypted connection. The ssl-encrypted connection must be established between the browser and the server before the browser sends the http request.
Https requests are in fact http requests that are sent over an ssl encrypted connection. If the server rejects to establish an ssl encrypted connection then the browser will have no connection to send the request over. The browser and the server will have no way of talking to each other. The browser will not be able to send the url that it wants to access and the server will not be able to respond with a redirect to another url.
So this is not possible. If you want to respond to https links, then you need an ssl certificate.
jQuery has the contains method. Here's a snippet for you:
<script type="text/javascript">
$(function() {
var foundin = $('*:contains("I am a simple string")');
});
</script>
The selector above selects any element that contains the target string. The foundin will be a jQuery object that contains any matched element. See the API information at: https://api.jquery.com/contains-selector/
One thing to note with the '*' wildcard is that you'll get all elements, including your html an body elements, which you probably don't want. That's why most of the examples at jQuery and other places use $('div:contains("I am a simple string")')
In MacOS, Mysql's executable file is located in /usr/local/mysql/bin/mysql
and you can easily login to it with the following command:
/usr/local/mysql/bin/mysql -u USERNAME -p
But this is a very long command and very boring, so you can add mysql path to Os's Environment variable and access to it much easier.
For macOS Catalina
and later
Starting with macOS Catalina, Mac devices use zsh
as the default login shell and interactive shell and you have to update .zprofile
file in your home directory.
echo 'export PATH="$PATH:/usr/local/mysql/bin"' >> ~/.zprofile
source ~/.zprofile
mysql -u USERNAME -p
For macOS Mojave
and earlier
Although you can always switch to zsh
, bash
is the default shell in macOS Mojave and earlier and with bash
you have to update .bash_profile
file.
echo 'export PATH="$PATH:/usr/local/mysql/bin"' >> ~/.bash_profile
source ~/.bash_profile
mysql -u USERNAME -p
@last_run_time
is a 9.4. User-Defined Variables and last_run_time datetime
one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.
Try: SELECT last_run_time;
UPDATE
Example:
/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$
CREATE PROCEDURE `sp_test`()
BEGIN
DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
DECLARE last_run_time DATETIME DEFAULT NULL;
DECLARE current_run_time DATETIME DEFAULT NOW();
-- Define the last run time
SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);
-- if there is no last run time found then use yesterday as starting point
IF(last_run_time IS NULL) THEN
SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
END IF;
SELECT last_run_time;
-- Insert variables in table2
INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$
DELIMITER ;
I recommend to read Microsoft guide for use Relationships, Navigation Properties and Foreign Keys in EF Code First, like this picture.
Guide link below:
https://docs.microsoft.com/en-gb/ef/ef6/fundamentals/relationships?redirectedfrom=MSDN
Use n module from npm in order to upgrade node . n is a node helper package that installs or updates a given node.js version.
sudo npm cache clean -f
sudo npm install -g n
sudo n stable
sudo ln -sf /usr/local/n/versions/node/<VERSION>/bin/node /usr/bin/nodejs
NOTE that the default installation for nodejs is in the /usr/bin/nodejs and not /usr/bin/node
To upgrade to latest version (and not current stable) version, you can use
sudo n latest
To undo:
sudo apt-get install --reinstall nodejs-legacy # fix /usr/bin/node
sudo n rm 6.0.0 # replace number with version of Node that was installed
sudo npm uninstall -g n
If you get the following error bash: /usr/bin/node: No such file or directory
then the path you have entered at
sudo ln -sf /usr/local/n/versions/node/<VERSION>/bin/node /usr/bin/nodejs
if wrong. so make sure to check if the update nodejs has been installed at the above path and the version you are entered is correct.
I would advise strongly against doing this on a production instance. It can seriously mess stuff up with your global npm packages and your ability to install new one.
put this line in parent construct : $this->load->database();
function __construct() {
parent::__construct();
$this->load->library('lib_name');
$model=array('model_name');
$this->load->model($model);
$this->load->database();
}
this way.. it should work..
Two ways can store HQL query results:
INSERT OVERWRITE DIRECTORY "HDFS Path" ROW FORMAT DELIMITED FIELDS TERMINATED BY '|'
SELECT * FROM XXXX LIMIT 10;
$hive -e "select * from table_Name" > ~/sample_output.txt
$hive -e "select * from table where city = 'London' and id >=100" > /home/user/outputdirectory/city details.csv
By typing 'jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10'
in Anaconda
PowerShell
or prompt, the Jupyter notebook will open with the new configuration. Try now to run your query.
Here is a sample code:
<?php
$sql="select * from Posts limit 20";
$response = array();
$posts = array();
$result=mysql_query($sql);
while($row=mysql_fetch_array($result)) {
$title=$row['title'];
$url=$row['url'];
$posts[] = array('title'=> $title, 'url'=> $url);
}
$response['posts'] = $posts;
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($response));
fclose($fp);
?>
How I got it working:
virtualenv -p python3.5 env/test
After sourcing my env:
pip install pymysql
pip install django
Then, I ran the startproject and inside the manage.py, I added this:
+ try:
+ import pymysql
+ pymysql.install_as_MySQLdb()
+ except:
+ pass
Also, updated this inside settings:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'foobar_db',
'USER': 'foobaruser',
'PASSWORD': 'foobarpwd',
}
}
I also have configparser==3.5.0
installed in my virtualenv, not sure if that was required or not...
Hope it helps,
PYTHON 3
import urllib.request
wp = urllib.request.urlopen("http://example.com")
pw = wp.read()
print(pw)
PYTHON 2
import urllib
import sys
wp = urllib.urlopen("http://example.com")
for line in wp:
sys.stdout.write(line)
While I have tested both the Codes in respective versions.
Python 3:
urllib.parse.quote_plus(string, safe='', encoding=None, errors=None)
here is what we did, in our situation we need an ad hoc query to be executed using a date restriction on demand, and the query is defined in a table.
Our new query needs to match data between different databases and include data from both of them.
It seems that the COLLATION is different between the db that imports data from the iSeries/AS400 system, and our reporting database - this could be because of the specific data types (such as Greek accents on names and so on).
So we used the below join clause:
...LEFT Outer join ImportDB..C4CTP C4 on C4.C4CTP COLLATE Latin1_General_CS_AS=CUS_Type COLLATE Latin1_General_CS_AS
grid.Columns[0].HeaderText
or
grid.Columns["columnname"].HeaderText
Just make option#1 Select Language:
http://closure-compiler.appspot.com/home will pick this error up with an accurate reference to the actual line number in the offending script.
I am not going to use this pattern in my own code since I'm not a big fan of using global variables. However, in a pinch it will work.
User is a promisified Mongoose model.
var globalVar = '';
User.findAsync({}).then(function(users){
globalVar = users;
}).then(function(){
console.log(globalVar);
});
GOT THE SOLUTION AFTER ALOT OF TIME GOOGLING
just get your ic_launcher and paste it in your drawables folder,
Go to your manifest and change android:icon="@drawable/ic_launcher"
Clean your project and rebuild
Hope it helps you
Also Model::all(['id'])->toArray()
it will only fetch id as array.
Create a function like so:
CREATE FUNCTION dbo.fn_FileExists(@path varchar(512))
RETURNS BIT
AS
BEGIN
DECLARE @result INT
EXEC master.dbo.xp_fileexist @path, @result OUTPUT
RETURN cast(@result as bit)
END;
GO
Edit your table and add a computed column (IsExists BIT). Set the expression to:
dbo.fn_FileExists(filepath)
Then just select:
SELECT * FROM dbo.MyTable where IsExists = 1
Update:
To use the function outside a computed column:
select id, filename, dbo.fn_FileExists(filename) as IsExists
from dbo.MyTable
Update:
If the function returns 0 for a known file, then there is likely a permissions issue. Make sure the SQL Server's account has sufficient permissions to access the folder and files. Read-only should be enough.
And YES, by default, the 'NETWORK SERVICE' account will not have sufficient right into most folders. Right click on the folder in question and select 'Properties', then click on the 'Security' tab. Click 'Edit' and add 'Network Service'. Click 'Apply' and retest.
use linq
from c in Customers
group c by DbFunctions.TruncateTime(c.CreateTime) into date
orderby date.Key descending
select new
{
Value = date.Count().ToString(),
Name = date.Key.ToString().Substring(0, 10)
}
Please incre max_iter to 10000 as default value is 1000. Possibly, increasing no. of iterations will help algorithm to converge. For me it converged and solver was -'lbfgs'
log_reg = LogisticRegression(solver='lbfgs',class_weight='balanced', max_iter=10000)
As is stated in the jQuery documentation http://api.jquery.com/jQuery.each/
return true
in jQuery.each
is the same as a continue
return false
is the same as a break
Set texts with different sizes and styles, and size and style for texts from cells ( with Range)
Sub EmailManuellAbsenden()
Dim ghApp As Object
Dim ghOldBody As String
Dim ghNewBody As String
Set ghApp = CreateObject("Outlook.Application")
With ghApp.CreateItem(0)
.To = Range("B2")
.CC = Range("B3")
.Subject = Range("B4")
.GetInspector.Display
ghOldBody = .htmlBody
ghNewBody = "<font style=""font-family: Calibri; font-size: 11pt;""/font>" & _
"<font style=""font-family: Arial; font-size: 14pt;"">Arial Text 14</font>" & _
Range("B5") & "<br>" & _
Range("B6") & "<br>" & _
"<font style=""font-family: Chiller; font-size: 21pt;"">Ciller 21</font>" &
Range("B5")
.htmlBody = ghNewBody & ghOldBody
End With
End Sub
'Fill B2 to B6 with some letters for testing
'"<font style=""font-family: Calibri; font-size: 15pt;""/font>" = works for all Range Objekts
Using this snippet, you can submit the form and avoid redirection. Instead you can pass the success function as argument and do whatever you want.
function submitForm(form, successFn){
if (form.getAttribute("id") != '' || form.getAttribute("id") != null){
var id = form.getAttribute("id");
} else {
console.log("Form id attribute was not set; the form cannot be serialized");
}
$.ajax({
type: form.method,
url: form.action,
data: $(id).serializeArray(),
dataType: "json",
success: successFn,
//error: errorFn(data)
});
}
And then just do:
var formElement = document.getElementById("yourForm");
submitForm(formElement, function() {
console.log("Form submitted");
});
This is how you do it
SELECT ID,NAME, (C_COUNTS+F_COUNTS) AS SUM_COUNTS
FROM TABLE
ORDER BY SUM_COUNTS LIMIT 20
The SUM function will add up all rows, so the order by
clause is useless, instead you will have to use the group by
clause.
Technically you shouldn't have to, that's the point of generics, so you can do compile-type checking:
public int indexOf(E arg0) {
...
}
but then the @Override may be a problem if you have a class hierarchy. Otherwise see Yishai's answer.
You can escape the apostrophe with a \
character as well:
mystring.replace('\'', '')
This code sample is taken from csharp-examples.net, written by Jan Slama:
To find nodes in an XML file you can use XPath expressions. Method XmlNode.SelectNodes returns a list of nodes selected by the XPath string. Method XmlNode.SelectSingleNode finds the first node that matches the XPath string.
XML:
<Names> <Name> <FirstName>John</FirstName> <LastName>Smith</LastName> </Name> <Name> <FirstName>James</FirstName> <LastName>White</LastName> </Name> </Names>
CODE:
XmlDocument xml = new XmlDocument(); xml.LoadXml(myXmlString); // suppose that myXmlString contains "<Names>...</Names>" XmlNodeList xnList = xml.SelectNodes("/Names/Name"); foreach (XmlNode xn in xnList) { string firstName = xn["FirstName"].InnerText; string lastName = xn["LastName"].InnerText; Console.WriteLine("Name: {0} {1}", firstName, lastName); }
You can use
insert into <table_name> select <fieldlist> from <tables>
You can listen to event on change of textarea and do the changes as per you want. Here is one example.
const textArea = document.getElementById('my_text_area');
textArea.addEventListener('input', () => {
var textLn = textArea.value.length;
if(textLn >= 100) {
textArea.style.fontSize = '10pt';
}
})
_x000D_
<html>
<textarea id='my_text_area' rows="4" cols="50" style="font-size:40pt">
This text will change font after 100.
</textarea>
</html>
_x000D_
Indeed, it is O(n^2). See also a very similar example with the same runtime here.
To work off the answer above (https://stackoverflow.com/a/44860918/2011818), you can also send the objects inline the "To" inside the Link object.
<Route path="/foo/:fooId" component={foo} / >
<Link to={{pathname:/foo/newb, sampleParam: "Hello", sampleParam2: "World!" }}> CLICK HERE </Link>
this.props.match.params.fooId //newb
this.props.location.sampleParam //"Hello"
this.props.location.sampleParam2 //"World!"
Try this:
DataGridViewRow row = dataGridView1.Rows[index row you want];
dataGridView1.CurrentRow = row;
Hope this help!
That's because there was an error in your query. MySQli->query()
will return false on error. Change it to something like::
$result = $this->database->query($query);
if (!$result) {
throw new Exception("Database Error [{$this->database->errno}] {$this->database->error}");
}
That should throw an exception if there's an error...
I'm surprised why no one suggested to use the WinForms Textbox.
XAML:
<WindowsFormsHost Margin="10" Width="70">
<wf:TextBox x:Name="textbox1"/>
</WindowsFormsHost>
Also don't forget the Winforms Namespace:
xmlns:wf="clr-namespace:System.Windows.Forms;assembly=System.Windows.Forms"
C#:
AutoCompleteStringCollection stringCollection = new AutoCompleteStringCollection(){"String 1", "String 2", "etc..."};
textbox1.AutoCompleteMode = AutoCompleteMode.SuggestAppend;
textbox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
textbox1.AutoCompleteCustomSource = stringCollection;
With Autocomplete, you need to do it in the Code behind, because for some reasons, others might can explain, it throws an exception.
With:
FILES = $(shell ls)
indented underneath all
like that, it's a build command. So this expands $(shell ls)
, then tries to run the command FILES ...
.
If FILES
is supposed to be a make
variable, these variables need to be assigned outside the recipe portion, e.g.:
FILES = $(shell ls)
all:
echo $(FILES)
Of course, that means that FILES
will be set to "output from ls
" before running any of the commands that create the .tgz files. (Though as Kaz notes the variable is re-expanded each time, so eventually it will include the .tgz files; some make variants have FILES := ...
to avoid this, for efficiency and/or correctness.1)
If FILES
is supposed to be a shell variable, you can set it but you need to do it in shell-ese, with no spaces, and quoted:
all:
FILES="$(shell ls)"
However, each line is run by a separate shell, so this variable will not survive to the next line, so you must then use it immediately:
FILES="$(shell ls)"; echo $$FILES
This is all a bit silly since the shell will expand *
(and other shell glob expressions) for you in the first place, so you can just:
echo *
as your shell command.
Finally, as a general rule (not really applicable to this example): as esperanto notes in comments, using the output from ls
is not completely reliable (some details depend on file names and sometimes even the version of ls
; some versions of ls
attempt to sanitize output in some cases). Thus, as l0b0 and idelic note, if you're using GNU make you can use $(wildcard)
and $(subst ...)
to accomplish everything inside make
itself (avoiding any "weird characters in file name" issues). (In sh
scripts, including the recipe portion of makefiles, another method is to use find ... -print0 | xargs -0
to avoid tripping over blanks, newlines, control characters, and so on.)
1The GNU Make documentation notes further that POSIX make added ::=
assignment in 2012. I have not found a quick reference link to a POSIX document for this, nor do I know off-hand which make
variants support ::=
assignment, although GNU make does today, with the same meaning as :=
, i.e., do the assignment right now with expansion.
Note that VAR := $(shell command args...)
can also be spelled VAR != command args...
in several make
variants, including all modern GNU and BSD variants as far as I know. These other variants do not have $(shell)
so using VAR != command args...
is superior in both being shorter and working in more variants.
You can change the value of a bool all you want. As for an if:
if randombool == True:
works, but you can also use:
if randombool:
If you want to test whether something is false you can use:
if randombool == False
but you can also use:
if not randombool:
You can use the ADB via a terminal to pass the file From Desktop to Emulator.
adb push <file-source-local> <destination-path-remote>
You can also copy file from emulator to Desktop
adb pull <file-source-remote> <destination-path>
How ever you can also use the Android Device Monitor to access files. Click on the Android Icon which can be found in the toolbar itself. It'll take few seconds to load. Once it's loaded, you can see a tab named "File Explorer". Now you could pull/push files from there.
i had this problem before , i am using yii2 and i solved it this way
$.fn.modal.Constructor.prototype.enforceFocus = $.noop;
You need to wrap the table inside another element and set the height of that element. Example with inline css:
<div style="height: 500px; overflow: auto;">
<table>
</table>
</div>
change type="number" to type="tel"
I was looking for something similar myself, preferably without using a library or sorting the entire list. My solution ended up similar to the question itself, just simplified a bit.
var firstBorn = People.FirstOrDefault(p => p.DateOfBirth == People.Min(p2 => p2.DateOfBirth));
The following is to generate the list of columns to use in a query (not to automate the query, as this was not specified):
SELECT
GROUP_CONCAT(
CONCAT('`', `COLUMN_NAME`, '`')
SEPARATOR ',\n'
) AS `cols`
FROM information_schema.`COLUMNS`
WHERE `TABLE_SCHEMA` = 'db'
AND `TABLE_NAME` = 'table_name_here'
AND `COLUMN_NAME` NOT IN ('exclude_col1', 'exclude_col2')
Will produce:
`included_col1`,
`included_col2`,
`included_col3`
You can then copy this to use in a query:
SELECT
`included_col1`,
`included_col2`,
`included_col3`
FROM db.table_name_here
Another approach would be to leverage the INSERT ALL
syntax from oracle,
INSERT ALL
INTO table1(email, campaign_id) VALUES (email, campaign_id)
WITH source_data AS
(SELECT '[email protected]' email,100 campaign_id
FROM dual
UNION ALL
SELECT '[email protected]' email,200 campaign_id
FROM dual)
SELECT email
,campaign_id
FROM source_data src
WHERE NOT EXISTS (SELECT 1
FROM table1 dest
WHERE src.email = dest.email
AND src.campaign_id = dest.campaign_id);
INSERT ALL
also allow us to perform a conditional insert into multiple tables based on a sub query as source.
There are some really clean and nice examples are there to refer.
<button>
<a href="https://accounts.google.com/ServiceLogin?continue=http%3A%2F%2Fmail.google.com%2Fmail%2F%3Fpc%3Den-ha-apac-in-bk-refresh14&service=mail&dsh=-3966619600017513905"
style="cursor:default">sign in</a>
</button>
Try this one,
myFrame.setVisible(true);
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
myComponent.grabFocus();
myComponent.requestFocus();//or inWindow
}
});
My solution to this error was that a copy and paste from another project that had a reference to @Model.Id
. This particular page didn't have a model but the error line was so far off from the actual error I about never found it!
Yet another way with the most powerful REDUCE method.
data = {key1: "value1", key2: "value2", key3: "value3"}; _x000D_
_x000D_
keyMap = {key1: "firstkey", key2: "secondkey", key3: "thirdkey"};_x000D_
_x000D_
mappedData = Object.keys(keyMap).reduce((obj,k) => Object.assign(obj, { [keyMap[k]]: data[k] }),{});_x000D_
_x000D_
console.log(mappedData);
_x000D_
Function ExtSql(ByVal sql As String) As Boolean
Dim cnn As SqlConnection
Dim cmd As SqlCommand
cnn = New SqlConnection(My.Settings.mySqlConnectionString)
Try
cnn.Open()
cmd = New SqlCommand
cmd.Connection = cnn
cmd.CommandType = CommandType.Text
cmd.CommandText = sql
cmd.ExecuteNonQuery()
cnn.Close()
cmd.Dispose()
Catch ex As Exception
cnn.Close()
Return False
End Try
Return True
End Function
For Windows 7 with NIO 2:
public static void main(String[] args) throws IOException {
Path file = Paths.get("c:/touch.txt");
AclFileAttributeView aclAttr = Files.getFileAttributeView(file, AclFileAttributeView.class);
System.out.println(aclAttr.getOwner());
for (AclEntry aclEntry : aclAttr.getAcl()) {
System.out.println(aclEntry);
}
System.out.println();
UserPrincipalLookupService upls = file.getFileSystem().getUserPrincipalLookupService();
UserPrincipal user = upls.lookupPrincipalByName(System.getProperty("user.name"));
AclEntry.Builder builder = AclEntry.newBuilder();
builder.setPermissions( EnumSet.of(AclEntryPermission.READ_DATA, AclEntryPermission.EXECUTE,
AclEntryPermission.READ_ACL, AclEntryPermission.READ_ATTRIBUTES, AclEntryPermission.READ_NAMED_ATTRS,
AclEntryPermission.WRITE_ACL, AclEntryPermission.DELETE
));
builder.setPrincipal(user);
builder.setType(AclEntryType.ALLOW);
aclAttr.setAcl(Collections.singletonList(builder.build()));
}
PHP syntax is little different in case of concatenation from JavaScript.
Instead of (+) plus
a (.) period
is used for string concatenation.
<?php
$selectBox = '<select name="number">';
for ($i=1;$i<=100;$i++)
{
$selectBox += '<option value="' . $i . '">' . $i . '</option>'; // <-- (Wrong) Replace + with .
$selectBox .= '<option value="' . $i . '">' . $i . '</option>'; // <-- (Correct) Here + is replaced .
}
$selectBox += '</select>'; // <-- (Wrong) Replace + with .
$selectBox .= '</select>'; // <-- (Correct) Here + is replaced .
echo $selectBox;
?>
For binding Dynamic Data in a DropDownList you can do the following:
Create ViewBag in Controller like below
ViewBag.ContribTypeOptions = yourFunctionValue();
now use this value in view like below:
@Html.DropDownListFor(m => m.ContribType,
new SelectList(@ViewBag.ContribTypeOptions, "ContribId",
"Value", Model.ContribTypeOptions.First().ContribId),
"Select, please")
It uses commas as separators. So you can either set sep=","
or just use read.csv
:
x <- read.csv(file="http://www.irs.gov/file_source/pub/irs-soi/countyinflow1011.csv")
dim(x)
## [1] 113593 9
The error is caused by spaces in some of the values, and unmatched quotes. There are no spaces in the header, so read.table
thinks that there is one column. Then it thinks it sees multiple columns in some of the rows. For example, the first two lines (header and first row):
State_Code_Dest,County_Code_Dest,State_Code_Origin,County_Code_Origin,State_Abbrv,County_Name,Return_Num,Exmpt_Num,Aggr_AGI
00,000,96,000,US,Total Mig - US & For,6973489,12948316,303495582
And unmatched quotes, for example on line 1336 (row 1335) which will confuse read.table
with the default quote
argument (but not read.csv
):
01,089,24,033,MD,Prince George's County,13,30,1040
Limit is very simple, example limit first 50 rows
val df_subset = data.limit(50)
Using numpy and taking care of BandGap's rounding errors:
from numpy.linalg import norm
from numpy import dot
import math
def angle_between(a,b):
arccosInput = dot(a,b)/norm(a)/norm(b)
arccosInput = 1.0 if arccosInput > 1.0 else arccosInput
arccosInput = -1.0 if arccosInput < -1.0 else arccosInput
return math.acos(arccosInput)
Note, this function will throw an exception if one of the vectors has zero magnitude (divide by 0).
As far I know, every concatenation implies a memory reallocation. So the problem is not the operator used to do it, the solution is to reduce the number of concatenations. For example do the concatenations outside of the iteration structures when you can.
Simply parsing the JSON and comparing the two objects is not enough because it wouldn't be the exact same object references (but might be the same values).
You need to do a deep equals.
From http://threebit.net/mail-archive/rails-spinoffs/msg06156.html - which seems the use jQuery.
Object.extend(Object, {
deepEquals: function(o1, o2) {
var k1 = Object.keys(o1).sort();
var k2 = Object.keys(o2).sort();
if (k1.length != k2.length) return false;
return k1.zip(k2, function(keyPair) {
if(typeof o1[keyPair[0]] == typeof o2[keyPair[1]] == "object"){
return deepEquals(o1[keyPair[0]], o2[keyPair[1]])
} else {
return o1[keyPair[0]] == o2[keyPair[1]];
}
}).all();
}
});
Usage:
var anObj = JSON.parse(jsonString1);
var anotherObj= JSON.parse(jsonString2);
if (Object.deepEquals(anObj, anotherObj))
...
import numpy as np
new_array=np.linspace(0,10,11).astype('int')
An alternative for casting the type when the array is made.
An .xsd file is called an XML schema. Via an XML schema, we may require a certain structure in a given XML - which elements in which order, how many times, with which attributes, how they are nested, etc. If we have a schema for our XML input, we can verify that it contains the data we need it to contain, and nothing else, with a few lines invoking a schema validator.
use just
jQuery.ajax ({
url: myurl,
type: "POST",
data: mydata,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(){
//
}
});
UPDATED @JK: If you write in your question only one code example with $.post you find one corresponding example in the answer. I don't want to repeat the same information which you already studied till know: $.post and $.get are short forms of $.ajax. So just use $.ajax and you can use the full set of it's parameters without having to change any global settings.
By the way I wouldn't recommend overwriting the standard $.post. It's my personal opinion, but for me it's important, not only that the program works, but also that all who read your program understand it with the same way. Overwriting standard methods without having a very important reason can follow to misunderstanding in reading of the program code. So I repeat my recommendation one more time: just use the original $.ajax form jQuery instead of jQuery.get
and jQuery.post
and you receive programs which not only perfectly work, but can be read by people without any misunderstandings.
We got this error when the connection string to our database was incorrect. The key to figuring this out was running the dotnet blah.dll which provided a stacktrace showing us that the sql server instance specified could not be found. Hope this helps someone.
I had the same problem, you have to load first the Moment.js file!
<script src="path/moment.js"></script>_x000D_
<script src="path/bootstrap-datetimepicker.js"></script>
_x000D_
Try this:
select convert(nvarchar,CAST(getdate()as time),100)
There is no performance difference.
A const_iterator
is an iterator that points to const value (like a const T*
pointer); dereferencing it returns a reference to a constant value (const T&
) and prevents modification of the referenced value: it enforces const
-correctness.
When you have a const reference to the container, you can only get a const_iterator
.
Edited: I mentionned “The const_iterator
returns constant pointers” which is not accurate, thanks to Brandon for pointing it out.
Edit: For COW objects, getting a non-const iterator (or dereferencing it) will probably trigger the copy. (Some obsolete and now disallowed implementations of std::string
use COW.)
Building on @Panagiotis Kanavos' answer, here's a working method as example which will also return the response as an object instead of a string:
using System.Text;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json; // Nuget Package
public static async Task<object> PostCallAPI(string url, object jsonObject)
{
try
{
using (HttpClient client = new HttpClient())
{
var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
var response = await client.PostAsync(url, content);
if (response != null)
{
var jsonString = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<object>(jsonString);
}
}
}
catch (Exception ex)
{
myCustomLogger.LogException(ex);
}
return null;
}
Keep in mind that this is only an example and that you'd probably would like to use HttpClient
as a shared instance instead of using it in a using-clause.
There are various ways of changing the status bar color.
1) Using the styles.xml. You can use the android:statusBarColor attribute to do this the easy but static way.
Note: You can also use this attribute with the Material theme.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="AppTheme" parent="AppTheme.Base">
<item name="android:statusBarColor">@android:color/transparent</item>
</style>
</resources>
2) You can get it done dynamically using the setStatusBarColor(int) method in the Window class. But remember that this method is only available for API 21 or higher. So be sure to check that, or your app will surely crash in lower devices.
Here is a working example of this method.
if (Build.VERSION.SDK_INT >= 21) {
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
window.setStatusBarColor(getResources().getColor(R.color.primaryDark));
}
where primaryDark is the 700 tint of the primary color I am using in my app. You can define this color in the colors.xml file.
Do give it a try and let me know if you have any questions. Hope it helps.
Initialize all your array elements to null first, then look for the null to find the empty slot
I found that simply setting the line-height and height to the same pixel quantity produced the most consistent result. By "most consistent" I mean optimally consistent but of course it is not 100% "pixel-perfect" across browsers. Additionally I found that Firefox (v. 17.x) tends to crowd the option text to the right against the drop-down arrow; I alleviated this with a small amount of padding-right set on the OPTION element only. This setting does not affect appearance in IE 7-9.
My result:
select, option {
font-size:10px;
height:19px;
line-height: 19px;
padding:0;
margin:0;
}
option {
padding-right:6px; /* Firefox */
}
NOTE -- my SELECT element uses a smaller font, 10px. Obviously you will need to adjust proportions accordingly for your specific UI context.
This post really helped me to finally get what I want. So I just wanted to contribute my code here to help others. Here is my code with some explanation.
The following code:
double moneyWithDecimals = 5.50;
double moneyNoDecimals = 5.00;
System.out.println(jeroensFormat(moneyWithDecimals));
System.out.println(jeroensFormat(moneyNoDecimals));
Will return:
€ 5,-
€ 5,50
The actual jeroensFormat() method:
public String jeroensFormat(double money)//Wants to receive value of type double
{
NumberFormat dutchFormat = NumberFormat.getCurrencyInstance();
money = money;
String twoDecimals = dutchFormat.format(money); //Format to string
if(tweeDecimalen.matches(".*[.]...[,]00$")){
String zeroDecimals = twoDecimals.substring(0, twoDecimals.length() -3);
return zeroDecimals;
}
if(twoDecimals.endsWith(",00")){
String zeroDecimals = String.format("€ %.0f,-", money);
return zeroDecimals; //Return with ,00 replaced to ,-
}
else{ //If endsWith != ,00 the actual twoDecimals string can be returned
return twoDecimals;
}
}
The method displayJeroensFormat that calls the method jeroensFormat()
public void displayJeroensFormat()//@parameter double:
{
System.out.println(jeroensFormat(10.5)); //Example for two decimals
System.out.println(jeroensFormat(10.95)); //Example for two decimals
System.out.println(jeroensFormat(10.00)); //Example for zero decimals
System.out.println(jeroensFormat(100.000)); //Example for zero decimals
}
Will have the following output:
€ 10,50
€ 10,95
€ 10,-
€ 100.000 (In Holland numbers bigger than € 999,- and wit no decimals don't have ,-)
This code uses your current currency. In my case that's Holland so the formatted string for me will be different than for someone in the US.
Just watch the last 3 characters of those numbers. My code has an if statement to check if the last 3 characters are equal to ",00". To use this in the US you might have to change that to ".00" if it doesn't work already.
dataURItoBlob(dataURI) {_x000D_
const byteString = window.atob(dataURI);_x000D_
const arrayBuffer = new ArrayBuffer(byteString.length);_x000D_
const int8Array = new Uint8Array(arrayBuffer);_x000D_
for (let i = 0; i < byteString.length; i++) {_x000D_
int8Array[i] = byteString.charCodeAt(i);_x000D_
}_x000D_
const blob = new Blob([int8Array], { type: 'application/pdf'});_x000D_
return blob;_x000D_
}_x000D_
_x000D_
// data should be your response data in base64 format_x000D_
_x000D_
const blob = this.dataURItoBlob(data);_x000D_
const url = URL.createObjectURL(blob);_x000D_
_x000D_
// to open the PDF in a new window_x000D_
window.open(url, '_blank');
_x000D_
All XAMPP packages come with Multibyte String (php_mbstring.dll) extension installed.
If you have accidentally removed DLL file from php/ext
folder, just add it back (get the copy from XAMPP zip archive - its downloadable).
If you have deleted the accompanying INI configuration line from php.ini
file, add it back as well:
extension=php_mbstring.dll
Also, ensure to restart your webserver (Apache) using XAMPP control panel.
Additional Info on Enabling PHP Extensions
/XAMPP/php/ext
directory)extension_dir = "ext"
)If you're using jQuery 2.1.4 or above, try this:
$("#" + this.d);
Or, you can define var before using it. It makes your code simpler.
var d = this.d
$("#" + d);
Consider a solution that will neatly handle arbitrarily many tables.
//ASSUMPTION: All tables must have the same columns
var tables = new List<DataTable>();
tables.Add(oneTableToRuleThemAll);
tables.Add(oneTableToFindThem);
tables.Add(oneTableToBringThemAll);
tables.Add(andInTheDarknessBindThem);
//Or in the real world, you might be getting a collection of tables from some abstracted data source.
//behold, a table too great and terrible to imagine
var theOneTable = tables.SelectMany(dt => dt.AsEnumerable()).CopyToDataTable();
Encapsulated into a helper for future reuse:
public static DataTable CombineDataTables(params DataTable[] args)
{
return args.SelectMany(dt => dt.AsEnumerable()).CopyToDataTable();
}
Just have a few tables declared in code?
var combined = CombineDataTables(dt1,dt2,dt3);
Want to combine into one of the existing tables instead of creating a new one?
dt1 = CombineDataTables(dt1,dt2,dt3);
Already have a collection of tables, instead of declared one by one?
//Pretend variable tables already exists
var tables = new[] { dt1, dt2, dt3 };
var combined = CombineDataTables(tables);
Here's another one:
substr(number_format(time() * rand(),0,'',''),0,6);
Here's my version of a Bash script that checks all repositories in a predefined folder:
https://gist.github.com/henryiii/5841984
It can differentiate between common situations, like pull needed and push needed, and it is multithreaded, so the fetch happens all at once. It has several commands, like pull and status.
Put a symlink (or the script) in a folder in your path, then it works as git all status
(, etc.). It only supports origin/master, but it can be edited or combined with another method.
Copy all order entries of home folder .iml file into your /src/main/main.iml file. This will solve the problem.
It formats the string as two uppercase hexadecimal characters.
In more depth, the argument "X2"
is a "format string" that tells the ToString()
method how it should format the string. In this case, "X2" indicates the string should be formatted in Hexadecimal.
byte.ToString()
without any arguments returns the number in its natural decimal representation, with no padding.
Microsoft documents the standard numeric format strings which generally work with all primitive numeric types' ToString()
methods. This same pattern is used for other types as well: for example, standard date/time format strings can be used with DateTime.ToString()
.
After much searching a way to show a progress bar just to make the most elegant charging could not find any way that would serve my purpose. Check the actual status of the request showed demaziado complex and sometimes snippets not then worked created a very simple way but it gives me the experience seeking (or almost), follows the code:
$.ajax({
type : 'GET',
url : url,
dataType: 'html',
timeout: 10000,
beforeSend: function(){
$('.my-box').html('<div class="progress"><div class="progress-bar progress-bar-success progress-bar-striped active" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 0%;"></div></div>');
$('.progress-bar').animate({width: "30%"}, 100);
},
success: function(data){
if(data == 'Unauthorized.'){
location.href = 'logout';
}else{
$('.progress-bar').animate({width: "100%"}, 100);
setTimeout(function(){
$('.progress-bar').css({width: "100%"});
setTimeout(function(){
$('.my-box').html(data);
}, 100);
}, 500);
}
},
error: function(request, status, err) {
alert((status == "timeout") ? "Timeout" : "error: " + request + status + err);
}
});
This is a nice example: The Repository Pattern Example in C#
Basically, repository hides the details of how exactly the data is being fetched/persisted from/to the database. Under the covers:
I had to run this first
sudo xcode-select --reset
then
sudo xcode-select -switch /Library/Developer/CommandLineTools
and then it worked.
What I do is
git add . (adding everything)
git stash
git stash drop
One liner: git add . && git stash && git stash drop
I was not able to clone a repository due to have logged on with other credentials.
To switch to another user, I >>desperate<< did:
git config --global --unset user.name
git config --global --unset user.email
git config --global --unset credential.helper
after, instead using ssh link, I used HTTPS link. It asked for credentials and it worked fine FOR ME!
This is a pretty old post but XCode 10 added the CommonCrypto module so you don't need a module map. Also with Swift 5, no need for the annoying casts.
You could do something like:
func decrypt(_ data: Data, iv: Data, key: Data) throws -> String {
var buffer = [UInt8](repeating: 0, count: data.count + kCCBlockSizeAES128)
var bufferLen: Int = 0
let status = CCCrypt(
CCOperation(kCCDecrypt),
CCAlgorithm(kCCAlgorithmAES128),
CCOptions(kCCOptionPKCS7Padding),
[UInt8](key),
kCCBlockSizeAES128,
[UInt8](iv),
[UInt8](data),
data.count,
&buffer,
buffer.count,
&bufferLen
)
guard status == kCCSuccess,
let str = String(data: Data(bytes: buffer, count: bufferLen),
encoding: .utf8) else {
throw NSError(domain: "AES", code: -1, userInfo: nil)
}
return str
}
You can also use rlutil:
rlutil.h
),setColor()
, cls()
, getch()
, gotoxy()
, etc.Your code would become something like this:
#include <stdio.h>
#include "rlutil.h"
int main(int argc, char* argv[])
{
setColor(BLUE);
printf("\n \n \t This is dummy program for text color ");
getch();
return 0;
}
Have a look at example.c and test.cpp for C and C++ examples.
import java.util.ArrayList;
/**
* @author potter
*
*/
public class storeAny {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
ArrayList<Object> anyTy=new ArrayList<Object>();
anyTy.add(new Integer(1));
anyTy.add(new String("Jesus"));
anyTy.add(new Double(12.88));
anyTy.add(new Double(12.89));
anyTy.add(new Double(12.84));
anyTy.add(new Double(12.82));
for (Object o : anyTy) {
if(o instanceof String){
System.out.println(o.toString());
} else if(o instanceof Integer) {
System.out.println(o.toString());
} else if(o instanceof Double) {
System.out.println(o.toString());
}
}
}
}
Split on newlines (environment agnostic) and print regularly -- no need to worry about encoding or xss:
@if (!string.IsNullOrWhiteSpace(text))
{
var lines = text.Split(new[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var line in lines)
{
<p>@line</p>
}
}
(remove empty entries is optional)
You may already know that putting your Button inside of a ToolBar gives you this behavior, but if you want something that will work across ALL current themes with any sort of predictability, you'll need to create a new ControlTemplate.
Prashant's solution does not work with a Button not in a toolbar when the Button has focus. It also doesn't work 100% with the default theme in XP -- you can still see faint gray borders when your container Background is white.
You may use pip
for that without using the network. See in the docs (search for "Install a particular source archive file"). Any of those should work:
pip install relative_path_to_seaborn.tar.gz
pip install absolute_path_to_seaborn.tar.gz
pip install file:///absolute_path_to_seaborn.tar.gz
Or you may uncompress the archive and use setup.py
directly with either pip
or python
:
cd directory_containing_tar.gz
tar -xvzf seaborn-0.10.1.tar.gz
pip install seaborn-0.10.1
python setup.py install
Of course, you should also download required packages and install them the same way before you proceed.
Do it without service
If you are so serious about doing it with services using mediaplayer
Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.idil);
player.setLooping(true); // Set looping
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TO DO
}
public IBinder onUnBind(Intent arg0) {
// TO DO Auto-generated method
return null;
}
public void onStop() {
}
public void onPause() {
}
@Override
public void onDestroy() {
player.stop();
player.release();
}
@Override
public void onLowMemory() {
}
}
Please call this service in Manifest Make sure there is no space at the end of the .BackgroundSoundService string
<service android:enabled="true" android:name=".BackgroundSoundService" />
You can also use the FileReader class :
var reader = new FileReader();
reader.onload = function (e) {
var data = this.result;
}
reader.readAsDataURL( file );
db.data.update({'name': 'zero'}, {'$set': {'value': NumberInt(0)}})
You can also use NumberLong.
My regular question is rather "anything new or changed in repo" so whatchanged comes handy. Found it here.
git whatchanged origin/master -n 1
try
if ! grep -q sysa /etc/passwd ; then
grep
returns true
if it finds the search target, and false
if it doesn't.
So NOT false
== true
.
if
evaluation in shells are designed to be very flexible, and many times doesn't require chains of commands (as you have written).
Also, looking at your code as is, your use of the $( ... )
form of cmd-substitution is to be commended, but think about what is coming out of the process. Try echo $(cat /etc/passwd | grep "sysa")
to see what I mean. You can take that further by using the -c
(count) option to grep and then do if ! [ $(grep -c "sysa" /etc/passwd) -eq 0 ] ; then
which works but is rather old school.
BUT, you could use the newest shell features (arithmetic evaluation) like
if ! (( $(grep -c "sysa" /etc/passwd) == 0 )) ; then ...`
which also gives you the benefit of using the c-lang based comparison operators, ==,<,>,>=,<=,%
and maybe a few others.
In this case, per a comment by Orwellophile, the arithmetic evaluation can be pared down even further, like
if ! (( $(grep -c "sysa" /etc/passwd) )) ; then ....
OR
if (( ! $(grep -c "sysa" /etc/passwd) )) ; then ....
Finally, there is an award called the Useless Use of Cat (UUOC)
. :-) Some people will jump up and down and cry gothca! I'll just say that grep
can take a file name on its cmd-line, so why invoke extra processes and pipe constructions when you don't have to? ;-)
I hope this helps.
In order to set the ImageView and Height Programatically, you can do
//Makesure you calculate the density pixel and multiply it with the size of width/height
float dpCalculation = getResources().getDisplayMetrics().density;
your_imageview.getLayoutParams().width = (int) (150 * dpCalculation);
//Set ScaleType according to your choice...
your_imageview.setScaleType(ImageView.ScaleType.CENTER_CROP);
Assuming lengths of portfolio and index are the same:
matrix = []
for i in range(len(portfolio)):
matrix.append([portfolio[i], index[i]])
Or a one-liner using list comprehension:
matrix2 = [[portfolio[i], index[i]] for i in range(len(portfolio))]
Actually its pretty easy to make integration between Csharp (VS) and Python with IronPython. It's not that much complex... As Chris Dunaway already said in answer section I started to build this inegration for my own project. N its pretty simple. Just follow these steps N you will get your results.
step 1 : Open VS and create new empty ConsoleApp project.
step 2 : Go to tools --> NuGet Package Manager --> Package Manager Console.
step 3 : After this open this link in your browser and copy the NuGet Command. Link: https://www.nuget.org/packages/IronPython/2.7.9
step 4 : After opening the above link copy the PM>Install-Package IronPython -Version 2.7.9 command and paste it in NuGet Console in VS. It will install the supportive packages.
step 5 : This is my code that I have used to run a .py file stored in my Python.exe directory.
using IronPython.Hosting;//for DLHE
using Microsoft.Scripting.Hosting;//provides scripting abilities comparable to batch files
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.Sockets;
class Hi
{
private static void Main(string []args)
{
Process process = new Process(); //to make a process call
ScriptEngine engine = Python.CreateEngine(); //For Engine to initiate the script
engine.ExecuteFile(@"C:\Users\daulmalik\AppData\Local\Programs\Python\Python37\p1.py");//Path of my .py file that I would like to see running in console after running my .cs file from VS.//process.StandardInput.Flush();
process.StandardInput.Close();//to close
process.WaitForExit();//to hold the process i.e. cmd screen as output
}
}
step 6 : save and execute the code
The port that the Admin button references is configurable. In the XAMPP install folder there is a xampp-control.ini
file. Changing the Apache entry under [ServicePorts]
will affect the url the Admin button opens.
[ServicePorts]
Apache=8080
I used xCode 7 and iOS 9.
in your .m
delete #import "VC.h"
save .m and link your outlet again it work fine.
in your .m
add #import "VC.h"
save .m
Here is yet another, compact version, with the generics syntax:
public static IEnumerable<T> FindLogicalChildren<T>(DependencyObject obj) where T : DependencyObject
{
if (obj != null) {
if (obj is T)
yield return obj as T;
foreach (DependencyObject child in LogicalTreeHelper.GetChildren(obj).OfType<DependencyObject>())
foreach (T c in FindLogicalChildren<T>(child))
yield return c;
}
}
Swift 4:
label.lineBreakMode = .byWordWrapping
label.numberOfLines = 0
label.translatesAutoresizingMaskIntoConstraints = false
label.preferredMaxLayoutWidth = superview.bounds.size.width - 10
To clarify a point in Thomas' excellent answer, it should be mentioned that append()
is thread safe.
This is because there is no concern that data being read will be in the same place once we go to write to it. The append()
operation does not read data, it only writes data to the list.
I use the InvokeOnClick()
method. It takes two arguments: Control and EventArgs. If you need the EventArgs, then create an instance of it and pass it in, else use InvokeOnClick(controlToClick, null);
. You can use a variety of Mouse event related arguments that derive from EventArgs such as MouseEventArgs.
Only know about this. Not sure how well does it against MySQL http://developer.mimer.se/validator/
git remote show origin
Replace 'origin' with whatever the name of your remote is.
You can now make it shorter and simpler by using the Object.fromEntries method (check browser support):
const raw = { item1: { prop:'1' }, item2: { prop:'2' }, item3: { prop:'3' } };
const allowed = ['item1', 'item3'];
const filtered = Object.fromEntries(
Object.entries(raw).filter(
([key, val])=>allowed.includes(key)
)
);
read more about: Object.fromEntries
It should be noted that the documentation recommends using a Layout
rather than Canvas.drawText
directly. My full answer about using a StaticLayout
is here, but I will provide a summary below.
String text = "This is some text.";
TextPaint textPaint = new TextPaint();
textPaint.setAntiAlias(true);
textPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
textPaint.setColor(0xFF000000);
int width = (int) textPaint.measureText(text);
StaticLayout staticLayout = new StaticLayout(text, textPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
staticLayout.draw(canvas);
Here is a fuller example in the context of a custom view:
public class MyView extends View {
String mText = "This is some text.";
TextPaint mTextPaint;
StaticLayout mStaticLayout;
// use this constructor if creating MyView programmatically
public MyView(Context context) {
super(context);
initLabelView();
}
// this constructor is used when created from xml
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
initLabelView();
}
private void initLabelView() {
mTextPaint = new TextPaint();
mTextPaint.setAntiAlias(true);
mTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
mTextPaint.setColor(0xFF000000);
// default to a single line of text
int width = (int) mTextPaint.measureText(mText);
mStaticLayout = new StaticLayout(mText, mTextPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
// New API alternate
//
// StaticLayout.Builder builder = StaticLayout.Builder.obtain(mText, 0, mText.length(), mTextPaint, width)
// .setAlignment(Layout.Alignment.ALIGN_NORMAL)
// .setLineSpacing(1, 0) // multiplier, add
// .setIncludePad(false);
// mStaticLayout = builder.build();
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
// Tell the parent layout how big this view would like to be
// but still respect any requirements (measure specs) that are passed down.
// determine the width
int width;
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthRequirement = MeasureSpec.getSize(widthMeasureSpec);
if (widthMode == MeasureSpec.EXACTLY) {
width = widthRequirement;
} else {
width = mStaticLayout.getWidth() + getPaddingLeft() + getPaddingRight();
if (widthMode == MeasureSpec.AT_MOST) {
if (width > widthRequirement) {
width = widthRequirement;
// too long for a single line so relayout as multiline
mStaticLayout = new StaticLayout(mText, mTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
}
}
}
// determine the height
int height;
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightRequirement = MeasureSpec.getSize(heightMeasureSpec);
if (heightMode == MeasureSpec.EXACTLY) {
height = heightRequirement;
} else {
height = mStaticLayout.getHeight() + getPaddingTop() + getPaddingBottom();
if (heightMode == MeasureSpec.AT_MOST) {
height = Math.min(height, heightRequirement);
}
}
// Required call: set width and height
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
// do as little as possible inside onDraw to improve performance
// draw the text on the canvas after adjusting for padding
canvas.save();
canvas.translate(getPaddingLeft(), getPaddingTop());
mStaticLayout.draw(canvas);
canvas.restore();
}
}
SOURCE: https://git-scm.com/book/en/v2/Distributed-Git-Maintaining-a-Project#Integrating-Contributed-Work
The other way to move introduced work from one branch to another is to cherry-pick it. A cherry-pick in Git is like a rebase for a single commit. It takes the patch that was introduced in a commit and tries to reapply it on the branch you’re currently on. This is useful if you have a number of commits on a topic branch and you want to integrate only one of them, or if you only have one commit on a topic branch and you’d prefer to cherry-pick it rather than run rebase. For example, suppose you have a project that looks like this:
If you want to pull commit e43a6 into your master branch, you can run
$ git cherry-pick e43a6
Finished one cherry-pick.
[master]: created a0a41a9: "More friendly message when locking the index fails."
3 files changed, 17 insertions(+), 3 deletions(-)
This pulls the same change introduced in e43a6, but you get a new commit SHA-1 value, because the date applied is different. Now your history looks like this:
Now you can remove your topic branch and drop the commits you didn’t want to pull in.
yo can extend your JS with a select method like this
Array.prototype.select = function(closure){
for(var n = 0; n < this.length; n++) {
if(closure(this[n])){
return this[n];
}
}
return null;
};
now you can use this:
var x = [1,2,3,4];
var a = x.select(function(v) {
return v == 2;
});
console.log(a);
or for objects in a array
var x = [{id: 1, a: true},
{id: 2, a: true},
{id: 3, a: true},
{id: 4, a: true}];
var a = x.select(function(obj) {
return obj.id = 2;
});
console.log(a);
You must extend the regional options like this (code split on multiple lines for readability):
var options = $.extend(
{}, // empty object
$.datepicker.regional["fr"], // fr regional
{ dateFormat: "d MM, y" /*, ... */ } // your custom options
);
$("#datepicker").datepicker(options);
The order of parameters is important because of the way jQuery.extend
works. Two incorrect examples:
/*
* This overwrites the global variable itself instead of creating a
* customized copy of french regional settings
*/
$.extend($.datepicker.regional["fr"], { dateFormat: "d MM, y"});
/*
* The desired dateFormat is overwritten by french regional
* settings' date format
*/
$.extend({ dateFormat: "d MM, y"}, $.datepicker.regional["fr"]);
PS: you also need to load the jQuery UI i18n files:
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/i18n/jquery-ui-i18n.min.js">
</script>
I had the exact same problem - I was running my nginx in Virtualbox. I did not have caching turned on. But looks like sendfile
was set to on
in nginx.conf
and that was causing the problem. @kolbyjack mentioned it above in the comments.
When I turned off sendfile
- it worked fine.
Sendfile is used to ‘copy data between one file descriptor and another‘ and apparently has some real trouble when run in a virtual machine environment, or at least when run through Virtualbox. Turning this config off in nginx causes the static file to be served via a different method and your changes will be reflected immediately and without question
It is related to this bug: https://www.virtualbox.org/ticket/12597
I am not able to add a comment to M. Kiewisch since I do not have enough reputation points (only have 41 but need more than 50 to comment).
Anyway, just want to point out that M. Kiewisch solution does not work as is and may need more tweaking. Consider for example
>>> df = pd.DataFrame({'a': [1, 2, 3, 5], 'b': [4, np.NaN, 6, 4]})
>>> df
a b
0 1 4.0
1 2 NaN
2 3 6.0
3 5 4.0
>>> df.groupby(['b']).sum()
a
b
4.0 6
6.0 3
>>> df.astype(str).groupby(['b']).sum()
a
b
4.0 15
6.0 3
nan 2
which shows that for group b=4.0, the corresponding value is 15 instead of 6. Here it is just concatenating 1 and 5 as strings instead of adding it as numbers.
Since version 4.14 of Linux kernel, vfs_read
and vfs_write
functions are no longer exported for use in modules. Instead, functions exclusively for kernel's file access are provided:
# Read the file from the kernel space.
ssize_t kernel_read(struct file *file, void *buf, size_t count, loff_t *pos);
# Write the file from the kernel space.
ssize_t kernel_write(struct file *file, const void *buf, size_t count,
loff_t *pos);
Also, filp_open
no longer accepts user-space string, so it can be used for kernel access directly (without dance with set_fs
).
And the more complex query if you need to search in a several groups:
(&(objectCategory=user)(|(memberOf=CN=GroupOne,OU=Security Groups,OU=Groups,DC=example,DC=com)(memberOf=CN=GroupTwo,OU=Security Groups,OU=Groups,DC=example,DC=com)(memberOf=CN=GroupThree,OU=Security Groups,OU=Groups,DC=example,DC=com)))
The same example with recursion:
(&(objectCategory=user)(|(memberOf:1.2.840.113556.1.4.1941:=CN=GroupOne,OU=Security Groups,OU=Groups,DC=example,DC=com)(memberOf:1.2.840.113556.1.4.1941:=CN=GroupTwo,OU=Security Groups,OU=Groups,DC=example,DC=com)(memberOf:1.2.840.113556.1.4.1941:=CN=GroupThree,OU=Security Groups,OU=Groups,DC=example,DC=com)))
If you use Mac, you are in luck. One can change the keymap for Intellij as Mac OS X, then you can use option+C.
Something like
create or replace procedure my_proc( p_rc OUT SYS_REFCURSOR )
as
begin
open p_rc
for select 1 col1
from dual;
end;
/
variable rc refcursor;
exec my_proc( :rc );
print rc;
will work in SQL*Plus or SQL Developer. I don't have any experience with Embarcardero Rapid XE2 so I have no idea whether it supports SQL*Plus commands like this.
Other than using time/datetime package, pandas can also be used to solve the same problem.Here is how we can use pandas to convert timestamp to readable date:
Timestamps can be in two formats:
13 digits(milliseconds) - To convert milliseconds to date, use:
import pandas
result_ms=pandas.to_datetime('1493530261000',unit='ms')
str(result_ms)
Output: '2017-04-30 05:31:01'
10 digits(seconds) - To convert seconds to date, use:
import pandas
result_s=pandas.to_datetime('1493530261',unit='s')
str(result_s)
Output: '2017-04-30 05:31:01'
You need the Python Imaging Library (PIL) but alas! the PIL project seems to have been abandoned. In particular, it hasn't been ported to Python 3. So if you want PIL functionality in Python 3, you'll do well do use Pillow, which is the semi-official fork of PIL and appears to be actively developed. Actually, if you need a modern PIL implementation at all I'd recommend Pillow. It's as simple as pip install pillow
. As it uses the same namespace as PIL it's essentially a drop-in replacement.
How "semi-official" is this fork? you may ask. The About page of the Pillow docs say this:
As more time passes since the last PIL release, the likelihood of a new PIL release decreases. However, we’ve yet to hear an official “PIL is dead” announcement. So if you still want to support PIL, please report issues here first, then open corresponding Pillow tickets here.
Please provide a link to the first ticket so we can track the issue(s) upstream.
However, the most recent PIL release on the official PIL site is dated November 15, 2009. I think we can safely proclaim Pillow as the successor of PIL after (as of this writing) nearly eight years of no new releases. So even if you don't need Python 3 support, I suggest you eschew the ancient PIL 1.1.6 distribution available in PyPI and just install fresh, up-to-date, compatible Pillow.
I was able to find objects by name using below code.
stkMultiChildControl = stkMulti.FindChild<StackPanel>("stkMultiControl_" + couter.ToString());
After becoming frustrated with the too many limitations of cut
, I wrote my own replacement, which I called cuts
for "cut on steroids".
cuts provides what is likely the most minimalist solution to this and many other related cut/paste problems.
One example, out of many, addressing this particular question:
$ cat text.txt
0 1 2 3
0 1 2 3 4
$ cuts 2 text.txt
2
2
cuts
supports:
paste
separately)and much more. None of which is provided by standard cut
.
See also: https://stackoverflow.com/a/24543231/1296044
Source and documentation (free software): http://arielf.github.io/cuts/
Type aptitude
to start the package manager. There you can see which applications are installed.
Use /
to search for packages. Try searching for apache2
and php5
(or whatever versions you want to use). If they are installed, they should be bold and have an i
in front of them. If they are not installed (p
in front of the line) and you want to install them (and you have root permissions), use +
to select them and then g
(twice) to install it.
Word of warning: Before doing that, it might be wise to have a quick look at some aptitude tutorial on the web.
If you tried all of above and the problem is still not solved then make sure that pushed branch name is unique and not exists in remotes. Error message might be misleading.
I am assuming: If you sent the JSON value through browser then any number you sent that will be the type float64 so you cant get the value directly int in golang.
So do the conversion like:
//As that says:
fmt.Fprintf(w, "Type = %v", val) // <--- Type = float64
var iAreaId int = int(val.(float64))
This way you can get exact value what you wanted.
If your equation does not fit on a single line, then the multline
environment probably is what you need:
\begin{multline}
first part of the equation \\
= second part of the equation
\end{multline}
If you also need some alignment respect to the first part, you can use split
:
\begin{equation}
\begin{split}
first part &= second part #1 \\
&= second part #2
\end{split}
\end{equation}
Both environments require the amsmath
package.
See also aligned
as pointed out in an answer below.
Right-click any series on the chart. In the "Format Data Series" dialog, there is a "Series Order" tab, in which you can move series up and down. I find this much easier than fiddling with the last argument of the series formula.
This is in Excel 2003 in Windows. There is a similar dialog in Excel 2011 for Mac:
You need to set the Content-Disposition
header on the HttpResponseMessage
:
HttpResponseMessage response = new HttpResponseMessage();
response.StatusCode = HttpStatusCode.OK;
response.Content = new StreamContent(result);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "foo.txt"
};
I assume you are on Windows. Instead of trying to run your program by double clicking on it's icon or clicking a button in your IDE, open up a command prompt, cd to the directory your program is in, and run it by typing its name on the command line.
After some modifications in my Web.config CORS suddenly stopped working in my Web API 2 project (at least for OPTIONS request during the preflight). It seems that you need to have the section mentioned below in your Web.config or otherwise the (global) EnableCorsAttribute will not work on OPTIONS requests. Note that this is the exact same section Visual Studio will add in a new Web API 2 project.
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0"/>
<remove name="OPTIONSVerbHandler"/>
<remove name="TRACEVerbHandler"/>
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0"/>
</handlers>
</system.webServer>
try this
Calendar c = Calendar.getInstance();
int mseconds = c.get(Calendar.MILLISECOND)
an alternative would be
Calendar rightNow = Calendar.getInstance();
long offset = rightNow.get(Calendar.ZONE_OFFSET) +
rightNow.get(Calendar.DST_OFFSET);
long sinceMid = (rightNow.getTimeInMils() + offset) %
(24 * 60 * 60 * 1000);
System.out.println(sinceMid + " milliseconds since midnight");
Ok, I had a problem with Notepad++ not remembering that I had chosen not the "Remember Current Session". I tried hacking the config file, but that didn't work. Then I found out that there is a secret config file in your C:\Users\myuseraccount\AppData\Roaming\Notepad++ directory (Windows 7 x64). Mine was empty, meaning who know where the config was really coming from, but I copied over the file with the one in C:\Program Files (x86)\Notepad++ and now everything works just like you would expect it to.
There's a benchmark of various matrix packages available in java up on http://code.google.com/p/java-matrix-benchmark/ for a few different hardware configurations. But it's no substitute for doing your own benchmark.
Performance is going to vary with the type of hardware you've got (cpu, cores, memory, L1-3 cache, bus speed), the size of the matrices and the algorithms you intend to use. Different libraries have different takes on concurrency for different algorithms, so there's no single answer. You may also find that the overhead of translating to the form expected by a native library negates the performance advantage for your use case (some of the java libraries have more flexible options regarding matrix storage, which can be used for further performance optimizations).
Generally though, JAMA, Jampack and COLT are getting old, and do not represent the state of the current performance available in Java for linear algebra. More modern libraries make more effective use of multiple cores and cpu caches. JAMA was a reference implementation, and pretty much implements textbook algorithms with little regard to performance. COLT and IBM Ninja were the first java libraries to show that performance was possible in java, even if they lagged 50% behind native libraries.
I was getting this error when I was trying to add gestureRecognizer to my ViewController's view and the target was view, instead of being self:
Instead of:
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self.view, action: #selector(handleTap(_:))))
Fixed to:
self.view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap(_:))))
And the error was gone.
in your view, instead of:
@Html.EditorFor(model => model.Comments[0].Comment)
just use:
@Html.TextAreaFor(model => model.Comments[0].Comment, 5, 1, null)
The definition of an inline
function doesn't have to be in a header file but, because of the one definition rule (ODR) for inline functions, an identical definition for the function must exist in every translation unit that uses it.
The easiest way to achieve this is by putting the definition in a header file.
If you want to put the definition of a function in a single source file then you shouldn't declare it inline
. A function not declared inline
does not mean that the compiler cannot inline the function.
Whether you should declare a function inline
or not is usually a choice that you should make based on which version of the one definition rules it makes most sense for you to follow; adding inline
and then being restricted by the subsequent constraints makes little sense.
According to other answers I am adding the parallel stages scenario:
pipeline {
agent any
stages {
stage('some parallel stage') {
parallel {
stage('parallel stage 1') {
when {
expression { ENV == "something" }
}
steps {
echo 'something'
}
}
stage('parallel stage 2') {
steps {
echo 'something'
}
}
}
}
}
}
As far as I understand getters and setters are to improve encapsulation. There is nothing complex about them in C#.
You define a property of on object like this:
int m_colorValue = 0;
public int Color
{
set { m_colorValue = value; }
get { return m_colorValue; }
}
This is the most simple use. It basically sets an internal variable or retrieves its value. You use a Property like this:
someObject.Color = 222; // sets a color 222
int color = someObject.Color // gets the color of the object
You could eventually do some processing on the value in the setters or getters like this:
public int Color
{
set { m_colorValue = value + 5; }
get { return m_colorValue - 30; }
}
if you skip set or get, your property will be read or write only. That's how I understand the stuff.
You can easily do that with a for loop,
public static void main(String[] args) {
String aToZ="ABCD.....1234"; // 36 letter.
String randomStr=generateRandom(aToZ);
}
private static String generateRandom(String aToZ) {
Random rand=new Random();
StringBuilder res=new StringBuilder();
for (int i = 0; i < 17; i++) {
int randIndex=rand.nextInt(aToZ.length());
res.append(aToZ.charAt(randIndex));
}
return res.toString();
}
requests
does not handle parsing XML responses, no. XML responses are much more complex in nature than JSON responses, how you'd serialize XML data into Python structures is not nearly as straightforward.
Python comes with built-in XML parsers. I recommend you use the ElementTree API:
import requests
from xml.etree import ElementTree
response = requests.get(url)
tree = ElementTree.fromstring(response.content)
or, if the response is particularly large, use an incremental approach:
response = requests.get(url, stream=True)
# if the server sent a Gzip or Deflate compressed response, decompress
# as we read the raw stream:
response.raw.decode_content = True
events = ElementTree.iterparse(response.raw)
for event, elem in events:
# do something with `elem`
The external lxml project builds on the same API to give you more features and power still.
$ git rm ./*.DS_Store
- remove all .DS_Store from git$ echo \.DS_Store >> .gitignore
- ignore .DS_Store in futurecommit & push
replace:
input, select, textarea{
color: #000;
}
with:
input, select, textarea{
color: #f00;
}
or color: #ff0000;
Instead to target on button class (.btn), here I target to button element itself and it works for me.
button:focus {
outline:none !important;
box-shadow:none !important;
}
And can use shadow-none
class for input field
I tried to avoid too much custom CSS and after reading some other examples I merged the ideas there and got this solution:
<div class="form-group has-feedback has-clear">
<input type="text" class="form-control" ng-model="ctrl.searchService.searchTerm" ng-change="ctrl.search()" placeholder="Suche"/>
<a class="glyphicon glyphicon-remove-sign form-control-feedback form-control-clear" ng-click="ctrl.clearSearch()" style="pointer-events: auto; text-decoration: none;cursor: pointer;"></a>
</div>
As I don't use bootstrap's JavaScript, just the CSS together with Angular, I don't need the classes has-clear and form-control-clear, and I implemented the clear function in my AngularJS controller. With bootstrap's JavaScript this might be possible without own JavaScript.
I don't know if there is an existing underscore method that does this, but you can achieve the same result with plain javascript.
Array.prototype.getIndexBy = function (name, value) {
for (var i = 0; i < this.length; i++) {
if (this[i][name] == value) {
return i;
}
}
return -1;
}
Then you can just do:
var data = tv[tv.getIndexBy("id", 2)]
If you are using one of those js libraries to insert Flash, I suggest adding plain object embed tag inside of <noscript/>
.
assuming that string1 is your whole operation
use mdas
double result;
string recurAndCheck(string operation){
if(operation.indexOf("/")){
String leftSide = recurAndCheck(operation.split("/")[0]);
string rightSide = recurAndCheck(operation.split("/")[1]);
result = Double.parseDouble(leftSide)/Double.parseDouble(rightSide);
} else if (..continue w/ *...) {
//same as above but change / with *
} else if (..continue w/ -) {
//change as above but change with -
} else if (..continuew with +) {
//change with add
} else {
return;
}
}
This will get you close, the add button has been removed out of the table so you might want to consider this...
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function() {
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
return false;
});
});
</script>
HTML markup looks like this
<a id="add">+</a></td>
<table id="mytable" width="300" border="1" cellspacing="0" cellpadding="2">
<tbody>
<tr>
<td>Name</td>
</tr>
<tr class="person">
<td><input type="text" name="name" id="name" /></td>
</tr>
</tbody>
</table>
EDIT To empty a value of a textbox after insert..
$('#mytable tbody>tr:last').clone(true).insertAfter('#mytable tbody>tr:last');
$('#mytable tbody>tr:last #name').val('');
return false;
EDIT2 Couldn't help myself, to reset all dropdown lists in the inserted TR you can do this
$("#mytable tbody>tr:last").each(function() {this.reset();});
I will leave the rest to you!
My configuration was like this. I had a QuartzJob , a Service Bean , and Dao . as usual it was configured with LocalSessionFactoryBean (for hibernate) , and SchedulerFactoryBean for Quartz framework. while writing the Quartz job , I by mistake annotated it with @Service , I should not have done that because I was using another strategy to wire the QuartzBean using AutowiringSpringBeanJobFactory extending SpringBeanJobFactory.
So what actually was happening is that due to Quartz Autowire , TX was getting injected to the Job Bean and at the same time Tx Context was set by virtue of @Service annotation and hence the TX was falling out of sync !!
I hope it help to those for whom above solutions really didn't solved the issue. I was using Spring 4.2.5 and Hibernate 4.0.1 ,
I see that in this thread there is a unnecessary suggestion to add @Transactional annotation to the DAO(@Repository) , that is a useless suggestion cause @Repository has all what it needs to have don't have to specially set that @transactional on DAOs , as the DAOs are called from the services which have already being injected by @Trasancational . I hope this might be helpful people who are using Quartz , Spring and Hibernate together.
Think of it as the natural orthogonal operation to split.
I understand why it is applicable to anything iterable and so can't easily be implemented just on list.
For readability, I'd like to see it in the language but I don't think that is actually feasible - if iterability were an interface then it could be added to the interface but it is just a convention and so there's no central way to add it to the set of things which are iterable.
You need to create folders inside "framework". Please Follow these steps:
cd storage/
mkdir -p framework/{sessions,views,cache}
You also need to set permissions to allow Laravel to write data in this directory.
chmod -R 775 framework
chown -R www-data:www-data framework
I use something similar, but with opposite logic, in a lot of my functions.
DWORD dwError = ERROR_SUCCESS;
do
{
if ( (dwError = SomeFunction()) != ERROR_SUCCESS )
{
/* handle error */
continue;
}
if ( (dwError = SomeOtherFunction()) != ERROR_SUCCESS )
{
/* handle error */
continue;
}
}
while ( 0 );
if ( dwError != ERROR_SUCCESS )
{
/* resource cleanup */
}
For pasting something that is the system clipboard you can just use SHIFT - INS.
It works in Windows, but I am guessing it works well in Linux too.
Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.
UPD 19.03.2019 Here is a version for browser on GitHub.
In principle you're doing it correct already. For what you want you do need two malloc()
s.
Just some comments:
struct Vector y = (struct Vector*)malloc(sizeof(struct Vector));
y->x = (double*)malloc(10*sizeof(double));
should be
struct Vector *y = malloc(sizeof *y); /* Note the pointer */
y->x = calloc(10, sizeof *y->x);
In the first line, you allocate memory for a Vector object. malloc()
returns a pointer to the allocated memory, so y must be a Vector pointer. In the second line you allocate memory for an array of 10 doubles.
In C you don't need the explicit casts, and writing sizeof *y
instead of sizeof(struct Vector)
is better for type safety, and besides, it saves on typing.
You can rearrange your struct and do a single malloc()
like so:
struct Vector{
int n;
double x[];
};
struct Vector *y = malloc(sizeof *y + 10 * sizeof(double));
I use this function in my python programs. The input for the function is as example:
value = time.time()
def stopWatch(value):
'''From seconds to Days;Hours:Minutes;Seconds'''
valueD = (((value/365)/24)/60)
Days = int (valueD)
valueH = (valueD-Days)*365
Hours = int(valueH)
valueM = (valueH - Hours)*24
Minutes = int(valueM)
valueS = (valueM - Minutes)*60
Seconds = int(valueS)
print Days,";",Hours,":",Minutes,";",Seconds
start = time.time() # What in other posts is described is
***your code HERE***
end = time.time()
stopWatch(end-start) #Use then my code