I feel your pain as I, too, am starting out to get Django and React.js working together. Did a couple of Django projects, and I think, React.js is a great match for Django. However, it can be intimidating to get started. We are standing on the shoulders of giants here ;)
Here's how I think, it all works together (big picture, please someone correct me if I'm wrong).
Communication between Django and 'the frontend' is done via the Rest framework. Make sure you get your authorization and permissions for the Rest framework in place.
I found a good boiler template for exactly this scenario and it works out of the box. Just follow the readme https://github.com/scottwoodall/django-react-template and once you are done, you have a pretty nice Django Reactjs project running. By no means this is meant for production, but rather as a way for you to dig in and see how things are connected and working!
One tiny change I'd like to suggest is this: Follow the setup instructions BUT before you get to the 2nd step to setup the backend (Django here https://github.com/scottwoodall/django-react-template/blob/master/backend/README.md), change the requirements file for the setup.
You'll find the file in your project at /backend/requirements/common.pip Replace its content with this
appdirs==1.4.0
Django==1.10.5
django-autofixture==0.12.0
django-extensions==1.6.1
django-filter==1.0.1
djangorestframework==3.5.3
psycopg2==2.6.1
this gets you the latest stable version for Django and its Rest framework.
I hope that helps.
this is how I implement it .
let dictionary = self.convertStringToDictionary(responceString)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "SOCKET_UPDATE"), object: dictionary)
This issue may be because in the recent past you have used IP address binding in your application configuration.
Steps to Solve the issue:
netsh http show iplisten
If you see some thing like below then this solution may not help you.
IP addresses present in the IP listen to list:
0.0.0.0
If you see something different than 0.0.0.0 then try below steps to fix this.
netsh http delete iplisten ipaddress=11.22.33.44
netsh http add iplisten ipaddress=0.0.0.0
iisreset
And now your issexpress is set to listen to any ping coming to localhost binding.
if you want to rotate inline elements, you should set the inline element to inline-block
first.
i {
display: inline-block;
}
i:hover {
animation: rotate-btn .5s linear 3;
-webkit-animation: rotate-btn .5s linear 3;
}
@keyframes rotate-btn {
0% {
transform: rotate(0);
}
100% {
transform: rotate(-360deg);
}
}
To remove spaces from left/right, use LTRIM/RTRIM. What you had
UPDATE *tablename*
SET *columnname* = LTRIM(RTRIM(*columnname*));
would have worked on ALL the rows. To minimize updates if you don't need to update, the update code is unchanged, but the LIKE expression in the WHERE clause would have been
UPDATE [tablename]
SET [columnname] = LTRIM(RTRIM([columnname]))
WHERE 32 in (ASCII([columname]), ASCII(REVERSE([columname])));
Note: 32 is the ascii code for the space character.
Try this.........
ProgressDialog pd1;
pd1=new ProgressDialog(<current context reference here>);
pd1.setMessage("Loading....");
pd1.setCancelable(false);
pd1.show();
To dismiss....
if(pd1!=null)
pd1.dismiss();
Global working tested solution.
getSupportFragmentManager()
keeps the null reference some times and View pager does not create new since it find reference to same fragment. So to over come this use getChildFragmentManager()
solves problem in simple way.
Don't do this:
new PagerAdapter(getSupportFragmentManager(), fragments);
Do this:
new PagerAdapter(getChildFragmentManager() , fragments);
Use pynum2word module that can be found at sourceforge
>>> import num2word
>>> num2word.to_card(15)
'fifteen'
>>> num2word.to_card(55)
'fifty-five'
>>> num2word.to_card(1555)
'one thousand, five hundred and fifty-five'
As of Git 2.19 you can simply:
git branch --sort=-committerdate
You can also:
git config branch.sort -committerdate
So whenever you list branches in the current repository, it will be listed sorted by committerdate.
If whenever you list branches, you want them sorted by comitterdate:
git config --global branch.sort -committerdate
Disclaimer: I'm the author of this feature in Git, and I implemented it when I saw this question.
Modern browsers allow cross-domain AJAX queries, it's called Cross-Origin Resource Sharing (see also this document for a shorter and more practical introduction), and recent versions of jQuery support it out of the box; you need a relatively recent browser version though (FF3.5+, IE8+, Safari 4+, Chrome4+; no Opera support AFAIK).
Old thread, but i wanted to update since i worked on this problem today, i didnt have jquery in my project so i did it the plain old javascript way, i also needed to block the content on the screen so in my xhtml
<img id="loading" src="#{request.contextPath}/images/spinner.gif" style="display: none;"/>
in my javascript
document.getElementsByClassName('myclass').style.opacity = '0.7'
document.getElementById('loading').style.display = "block";
Well Facebook has undergone MANY many changes and it wasn't originally designed to be efficient. It was designed to do it's job. I have absolutely no idea what the code looks like and you probably won't find much info about it (for obvious security and copyright reasons), but just take a look at the API. Look at how often it changes and how much of it doesn't work properly, anymore, or at all.
I think the biggest ace up their sleeve is the Hiphop. http://developers.facebook.com/blog/post/358 You can use HipHop yourself: https://github.com/facebook/hiphop-php/wiki
But if you ask me it's a very ambitious and probably time wasting task. Hiphop only supports so much, it can't simply convert everything to C++. So what does this tell us? Well, it tells us that Facebook is NOT fully taking advantage of the PHP language. It's not using the latest 5.3 and I'm willing to bet there's still a lot that is PHP 4 compatible. Otherwise, they couldn't use HipHop. HipHop IS A GOOD IDEA and needs to grow and expand, but in it's current state it's not really useful for that many people who are building NEW PHP apps.
There's also PHP to JAVA via things like Resin/Quercus. Again, it doesn't support everything...
Another thing to note is that if you use any non-standard PHP module, you aren't going to be able to convert that code to C++ or Java either. However...Let's take a look at PHP modules. They are ARE compiled in C++. So if you can build PHP modules that do things (like parse XML, etc.) then you are basically (minus some interaction) working at the same speed. Of course you can't just make a PHP module for every possible need and your entire app because you would have to recompile and it would be much more difficult to code, etc.
However...There are some handy PHP modules that can help with speed concerns. Though at the end of the day, we have this awesome thing known as "the cloud" and with it, we can scale our applications (PHP included) so it doesn't matter as much anymore. Hardware is becoming cheaper and cheaper. Amazon just lowered it's prices (again) speaking of.
So as long as you code your PHP app around the idea that it will need to one day scale...Then I think you're fine and I'm not really sure I'd even look at Facebook and what they did because when they did it, it was a completely different world and now trying to hold up that infrastructure and maintain it...Well, you get things like HipHop.
Now how is HipHop going to help you? It won't. It can't. You're starting fresh, you can use PHP 5.3. I'd highly recommend looking into PHP 5.3 frameworks and all the new benefits that PHP 5.3 brings to the table along with the SPL libraries and also think about your database too. You're most likely serving up content from a database, so check out MongoDB and other types of databases that are schema-less and document-oriented. They are much much faster and better for the most "common" type of web site/app.
Look at NEW companies like Foursquare and Smugmug and some other companies that are utilizing NEW technology and HOW they are using it. For as successful as Facebook is, I honestly would not look at them for "how" to build an efficient web site/app. I'm not saying they don't have very (very) talented people that work there that are solving (their) problems creatively...I'm also not saying that Facebook isn't a great idea in general and that it's not successful and that you shouldn't get ideas from it....I'm just saying that if you could view their entire source code, you probably wouldn't benefit from it.
Today things have changed a little.
Now we avoid use ProgressDialog to show spinning progress:
If you want to put in your app a spinning progress you should use an Activity indicators:
http://developer.android.com/design/building-blocks/progress.html#activity
Note that when using ASP.Net MVC, with using (Ajax.BeginForm(...
, setting the ajaxStart
will not work.
Use the AjaxOptions
to overcome this issue:
(Ajax.BeginForm("ActionName", new AjaxOptions { OnBegin = "uiOfProccessingAjaxAction", OnComplete = "uiOfProccessingAjaxActionComplete" }))
var array = searchTerms.split(",");
for (var i in array){
alert(array[i]);
}
The code is valid (i.e, will compile and execute) in both cases.
One of my lecturers at Uni told us that it is not desirable to have continue
, return
statements in any loop - for
or while
. The reason for this is that when examining the code, it is not not immediately clear whether the full length of the loop will be executed or the return
or continue
will take effect.
See Why is continue inside a loop a bad idea? for an example.
The key point to keep in mind is that for simple scenarios like this it doesn't (IMO) matter but when you have complex logic determining the return value, the code is 'generally' more readable if you have a single return statement instead of several.
With regards to the Garbage Collection - I have no idea why this would be an issue.
See these answers:
Connecting to wi-fi using adb shell
However, I'm pretty sure that Google actually stores your email and password (at the time of saving to the device) for times like these. So when it needs to be unlocked, it won't require an internet connection.
I could be wrong. Either way, when I had this issue, I had internet connectivity, and I knew my username and password and it didn't care, kept saying they were wrong (even though I was logging into my email). Had to format the phone at the time!
Good luck.
You could do it in one line (useful for ci-environments):
taskkill /fi "Services eq SERVICE_NAME" /F
Filter -> Services -> ServiceName equals SERVICE_NAMES -> Force
Source: https://technet.microsoft.com/en-us/library/bb491009.aspx
A little late to the party but in one line provided that you have glob2 and humanize installed. Note that in Python 3, the default iglob
has a recursive mode. How to modify the code for Python 3 is left as a trivial exercise for the reader.
>>> import os
>>> from humanize import naturalsize
>>> from glob2 import iglob
>>> naturalsize(sum(os.path.getsize(x) for x in iglob('/var/**'))))
'546.2 MB'
So, as was mentioned in a couple comments containing the data in an array is simpler but the solution does not scale well in terms of efficiency as the data set size increases. You really should only use an iterator when you want to access a random object in the array, otherwise, generators are the way to go. Below I have prototyped a reader function which reads each json object individually and returns a generator.
The basic idea is to signal the reader to split on the carriage character "\n"
(or "\r\n"
for Windows). Python can do this with the file.readline()
function.
import json
def json_reader(filename):
with open(filename) as f:
for line in f:
yield json.loads(line)
However, this method only really works when the file is written as you have it -- with each object separated by a newline character. Below I wrote an example of a writer that separates an array of json objects and saves each one on a new line.
def json_writer(file, json_objects):
with open(file, "w") as f:
for jsonobj in json_objects:
jsonstr = json.dumps(jsonobj)
f.write(jsonstr + "\n")
You could also do the same operation with file.writelines()
and a list comprehension:
...
json_strs = [json.dumps(j) + "\n" for j in json_objects]
f.writelines(json_strs)
...
And if you wanted to append the data instead of writing a new file just change open(file, "w")
to open(file, "a")
.
In the end I find this helps a great deal not only with readability when I try and open json files in a text editor but also in terms of using memory more efficiently.
On that note if you change your mind at some point and you want a list out of the reader, Python allows you to put a generator function inside of a list and populate the list automatically. In other words, just write
lst = list(json_reader(file))
On Linux Mint (Debian Based) go to /opt/lampp/etc/httpd.conf
Find YOUR_OWN_FILES_LOCATION to, of course, your files location.
DocumentRoot "YOUR_OWN_FILES_LOCATION"
<Directory "YOUR_OWN_FILES_LOCATION">
#
# Possible values for the Options directive are "None", "All",
# or any combination of:
# Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important. Please see
# http://httpd.apache.org/docs/trunk/mod/core.html#options
# for more information.
#
#Options Indexes FollowSymLinks
# XAMPP
Options Indexes FollowSymLinks ExecCGI Includes
#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
# Options FileInfo AuthConfig Limit
#
#AllowOverride None
# since XAMPP 1.4:
AllowOverride All
#
# Controls who can get stuff from this server.
#
Require all granted
</Directory>
You might already know this, but to check that you're getting this stuff right have a look at http://www.subnet-calculator.com/ - you can see there how the bits represent the network and host portions of the address.
I was in trouble to import an Enum in typescript
error TS2307: Cannot find module...
What I did to make it work was migrate the enum to another file and make this change:
export enum MyEnum{
VALUE = "MY_VALUE"
}
to
export enum MyEnum{
VALUE = 1
}
If your end goal is to add elements to your page, just manipulate the DOM directly. Don't use string concatenation to try to create HTML - what a pain! See how much more straightforward it is to just create your element, instead of the HTML that represents your element:
var x = document.createElement("option");
x.value = col;
x.text = "Very roomy";
x.selected = col == "screwdriver";
Then, later when you put the element in your page, instead of setting the innerHTML
of the parent element, call appendChild()
:
mySelectElement.appendChild(x);
I've tried so many things.
Finally, It is the most suitable code to hide and show full screen mode.
private fun hideSystemUi() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
window.setDecorFitsSystemWindows(true)
} else {
// hide status bar
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
window.decorView.systemUiVisibility =
View.SYSTEM_UI_FLAG_IMMERSIVE or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
}
}
private fun showSystemUi() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
window.setDecorFitsSystemWindows(false)
} else {
// Show status bar
window.clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
window.decorView.systemUiVisibility = SYSTEM_UI_FLAG_LAYOUT_STABLE
}
}
It Implemented it in this app : Android Breakdown.
Go to Videos(Bottom Bar) > Play Any Video > Toggle Fullscreen
Solving this problem is easy:
net stop W3SVC
and Enter.You can now click in WAMPP and restart all services. Open your browser and navigate to "localhost".
If you need to start W3SVC again,
net start W3SVC
and Enter.You may also insert the element using the slice indexing in the list. For example:
>>> a = [1, 2, 4]
>>> insert_at = 2 # Index at which you want to insert item
>>> b = a[:] # Created copy of list "a" as "b".
# Skip this step if you are ok with modifying the original list
>>> b[insert_at:insert_at] = [3] # Insert "3" within "b"
>>> b
[1, 2, 3, 4]
For inserting multiple elements together at a given index, all you need to do is to use a list
of multiple elements that you want to insert. For example:
>>> a = [1, 2, 4]
>>> insert_at = 2 # Index starting from which multiple elements will be inserted
# List of elements that you want to insert together at "index_at" (above) position
>>> insert_elements = [3, 5, 6]
>>> a[insert_at:insert_at] = insert_elements
>>> a # [3, 5, 6] are inserted together in `a` starting at index "2"
[1, 2, 3, 5, 6, 4]
To know more about slice indexing, you can refer: Understanding slice notation.
Note: In Python 3.x, difference of performance between slice indexing and list.index(...)
is significantly reduced and both are almost equivalent. However, in Python 2.x, this difference is quite noticeable. I have shared performance comparisons later in this answer.
Alternative using list comprehension (but very slow in terms of performance):
As an alternative, it can be achieved using list comprehension with enumerate
too. (But please don't do it this way. It is just for illustration):
>>> a = [1, 2, 4]
>>> insert_at = 2
>>> b = [y for i, x in enumerate(a) for y in ((3, x) if i == insert_at else (x, ))]
>>> b
[1, 2, 3, 4]
Here's the timeit
comparison of all the answers with list of 1000 elements on Python 3.9.1 and Python 2.7.16. Answers are listed in the order of performance for both the Python versions.
My answer using sliced insertion - Fastest ( 2.25 µsec per loop)
python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
100000 loops, best of 5: 2.25 µsec per loop
Rushy Panchal's answer with most votes using list.insert(...)
- Second (2.33 µsec per loop)
python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
100000 loops, best of 5: 2.33 µsec per loop
ATOzTOA's accepted answer based on merge of sliced lists - Third (5.01 µsec per loop)
python3 -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
50000 loops, best of 5: 5.01 µsec per loop
My answer with List Comprehension and enumerate
- Fourth (very slow with 135 µsec per loop)
python3 -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
2000 loops, best of 5: 135 µsec per loop
My answer using sliced insertion - Fastest (2.09 µsec per loop)
python -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
100000 loops, best of 3: 2.09 µsec per loop
Rushy Panchal's answer with most votes using list.insert(...)
- Second (2.36 µsec per loop)
python -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
100000 loops, best of 3: 2.36 µsec per loop
ATOzTOA's accepted answer based on merge of sliced lists - Third (4.44 µsec per loop)
python -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
100000 loops, best of 3: 4.44 µsec per loop
My answer with List Comprehension and enumerate
- Fourth (very slow with 103 µsec per loop)
python -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
10000 loops, best of 3: 103 µsec per loop
This code is for the headset profiles, probably it will work for other profiles too. First you need to provide profile listener (Kotlin code):
private val mProfileListener = object : BluetoothProfile.ServiceListener {
override fun onServiceConnected(profile: Int, proxy: BluetoothProfile) {
if (profile == BluetoothProfile.HEADSET)
mBluetoothHeadset = proxy as BluetoothHeadset
}
override fun onServiceDisconnected(profile: Int) {
if (profile == BluetoothProfile.HEADSET) {
mBluetoothHeadset = null
}
}
}
Then while checking bluetooth:
mBluetoothAdapter.getProfileProxy(context, mProfileListener, BluetoothProfile.HEADSET)
if (!mBluetoothAdapter.isEnabled) {
return Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
}
It takes a bit of time until onSeviceConnected is called. After that you may get the list of the connected headset devices from:
mBluetoothHeadset!!.connectedDevices
It is just a collection of routines (functional programming) or class definitions(object oriented programming). The reason behind is simply code reuse, i.e. get the code that has already been written by other developers. The classes or routines normally define specific operations in a domain specific area. For example, there are some libraries of mathematics which can let developer just call the function without redo the implementation of how an algorithm works.
In framework, all the control flow is already there, and there are a bunch of predefined white spots that we should fill out with our code. A framework is normally more complex. It defines a skeleton where the application defines its own features to fill out the skeleton. In this way, your code will be called by the framework when appropriately. The benefit is that developers do not need to worry about if a design is good or not, but just about implementing domain specific functions.
The key difference between a library and a framework is “Inversion of Control”. When you call a method from a library, you are in control. But with a framework, the control is inverted: the framework calls you. Source.
Both of them defined API, which is used for programmers to use. To put those together, we can think of a library as a certain function of an application, a framework as the skeleton of the application, and an API is connector to put those together. A typical development process normally starts with a framework, and fill out functions defined in libraries through API.
You can use the title element as Phrogz indicated. There are also some good tooltips like jQuery's Tipsy http://onehackoranother.com/projects/jquery/tipsy/ (which can be used to replace all title elements), Bob Monteverde's nvd3 or even the Twitter's tooltip from their Bootstrap http://twitter.github.com/bootstrap/
wmic bios get serialnumber
if run from a command line (start-run should also do the trick) prints out on screen the Serial Number of the product,
(for example in a toshiba laptop it would print out the serial number of the laptop.
with this serial number you can then identify your laptop model if you need ,from the makers service website-usually..:):)
I had to do exactly that.:):)
i use this
<style>
html, body {
height: 100%;
margin: 0;
padding: 0 0;
}
.container-fluid {
height: 100%;
display: table;
width: 100%;
padding-right: 0;
padding-left: 0;
}
.row-fluid {
height: 100%;
display: table-cell;
vertical-align: middle;
width: 100%;
}
.centering {
float: none;
margin: 0 auto;
}
</style>
<body>
<div class="container-fluid">
<div class="row-fluid">
<div class="offset3 span6 centering">
content here
</div>
</div>
</div>
</body>
if you have this kind of problem with ispconfig3 and got an error like this
open_basedir restriction in effect. File(/var/www/clients/client7/web15) is not within the allowed path(s):.........
To solve it (in my case) , just set PHP to SuPHP in the Website's panel of ispconfig3
Hope it helps someone :)
- Import project folders into the eclipse workspace.(when projects use different Jre).
- Update or Reinstall eclipse
- Change Jre or Build related Settings.
- Or by there is a configuration mismatch.
You get two errors for each misconfigured files.
- The project cannot be built until build path errors are resolved.
- Unbound classpath container: 'JRE System Library.
- Select each project and apply Quick fix(Ctrl+1)
- Either Replace the project's JRE with default JRE or Specify Alternate JRE (or JDK).
You can do the same by right-click project-->Properties(from context menu)-->Java Build Path-->Libraries-->select current unbound library -->Remove-->Add Libraries-->Jre System library-->select default or alternate Jre.
Or directly choose Build Path-->Add libraries in project's context menu.
EITHER
- Open the current workspace (in which your project is) in File Explorer.
- Delete all org.eclipse.jdt.core.prefs file present in .settings folder of your imported projects.(Be careful while deleting. Don't delete any files or folders inside .metadata folder.)**
- Now,Select the .classpath files of projects (those with errors) and open them in a powerful text editor(such as Notepad++).
- Find the line similar to
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.6"/>
and replace it with<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
- Save all the files. And Refresh or restart Eclipse IDE. All the problems are gone.
OR
Get the JRE used by the projects and install on your computer and then specify it..
One of the way to do this is you can use ResponseEntity as a return object.
@RequestMapping(value="/rawdata/", method = RequestMethod.PUT)
public ResponseEntity<?> create(@RequestBody String data) {
if(everything_fine)
return new ResponseEntity<>(RestModel, HttpStatus.OK);
else
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
Google updated play store two months before. This is the solution working right now for me..
class GetVersionCode extends AsyncTask<Void, String, String> {
@Override
protected String doInBackground(Void... voids) {
String newVersion = null;
try {
Document document = Jsoup.connect("https://play.google.com/store/apps/details?id=" + MainActivity.this.getPackageName() + "&hl=en")
.timeout(30000)
.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
.referrer("http://www.google.com")
.get();
if (document != null) {
Elements element = document.getElementsContainingOwnText("Current Version");
for (Element ele : element) {
if (ele.siblingElements() != null) {
Elements sibElemets = ele.siblingElements();
for (Element sibElemet : sibElemets) {
newVersion = sibElemet.text();
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return newVersion;
}
@Override
protected void onPostExecute(String onlineVersion) {
super.onPostExecute(onlineVersion);
if (onlineVersion != null && !onlineVersion.isEmpty()) {
if (Float.valueOf(currentVersion) < Float.valueOf(onlineVersion)) {
//show anything
}
}
Log.d("update", "Current version " + currentVersion + "playstore version " + onlineVersion);
}
}
and don't forget to add JSoup library
dependencies {
compile 'org.jsoup:jsoup:1.8.3'}
and on Oncreate()
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String currentVersion;
try {
currentVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
new GetVersionCode().execute();
}
that's it.. Thanks to this link
You can achieve this using Lodash _.assign
function.
library[title] = _.assign({}, {'foregrounds': foregrounds }, {'backgrounds': backgrounds });
// This is my JSON object generated from a database_x000D_
var library = {_x000D_
"Gold Rush": {_x000D_
"foregrounds": ["Slide 1", "Slide 2", "Slide 3"],_x000D_
"backgrounds": ["1.jpg", "", "2.jpg"]_x000D_
},_x000D_
"California": {_x000D_
"foregrounds": ["Slide 1", "Slide 2", "Slide 3"],_x000D_
"backgrounds": ["3.jpg", "4.jpg", "5.jpg"]_x000D_
}_x000D_
}_x000D_
_x000D_
// These will be dynamically generated vars from editor_x000D_
var title = "Gold Rush";_x000D_
var foregrounds = ["Howdy", "Slide 2"];_x000D_
var backgrounds = ["1.jpg", ""];_x000D_
_x000D_
function save() {_x000D_
_x000D_
// If title already exists, modify item_x000D_
if (library[title]) {_x000D_
_x000D_
// override one Object with the values of another (lodash)_x000D_
library[title] = _.assign({}, {_x000D_
'foregrounds': foregrounds_x000D_
}, {_x000D_
'backgrounds': backgrounds_x000D_
});_x000D_
console.log(library[title]);_x000D_
_x000D_
// Save to Database. Then on callback..._x000D_
// console.log('Changes Saved to <b>' + title + '</b>');_x000D_
}_x000D_
_x000D_
// If title does not exist, add new item_x000D_
else {_x000D_
// Format it for the JSON object_x000D_
var item = ('"' + title + '" : {"foregrounds" : ' + foregrounds + ',"backgrounds" : ' + backgrounds + '}');_x000D_
_x000D_
// THE PROBLEM SEEMS TO BE HERE??_x000D_
// Error: "Result of expression 'library.push' [undefined] is not a function"_x000D_
library.push(item);_x000D_
_x000D_
// Save to Database. Then on callback..._x000D_
console.log('Added: <b>' + title + '</b>');_x000D_
}_x000D_
}_x000D_
_x000D_
save();
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>
_x000D_
Neither. You should separate content and presentation, giving your HTML code logical codes. Think of it this way; to a blind person, or on a browser that cannot display colors, what is left of your code? Why do you want it to be red?
Most probably, your decision to make text red is because you want to give it emphasis. So your HTML code should be:
<em>test</em>
This way, even non-visual browsers can make sure they give the text emphasis in one way or another.
Next step is to make the text red. But you don't want to add the color code everywhere, much more efficient to just add it once:
<style>
em { color: red; }
</style>
This way, all emphasized code on your website becomes red, making it more constant.
I need to see your submit button html tag for better help. I am not familiar with php and how it handles the postback, but I guess depending on what you want to do, you have three options:
onclick
button on the client-side: In this case you only need to call a javascript function.function foo() {_x000D_
alert("Submit button clicked!");_x000D_
return true;_x000D_
}
_x000D_
<input type="submit" value="submit" onclick="return foo();" />
_x000D_
If you want to handle the click on the server-side, you should first make sure that the form tag method attribute is set to post
:
<form method="post">
You can use onsubmit
event from form
itself to bind your function to it.
<form name="frm1" method="post" onsubmit="return greeting()">_x000D_
<input type="text" name="fname">_x000D_
<input type="submit" value="Submit">_x000D_
</form>
_x000D_
Here is the code:-
telephonyManager = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
deviceId = telephonyManager.getDeviceId();
Log.d(TAG, "getDeviceId() " + deviceId);
phoneType = telephonyManager.getPhoneType();
Log.d(TAG, "getPhoneType () " + phoneType);
Options (Query Results/SQL Server/Results to Grid Page)
To change the options for the current queries, click Query Options on the Query menu, or right-click in the SQL Server Query window and select Query Options.
...
Maximum Characters Retrieved
Enter a number from 1 through 65535 to specify the maximum number of characters that will be displayed in each cell.
Maximum is, as you see, 64k. The default is much smaller.
BTW Results to Text has even more drastic limitation:
Maximum number of characters displayed in each column
This value defaults to 256. Increase this value to display larger result sets without truncation. The maximum value is 8,192.
pip install --ignore-installed six
Source: 1233 thumbs up on this comment
There is no mistake in your bash script. But you are executing it with sh which has a less extensive syntax ;)
So, run bash ./choose.sh
instead :)
ES6 introduces the new Math.trunc
method. This allows to fix @MarkElliot's answer to make it work for negative numbers too:
var div = Math.trunc(y/x);
var rem = y % x;
Note that Math
methods have the advantage over bitwise operators that they work with numbers over 231.
Clean implementation with no dependencies. https://jsfiddle.net/h3hqydxa/1/
<style type="text/css">
.dateField {
width: 150px;
height: 32px;
border: none;
position: absolute;
top: 32px;
left: 32px;
opacity: 0.5;
font-size: 12px;
font-weight: 300;
font-family: Arial;
opacity: 0;
}
.fakeDateField {
width: 100px; /* less, so we don't intercept click on browser chrome for date picker. could also change this at runtime */
height: 32px; /* same as above */
border: none;
position: absolute; /* position overtop the date field */
top: 32px;
left: 32px;
display: visible;
font-size: 12px; /* same as above */
font-weight: 300; /* same as above */
font-family: Arial; /* same as above */
line-height: 32px; /* for vertical centering */
}
</style>
<input class="dateField" id="dateField" type="date"></input>
<div id="fakeDateField" class="fakeDateField"><em>(initial value)</em></div>
<script>
var dateField = document.getElementById("dateField");
var fakeDateField = document.getElementById("fakeDateField");
fakeDateField.addEventListener("click", function() {
document.getElementById("dateField").focus();
}, false);
dateField.addEventListener("focus", function() {
fakeDateField.style.opacity = 0;
dateField.style.opacity = 1;
});
dateField.addEventListener("blur", function() {
fakeDateField.style.opacity = 1;
dateField.style.opacity = 0;
});
dateField.addEventListener("change", function() {
// this method could be replaced by momentJS stuff
if (dateField.value.length < 1) {
return;
}
var date = new Date(dateField.value);
var day = date.getUTCDate();
var month = date.getUTCMonth() + 1; //zero-based month values
fakeDateField.innerHTML = (month < 10 ? "0" : "") + month + " / " + day;
});
</script>
When you cherry-pick, it creates a new commit with a new SHA. If you do:
git cherry-pick -x <sha>
then at least you'll get the commit message from the original commit appended to your new commit, along with the original SHA, which is very useful for tracking cherry-picks.
With absolute or relative positioning, you can do all sorts of overlapping. You've probably want the logo to be styled as such:
div#logo {
position: absolute;
left: 100px; // or whatever
}
Note: absolute position has its eccentricities. You'll probably have to experiment a little, but it shouldn't be too hard to do what you want.
Paste this into your CMakeLists.txt:
# find python
execute_process(COMMAND python-config --prefix OUTPUT_VARIABLE PYTHON_SEARCH_PATH)
string(REGEX REPLACE "\n$" "" PYTHON_SEARCH_PATH "${PYTHON_SEARCH_PATH}")
file(GLOB_RECURSE PYTHON_DY_LIBS ${PYTHON_SEARCH_PATH}/lib/libpython*.dylib ${PYTHON_SEARCH_PATH}/lib/libpython*.so)
if (PYTHON_DY_LIBS)
list(GET PYTHON_DY_LIBS 0 PYTHON_LIBRARY)
message("-- Find shared libpython: ${PYTHON_LIBRARY}")
else()
message(WARNING "Cannot find shared libpython, try find_package")
endif()
find_package(PythonInterp)
find_package(PythonLibs ${PYTHON_VERSION_STRING} EXACT)
I have placed here complete bins for above query. you can check demo link too.
Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop
HTML
<div id="panel">
<input type="button" class="button" value="1" id="btn1">
<input type="button" class="button" value="2" id="btn2">
<input type="button" class="button" value="3" id="btn3">
<br>
<input type="text" id="valueFromMyModal">
<!-- Dialog Box-->
<div class="dialog" id="myform">
<form>
<label id="valueFromMyButton">
</label>
<input type="text" id="name">
<div align="center">
<input type="button" value="Ok" id="btnOK">
</div>
</form>
</div>
</div>
JQuery
$(function() {
$(".button").click(function() {
$("#myform #valueFromMyButton").text($(this).val().trim());
$("#myform input[type=text]").val('');
$("#myform").show(500);
});
$("#btnOK").click(function() {
$("#valueFromMyModal").val($("#myform input[type=text]").val().trim());
$("#myform").hide(400);
});
});
CSS
.button{
border:1px solid #333;
background:#6479fd;
}
.button:hover{
background:#a4a9fd;
}
.dialog{
border:5px solid #666;
padding:10px;
background:#3A3A3A;
position:absolute;
display:none;
}
.dialog label{
display:inline-block;
color:#cecece;
}
input[type=text]{
border:1px solid #333;
display:inline-block;
margin:5px;
}
#btnOK{
border:1px solid #000;
background:#ff9999;
margin:5px;
}
#btnOK:hover{
border:1px solid #000;
background:#ffacac;
}
Demo: http://codebins.com/bin/4ldqp78/2/How%20to%20make%20a%20simple%20modal%20pop
If its not too late to add most of the options in one answer:
There are a couple of options:
set an environment variable and get it from there:
export PGPASSWORD='password'
and then run your psql to login or even run the command from there:
psql -h clustername -U username -d testdb
On windows you will have to use "set" :
set PGPASSWORD=pass and then login to the psql bash.
You have to implement KeyListener
,take a look here:
http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyListener.html
More details on how to use it: http://docs.oracle.com/javase/tutorial/uiswing/events/keylistener.html
@tableName
Table variables are alive for duration of the script running only i.e. they are only session level objects.
To test this, open two query editor windows under sql server management studio, and create table variables with same name but different structures. You will get an idea. The @tableName
object is thus temporary and used for our internal processing of data, and it doesn't contribute to the actual database structure.
There is another type of table object which can be created for temporary use. They are #tableName
objects declared like similar create statement for physical tables:
Create table #test (Id int, Name varchar(50))
This table object is created and stored in temp database. Unlike the first one, this object is more useful, can store large data and takes part in transactions etc. These tables are alive till the connection is open. You have to drop the created object by following script before re-creating it.
IF OBJECT_ID('tempdb..#test') IS NOT NULL
DROP TABLE #test
Hope this makes sense !
in plain javascript:
function test() {
var cboxes = document.getElementsByName('mailId[]');
var len = cboxes.length;
for (var i=0; i<len; i++) {
alert(i + (cboxes[i].checked?' checked ':' unchecked ') + cboxes[i].value);
}
}
function selectOnlyOne(current_clicked) {
var cboxes = document.getElementsByName('mailId[]');
var len = cboxes.length;
for (var i=0; i<len; i++) {
cboxes[i].checked = (cboxes[i] == current);
}
}
Use height()
:
var result = $("#myDiv").height();
alert(result);
This will give you the unit-less computed height in pixels. "px" will be stripped from the result. I.e. if the height is 400px, the result will be 400, but the result will be in pixels.
If you want to do it without jQuery, you can use plain JavaScript:
var result = document.getElementById("myDiv").offsetHeight;
You can load your External JS files in Angular and you can load them directly instead of defining in index.html file.
component.ts:
ngOnInit() {
this.loadScripts();
}
loadScripts() {
const dynamicScripts = [
//scripts to be loaded
"assets/lib/js/hand-1.3.8.js",
"assets/lib/js/modernizr.jr.js",
"assets/lib/js/jquery-2.2.3.js",
"assets/lib/js/jquery-migrate-1.4.1.js",
"assets/js/jr.utils.js"
];
for (let i = 0; i < dynamicScripts.length; i++) {
const node = document.createElement('script');
node.src = dynamicScripts[i];
node.type = 'text/javascript';
node.async = false;
document.getElementById('scripts').appendChild(node);
}
}
component.html:
<div id="scripts">
</div>
You can also load styles similarly.
component.ts:
ngOnInit() {
this.loadStyles();
}
loadStyles() {
const dynamicStyles = [
//styles to be loaded
"assets/lib/css/ui.css",
"assets/lib/css/material-theme.css",
"assets/lib/css/custom-style.css"
];
for (let i = 0; i < dynamicStyles.length; i++) {
const node = document.createElement('link');
node.href = dynamicStyles[i];
node.rel = 'stylesheet';
document.getElementById('styles').appendChild(node);
}
}
component.html:
<div id="styles">
</div>
.foo img:last-child{display:none}_x000D_
.foo:hover img:first-child{display:none}_x000D_
.foo:hover img:last-child{display:inline-block}
_x000D_
<body> _x000D_
<a class="foo" href="#">_x000D_
<img src="http://lojanak.com/image/9/280/280/1/0" />_x000D_
<img src="http://lojanak.com/image/0/280/280/1/0" />_x000D_
</a>_x000D_
</body>
_x000D_
Use this code.
driver.FindElement(By.XPath(".//[@id='header']/div/div[3]/div/form/input[1]")).SendKeys("25025");
One simple use case when reverting change:
1. Use reset if you want to undo staging of a modified file.
2. Use checkout if you want to discard changes to unstaged file/s.
If you are using unix like OS, you can create a soft link to your target folder.
E.g. I want to see golang source while I am using VSCode. So, I create a soft link to go/src
under my project folder.
ln -s /usr/local/go/src gosrc
Hope this helps!
Update: 11/28, 2017
Multi Root Workspaces[0] landed in the stable build, finally. https://code.visualstudio.com/updates/v1_18#_support-for-multi-root-workspaces
NOTICE: This is never a recommended use of git. This will overwrite changes on the remote. Only do this if you know 100% that your local changes should be pushed to the remote master.
Try this: git push -f origin master
$ git help repository-layout
A Git repository comes in two different flavours:
- a .git directory at the root of the working tree;
- a .git directory that is a bare repository (i.e. without its own working tree), that is typically used for exchanging histories with others by pushing into it and fetching from it.
The best way to do this in my opinion is to use python's itertools
package.
>>>import itertools
>>>l1 = [1,2,3]
>>>l2 = [10,20,30]
>>>[l*2 for l in itertools.chain(*[l1,l2])]
[2, 4, 6, 20, 40, 60]
I would say you have two options:
to get all parent divs styled with 100%
height (including body and html)
to use absolute positioning for one of the parent divs (for example #content
) and then all child divs set to height 100%
I had the same issue when switching from a dev branch to master branch. What I did was commit my changes and switch to the master branch. You might have uncommitted changes.
Well there are a few ways to go about this depending on the intended behavior, but this link should give you all the best solutions and not surprisingly is from Dianne Hackborn
http://groups.google.com/group/android-developers/browse_thread/thread/d2a5c203dad6ec42
Essentially you have the following options
FragmentManager.popBackStack(String name,
FragmentManager.POP_BACK_STACK_INCLUSIVE)
.FragmentManager.getBackStackEntryCount()
/getBackStackEntryAt().getId()
to retrieve the ID of the first entry on the back stack, and
FragmentManager.popBackStack(int id,
FragmentManager.POP_BACK_STACK_INCLUSIVE)
.FragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE)
is supposed to pop the entire back stack... I think the documentation for
that is just wrong. (Actually I guess it just doesn't cover the case where
you pass in POP_BACK_STACK_INCLUSIVE
), Try this :
sc delete Apache2.4
or try this :
C:\Apache24\bin>httpd -k uninstall
hope this will be helpful
For those that want a nice conditional:
DECLARE @MyDate DATETIME = 'some date in future' --example DateAdd(day,5,GetDate())
IF @MyDate < DATEADD(DAY,1,GETDATE())
BEGIN
PRINT 'Date NOT greater than today...'
END
ELSE
BEGIN
PRINT 'Date greater than today...'
END
There is a third recovery mode not mentioned above. The recovery mode ultimately determines how large the LDF files become and how ofter they are written to. In cases where you are going to be doing any type of bulk inserts, you should set the DB to be in "BULK/LOGGED". This makes bulk inserts move speedily along and can be changed on the fly.
To do so,
USE master ;
ALTER DATABASE model SET RECOVERY BULK_LOGGED ;
To change it back:
USE master ;
ALTER DATABASE model SET RECOVERY FULL ;
In the spirit of adding to the conversation about why someone would not want an LDF, I add this: We do multi-dimensional modelling. Essentially we use the DB as a large store of variables that are processed in bulk using external programs. We do not EVER require rollbacks. If we could get a performance boost by turning of ALL logging, we'd take it in a heart beat.
You must declare
int add(int a, int b);
(note to the semicolon)
in a header file and include the file into both files.
Including it into Main.c will tell compiler how the function should be called.
Including into the second file will allow you to check that declaration is valid (compiler would complain if declaration and implementation were not matched).
Then you must compile both *.c files into one project. Details are compiler-dependent.
As a hack, you could consider having a special handling on the client side, converting 'Null' string to something that will never occur, for example, XXNULLXX and converting back on the server.
It is not pretty, but it may solve the issue for such a boundary case.
The ARM is like an Italian sports car:
The x86 is like an American muscle car:
In summary: the x86 is based on a design from 1974 and is good in a straight line (but uses a lot of fuel). The arm uses little fuel, does not slowdown for corners (branches).
Metaphor over, here are some real differences.
find / -exec grep -lR "{test-string}" {} \;
for(var y=birthyear; y <= thisyear; y++){
if( (y % 4 == 0 && y % 100 == 0) || y % 400 == 0 ) {
days = days-366;
number_of_long_years++;
} else {
days=days-365;
}
year++;
}
can you try this way??
At the time of writing in 2013, this was one way to do it. Composer has added support for better ways: See @igorw 's answer
DO YOU HAVE A REPOSITORY?
Git, Mercurial and SVN is supported by Composer.
DO YOU HAVE WRITE ACCESS TO THE REPOSITORY?
Yes?
DOES THE REPOSITORY HAVE A composer.json
FILE
If you have a repository you can write to: Add a composer.json
file, or fix the existing one, and DON'T use the solution below.
Go to @igorw 's answer
ONLY USE THIS IF YOU DON'T HAVE A REPOSITORY
OR IF THE REPOSITORY DOES NOT HAVE A composer.json
AND YOU CANNOT ADD IT
This will override everything that Composer may be able to read from the original repository's composer.json
, including the dependencies of the package and the autoloading.
Using the package
type will transfer the burden of correctly defining everything onto you. The easier way is to have a composer.json
file in the repository, and just use it.
This solution really only is for the rare cases where you have an abandoned ZIP download that you cannot alter, or a repository you can only read, but it isn't maintained anymore.
"repositories": [
{
"type":"package",
"package": {
"name": "l3pp4rd/doctrine-extensions",
"version":"master",
"source": {
"url": "https://github.com/l3pp4rd/DoctrineExtensions.git",
"type": "git",
"reference":"master"
}
}
}
],
"require": {
"l3pp4rd/doctrine-extensions": "master"
}
1. From Package Explorer
open the Filters...
dialog:
2. Then uncheck .* resources
option:
Use the gca
("get current axes") helper function:
ax = plt.gca()
Example:
import matplotlib.pyplot as plt
import matplotlib.finance
quotes = [(1, 5, 6, 7, 4), (2, 6, 9, 9, 6), (3, 9, 8, 10, 8), (4, 8, 8, 9, 8), (5, 8, 11, 13, 7)]
ax = plt.gca()
h = matplotlib.finance.candlestick(ax, quotes)
plt.show()
16 July 2020 - Kotlin Answer
Coding in Android Studio 4.0 with Kotlin:
fragmentManager?.popBackStack()
Happy coding!
@canerkaseler
I stumbled upon the same problem: a page with many independent animations, each one with its own parameters, which must be repeated forever.
Merging this clue with this other clue I found an easy solution: after the end of all your animations the wrapping div
is restored, forcing the animations to restart.
All you have to do is to add these few lines of Javascript, so easy they don't even need any external library, in the <head>
section of your page:
<script>
setInterval(function(){
var container = document.getElementById('content');
var tmp = container.innerHTML;
container.innerHTML= tmp;
}, 35000 // length of the whole show in milliseconds
);
</script>
BTW, the closing </head>
in your code is misplaced: it must be before the starting <body>
.
As for "Why not use int or unsigned int?", simply because it's semantically more meaningful not to. There's the practical reason that it can be, say, typedef
d as an int
and then upgraded to a long
later, without anyone having to change their code, of course, but more fundamentally than that a type is supposed to be meaningful. To vastly simplify, a variable of type size_t
is suitable for, and used for, containing the sizes of things, just like time_t
is suitable for containing time values. How these are actually implemented should quite properly be the implementation's job. Compared to just calling everything int
, using meaningful typenames like this helps clarify the meaning and intent of your program, just like any rich set of types does.
If you are using SQL Server (starting with vNext) or Azure SQL Database then you can use the below query.
SELECT TRIM(ColumnName) from TableName;
For other SQL SERVER Database you can use the below query.
SELECT LTRIM(RTRIM(ColumnName)) from TableName
LTRIM - Removes spaces from the left
example: select LTRIM(' test ') as trim
= 'test '
RTRIM - Removes spaces from the right
example: select RTRIM(' test ') as trim
= ' test'
You do not need it.
If your action has the HttpPost
attribute, then you do not need to bother with setting the JsonRequestBehavior
and use the overload without it. There is an overload for each method without the JsonRequestBehavior
enum. Here they are:
Without JsonRequestBehavior
protected internal JsonResult Json(object data);
protected internal JsonResult Json(object data, string contentType);
protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding);
With JsonRequestBehavior
protected internal JsonResult Json(object data, JsonRequestBehavior behavior);
protected internal JsonResult Json(object data, string contentType,
JsonRequestBehavior behavior);
protected internal virtual JsonResult Json(object data, string contentType,
Encoding contentEncoding, JsonRequestBehavior behavior);
All of these look more complicated than they need to be! Here is a short and sweet way to convert a time interval into hours, minutes and seconds:
NSTimeInterval timeInterval = 326.4;
long seconds = lroundf(timeInterval); // Since modulo operator (%) below needs int or long
int hour = seconds / 3600;
int mins = (seconds % 3600) / 60;
int secs = seconds % 60;
Note when you put a float into an int, you get floor() automatically, but you can add it to the first two if if makes you feel better :-)
Using the code below, you can get the unique device ID of an Android OS device as a string.
deviceId = Secure.getString(getApplicationContext().getContentResolver(), Secure.ANDROID_ID);
This is how you do it in Visual Studio 2010.
Because it is finicky, this can be quite painful, actually, because you are trying to do something so incredibly simple, but it isn't straight forward and there are many gotchas that Visual Studio doesn't tell you about. If at any point you feel angry or like you want to sink your teeth into a 2 by 4 and scream, by all means, please do so.
Gotchas:
1) Open VIEW > RESOURCE VIEW (in the middle of the VIEW menu), or press Ctrl+Shift+E to get it to appear.
2) In Resource view, right click the project name and say ADD > RESOURCE...
3) Assuming you have already generated an .ico file yourself, choose Icon from the list of crap that appears, then click IMPORT.
4) At this dialog *.ico
files aren't listed, and you can't use a regular PNG or JPG image as an icon, so change the file filter to *.ico
using the dropdown. Misleading UI, I know, I know.
5) If you compile your project now, it will automatically stick the .ico with the lowest ID (as listed in resource.h
) as the icon of your .exe file.
6) If you load a bunch of ICO files into the project for whatever reason, be sure the .ico you want Visual Studio to use has the lowest id in resource.h
. You can edit this file manually with no problems
Eg.
//resource.h
#define IDI_ICON1 102
#define IDI_ICON2 103
IDI_ICON1 is used
//resource.h
#define IDI_ICON1 106
#define IDI_ICON2 103
Now IDI_ICON2 is used.
I think that the idea of setting the Auto Return values as described above by Kevin is a bit strange!
Say, for example, that you have a number of websites that use the same PayPal account to handle your payments, or say that you have a number of sections in one website that perform different purchasing tasks, and require different return-addresses when the payment is completed. If I put a button on my page as described above in the 'Sample form using PHP for direct payments' section, you can see that there is a line there:
input type="hidden" name="return" value="https://www.yoursite.com/checkout_complete.php"
where you set the individual return value. Why does it have to be set generally, in the profile section as well?!?!
Also, because you can only set one value in the Profile Section, it means (AFAIK) that you cannot use the Auto Return on a site with multiple actions.
Comments please??
As a general rule, you can use Database_Default collation so you don't need to figure out which one to use. However, I strongly suggest reading Simons Liew's excellent article Understanding the COLLATE DATABASE_DEFAULT clause in SQL Server
SELECT *
FROM [FAEB].[dbo].[ExportaComisiones] AS f
JOIN [zCredifiel].[dbo].[optPerson] AS p
ON (p.vTreasuryId = f.RFC) COLLATE Database_Default
After having read lots of discussions, I have prepared a simple solution but I don't want to use lots of Jquery and CSS, just some javascript.
HTML Code:
<input type="date" id="dt" onchange="mydate1();" hidden/>
<input type="text" id="ndt" onclick="mydate();" hidden />
<input type="button" Value="Date" onclick="mydate();" />
CSS Code:
#dt {
text-indent: -500px;
height: 25px;
width: 200px;
}
Javascript Code :
function mydate() {
//alert("");
document.getElementById("dt").hidden = false;
document.getElementById("ndt").hidden = true;
}
function mydate1() {
d = new Date(document.getElementById("dt").value);
dt = d.getDate();
mn = d.getMonth();
mn++;
yy = d.getFullYear();
document.getElementById("ndt").value = dt + "/" + mn + "/" + yy
document.getElementById("ndt").hidden = false;
document.getElementById("dt").hidden = true;
}
Output:
Suppose that you have a JSON object like:
var example = {
"prop1": "value1",
"prop2": [ "value2_0", "value2_1"],
"prop3": {
"prop3_1": "value3_1"
}
}
The wrong way to iterate through its 'properties':
function recursivelyIterateProperties(jsonObject) {
for (var prop in Object.keys(jsonObject)) {
console.log(prop);
recursivelyIterateProperties(jsonObject[prop]);
}
}
You might be surprised of seeing the console logging 0
, 1
, etc. when iterating through the properties of prop1
and prop2
and of prop3_1
. Those objects are sequences, and the indexes of a sequence are properties of that object in Javascript.
A better way to recursively iterate through a JSON object properties would be to first check if that object is a sequence or not:
function recursivelyIterateProperties(jsonObject) {
for (var prop in Object.keys(jsonObject)) {
console.log(prop);
if (!(typeof(jsonObject[prop]) === 'string')
&& !(jsonObject[prop] instanceof Array)) {
recursivelyIterateProperties(jsonObject[prop]);
}
}
}
If you want to find properties inside of objects in arrays, then do the following:
function recursivelyIterateProperties(jsonObject) {
if (jsonObject instanceof Array) {
for (var i = 0; i < jsonObject.length; ++i) {
recursivelyIterateProperties(jsonObject[i])
}
}
else if (typeof(jsonObject) === 'object') {
for (var prop in Object.keys(jsonObject)) {
console.log(prop);
if (!(typeof(jsonObject[prop]) === 'string')) {
recursivelyIterateProperties(jsonObject[prop]);
}
}
}
}
Simply unregister the default StringHttpMessageConverter
instance:
@Configuration
public class WebMvcConfiguration extends WebMvcConfigurationSupport {
/**
* Unregister the default {@link StringHttpMessageConverter} as we want Strings
* to be handled by the JSON converter.
*
* @param converters List of already configured converters
* @see WebMvcConfigurationSupport#addDefaultHttpMessageConverters(List)
*/
@Override
protected void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.stream()
.filter(c -> c instanceof StringHttpMessageConverter)
.findFirst().ifPresent(converters::remove);
}
}
Tested with both controller action handler methods and controller exception handlers:
@RequestMapping("/foo")
public String produceFoo() {
return "foo";
}
@ExceptionHandler(FooApiException.class)
public String fooException(HttpServletRequest request, Throwable e) {
return e.getMessage();
}
Final notes:
extendMessageConverters
is available since Spring 4.1.3, if are running on a previous version you can implement the same technique using configureMessageConverters
, it just takes a little bit more work.In my case where I had the problem I was referring to a module when I tried extending the class.
import logging
class UserdefinedLogging(logging):
If you look at the Documentation Info, you'll see "logging" displayed as module.
In this specific case I had to simply inherit the logging module to create an extra class for the logging.
You certainly are able to have multiple CTEs in a single query expression. You just need to separate them with a comma. Here is an example. In the example below, there are two CTEs. One is named CategoryAndNumberOfProducts
and the second is named ProductsOverTenDollars
.
WITH CategoryAndNumberOfProducts (CategoryID, CategoryName, NumberOfProducts) AS
(
SELECT
CategoryID,
CategoryName,
(SELECT COUNT(1) FROM Products p
WHERE p.CategoryID = c.CategoryID) as NumberOfProducts
FROM Categories c
),
ProductsOverTenDollars (ProductID, CategoryID, ProductName, UnitPrice) AS
(
SELECT
ProductID,
CategoryID,
ProductName,
UnitPrice
FROM Products p
WHERE UnitPrice > 10.0
)
SELECT c.CategoryName, c.NumberOfProducts,
p.ProductName, p.UnitPrice
FROM ProductsOverTenDollars p
INNER JOIN CategoryAndNumberOfProducts c ON
p.CategoryID = c.CategoryID
ORDER BY ProductName
I don't know the reasoning behind this, but I set my parent container to display:flex
and the child containers to display:inline-block
and they stayed inline despite the combined width of the children exceeding the parent.
Didn't need to toy with max-width
, max-height
, white-space
, or anything else.
Hope that helps someone.
I know you don't want to obfuscate, but maybe you should check out dotfuscator, it will take your compiled assemblies and obfuscate them for you. I think it can even encrypt them.
simply use: date("Y-m-d H:i:s")
this will give you your date and time like '2020-08-22 12:20:30' this .
add date_default_timezone_set("your time zone")
before date() function to get the time date of your area/zone.
here you can find you time zone
Remove those char * ret
declarations inside if
blocks which hide outer ret
. Therefor you have memory leak and on the other hand un-allocated memory for ret
.
To compare a c-style string you should use strcmp(array,"")
not array!=""
. Your final code should looks like below:
char* appendCharToCharArray(char* array, char a)
{
size_t len = strlen(array);
char* ret = new char[len+2];
strcpy(ret, array);
ret[len] = a;
ret[len+1] = '\0';
return ret;
}
Note that, you must handle the allocated memory of returned ret
somewhere by delete[]
it.
Why you don't use std::string
? it has .append
method to append a character at the end of a string:
std::string str;
str.append('x');
// or
str += x;
I was facing the same problem because
System.Net.Http.Formatting
version written inside webconfig was 5.0.3 but inside the bin folder the library System.Net.Http.Formatting dll version was 4.0.2
so I just replaced with the same given inside bin
just do this clean project and build
You can do:
>>> a = 'ZENOVW'
>>> ''.join(sorted(a))
'ENOVWZ'
I tried some of these solutions, but they didn't quite work (though they were very much on the right track!)
In the end my error was:
FATAL: password authentication failed for user
when I ran the following command: psql
So then I ran these two commands:
dropdb()
createdb()
NOTE: this will remove the db, but I didn't need it and for some reason I could no longer access pqsl, so I removed and recreated it.
Then psql
worked again.
I am using ASP.NET MVC3 with SSRS 2008 and I couldn't get @Adrian's to work 100% for me when trying to get reports from a remote server.
Finally, I found that I needed to change the Page_Load method in ViewUserControl1.ascx to look like this:
ReportViewer1.ProcessingMode = ProcessingMode.Remote;
ServerReport serverReport = ReportViewer1.ServerReport;
serverReport.ReportServerUrl = new Uri("http://<Server Name>/reportserver");
serverReport.ReportPath = "/My Folder/MyReport";
serverReport.Refresh();
I had been missing the ProcessingMode.Remote.
References:
http://msdn.microsoft.com/en-us/library/aa337091.aspx - ReportViewer
Date values in JS are datetime values.
So, direct date computations are inconsistent:
(2013-11-05 00:00:00) - (2013-11-04 10:10:10) < 1 day
for example we need to convert de 2nd date:
(2013-11-05 00:00:00) - (2013-11-04 00:00:00) = 1 day
the method could be truncate the mills in both dates:
var date1 = new Date('2013/11/04 00:00:00');_x000D_
var date2 = new Date('2013/11/04 10:10:10'); //less than 1_x000D_
var start = Math.floor(date1.getTime() / (3600 * 24 * 1000)); //days as integer from.._x000D_
var end = Math.floor(date2.getTime() / (3600 * 24 * 1000)); //days as integer from.._x000D_
var daysDiff = end - start; // exact dates_x000D_
console.log(daysDiff);_x000D_
_x000D_
date2 = new Date('2013/11/05 00:00:00'); //1_x000D_
_x000D_
var start = Math.floor(date1.getTime() / (3600 * 24 * 1000)); //days as integer from.._x000D_
var end = Math.floor(date2.getTime() / (3600 * 24 * 1000)); //days as integer from.._x000D_
var daysDiff = end - start; // exact dates_x000D_
console.log(daysDiff);
_x000D_
If you are programming in PHP, it is useful to split lines by \n
and then trim()
each line (provided you don't care about whitespace) to give you a "clean" line regardless.
foreach($line in explode("\n", $data))
{
$line = trim($line);
...
}
For Tomcat running on Ubuntu server, to find out which Java is being used, use "ps -ef | grep tomcat" command:
Sample:
/home/mcp01$ **ps -ef |grep tomcat**
tomcat7 28477 1 0 10:59 ? 00:00:18 **/usr/local/java/jdk1.7.0_15/bin/java** -Djava.util.logging.config.file=/var/lib/tomcat7/conf/logging.properties -Djava.awt.headless=true -Xmx512m -XX:+UseConcMarkSweepGC -Djava.net.preferIPv4Stack=true -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.endorsed.dirs=/usr/share/tomcat7/endorsed -classpath /usr/share/tomcat7/bin/bootstrap.jar:/usr/share/tomcat7/bin/tomcat-juli.jar -Dcatalina.base=/var/lib/tomcat7 -Dcatalina.home=/usr/share/tomcat7 -Djava.io.tmpdir=/tmp/tomcat7-tomcat7-tmp org.apache.catalina.startup.Bootstrap start
1005 28567 28131 0 11:34 pts/1 00:00:00 grep --color=auto tomcat
Then, we can go in to: cd /usr/local/java/jdk1.7.0_15/jre/lib/security
Default cacerts file is located in here. Insert the untrusted certificate into it.
for who needs complete example code. Right+Left added
var keyPressed = {};
document.addEventListener('keydown', function(e) {
keyPressed[e.key + e.location] = true;
if(keyPressed.Shift1 == true && keyPressed.Control1 == true){
// Left shift+CONTROL pressed!
keyPressed = {}; // reset key map
}
if(keyPressed.Shift2 == true && keyPressed.Control2 == true){
// Right shift+CONTROL pressed!
keyPressed = {};
}
}, false);
document.addEventListener('keyup', function(e) {
keyPressed[e.key + e.location] = false;
keyPressed = {};
}, false);
Old question but nowadays CSS3 makes vertical alignment really simple!
Just add to the <div>
this css:
display:flex;
align-items:center;
justify-content:center;
Live Example:
.img_thumb {_x000D_
float: left;_x000D_
height: 120px;_x000D_
margin-bottom: 5px;_x000D_
margin-left: 9px;_x000D_
position: relative;_x000D_
width: 147px;_x000D_
background-color: rgba(0, 0, 0, 0.5);_x000D_
border-radius: 3px;_x000D_
display:flex;_x000D_
align-items:center;_x000D_
justify-content:center;_x000D_
}
_x000D_
<div class="img_thumb">_x000D_
<a class="images_class" href="http://i.imgur.com/2FMLuSn.jpg" rel="images">_x000D_
<img src="http://i.imgur.com/2FMLuSn.jpg" title="img_title" alt="img_alt" />_x000D_
</a>_x000D_
</div>
_x000D_
You can compare the length of the string with one where the commas are removed:
len(value) - len(replace(value,',',''))
Visio professional has a database reverse-engineering tool built into it. You should be able to use it with MySQL through an ODBC driver. It works best when you reverse engineer the database and then create the diagrams by dragging them off the tables and views panel. It will drag any foreign key objects and put them on the diagram as well.
In your Jenkins job configuration, tick the box named "This build is parameterized
", click the "Add Parameter
" button and select the "String Parameter
" drop down value.
Now define your parameter - example:
Now you can use your parameter in your job / build pipeline, example:
Next to trigger the build with own/custom parameter, invoke the following URL (using either POST or GET):
http://JENKINS_SERVER_ADDRESS/job/YOUR_JOB_NAME/buildWithParameters?myparam=myparam_value
Two more (similar) approaches with one generalized example:
1) first approach - removing field in save() method, e.g. (not tested ;) ):
def save(self, *args, **kwargs):
for fname in self.readonly_fields:
if fname in self.cleaned_data:
del self.cleaned_data[fname]
return super(<form-name>, self).save(*args,**kwargs)
2) second approach - reset field to initial value in clean method:
def clean_<fieldname>(self):
return self.initial[<fieldname>] # or getattr(self.instance, fieldname)
Based on second approach I generalized it like this:
from functools import partial
class <Form-name>(...):
def __init__(self, ...):
...
super(<Form-name>, self).__init__(*args, **kwargs)
...
for i, (fname, field) in enumerate(self.fields.iteritems()):
if fname in self.readonly_fields:
field.widget.attrs['readonly'] = "readonly"
field.required = False
# set clean method to reset value back
clean_method_name = "clean_%s" % fname
assert clean_method_name not in dir(self)
setattr(self, clean_method_name, partial(self._clean_for_readonly_field, fname=fname))
def _clean_for_readonly_field(self, fname):
""" will reset value to initial - nothing will be changed
needs to be added dynamically - partial, see init_fields
"""
return self.initial[fname] # or getattr(self.instance, fieldname)
Here is the hack solution I came up with for a specific layout. This solution is similar to Matt Gallagher solution in that is scrolls a section into view. I am still new to iPhone development, and am not familiar with how the layouts work. Thus, this hack.
My implementation needed to support scrolling when clicking in a field, and also scrolling when the user selects next on the keyboard.
I had a UIView with a height of 775. The controls are spread out basically in groups of 3 over a large space. I ended up with the following IB layout.
UIView -> UIScrollView -> [UI Components]
Here comes the hack
I set the UIScrollView height to 500 units larger then the actual layout (1250). I then created an array with the absolute positions I need to scroll to, and a simple function to get them based on the IB Tag number.
static NSInteger stepRange[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 140, 140, 140, 140, 140, 410
};
NSInteger getScrollPos(NSInteger i) {
if (i < TXT_FIELD_INDEX_MIN || i > TXT_FIELD_INDEX_MAX) {
return 0 ;
return stepRange[i] ;
}
Now all you need to do is use the following two lines of code in textFieldDidBeginEditing and textFieldShouldReturn (the latter one if you are creating a next field navigation)
CGPoint point = CGPointMake(0, getScrollPos(textField.tag)) ;
[self.scrollView setContentOffset:point animated:YES] ;
An example.
- (void) textFieldDidBeginEditing:(UITextField *)textField
{
CGPoint point = CGPointMake(0, getScrollPos(textField.tag)) ;
[self.scrollView setContentOffset:point animated:YES] ;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
NSInteger nextTag = textField.tag + 1;
UIResponder* nextResponder = [textField.superview viewWithTag:nextTag];
if (nextResponder) {
[nextResponder becomeFirstResponder];
CGPoint point = CGPointMake(0, getScrollPos(nextTag)) ;
[self.scrollView setContentOffset:point animated:YES] ;
}
else{
[textField resignFirstResponder];
}
return YES ;
}
This method does not 'scroll back' as other methods do. This was not a requirement. Again this was for a fairly 'tall' UIView, and I did not have days to learn the internal layout engines.
in flask using flask.ext.script, you can do it like this:
python manage.py runserver -h 127.0.0.1 -p 8000
UEFA or FIFA don't seem to provide any API to get the information you want. However, there are some third-party services which support that:
OPTA - Both commercial and free. They have incredible database about matches. Whoscored.com currently uses it.
Others: livescoreboards, xmlsoccer, ...
Here is the simplest version, hope it helps someone,
$('#cancel-button').click(function() {
var $form = $(this).closest('form');
$form.find('*[data-validation]').attr('data-validation', null);
$form.get(0).submit();
});
Multi-scale plots are rare to find beyond two axes... Luckily in Matlab it is possible, but you have to fully overlap axes and play with tickmarks so as not to hide info.
Below is a nice working sample. I hope this is what you are looking for (although colors could be much nicer)!
close all
clear all
display('Generating data');
x = 0:10;
y1 = rand(1,11);
y2 = 10.*rand(1,11);
y3 = 100.*rand(1,11);
y4 = 100.*rand(1,11);
display('Plotting');
figure;
ax1 = gca;
get(ax1,'Position')
set(ax1,'XColor','k',...
'YColor','b',...
'YLim',[0,1],...
'YTick',[0, 0.2, 0.4, 0.6, 0.8, 1.0]);
line(x, y1, 'Color', 'b', 'LineStyle', '-', 'Marker', '.', 'Parent', ax1)
ax2 = axes('Position',get(ax1,'Position'),...
'XAxisLocation','bottom',...
'YAxisLocation','left',...
'Color','none',...
'XColor','k',...
'YColor','r',...
'YLim',[0,10],...
'YTick',[1, 3, 5, 7, 9],...
'XTick',[],'XTickLabel',[]);
line(x, y2, 'Color', 'r', 'LineStyle', '-', 'Marker', '.', 'Parent', ax2)
ax3 = axes('Position',get(ax1,'Position'),...
'XAxisLocation','bottom',...
'YAxisLocation','right',...
'Color','none',...
'XColor','k',...
'YColor','g',...
'YLim',[0,100],...
'YTick',[0, 20, 40, 60, 80, 100],...
'XTick',[],'XTickLabel',[]);
line(x, y3, 'Color', 'g', 'LineStyle', '-', 'Marker', '.', 'Parent', ax3)
ax4 = axes('Position',get(ax1,'Position'),...
'XAxisLocation','bottom',...
'YAxisLocation','right',...
'Color','none',...
'XColor','k',...
'YColor','c',...
'YLim',[0,100],...
'YTick',[10, 30, 50, 70, 90],...
'XTick',[],'XTickLabel',[]);
line(x, y4, 'Color', 'c', 'LineStyle', '-', 'Marker', '.', 'Parent', ax4)
(source: pablorodriguez.info)
As kovpas has shown you can use the bounding box in most cases, although it is not always guaranteed that the bounding box will fit neatly around the text. A box with a height of 50 and font size of 12 may not give the results you want depending on the UILabel configuration.
Query the UIString within the UILabel to determine its exact metrics and use these to better place your underline regardless of the enclosing bounding box or frame using the drawing code already provided by kovpas.
You should also look at UIFont's "leading" property that gives the distance between baselines based on a particular font. The baseline is where you would want your underline to be drawn.
Look up the UIKit additions to NSString:
(CGSize)sizeWithFont:(UIFont *)font
//Returns the size of the string if it were to be rendered with the specified font on a single line.
(CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size
// Returns the size of the string if it were rendered and constrained to the specified size.
(CGSize)sizeWithFont:(UIFont *)font constrainedToSize:(CGSize)size lineBreakMode:(UILineBreakMode)lineBreakMode
//Returns the size of the string if it were rendered with the specified constraints.
IF EXISTS(SELECT TOP 1 1 FROM sys.default_constraints WHERE parent_object_id = OBJECT_ID(N'[dbo].[ChannelPlayerSkins]') AND name = 'FK_ChannelPlayerSkins_Channels')
BEGIN
DROP CONSTRAINT FK_ChannelPlayerSkins_Channels
END
GO
Html.Hidden and Html.HiddenFor used to generate name-value pairs which waited by action method in controller. Sample Usage(*):
@using (Html.BeginForm("RemoveFromCart", "Cart")) {
@Html.Hidden("ProductId", line.Product.ProductID)
@Html.HiddenFor(x => x.ReturnUrl)
<input class="btn btn-sm btn-warning"
type="submit" value="Remove" />
}
If your action method wait for "ProductId" you have to generate this name in form via using (Html.Hidden or Html.HiddenFor) For the case it is not possible to generate this name with strongly typed model you simple write this name with a string thats "ProductId".
public ViewResult RemoveFromCart(int productId, string returnUrl){...}
If I had written Html.HiddenFor(x => line.Product.ProductID), the helper would render a hidden field with the name "line.Product.ProductID". The name of the field would not match the names of the parameters for the "RemoveFromCart" action method which waiting the name of "ProductId". This would prevent the default model binders from working, so the MVC Framework would not be able to call the method.
*Adam Freeman (Apress - Pro ASP.Net MVC 5)
Add this to your gradle file.
implementation 'com.android.support:support-annotations:27.1.1'
You can do this in jquery by setting the attribute disabled to 'disabled'.
$(this).prop('disabled', true);
I have made a simple example http://jsfiddle.net/4gnXL/2/
You most likely mean "yyyy-MM-dd" small latter 'm' would imply minutes section.
You should do two things
add spring.jackson.serialization.write-dates-as-timestamps:false
in your application.properties
this will disable converting dates to timestamps and instead use a ISO-8601 compliant format
You can than customize the format by annotating the getter method of you dateOfBirth
property with @JsonFormat(pattern="yyyy-MM-dd")
combo.Items.FindByValue("1").Selected = true;
Here is another suggestion. If you can prepend http:// to your url string you can do this
string path = "http://www.example.com/aaa/bbb.jpg";
Uri uri = new Uri(path);
string expectedString =
uri.PathAndQuery.Remove(uri.PathAndQuery.LastIndexOf("."));
echo "echo "we are now going to work with ${ser}" " >> $servfile
Escape all " within quotes with \. Do this with variables like \$servicetest too:
echo "echo \"we are now going to work with \${ser}\" " >> $servfile
echo "read -p \"Please enter a service: \" ser " >> $servfile
echo "if [ \$servicetest > /dev/null ];then " >> $servfile
You can use following formulas.
For Excel 2007 or later:
=IFERROR(VLOOKUP(D3,List!A:C,3,FALSE),"No Match")
For Excel 2003:
=IF(ISERROR(MATCH(D3,List!A:A, 0)), "No Match", VLOOKUP(D3,List!A:C,3,FALSE))
Note, that
List!A:C
in VLOOKUP
and returns value from column ? 3
VLOOKUP
equals to FALSE
, in that case VLOOKUP
will only find an exact match, and the values in the first column of List!A:C
do not need to be sorted (opposite to case when you're using TRUE
).You can try this:
Me.cbo1.Text = Me.Cbo1.Items(0).Tostring
From you main machine, start -> search -> "remote desktop connection" -> click on "remote desktop connection" -> Click "Options" Beside to "Connect Button" -> Display Tab - > Then increase Display Configuriton Size. If this will not work, try the same thing by closing remote desktop. But this will give you solution.
In IntelliJ IDEA 14, it has moved to: File -> Settings -> Editor -> General -> "Show quick doc on mouse move"
For category relations insertion I came across the same problem and had no idea, except that in my eloquent model I used Self() to have an instance of the same class in foreach to record multiple saves and grabing ids.
foreach($arCategories as $v)
{
if($v>0){
$obj = new Self(); // this is to have new instance of own
$obj->page_id = $page_id;
$obj->category_id = $v;
$obj->save();
}
}
without "$obj = new Self()" it only saves single record (when $obj was $this)
I had the same problem while I was testing a project and it turned that running Fiddler was the cause for this error..!!
If you are using Fiddler to intercept the http request, shut it down ...
This is one of the many causes for such error.
To fix Fiddler you may need to Reset Fiddler Https Certificates.
There is a command line option for logging. The output is saved to screenlog.n file, where n is a number of the screen. From man pages of screen:
‘-L’ Tell screen to turn on automatic output logging for the windows.
You could set the width of the abbrev column to a fixed pixel width, then set the width of the description column to the width of the DataGridView, minus the sum of the widths of the other columns and some extra margin (if you want to prevent a horizontal scrollbar from appearing on the DataGridView):
dataGridView1.Columns[1].Width = 108; // or whatever width works well for abbrev
dataGridView1.Columns[2].Width =
dataGridView1.Width
- dataGridView1.Columns[0].Width
- dataGridView1.Columns[1].Width
- 72; // this is an extra "margin" number of pixels
If you wanted the description column to always take up the "remainder" of the width of the DataGridView, you could put something like the above code in a Resize
event handler of the DataGridView.
The error tells you that there is an error but you don´t catch it. This is how you can catch it:
getAllPosts().then(response => {
console.log(response);
}).catch(e => {
console.log(e);
});
You can also just put a console.log(reponse)
at the beginning of your API callback function, there is definitely an error message from the Graph API in it.
More information: https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/Promise/catch
Or with async/await:
//some async function
try {
let response = await getAllPosts();
} catch(e) {
console.log(e);
}
If you want to calculate it yourself, then you can use the Haversine formula:
var rad = function(x) {
return x * Math.PI / 180;
};
var getDistance = function(p1, p2) {
var R = 6378137; // Earth’s mean radius in meter
var dLat = rad(p2.lat() - p1.lat());
var dLong = rad(p2.lng() - p1.lng());
var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) *
Math.sin(dLong / 2) * Math.sin(dLong / 2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
var d = R * c;
return d; // returns the distance in meter
};
Your config file does not include any references to "origin" remote. That section looks like this:
[remote "origin"]
url = [email protected]:repository.git
fetch = +refs/heads/*:refs/remotes/origin/*
You need to add the remote using git remote add
before you can use it.
To change the size of (almost) all text elements, in one place, and synchronously, rel()
is quite efficient:
g+theme(text = element_text(size=rel(3.5))
You might want to tweak the number a bit, to get the optimum result. It sets both the horizontal and vertical axis labels and titles, and other text elements, on the same scale. One exception is faceted grids' titles which must be manually set to the same value, for example if both x and y facets are used in a graph:
theme(text = element_text(size=rel(3.5)),
strip.text.x = element_text(size=rel(3.5)),
strip.text.y = element_text(size=rel(3.5)))
I would check datatypes.
current_date has "date" datatype, 10 is a number, and Table.date - you need to look at your table.
As a more general pattern to follow, I tend to use an @After
block in the test:
@After
public void after() {
verifyNoMoreInteractions(<your mock1>, <your mock2>...);
}
Then the test is free to verify only what should be called.
Also, I found that I often forgot to check for "no interactions", only to later discover that things were being called that shouldn't have been.
So I find this pattern useful for catching all unexpected calls that haven't specifically been verified.
Try this:
document.getElementById('*spaM4').textContent
If you need to target < IE9 then you need to use .innerText
The simplest way might be:
var func='myDynamicFunction_'+myHandler;
var arg1 = 100, arg2 = 'abc';
window[func].apply(null,[arg1, arg2]);
Assuming, that target function is already attached to a "window" object.
This is a very common issue.
One solution is to kill adb server and restart it through command prompt. Sometimes this may not help out.
Just go to Window Task Manager to kill adb process and restart Eclipse.
Will work perfect :)
In archaic C and C++, inline
is like register
: a suggestion (nothing more than a suggestion) to the compiler about a possible optimization.
In modern C++, inline
tells the linker that, if multiple definitions (not declarations) are found in different translation units, they are all the same, and the linker can freely keep one and discard all the other ones.
inline
is mandatory if a function (no matter how complex or "linear") is defined in a header file, to allow multiple sources to include it without getting a "multiple definition" error by the linker.
Member functions defined inside a class are "inline" by default, as are template functions (in contrast to global functions).
//fileA.h
inline void afunc()
{ std::cout << "this is afunc" << std::endl; }
//file1.cpp
#include "fileA.h"
void acall()
{ afunc(); }
//main.cpp
#include "fileA.h"
void acall();
int main()
{
afunc();
acall();
}
//output
this is afunc
this is afunc
Note the inclusion of fileA.h into two .cpp files, resulting in two instances of afunc()
.
The linker will discard one of them.
If no inline
is specified, the linker will complain.
When you want to create an external_table, all field's name must be written in UPPERCASE.
Done.
Insted of using System.Net.WebClient I would recommend to have a look on System.Net.Http.HttpClient which was introduced with net 4.5 and makes your life much easier.
Also microsoft recommends to use the HttpClient on this article
http://msdn.microsoft.com/en-us/library/system.net.webclient(VS.90).aspx
An example could look like this:
var client = new HttpClient();
var content = new MultipartFormDataContent
{
{ new StringContent("myUserId"), "userid"},
{ new StringContent("myFileName"), "filename"},
{ new StringContent("myPassword"), "password"},
{ new StringContent("myType"), "type"}
};
var responseMessage = await client.PostAsync("some url", content);
var stream = await responseMessage.Content.ReadAsStreamAsync();
Okey , so its a basic problem , dont worry about this just write the <View> component and wrap it around the <Text> component
<View style={{alignItems: 'center'}}>
<Text> Write your Text Here</Text>
</View>
alignitems:center is a prop use to center items on crossaxis
justifycontent:'center' is a prop use to center items on mainaxis
There are no associative arrays in JavaScript. However, there are objects with named properties, so just don't initialise your "array" with new Array
, then it becomes a generic object.
If you put a comment in
"""
long comment here
"""
in the middle of a script, Python/linters won't recognize that. Folding will be messed up, as the above comment is not part of the standard recommendations. It's better to use
# Long comment
# here.
If you use Vim, you can plugins like commentary.vim, to automatically comment out long lines of comments by pressing Vjgcc
. Where Vj
selects two lines of code, and gcc
comments them out.
If you don’t want to use plugins like the above you can use search and replace like
:.,.+1s/^/# /g
This will replace the first character on the current and next line with #
.
What the error is telling, is that you can't convert an entire list into an integer. You could get an index from the list and convert that into an integer:
x = ["0", "1", "2"]
y = int(x[0]) #accessing the zeroth element
If you're trying to convert a whole list into an integer, you are going to have to convert the list into a string first:
x = ["0", "1", "2"]
y = ''.join(x) # converting list into string
z = int(y)
If your list elements are not strings, you'll have to convert them to strings before using str.join
:
x = [0, 1, 2]
y = ''.join(map(str, x))
z = int(y)
Also, as stated above, make sure that you're not returning a nested list.
Synchronize the data/object that you have saved into NSUserDefaults
-(void)saveCustomObject:(Player *)object
{
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
[prefs setObject:myEncodedObject forKey:@"testing"];
[prefs synchronize];
}
Hope this will help you. Thanks
I used Fiddler as a proxy. Fiddler redirects localhost calls to a external server.
I configured Firefox to use manual proxy (127.0.0.1 port 8888). Fiddler capture the calls and redirect them to another server, by using URL filters.
In my case, just using flex-shrink: 0
didn't work. But adding flex-grow: 1
to it worked.
.item {
flex-shrink: 0;
flex-grow: 1;
}
HTTP request POST in java does not dump the answer?
public class HttpClientExample
{
private final String USER_AGENT = "Mozilla/5.0";
public static void main(String[] args) throws Exception
{
HttpClientExample http = new HttpClientExample();
System.out.println("\nTesting 1 - Send Http POST request");
http.sendPost();
}
// HTTP POST request
private void sendPost() throws Exception {
String url = "http://www.wmtechnology.org/Consultar-RUC/index.jsp";
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url);
// add header
post.setHeader("User-Agent", USER_AGENT);
List<NameValuePair> urlParameters = new ArrayList<>();
urlParameters.add(new BasicNameValuePair("accion", "busqueda"));
urlParameters.add(new BasicNameValuePair("modo", "1"));
urlParameters.add(new BasicNameValuePair("nruc", "10469415177"));
post.setEntity(new UrlEncodedFormEntity(urlParameters));
HttpResponse response = client.execute(post);
System.out.println("\nSending 'POST' request to URL : " + url);
System.out.println("Post parameters : " + post.getEntity());
System.out.println("Response Code : " +response.getStatusLine().getStatusCode());
BufferedReader rd = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuilder result = new StringBuilder();
String line = "";
while ((line = rd.readLine()) != null)
{
result.append(line);
System.out.println(line);
}
}
}
This is the web: http://www.wmtechnology.org/Consultar-RUC/index.jsp,from you can consult Ruc without captcha. Your opinions are welcome!
Enable mod_headers in Apache2 to be able to use Header directive :
a2enmod headers
Call me simplistic, but I just do:
<a href="<%: Url.Action("ActionName", "ControllerName") %>">
<button>Button Text</button>
</a>
And you just take care of the hyperlink highlight. Our users love it :)
Do you by any chance have two PUBLICclass
classes in your project, where one is public (the one of which you posted the signature here), and another one which is package visible, and you import the wrong one in your code ?
for (int i = 0; i < 8; i++) {
//code
}
In simplest terms
int i = 0;
if (i < 8) //code
i = i + 1; //i = 1
if (i < 8) //code
i = i + 1; //i = 2
if (i < 8) //code
i = i + 1; //i = 3
if (i < 8) //code
i = i + 1; //i = 4
if (i < 8) //code
i = i + 1; //i = 5
if (i < 8) //code
i = i + 1; //i = 6
if (i < 8) //code
i = i + 1; //i = 7
if (i < 8) //code
i = i + 1; //i = 8
if (i < 8) //code - this if won't pass
You have a view model to which your view is strongly typed => use strongly typed helpers:
<%= Html.DropDownListFor(
x => x.SelectedAccountId,
new SelectList(Model.Accounts, "Value", "Text")
) %>
Also notice that I use a SelectList
for the second argument.
And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:
public ActionResult AccountTransaction()
{
var accounts = Services.AccountServices.GetAccounts(false);
var viewModel = new AccountTransactionView
{
Accounts = accounts.Select(a => new SelectListItem
{
Text = a.Description,
Value = a.AccountId.ToString()
})
};
return View(viewModel);
}
Clunky, but it'll work.
SELECT TOP 10 * FROM table WHERE id NOT IN (SELECT TOP 10 id FROM table ORDER BY id) FROM table ORDER BY id
MSSQL's omission of a LIMIT clause is criminal, IMO. You shouldn't have to do this kind of kludgy workaround.
This kind of code perhaps should work for You
SELECT
*,
CASE
WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
ELSE '00'
END AS modifiedpvc
FROM my_table;
gid | datepose | pvc | modifiedpvc
-----+----------+-----+-------------
1 | 1961 | 01 | 00
2 | 1949 | | 01
3 | 1990 | 02 | 00
1 | 1981 | | 02
1 | | 03 | 00
1 | | | 03
(6 rows)
cdecl
is a great tool for deciphering weird syntax like function pointer declarations. You can use it to generate them as well.
As far as tips for making complicated declarations easier to parse for future maintenance (by yourself or others), I recommend making typedef
s of small chunks and using those small pieces as building blocks for larger and more complicated expressions. For example:
typedef int (*FUNC_TYPE_1)(void);
typedef double (*FUNC_TYPE_2)(void);
typedef FUNC_TYPE_1 (*FUNC_TYPE_3)(FUNC_TYPE_2);
rather than:
typedef int (*(*FUNC_TYPE_3)(double (*)(void)))(void);
cdecl
can help you out with this stuff:
cdecl> explain int (*FUNC_TYPE_1)(void)
declare FUNC_TYPE_1 as pointer to function (void) returning int
cdecl> explain double (*FUNC_TYPE_2)(void)
declare FUNC_TYPE_2 as pointer to function (void) returning double
cdecl> declare FUNC_TYPE_3 as pointer to function (pointer to function (void) returning double) returning pointer to function (void) returning int
int (*(*FUNC_TYPE_3)(double (*)(void )))(void )
And is (in fact) exactly how I generated that crazy mess above.
Bootstrap modal exposes events. Listen for the the shown
event like this
$('#my-modal').on('shown', function(){
// code here
});
You don't really need a specific client, it's fairly simple with most libraries. For example in jQuery you can just call the generic $.ajax
function with the type of request you want to make:
$.ajax({
url: 'http://example.com/',
type: 'PUT',
data: 'ID=1&Name=John&Age=10', // or $('#myform').serializeArray()
success: function() { alert('PUT completed'); }
});
You can replace PUT
with GET
/POST
/DELETE
or whatever.
In makefile language $@
means "name of the target", so rm -f $@
translates to rm -f clean
.
You need to specify to rm
what exactly you want to delete, like rm -f *.o code1 code2
You can learn commands from the command palette Ctrl/Cmd + Shift + P). Look for "Go to Bracket". The keybinding is also shown there.
Installing mysqlclient
using anaconda
is pretty simple and straight forward
.
conda install -c bioconda mysqlclient
and then, install pymysql
using pip.
pip install pymysql
happy learning..
In-order to fix this, terminate or close the server you are running. If you are using Eclipse IDE, then follow this,
Run > Debug
Right-click the running process and click on Terminate.
Instead of Googling for %02d
you should have been searching for sprintf()
function.
%02d
means "format the integer with 2 digits, left padding it with zeroes", so:
Format Data Result %02d 1 01 %02d 11 11
Although there are a lot of good tips here I'd like to answer the question you asked:
So in other words can they work hand in hand just like Apache/Perl or Apache/PHP etc..
YES, you can run Node.js on Apache along side Perl and PHP IF you run it as a CGI module. As of yet, I am unable to find a mod-node for Apache but check out: CGI-Node for Apache here http://www.cgi-node.org/ .
The interesting part about cgi-node is that it uses JavaScript exactly like you would use PHP to generate dynamic content, service up static pages, access SQL database etc. You can even share core JavaScript libraries between the server and the client/browser.
I think the shift to a single language between client and server is happening and JavaScript seems to be a good candidate.
A quick example from cgi-node.org site:
<? include('myJavaScriptFile.js'); ?>
<html>
<body>
<? var helloWorld = 'Hello World!'; ?>
<b><?= helloWorld ?><br/>
<? for( var index = 0; index < 10; index++) write(index + ' '); ?>
</body>
</html>
This outputs:
Hello World!
0 1 2 3 4 5 6 7 8 9
You also have full access to the HTTP request. That includes forms, uploaded files, headers etc.
I am currently running Node.js through the cgi-node module on Godaddy.
CGI-Node.org site has all the documentation to get started.
I know I'm raving about this but it is finally a relief to use something other than PHP. Also, to be able to code JavaScript on both client and server.
Hope this helps.
I came across this post while trying to figure out how to get OrderedDict to work. PyDev for Eclipse couldn't find OrderedDict at all, so I ended up deciding to make a tuple of my dictionary's key values as I would like them to be ordered. When I needed to output my list, I just iterated through the tuple's values and plugged the iterated 'key' from the tuple into the dictionary to retrieve my values in the order I needed them.
example:
test_dict = dict( val1 = "hi", val2 = "bye", val3 = "huh?", val4 = "what....")
test_tuple = ( 'val1', 'val2', 'val3', 'val4')
for key in test_tuple: print(test_dict[key])
It's a tad cumbersome, but I'm pressed for time and it's the workaround I came up with.
note: the list of lists approach that somebody else suggested does not really make sense to me, because lists are ordered and indexed (and are also a different structure than dictionaries).
If your solution doesn't have to be general, i.e. only needs to work for strings like your example, you could do:
var1=$(echo $STR | cut -f1 -d-)
var2=$(echo $STR | cut -f2 -d-)
I chose cut
here because you could simply extend the code for a few more variables...
It is quite evident that there is only a single id
corresponding to a single username
because username
is unique.
But the actual problem lies in the query itself-
$sql = "SELECT 'id' FROM Users WHERE username='$name'";
+----+
| id |
+----+
| id |
+----+
i.e. 'id'
actually is treated as a string not as the id
attribute.
$sql = "SELECT `id` FROM Users WHERE username='$name'";
i.e. use grave accent(`) instead of single quote(').
or
$sql = "SELECT id FROM Users WHERE username='$name'";
session_start();
$name = $_GET["username"];
$sql = "SELECT `id` FROM Users WHERE username='$name'";
$result = mysql_query($sql);
$row=mysql_fetch_array($result)
$value = $row[0];
$_SESSION['myid'] = $value;
Thanks for all help at this issue. I'll post here my solution:
Package Header
CREATE OR REPLACE PACKAGE X IS
TYPE exch_row IS RECORD(
currency_cd VARCHAR2(9),
exch_rt_eur NUMBER,
exch_rt_usd NUMBER);
TYPE exch_tbl IS TABLE OF X.exch_row;
FUNCTION GetExchangeRate RETURN X.exch_tbl PIPELINED;
END X;
Package Body
CREATE OR REPLACE PACKAGE BODY X IS
FUNCTION GetExchangeRate RETURN X.exch_tbl
PIPELINED AS
exch_rt_usd NUMBER := 1.0; --todo
rw exch_row;
BEGIN
FOR rw IN (SELECT c.currency_cd AS currency_cd, e.exch_rt AS exch_rt_eur, (e.exch_rt / exch_rt_usd) AS exch_rt_usd
FROM exch e, currency c
WHERE c.currency_key = e.currency_key
) LOOP
PIPE ROW(rw);
END LOOP;
END;
PROCEDURE DoIt IS
BEGIN
DECLARE
CURSOR c0 IS
SELECT i.DOC,
i.doc_currency,
i.net_value,
i.net_value / rt.exch_rt_usd AS net_value_in_usd,
i.net_value / rt.exch_rt_eur AS net_value_in_euro,
FROM item i, (SELECT * FROM TABLE(X.GetExchangeRate())) rt
WHERE i.doc_currency = rt.currency_cd;
TYPE c0_type IS TABLE OF c0%ROWTYPE;
items c0_type;
BEGIN
OPEN c0;
LOOP
FETCH c0 BULK COLLECT
INTO items LIMIT batchsize;
EXIT WHEN items.COUNT = 0;
FORALL i IN items.FIRST .. items.LAST SAVE EXCEPTIONS
INSERT INTO detail_items VALUES items (i);
END LOOP;
CLOSE c0;
COMMIT;
EXCEPTION
WHEN OTHERS THEN
RAISE;
END;
END;
END X;
Please review.
I made good experiences with Scala.
I use the simple build tool (sbt: http://code.google.com/p/simple-build-tool/) with the Android-Plugin (http://github.com/jberkel/android-plugin)
Just make sure to put width and height for the foreground the same with the background, or try to have top, bottom, left and right properties.
<style>
.foreground, .background {
position: absolute;
}
.foreground {
z-index: 1;
}
.background {
background-image: url(your/image/here.jpg);
opacity: 0.4;
}
</style>
<div class="foreground"></div>
<div class="background"></div>
The reverse() is used to adhere the django DRY principle i.e if you change the url in future then you can reference that url using reverse(urlname).
Might be super trivial but worth a check prior to waste some time.
At my case the mysql
service was down.
When you have a java app including JPA / Hibernate it is checking the database connection on startup. Just found out by looking into the looks where it had an entity manager error.
Select "File" -> "Project Structure".
Under "Project Settings" select "Project"
From there you can select the "Project SDK".
This answer is late but it might help someone like it helped me
Just ensure you have given the user permission for the destination file
sudo chown -R www-data:www-data /Users/George/Desktop/uploads/
A new cause for this in the .net core era is having a project loaded for an unsupported .net core version. For instance if you loaded a project from GitHub that was set to use:
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>
But you only have 2.1 installed or find yourself using Visual Studio 2017 then the compiler wont be able to find the SDK code and thus provide intellisense.
The solution in that case might be to right click on your project and select Edit MyProject.csproj from the context menu and change the target framework as necessary:
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
</PropertyGroup>
This assumes whatever project you loaded can actually be run under a lesser target framework.
You might want to check out Remy Sharp's recent article on fixed floating elements at jQuery for Designers, which has a nice video and writeup on how to apply this effect in client script
Add the type for the script
<script src="https://maps.googleapis.com/maps/api/js" type="text/javascript"></script>
So the important part is the type text/javascript.
first create folder by command line mkdir C:\data\db (This is for database) then run command mongod --port 27018 by one command prompt(administration mode)- you can give name port number as your wish
Well, since 'X' is a char and not an int, you cannot actually replace it in the matrix itself, however, the following code should print an 'x' char whenever it comes across a 1.
public void printGrid(int[][] in){
for(int i = 0; i < 20; i++){
for(int j = 0; j < 20; j++){
if(in[i][j] == 1)
System.out.print('X' + "\t");
else
System.out.print(in[i][j] + "\t");
}
System.out.print("\n");
}
}
android:background="#64B5F6"
You can change the value after '#' according to your own specification or need depending on how you want to use them.
Here is a sample code:
<TextView_x000D_
android:text="Abir"_x000D_
android:layout_width="match_parent"_x000D_
android:layout_height="wrap_content"_x000D_
android:textSize="24sp"_x000D_
android:background="#D4E157" />
_x000D_
Thank you :)
Separate your rules with a semi colon in a single declaration:
<span style="color:blue;font-style:italic">Test</span>
Just make sure you add box-sizing:border-box;
to your #myWorkContent
.
https://github.com/quartzjer/js0n
Ugliest interface possible, but does what you ask. Zero allocations.
http://zserge.com/jsmn.html Another zero-allocation approach.
The solutions posted above all do dynamic memory allocation, hence will be inevitably end up slower at some point, depending on the data structure - and will be dangerous to include in a heap constrained environment like an embedded system.
Benchmarks of vjson, rapidjson and sajson here : http://chadaustin.me/2013/01/json-parser-benchmarking/ if you are interested in that sort of thing.
And to answer your "writer" part of the question i doubt that you could beat an efficient
printf("{%s:%s}",name,value)
implementation with any library - assuming your printf/sprintf implementation itself is lightweight of course.
EDIT: actually let me take that back, RapidJson allows on-stack allocation only through its MemoryPoolAllocator and actually makes this a default for its GenericReader. I havent done the comparison but i would expect it to be more robust than anything else listed here. It also doesnt have any dependencies, and it doesnt throw exceptions which probably makes it ultimately suitable for embedded. Fully header based lib so, easy to include anywhere.
I find NPOI very usefull for working with Excel Files, here is my implementation (Comments are in Spanish, sorry for that):
This Method Opens an Excel (both xls or xlsx) file and converts it into a DataTable.
/// <summary>Abre un archivo de Excel (xls o xlsx) y lo convierte en un DataTable.
/// LA PRIMERA FILA DEBE CONTENER LOS NOMBRES DE LOS CAMPOS.</summary>
/// <param name="pRutaArchivo">Ruta completa del archivo a abrir.</param>
/// <param name="pHojaIndex">Número (basado en cero) de la hoja que se desea abrir. 0 es la primera hoja.</param>
private DataTable Excel_To_DataTable(string pRutaArchivo, int pHojaIndex)
{
// --------------------------------- //
/* REFERENCIAS:
* NPOI.dll
* NPOI.OOXML.dll
* NPOI.OpenXml4Net.dll */
// --------------------------------- //
/* USING:
* using NPOI.SS.UserModel;
* using NPOI.HSSF.UserModel;
* using NPOI.XSSF.UserModel; */
// AUTOR: Ing. Jhollman Chacon R. 2015
// --------------------------------- //
DataTable Tabla = null;
try
{
if (System.IO.File.Exists(pRutaArchivo))
{
IWorkbook workbook = null; //IWorkbook determina si es xls o xlsx
ISheet worksheet = null;
string first_sheet_name = "";
using (FileStream FS = new FileStream(pRutaArchivo, FileMode.Open, FileAccess.Read))
{
workbook = WorkbookFactory.Create(FS); //Abre tanto XLS como XLSX
worksheet = workbook.GetSheetAt(pHojaIndex); //Obtener Hoja por indice
first_sheet_name = worksheet.SheetName; //Obtener el nombre de la Hoja
Tabla = new DataTable(first_sheet_name);
Tabla.Rows.Clear();
Tabla.Columns.Clear();
// Leer Fila por fila desde la primera
for (int rowIndex = 0; rowIndex <= worksheet.LastRowNum; rowIndex++)
{
DataRow NewReg = null;
IRow row = worksheet.GetRow(rowIndex);
IRow row2 = null;
IRow row3 = null;
if (rowIndex == 0)
{
row2 = worksheet.GetRow(rowIndex + 1); //Si es la Primera fila, obtengo tambien la segunda para saber el tipo de datos
row3 = worksheet.GetRow(rowIndex + 2); //Y la tercera tambien por las dudas
}
if (row != null) //null is when the row only contains empty cells
{
if (rowIndex > 0) NewReg = Tabla.NewRow();
int colIndex = 0;
//Leer cada Columna de la fila
foreach (ICell cell in row.Cells)
{
object valorCell = null;
string cellType = "";
string[] cellType2 = new string[2];
if (rowIndex == 0) //Asumo que la primera fila contiene los titlos:
{
for (int i = 0; i < 2; i++)
{
ICell cell2 = null;
if (i == 0) { cell2 = row2.GetCell(cell.ColumnIndex); }
else { cell2 = row3.GetCell(cell.ColumnIndex); }
if (cell2 != null)
{
switch (cell2.CellType)
{
case CellType.Blank: break;
case CellType.Boolean: cellType2[i] = "System.Boolean"; break;
case CellType.String: cellType2[i] = "System.String"; break;
case CellType.Numeric:
if (HSSFDateUtil.IsCellDateFormatted(cell2)) { cellType2[i] = "System.DateTime"; }
else
{
cellType2[i] = "System.Double"; //valorCell = cell2.NumericCellValue;
}
break;
case CellType.Formula:
bool continuar = true;
switch (cell2.CachedFormulaResultType)
{
case CellType.Boolean: cellType2[i] = "System.Boolean"; break;
case CellType.String: cellType2[i] = "System.String"; break;
case CellType.Numeric:
if (HSSFDateUtil.IsCellDateFormatted(cell2)) { cellType2[i] = "System.DateTime"; }
else
{
try
{
//DETERMINAR SI ES BOOLEANO
if (cell2.CellFormula == "TRUE()") { cellType2[i] = "System.Boolean"; continuar = false; }
if (continuar && cell2.CellFormula == "FALSE()") { cellType2[i] = "System.Boolean"; continuar = false; }
if (continuar) { cellType2[i] = "System.Double"; continuar = false; }
}
catch { }
} break;
}
break;
default:
cellType2[i] = "System.String"; break;
}
}
}
//Resolver las diferencias de Tipos
if (cellType2[0] == cellType2[1]) { cellType = cellType2[0]; }
else
{
if (cellType2[0] == null) cellType = cellType2[1];
if (cellType2[1] == null) cellType = cellType2[0];
if (cellType == "") cellType = "System.String";
}
//Obtener el nombre de la Columna
string colName = "Column_{0}";
try { colName = cell.StringCellValue; }
catch { colName = string.Format(colName, colIndex); }
//Verificar que NO se repita el Nombre de la Columna
foreach (DataColumn col in Tabla.Columns)
{
if (col.ColumnName == colName) colName = string.Format("{0}_{1}", colName, colIndex);
}
//Agregar el campos de la tabla:
DataColumn codigo = new DataColumn(colName, System.Type.GetType(cellType));
Tabla.Columns.Add(codigo); colIndex++;
}
else
{
//Las demas filas son registros:
switch (cell.CellType)
{
case CellType.Blank: valorCell = DBNull.Value; break;
case CellType.Boolean: valorCell = cell.BooleanCellValue; break;
case CellType.String: valorCell = cell.StringCellValue; break;
case CellType.Numeric:
if (HSSFDateUtil.IsCellDateFormatted(cell)) { valorCell = cell.DateCellValue; }
else { valorCell = cell.NumericCellValue; } break;
case CellType.Formula:
switch (cell.CachedFormulaResultType)
{
case CellType.Blank: valorCell = DBNull.Value; break;
case CellType.String: valorCell = cell.StringCellValue; break;
case CellType.Boolean: valorCell = cell.BooleanCellValue; break;
case CellType.Numeric:
if (HSSFDateUtil.IsCellDateFormatted(cell)) { valorCell = cell.DateCellValue; }
else { valorCell = cell.NumericCellValue; }
break;
}
break;
default: valorCell = cell.StringCellValue; break;
}
//Agregar el nuevo Registro
if (cell.ColumnIndex <= Tabla.Columns.Count - 1) NewReg[cell.ColumnIndex] = valorCell;
}
}
}
if (rowIndex > 0) Tabla.Rows.Add(NewReg);
}
Tabla.AcceptChanges();
}
}
else
{
throw new Exception("ERROR 404: El archivo especificado NO existe.");
}
}
catch (Exception ex)
{
throw ex;
}
return Tabla;
}
This Second method does the oposite, saves a DataTable into an Excel File, yeah it can either be xls or the new xlsx, your choise!
/// <summary>Convierte un DataTable en un archivo de Excel (xls o Xlsx) y lo guarda en disco.</summary>
/// <param name="pDatos">Datos de la Tabla a guardar. Usa el nombre de la tabla como nombre de la Hoja</param>
/// <param name="pFilePath">Ruta del archivo donde se guarda.</param>
private void DataTable_To_Excel(DataTable pDatos, string pFilePath)
{
try
{
if (pDatos != null && pDatos.Rows.Count > 0)
{
IWorkbook workbook = null;
ISheet worksheet = null;
using (FileStream stream = new FileStream(pFilePath, FileMode.Create, FileAccess.ReadWrite))
{
string Ext = System.IO.Path.GetExtension(pFilePath); //<-Extension del archivo
switch (Ext.ToLower())
{
case ".xls":
HSSFWorkbook workbookH = new HSSFWorkbook();
NPOI.HPSF.DocumentSummaryInformation dsi = NPOI.HPSF.PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "Cutcsa"; dsi.Manager = "Departamento Informatico";
workbookH.DocumentSummaryInformation = dsi;
workbook = workbookH;
break;
case ".xlsx": workbook = new XSSFWorkbook(); break;
}
worksheet = workbook.CreateSheet(pDatos.TableName); //<-Usa el nombre de la tabla como nombre de la Hoja
//CREAR EN LA PRIMERA FILA LOS TITULOS DE LAS COLUMNAS
int iRow = 0;
if (pDatos.Columns.Count > 0)
{
int iCol = 0;
IRow fila = worksheet.CreateRow(iRow);
foreach (DataColumn columna in pDatos.Columns)
{
ICell cell = fila.CreateCell(iCol, CellType.String);
cell.SetCellValue(columna.ColumnName);
iCol++;
}
iRow++;
}
//FORMATOS PARA CIERTOS TIPOS DE DATOS
ICellStyle _doubleCellStyle = workbook.CreateCellStyle();
_doubleCellStyle.DataFormat = workbook.CreateDataFormat().GetFormat("#,##0.###");
ICellStyle _intCellStyle = workbook.CreateCellStyle();
_intCellStyle.DataFormat = workbook.CreateDataFormat().GetFormat("#,##0");
ICellStyle _boolCellStyle = workbook.CreateCellStyle();
_boolCellStyle.DataFormat = workbook.CreateDataFormat().GetFormat("BOOLEAN");
ICellStyle _dateCellStyle = workbook.CreateCellStyle();
_dateCellStyle.DataFormat = workbook.CreateDataFormat().GetFormat("dd-MM-yyyy");
ICellStyle _dateTimeCellStyle = workbook.CreateCellStyle();
_dateTimeCellStyle.DataFormat = workbook.CreateDataFormat().GetFormat("dd-MM-yyyy HH:mm:ss");
//AHORA CREAR UNA FILA POR CADA REGISTRO DE LA TABLA
foreach (DataRow row in pDatos.Rows)
{
IRow fila = worksheet.CreateRow(iRow);
int iCol = 0;
foreach (DataColumn column in pDatos.Columns)
{
ICell cell = null; //<-Representa la celda actual
object cellValue = row[iCol]; //<- El valor actual de la celda
switch (column.DataType.ToString())
{
case "System.Boolean":
if (cellValue != DBNull.Value)
{
cell = fila.CreateCell(iCol, CellType.Boolean);
if (Convert.ToBoolean(cellValue)) { cell.SetCellFormula("TRUE()"); }
else { cell.SetCellFormula("FALSE()"); }
cell.CellStyle = _boolCellStyle;
}
break;
case "System.String":
if (cellValue != DBNull.Value)
{
cell = fila.CreateCell(iCol, CellType.String);
cell.SetCellValue(Convert.ToString(cellValue));
}
break;
case "System.Int32":
if (cellValue != DBNull.Value)
{
cell = fila.CreateCell(iCol, CellType.Numeric);
cell.SetCellValue(Convert.ToInt32(cellValue));
cell.CellStyle = _intCellStyle;
}
break;
case "System.Int64":
if (cellValue != DBNull.Value)
{
cell = fila.CreateCell(iCol, CellType.Numeric);
cell.SetCellValue(Convert.ToInt64(cellValue));
cell.CellStyle = _intCellStyle;
}
break;
case "System.Decimal":
if (cellValue != DBNull.Value)
{
cell = fila.CreateCell(iCol, CellType.Numeric);
cell.SetCellValue(Convert.ToDouble(cellValue));
cell.CellStyle = _doubleCellStyle;
}
break;
case "System.Double":
if (cellValue != DBNull.Value)
{
cell = fila.CreateCell(iCol, CellType.Numeric);
cell.SetCellValue(Convert.ToDouble(cellValue));
cell.CellStyle = _doubleCellStyle;
}
break;
case "System.DateTime":
if (cellValue != DBNull.Value)
{
cell = fila.CreateCell(iCol, CellType.Numeric);
cell.SetCellValue(Convert.ToDateTime(cellValue));
//Si No tiene valor de Hora, usar formato dd-MM-yyyy
DateTime cDate = Convert.ToDateTime(cellValue);
if (cDate != null && cDate.Hour > 0) { cell.CellStyle = _dateTimeCellStyle; }
else { cell.CellStyle = _dateCellStyle; }
}
break;
default:
break;
}
iCol++;
}
iRow++;
}
workbook.Write(stream);
stream.Close();
}
}
}
catch (Exception ex)
{
throw ex;
}
}
With this 2 methods you can Open an Excel file, load it into a DataTable, do your modifications and save it back into an Excel file.
Hope you guys find this usefull.
All you need to do is pass the JspWriter object into your method as a parameter i.e.
void someOutput(JspWriter stream)
Then call it via:
<% someOutput(out) %>
The writer object is a local variable inside _jspService so you need to pass it into your utility method. The same would apply for all the other built in references (e.g. request, response, session).
A great way to see whats going on is to use Tomcat as your server and drill down into the 'work' directory for the '.java' file generated from your 'jsp' page. Alternatively in weblogic you can use the 'weblogic.jspc' page compiler to view the Java that will be generated when the page is requested.
Turns out for me this error was actually telling the truth - I was trying to resize a Null image, which was usually the 'last' frame of a video file, so the assertion was valid.
Now I have an extra step before attempting the resize operation, which is to do the assertion myself:
def getSizedFrame(width, height):
"""Function to return an image with the size I want"""
s, img = self.cam.read()
# Only process valid image frames
if s:
img = cv2.resize(img, (width, height), interpolation = cv2.INTER_AREA)
return s, img
Now I don't see the error.
In the distribution I use, the tasks are listed in the task list by default (at least for Java). For other content types, you may check the following settings.
Display the Tasks View: Window > Show View > Other > General > Tasks
For non-Java Task Tags: check the following settings: Window > Preferences > General > Editors > Structured Text Editors > Task Tags You can enable searching for task tags in the [Task Tags] tab and select the content types in the [Filters] tab.
For Java task tags, you should look in: Window > Preferences > Java > Compiler > Task Tags
J.
Your Problem were the slice declarations in your data structs
(except for Track
, they shouldn't be slices...). This was compounded by some rather goofy fieldnames in the fetched json file, which can be fixed via structtags, see godoc.
The code below parsed the json successfully. If you've further questions, let me know.
package main
import "fmt"
import "net/http"
import "io/ioutil"
import "encoding/json"
type Tracks struct {
Toptracks Toptracks_info
}
type Toptracks_info struct {
Track []Track_info
Attr Attr_info `json: "@attr"`
}
type Track_info struct {
Name string
Duration string
Listeners string
Mbid string
Url string
Streamable Streamable_info
Artist Artist_info
Attr Track_attr_info `json: "@attr"`
}
type Attr_info struct {
Country string
Page string
PerPage string
TotalPages string
Total string
}
type Streamable_info struct {
Text string `json: "#text"`
Fulltrack string
}
type Artist_info struct {
Name string
Mbid string
Url string
}
type Track_attr_info struct {
Rank string
}
func perror(err error) {
if err != nil {
panic(err)
}
}
func get_content() {
url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
res, err := http.Get(url)
perror(err)
defer res.Body.Close()
decoder := json.NewDecoder(res.Body)
var data Tracks
err = decoder.Decode(&data)
if err != nil {
fmt.Printf("%T\n%s\n%#v\n",err, err, err)
switch v := err.(type){
case *json.SyntaxError:
fmt.Println(string(body[v.Offset-40:v.Offset]))
}
}
for i, track := range data.Toptracks.Track{
fmt.Printf("%d: %s %s\n", i, track.Artist.Name, track.Name)
}
}
func main() {
get_content()
}
Are there situations in which sys.stdout.write() is preferable to print?
For example I'm working on small function which prints stars in pyramid format upon passing the number as argument, although you can accomplish this using end="" to print in a separate line, I used sys.stdout.write in co-ordination with print to make this work. To elaborate on this stdout.write prints in the same line where as print always prints its contents in a separate line.
import sys
def printstars(count):
if count >= 1:
i = 1
while (i <= count):
x=0
while(x<i):
sys.stdout.write('*')
x = x+1
print('')
i=i+1
printstars(5)
I see the picture, and all your classes are in the same package. So you don't have to import, you can create a new instance without the import sentence.
After trying many suggestions from various sites and similar questions, what worked for me was to uninstall all Python stuff and reinstall Anaconda only (see https://stackoverflow.com/a/38330088/1083292)
The previous Python installation I had was not only redundant but only caused me trouble.
Here is a quick edit of Enve's answer. I do like roXor's solution, but background images are not necessary. And everbody seems to forgot a preventDefault
as well.
$(document).ready(function() {_x000D_
$(".slidingDiv").hide();_x000D_
_x000D_
$('.show_hide').click(function(e) {_x000D_
$(".slidingDiv").slideToggle("fast");_x000D_
var val = $(this).text() == "-" ? "+" : "-";_x000D_
$(this).hide().text(val).fadeIn("fast");_x000D_
e.preventDefault();_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<a href="#" class="show_hide">+</a>_x000D_
_x000D_
<div class="slidingDiv">_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta._x000D_
Mauris massa. Vestibulum lacinia arcu eget nulla. </p>_x000D_
_x000D_
<p>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis._x000D_
Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. </p>_x000D_
_x000D_
</div>
_x000D_
you can just cast it
int dbValue = 2;
EnumDisplayStatus enumValue = (EnumDisplayStatus)dbValue;
string stringName = enumValue.ToString(); //Visible
ah.. kent beat me to it :)
You can get maximum column value and increment it:
InnoDB uses the following algorithm to initialize the auto-increment counter for a table t that contains an AUTO_INCREMENT column named ai_col: After a server startup, for the first insert into a table t, InnoDB executes the equivalent of this statement:
SELECT MAX(ai_col) FROM t FOR UPDATE;
InnoDB increments by one the value retrieved by the statement and assigns it to the column and to the auto-increment counter for the table. If the table is empty, InnoDB uses the value 1.
Also you can use SHOW TABLE STATUS and its "Auto_increment" value.
CSTR({number_field}, 0, '')
The second placeholder is for decimals.
The last placeholder is for thousands separator.
.show-grid [class*="span"]
It's a CSS selector that selects all elements with the class show-grid that has a child element whose class contains the name span.
You need to add sqljdbc_auth.dll in your C:/windows/System32 folder. You can download it from http://www.microsoft.com/en-us/download/details.aspx?displaylang=en&id=11774 .
I assume you have updated ADT with version 22 and R.java file is not getting generated.
If this is the case, then here is the solution:
Hope you know Android studio has gradle building tool. Same as in eclipse they have given new component in the Tools folder called Android SDK Build-tools that needs to be installed. Open the Android SDK Manager, select the newly added build tools, install it, restart the SDK Manager after the update.
I had the issue where after updating the SDK it would only update to version 20 and kept telling me that ANDROID 4.1 (API16) was available and only part of ANDROID 4.2 (API17) was available and there was no update to version 21.
After restarting several times and digging I found (was not obvious to me) going to the SDK Manager and going to FILE -> RELOAD solved the problem. Immediately the other uninstalled parts of API17 were there and I was able to update the SDK. Once updated to 4.2 then I could re-update to version 21 and voila.
Good luck! David
Step 1
Go to S:\MAMP
enter code here
\bin\apache\conf\
open httpd.conf
file and change
#Include conf/extra/httpd-vhosts.conf
to
Include conf/extra/httpd-vhosts.conf
i.e. uncomment the line so that it can includes the virtual hosts file.
Step 2
Go to S:\MAMP\bin\apache\conf\extra
and open httpd-vhosts.conf
file and add the following code
<VirtualHost myWebsite.local>
DocumentRoot "S:\MAMP\htdocs/myWebsite/"
ServerName myWebsite.local
ServerAlias myWebsite.local
<Directory "S:\MAMP\htdocsmyWebsite/">
Order allow,deny
Allow from all
</Directory>
</VirtualHost>
change myWebsite.local
and S:\MAMP\htdocs/myWebsite/
as per your requirements.
Step 3
Open hosts
file in C:/Windows/System32/drivers/etc/
and add the following line ( Don't delete anything )
127.0.0.1 myWebsite.local
change myWebsite.local
as per your name requirements
Step 4
restart your server. That's it
After the ENABLE TRIGGER OR DISABLE TRIGGER in a new line write GO, Example:
DISABLE TRIGGER dbo.tr_name ON dbo.table_name
GO
-- some update statement
ENABLE TRIGGER dbo.tr_name ON dbo.table_name
GO
Also check if the script has no batch seperator commands (remove the 'GO' statements on a single line).
I added the DOCTYPE
directive you see here:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xsl:stylesheet [
<!ENTITY nl "
">
]>
<xsl:stylesheet xmlns:x="http://www.w3.org/2005/02/query-test-XQTSCatalog"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
version="2.0">
This allows me to use &nl;
instead of 

to produce a newline in the output. Like other solutions, this is typically placed inside a <xsl:text>
tag.
The answer above is probably the correct way to do it, but didn't work for me.
The hacky way that solved it for me was the following:
ax = <whatever your plot is>
# get the current labels
labels = [item.get_text() for item in ax.get_xticklabels()]
# Beat them into submission and set them back again
ax.set_xticklabels([str(round(float(label), 2)) for label in labels])
# Show the plot, and go home to family
plt.show()
Using LIKE:
SELECT *
FROM TABLE
WHERE column LIKE '%cats%' --case-insensitive
You can also use the special word like
:
Public Sub Search()
If "My Big String with, in the middle" Like "*,*" Then
Debug.Print ("Found ','")
End If
End Sub
Download the following jars and add it to your WEB-INF/lib
directory:
UPDATE totals
SET total = total + 1
WHERE name = 'bill';
If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:
UPDATE totals
SET total = total + 1
WHERE name = 'bill'
AND total = 203;
Use:
git remote prune <remote>
Where <remote>
is a remote source name like origin or upstream.
Example: git remote prune origin