The only solution that worked for me
Other solutions I have tried, which didn't work.
Cleaning/Rebuilding
Cleaning bin, obj folders
Changing namespace
I had the same problem, then I found out that I had duplicate api controller class names in other project and despite the fact that the "routePrefix" and namespace and project name were different but still they returned 404, I changed the class names and it worked.
To differentiate the routes, try adding a constraint that id must be numeric:
RouteTable.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
constraints: new { id = @"\d+" }, // Only matches if "id" is one or more digits.
defaults: new { id = System.Web.Http.RouteParameter.Optional }
);
Uncheck this in Windows Explorer.
"Hide file type extensions for known types"
You need to concatenate your string.
document.getElementById(tabName).style.backgroundImage = 'url(buttons/' + imagePrefix + '.png)';
The way you had it, it's just making 1 long string and not actually interpreting imagePrefix.
I would even suggest creating the string separate:
function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
var urlString = 'url(buttons/' + imagePrefix + '.png)';
document.getElementById(tabName).style.backgroundImage = urlString;
}
As mentioned by David Thomas below, you can ditch the double quotes in your string. Here is a little article to get a better idea of how strings and quotes/double quotes are related: http://www.quirksmode.org/js/strings.html
It is a syntax. In the function arguments int (&myArray)[100]
parenthesis that enclose the &myArray
are necessary. if you don't use them, you will be passing an array of references
and that is because the subscript operator []
has higher precedence over the & operator
.
E.g. int &myArray[100] // array of references
So, by using type construction ()
you tell the compiler that you want a reference to an array of 100 integers.
E.g int (&myArray)[100] // reference of an array of 100 ints
> use the -O option. [...] If the tar file is corrupt, the process will abort with an error.
Sometimes yes, but sometimes not. Let's see an example of a corrupted file:
echo Pete > my_name
tar -cf my_data.tar my_name
# // Simulate a corruption
sed < my_data.tar 's/Pete/Fool/' > my_data_now.tar
# // "my_data_now.tar" is the corrupted file
tar -xvf my_data_now.tar -O
It shows:
my_name
Fool
Even if you execute
echo $?
tar said that there was no error:
0
but the file was corrupted, it has now "Fool" instead of "Pete".
Had same problem - it was somewhere in the ca certificate, so I used the ca bundle used for curl, and it worked. You can download the curl ca bundle here: https://curl.haxx.se/docs/caextract.html
For encryption and security issues see this helpful article:
https://www.venditan.com/labs/2014/06/26/ssl-and-php-streams-part-1-you-are-doing-it-wrongtm/432
Here is the example:
$url = 'https://www.example.com/api/list';
$cn_match = 'www.example.com';
$data = array (
'apikey' => '[example api key here]',
'limit' => intval($limit),
'offset' => intval($offset)
);
// use key 'http' even if you send the request to https://...
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'method' => 'POST',
'content' => http_build_query($data)
)
, 'ssl' => array(
'verify_peer' => true,
'cafile' => [path to file] . "cacert.pem",
'ciphers' => 'HIGH:TLSv1.2:TLSv1.1:TLSv1.0:!SSLv3:!SSLv2',
'CN_match' => $cn_match,
'disable_compression' => true,
)
);
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
Hope that helps
For complicated objects and when performance is not significant i use gson to serialize the object to json text, then deserialize the text to get new object.
gson which based on reflection will works in most cases, except that transient
fields will not be copied and objects with circular reference with cause StackOverflowError
.
public static <ObjectType> ObjectType Copy(ObjectType AnObject, Class<ObjectType> ClassInfo)
{
Gson gson = new GsonBuilder().create();
String text = gson.toJson(AnObject);
ObjectType newObject = gson.fromJson(text, ClassInfo);
return newObject;
}
public static void main(String[] args)
{
MyObject anObject ...
MyObject copyObject = Copy(o, MyObject.class);
}
In Angular 6, with your router you can use:
RouterModule.forRoot(routes, { useHash: false })
This is how you do it
SELECT ID,NAME, (C_COUNTS+F_COUNTS) AS SUM_COUNTS
FROM TABLE
ORDER BY SUM_COUNTS LIMIT 20
The SUM function will add up all rows, so the order by
clause is useless, instead you will have to use the group by
clause.
static String toCamelCase(String s){
String[] parts = s.split(" ");
String camelCaseString = "";
for (String part : parts){
if(part!=null && part.trim().length()>0)
camelCaseString = camelCaseString + toProperCase(part);
else
camelCaseString=camelCaseString+part+" ";
}
return camelCaseString;
}
static String toProperCase(String s) {
String temp=s.trim();
String spaces="";
if(temp.length()!=s.length())
{
int startCharIndex=s.charAt(temp.indexOf(0));
spaces=s.substring(0,startCharIndex);
}
temp=temp.substring(0, 1).toUpperCase() +
spaces+temp.substring(1).toLowerCase()+" ";
return temp;
}
public static void main(String[] args) {
String string="HI tHiS is SomE Statement";
System.out.println(toCamelCase(string));
}
First you need to install cors
by using below command :
npm install cors --save
Now add the following code to your app starting file like ( app.js or server.js
)
var express = require('express');
var app = express();
var cors = require('cors');
var bodyParser = require('body-parser');
//enables cors
app.use(cors({
'allowedHeaders': ['sessionId', 'Content-Type'],
'exposedHeaders': ['sessionId'],
'origin': '*',
'methods': 'GET,HEAD,PUT,PATCH,POST,DELETE',
'preflightContinue': false
}));
require('./router/index')(app);
In case you get this error, it might also be related to how you included the JavaScript file into your html page. When loading modules, you have to explicitly declare those files as such. Here's an example:
//module.js:
function foo(){
return "foo";
}
var bar = "bar";
export { foo, bar };
When you include the script like this:
<script src="module.js"></script>
You will get the error:
Uncaught SyntaxError: Unexpected token export
You need to include the file with a type attribute set to "module":
<script type="module" src="module.js"></script>
then it should work as expected and you are ready to import your module in another module:
import { foo, bar } from "./module.js";
console.log( foo() );
console.log( bar );
You are mixing a lot of things, which makes it hard to answer your question. The short answer is: As far as I know, what you want to do is just not possible in Python - for good reason!
The longer answer is that you should make yourself more comfortable with Python, if you want to develop in Python. Comprehensions are not hard to read. You might not be used to reading them, but you have to get used to it if you want to be a Python developer. If there is a language that fits your needs better, choose that one. If you choose Python, be prepared to solve problems in a pythonic way. Of course you are free to fight against Python, But it will not be fun! ;-)
And if you would tell us what your real problem is, you might even get a pythonic answer. "Getting something in one line" us usually not a programming problem.
If you want to pass the cookie to the browser, you have to append to the headers to be sent back. If you're using wsgi:
import requests
...
def application(environ, start_response):
cookie = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}
response_headers = [('Content-type', 'text/plain')]
response_headers.append(('Set-Cookie',cookie))
...
return [bytes(post_env),response_headers]
I'm successfully able to authenticate with Bugzilla and TWiki hosted on the same domain my python wsgi script is running by passing auth user/password to my python script and pass the cookies to the browser. This allows me to open the Bugzilla and TWiki pages in the same browser and be authenticated. I'm trying to do the same with SuiteCRM but i'm having trouble with SuiteCRM accepting the session cookies obtained from the python script even though it has successfully authenticated.
Be careful, the solution proposed with $a = array_combine($a, $a);
will not work for numeric values.
I for example wanted to have a memory array(128,256,512,1024,2048,4096,8192,16384)
to be the keys as well as the values however PHP manual states:
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
So I solved it like this:
foreach($array as $key => $val) {
$new_array[$val]=$val;
}
All of these are good answers but I think there's more to explain why None
is useful.
Imagine you collecting RSVPs to a wedding. You want to record whether each person will attend. If they are attending, you set person.attending = True
. If they are not attending you set person.attending = False
. If you have not received any RSVP, then person.attending = None
. That way you can distinguish between no information - None
- and a negative answer.
Reason for the error:
Column
tries to expands in vertical axis, and so does the ListView
, hence you need to constrain the height of ListView
.
Solutions
Use either Expanded
or Flexible
if you want to allow ListView
to take up entire left space in Column
.
Column(
children: <Widget>[
Expanded(
child: ListView(...),
)
],
)
Use SizedBox
if you want to restrict the size of ListView
to a certain height.
Column(
children: <Widget>[
SizedBox(
height: 200, // constrain height
child: ListView(),
)
],
)
Use shrinkWrap
, if your ListView
isn't too big.
Column(
children: <Widget>[
ListView(
shrinkWrap: true, // use it
)
],
)
The steps I needed to perform were:
System.Web.Http.WebHost
.App_Start\WebApiConfig.cs
(see code snippet below).System.Web.Http
in Global.asax.cs
.WebApiConfig.Register(GlobalConfiguration.Configuration)
in MvcApplication.Application_Start()
(in file Global.asax.cs
), before registering the default Web Application route as that would otherwise take precedence.System.Web.Http.ApiController
.I could then learn enough from the tutorial (Your First ASP.NET Web API) to define my API controller.
App_Start\WebApiConfig.cs:
using System.Web.Http;
class WebApiConfig
{
public static void Register(HttpConfiguration configuration)
{
configuration.Routes.MapHttpRoute("API Default", "api/{controller}/{id}",
new { id = RouteParameter.Optional });
}
}
Global.asax.cs:
using System.Web.Http;
...
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterGlobalFilters(GlobalFilters.Filters);
WebApiConfig.Register(GlobalConfiguration.Configuration);
RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
Update 10.16.2015:
Word has it, the NuGet package Microsoft.AspNet.WebApi must be installed for the above to work.
If PowerShell is open in a directory other than the target file, e.g.:
If someScript.ps1
is located here: C:\SlowLearner\some_missing_path\someScript.ps1
, then C:\SlowLearner>. ./someScript.ps1
wont work.
In that case, navigate to the path: cd some_missing_path
then this would work:
C:\SlowLearner\some_missing_path>. ./someScript.ps1
A semaphore is a signaling mechanism used to coordinate between threads. Example: One thread is downloading files from the internet and another thread is analyzing the files. This is a classic producer/consumer scenario. The producer calls signal()
on the semaphore when a file is downloaded. The consumer calls wait()
on the same semaphore in order to be blocked until the signal indicates a file is ready. If the semaphore is already signaled when the consumer calls wait, the call does not block. Multiple threads can wait on a semaphore, but each signal will only unblock a single thread.
A counting semaphore keeps track of the number of signals. E.g. if the producer signals three times in a row, wait()
can be called three times without blocking. A binary semaphore does not count but just have the "waiting" and "signalled" states.
A mutex (mutual exclusion lock) is a lock which is owned by a single thread. Only the thread which have acquired the lock can realease it again. Other threads which try to acquire the lock will be blocked until the current owner thread releases it. A mutex lock does not in itself lock anything - it is really just a flag. But code can check for ownership of a mutex lock to ensure that only one thread at a time can access some object or resource.
A monitor is a higher-level construct which uses an underlying mutex lock to ensure thread-safe access to some object. Unfortunately the word "monitor" is used in a few different meanings depending on context and platform and context, but in Java for example, a monitor is a mutex lock which is implicitly associated with an object, and which can be invoked with the synchronized
keyword. The synchronized
keyword can be applied to a class, method or block and ensures only one thread can execute the code at a time.
Plus operator is perfectly fine solution to concatenate two Python strings. But if you keep adding more than two strings (n > 25) , you might want to think something else.
''.join([a, b, c])
trick is a performance optimization.
You could put the body of your script into a function and then you could return from that function.
def main():
done = True
if done:
return
# quit/stop/exit
else:
# do other stuff
if __name__ == "__main__":
#Run as main program
main()
When running Tomcat under jsvc, it will not respond to the shutdown signal on the specified shutdown port which is sent from the shutdown.sh script. The only way that I'm aware of is to kill the process, however you'll need to kill the ones listed as jsvc, not java.
Use this CSS:
background-size: 100% 100%
It might help who is looking for the same solution.
select * from tablename ORDER BY ABS(column_name)
There is no built-in method for Node to change the CWD of the underlying shell running the Node process.
You can change the current working directory of the Node process through the command process.chdir()
.
var process = require('process');
process.chdir('../');
When the Node process exists, you will find yourself back in the CWD you started the process in.
A modified version of solution by ssh_imov
function removeParam(uri, keyValue) {
var re = new RegExp("([&\?]"+ keyValue + "*$|" + keyValue + "&|[?&]" + keyValue + "(?=#))", "i");
return uri.replace(re, '');
}
Call like this
removeParam("http://google.com?q=123&q1=234&q2=567", "q1=234");
// returns http://google.com?q=123&q2=567
Maybe check for any thing that you have changed under the php.ini file. For example I changed the ";intl.default_locale =" to ";intl.default_locale = en_utf8" in order to enable the "Internationalization extension (Intl)" without adding the "extension=php_intl.dll" then this same error occurred. So I suggest to check for similar mistakes.
managed to fix this by copying the below folder from another Visual Studio setup (non-express)
from C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\atlmfc
to C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\atlmfc
It turns out that it was shrinking and growing correctly, providing the desired behaviour all along; except that in all current browsers flexbox wasn't accounting for the vertical scrollbar! Which is why the content appears to be getting cut off.
You can see here, which is the original code I was using before I added the fixed widths, that it looks like the column isn't growing to accomodate the text:
http://jsfiddle.net/2w157dyL/1/
However if you make the content in that column wider, you'll see that it always cuts it off by the same amount, which is the width of the scrollbar.
So the fix is very, very simple - add enough right padding to account for the scrollbar:
http://jsfiddle.net/2w157dyL/2/
main > section {_x000D_
overflow-y: auto;_x000D_
padding-right: 2em;_x000D_
}
_x000D_
It was when I was trying some things suggested by Michael_B (specifically adding a padding buffer) that I discovered this, thanks so much!
Edit: I see that he also posted a fiddle which does the same thing - again, thanks so much for all your help
For your first question, find the position of some value in a list x using index(), like so:
x.index(value)
For your second question, to check for multiple same values you should split your list into chunks and use the same logic from above. They say divide and conquer. It works. Try this:
value = 1
x = [1,2,3,4,5,6,2,1,4,5,6]
chunk_a = x[:int(len(x)/2)] # get the first half of x
chunk_b = x[int(len(x)/2):] # get the rest half of x
print(chunk_a.index(value))
print(chunk_b.index(value))
Hope that helps!
dict1={'a':1, 'b':'banana'}
To list the dictionary in Python 2.x:
for k,v in dict1.iteritems():
print k,v
In Python 3.x use:
for k,v in dict1.items():
print(k,v)
# a 1
# b banana
Finally, as others have indicated, if you want a running index, you can have that too:
for i in enumerate(dict1.items()):
print(i)
# (0, ('a', 1))
# (1, ('b', 'banana'))
But this defeats the purpose of a dictionary (map, associative array) , which is an efficient data structure for telephone-book-style look-up. Dictionary ordering could be incidental to the implementation and should not be relied upon. If you need the order, use OrderedDict instead.
If you write it as the following in SQL server then there would be no danger of wiping the database table unless all of the values in that table happen to actually be between those values:
DELETE FROM [dbo].[TableName] WHERE [TableName].[IdField] BETWEEN 79 AND 296
As it wasn't already suggested here, but is probably one of the easiest solutions:
import subprocess
def play_mp3(path):
subprocess.Popen(['mpg123', '-q', path]).wait()
It depends on any mpg123 compliant player, which you get e.g. for Debian using:
apt-get install mpg123
or
apt-get install mpg321
You can use type
or isinstance
.
In Python 2:
>>> type(u'abc') # Python 2 unicode string literal
<type 'unicode'>
>>> type('abc') # Python 2 byte string literal
<type 'str'>
In Python 2, str
is just a sequence of bytes. Python doesn't know what
its encoding is. The unicode
type is the safer way to store text.
If you want to understand this more, I recommend http://farmdev.com/talks/unicode/.
In Python 3:
>>> type('abc') # Python 3 unicode string literal
<class 'str'>
>>> type(b'abc') # Python 3 byte string literal
<class 'bytes'>
In Python 3, str
is like Python 2's unicode
, and is used to
store text. What was called str
in Python 2 is called bytes
in Python 3.
You can call decode
. If it raises a UnicodeDecodeError exception, it wasn't valid.
>>> u_umlaut = b'\xc3\x9c' # UTF-8 representation of the letter 'Ü'
>>> u_umlaut.decode('utf-8')
u'\xdc'
>>> u_umlaut.decode('ascii')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 0: ordinal not in range(128)
import android.app.Activity;
import android.util.Log;
import android.widget.ImageView;
/**
* Created by atiq.mumtaz on 25.04.2016.
*/
public class GifImage_Player extends Thread
{
Activity activity;
ImageView image_view;
boolean is_running=false;
int pause_time;
int[] drawables;
public GifImage_Player(Activity activity,ImageView img_view,int[] drawable)
{
this.activity=activity;
this.image_view=img_view;
this.is_running=true;
pause_time=25;
this.drawables=drawable;
}
public void set_pause_time(int interval)
{
this.pause_time=interval;
}
public void stop_playing()
{
this.is_running=false;
}
public void run()
{
Log.d("Gif Player","Gif Player Stopped");
int pointer=0;
while (this.is_running)
{
if(drawables.length>0)
{
if((drawables.length-1)==pointer)
{
pointer=0;
}
try
{
activity.runOnUiThread(new Run(pointer));
Thread.sleep(pause_time);
}
catch (Exception e)
{
Log.d("GifPlayer","Exception: "+e.getMessage());
is_running=false;
}
pointer++;
}
}
Log.d("Gif Player","Gif Player Stopped");
}
class Run implements Runnable
{
int pointer;
public Run(int pointer)
{
this.pointer=pointer;
}
public void run()
{
image_view.setImageResource(drawables[pointer]);
}
}
}
/////////////////////////////Usage///////////////////////////////////////
int[] int_array=new int[]{R.drawable.tmp_0,R.drawable.tmp_1,R.drawable.tmp_2,R.drawable.tmp_3
,R.drawable.tmp_4,R.drawable.tmp_5,R.drawable.tmp_6,R.drawable.tmp_7,R.drawable.tmp_8,R.drawable.tmp_9,
R.drawable.tmp_10,R.drawable.tmp_11,R.drawable.tmp_12,R.drawable.tmp_13,R.drawable.tmp_14,R.drawable.tmp_15,
R.drawable.tmp_16,R.drawable.tmp_17,R.drawable.tmp_18,R.drawable.tmp_19,R.drawable.tmp_20,R.drawable.tmp_21,R.drawable.tmp_22,R.drawable.tmp_23};
GifImage_Player gif_player;
gif_player=new GifImage_Player(this,(ImageView)findViewById(R.id.mygif),int_array);
gif_player.start();
I use this:
jQuery Plugin
(function($){
$.fn.getFormData = function(){
var data = {};
var dataArray = $(this).serializeArray();
for(var i=0;i<dataArray.length;i++){
data[dataArray[i].name] = dataArray[i].value;
}
return data;
}
})(jQuery);
HTML Form
<form id='myform'>
<input name='myVar1' />
<input name='myVar2' />
</form>
Get the Data
var myData = $("#myForm").getFormData();
You can also use query(), i.e.:
df_filtered = df.query('a == 4 & b != 2')
Yes, Json.Net is what you need. You basically want to deserialize a Json string into an array of objects
.
See their examples:
string myJsonString = @"{
"Name": "Apple",
"Expiry": "\/Date(1230375600000+1300)\/",
"Price": 3.99,
"Sizes": [
"Small",
"Medium",
"Large"
]
}";
// Deserializes the string into a Product object
Product myProduct = JsonConvert.DeserializeObject<Product>(myJsonString);
If you in any doubt, have a look at JDK source code
ArrayList.clear()
source code:
public void clear() {
modCount++;
// Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
You will see that size
is set to 0 so you start from 0 position.
Please note that when adding elements to ArrayList
, the backend array is extended (i.e. array data is copied to bigger array if needed) in order to be able to add new items. When performing ArrayList.clear()
you only remove references to array elements and sets size
to 0, however, capacity
stays as it was.
It sounds like your site has CSS or JS that depends on running in quirks mode. Which is why you need garbage above your doctype to render "correctly". I suggest removing said garbage and then fixing your CSS+JS to actually work in standards mode; you'll save yourself a lot of pain in the long run.
It will be faster to just make a HEAD request so no HTML will be fetched.
Also I am sure google would like it better this way :)
try:
import httplib
except:
import http.client as httplib
def have_internet():
conn = httplib.HTTPConnection("www.google.com", timeout=5)
try:
conn.request("HEAD", "/")
conn.close()
return True
except:
conn.close()
return False
Well, actually I'll have to say David is right with his solution, but there are some topics disturbing me:
ViewModel
, and include the Model as member in the ViewModel
, then you effectively sent your model to the View => this is BADSo how can you create a better coupling?
I would use a tool like AutoMapper
or ValueInjecter to map between ViewModel
and Model.
AutoMapper
does seem to have the better syntax and feel to it, but the current version lacks a
very severe topic: It is not able to perform the mapping from ViewModel
to Model (under certain circumstances like flattening, etc., but this is off topic)
So at present I prefer to use ValueInjecter
.
So you create a ViewModel
with the fields you need in the view.
You add the SelectList items you need as lookups.
And you add them as SelectLists already. So you can query from a LINQ enabled sourc, select the ID and text field and store it as a selectlist:
You gain that you do not have to create a new type (dictionary) as lookup and you just move the new SelectList
from the view to the controller.
// StaffTypes is an IEnumerable<StaffType> from dbContext
// viewModel is the viewModel initialized to copy content of Model Employee
// viewModel.StaffTypes is of type SelectList
viewModel.StaffTypes =
new SelectList(
StaffTypes.OrderBy( item => item.Name )
"StaffTypeID",
"Type",
viewModel.StaffTypeID
);
In the view you just have to call
@Html.DropDownListFor( model => mode.StaffTypeID, model.StaffTypes )
Back in the post element of your method in the controller you have to take a parameter of the type of your ViewModel
. You then check for validation.
If the validation fails, you have to remember to re-populate the viewModel.StaffTypes
SelectList, because this item will be null on entering the post function.
So I tend to have those population things separated into a function.
You just call back return new View(viewModel)
if anything is wrong.
Validation errors found by MVC3 will automatically be shown in the view.
If you have your own validation code you can add validation errors by specifying which field they belong to. Check documentation on ModelState
to get info on that.
If the viewModel
is valid you have to perform the next step:
If it is a create of a new item, you have to populate a model from the viewModel
(best suited is ValueInjecter
). Then you can add it to the EF collection of that type and commit changes.
If you have an update, you get the current db item first into a model. Then you can copy the values from the viewModel
back to the model (again using ValueInjecter
gets you do that very quick).
After that you can SaveChanges
and are done.
Feel free to ask if anything is unclear.
$("#txtfromdate").datepicker({
numberOfMonths: 2,
maxDate: 0,
dateFormat: 'dd-M-yy'
}).attr('readonly', 'readonly');
add the readonly attribute in the jquery.
Removes only the leading & trailing spaces.
From Java Doc, "Returns a string whose value is this string, with any leading and trailing whitespace removed."
System.out.println(" D ev Dum my ".trim());
"D ev Dum my"
Replaces all the empty strings in the word,
System.out.println(" D ev Dum my ".replace(" ",""));
System.out.println(" D ev Dum my ".replaceAll(" ",""));
System.out.println(" D ev Dum my ".replaceAll("\\s+",""));
Output:
"DevDummy"
"DevDummy"
"DevDummy"
Note: "\s+" is the regular expression similar to the empty space character.
Reference : https://www.codedjava.com/2018/06/replace-all-spaces-in-string-trim.html
for superclasses with many members I would suggest you to use @Delegate
@Data
public class A {
@Delegate public class AInner{
private final int x;
private final int y;
}
}
@Data
@EqualsAndHashCode(callSuper = true)
public class B extends A {
private final int z;
public B(A.AInner a, int z) {
super(a);
this.z = z;
}
}
How about:
select salesid from AXDelNotesNoTracking group by salesid having count(*) > 1;
This should work:
<span class="vote-up@(puzzle.UserVote == VoteType.Up ? "-selected" : "")">Vote Up</span>
You can use Array.prototype.find function in javascript. Array find MDN.
So to find string in array of string, the code becomes very simple. Plus as browser implementation, it will provide good performance.
Ex.
var strs = ['abc', 'def', 'ghi', 'jkl', 'mno'];
var value = 'abc';
strs.find(
function(str) {
return str == value;
}
);
or using lambda expression it will become much shorter
var strs = ['abc', 'def', 'ghi', 'jkl', 'mno'];
var value = 'abc';
strs.find((str) => str === value);
Escaping a double quote can absolutely be necessary in sed: for instance, if you are using double quotes in the entire sed expression (as you need to do when you want to use a shell variable).
Here's an example that touches on escaping in sed but also captures some other quoting issues in bash:
# cat inventory
PURCHASED="2014-09-01"
SITE="Atlanta"
LOCATION="Room 154"
Let's say you wanted to change the room using a sed script that you can use over and over, so you variablize the input as follows:
# i="Room 101" (these quotes are there so the variable can contains spaces)
This script will add the whole line if it isn't there, or it will simply replace (using sed) the line that is there with the text plus the value of $i.
if grep -q LOCATION inventory; then
## The sed expression is double quoted to allow for variable expansion;
## the literal quotes are both escaped with \
sed -i "/^LOCATION/c\LOCATION=\"$i\"" inventory
## Note the three layers of quotes to get echo to expand the variable
## AND insert the literal quotes
else
echo LOCATION='"'$i'"' >> inventory
fi
P.S. I wrote out the script above on multiple lines to make the comments parsable but I use it as a one-liner on the command line that looks like this:
i="your location"; if grep -q LOCATION inventory; then sed -i "/^LOCATION/c\LOCATION=\"$i\"" inventory; else echo LOCATION='"'$i'"' >> inventory; fi
You can't checkout a single directory of a repository because the entire repository is handled by the single .git folder in the root of the project instead of subversion's myriad of .svn directories.
The problem with working on plugins in a single repository is that making a commit to, e.g., mytheme will increment the revision number for myplugin, so even in subversion it is better to use separate repositories.
The subversion paradigm for sub-projects is svn:externals which translates somewhat to submodules in git (but not exactly in case you've used svn:externals before.)
Window->Preferences->Java->Code Style->Formatter->Edit->Indentation = "Spaces Only"
Posting another alternative to be more complete. When I tried the "pre" based answers, they added extra vertical line breaks as well.
Each tab can be converted to a sequence non-breaking spaces which require no wrapping.
" "
This is not recommended for repeated/extensive use within a page. A div margin/padding approach would appear much cleaner.
A really good way to make a tooltip is described here: Simple D3 tooltip example
You have to append a div
var tooltip = d3.select("body")
.append("div")
.style("position", "absolute")
.style("z-index", "10")
.style("visibility", "hidden")
.text("a simple tooltip");
Then you can just toggle it using
.on("mouseover", function(){return tooltip.style("visibility", "visible");})
.on("mousemove", function(){return tooltip.style("top",
(d3.event.pageY-10)+"px").style("left",(d3.event.pageX+10)+"px");})
.on("mouseout", function(){return tooltip.style("visibility", "hidden");});
d3.event.pageX
/ d3.event.pageY
is the current mouse coordinate.
If you want to change the text you can use tooltip.text("my tooltip text");
var myData = ds.Tables[0].AsEnumerable().Select(r => new Employee {
Name = r.Field<string>("Name"),
Age = r.Field<int>("Age")
});
var list = myData.ToList(); // For if you really need a List and not IEnumerable
To correctly save the instance state of Fragment
you should do the following:
1. In the fragment, save instance state by overriding onSaveInstanceState()
and restore in onActivityCreated()
:
class MyFragment extends Fragment {
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
...
if (savedInstanceState != null) {
//Restore the fragment's state here
}
}
...
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Save the fragment's state here
}
}
2. And important point, in the activity, you have to save the fragment's instance in onSaveInstanceState()
and restore in onCreate()
.
class MyActivity extends Activity {
private MyFragment
public void onCreate(Bundle savedInstanceState) {
...
if (savedInstanceState != null) {
//Restore the fragment's instance
mMyFragment = getSupportFragmentManager().getFragment(savedInstanceState, "myFragmentName");
...
}
...
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//Save the fragment's instance
getSupportFragmentManager().putFragment(outState, "myFragmentName", mMyFragment);
}
}
Hope this helps.
You can try the following method(python3.6.2):
case one:
@app.route('/hello')
def hello():
headers={ 'content-type':'text/plain' ,'location':'http://www.stackoverflow'}
response = make_response('<h1>hello world</h1>',301)
response.headers = headers
return response
case two:
@app.route('/hello')
def hello():
headers={ 'content-type':'text/plain' ,'location':'http://www.stackoverflow.com'}
return '<h1>hello world</h1>',301,headers
I am using Flask .And if you want to return json,you can write this:
import json #
@app.route('/search/<keyword>')
def search(keyword):
result = Book.search_by_keyword(keyword)
return json.dumps(result),200,{'content-type':'application/json'}
from flask import jsonify
@app.route('/search/<keyword>')
def search(keyword):
result = Book.search_by_keyword(keyword)
return jsonify(result)
SELECT DISTINCT *
INTO tempdb.dbo.tmpTable
FROM myTable
TRUNCATE TABLE myTable
INSERT INTO myTable SELECT * FROM tempdb.dbo.tmpTable
DROP TABLE tempdb.dbo.tmpTable
Not to repeat what everyone already have said but keep the following cheat sheet handly for File manipulations:
System.IO.File.ReadAllBytes(filename);
File.Exists(filename)
Path.Combine(folderName, resOfThePath);
Path.GetFullPath(path); // converts a relative path to absolute one
Path.GetExtension(path);
Define the width as 960px, or whatever you prefer, and you're good to go!
#main {
margin: 0 auto !important;
float: none !important;
text-align: center;
width: 960px;
}
(I couldn't figure this out until I fixed the width, nothing else worked.)
nproc
is what you are looking for.
More here : http://www.cyberciti.biz/faq/linux-get-number-of-cpus-core-command/
Lets say your data is -
data = {'a': [ [1, 2] ], 'b': [ [3, 4] ],'c':[ [5,6]] }
You can use the data.items()
method to get the dictionary elements. Note, in django templates we do NOT put ()
. Also some users mentioned values[0]
does not work, if that is the case then try values.items
.
<table>
<tr>
<td>a</td>
<td>b</td>
<td>c</td>
</tr>
{% for key, values in data.items %}
<tr>
<td>{{key}}</td>
{% for v in values[0] %}
<td>{{v}}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
Am pretty sure you can extend this logic to your specific dict.
To iterate over dict keys in a sorted order - First we sort in python then iterate & render in django template.
return render_to_response('some_page.html', {'data': sorted(data.items())})
In template file:
{% for key, value in data %}
<tr>
<td> Key: {{ key }} </td>
<td> Value: {{ value }} </td>
</tr>
{% endfor %}
git log --tags --no-walk --pretty="format:%d" | sed 2q | sed 's/[()]//g' | sed s/,[^,]*$// | sed 's ...... '
IF YOU NEED MORE THAN ONE LAST TAG
(git describe --tags sometimes gives wrong hashes, i dont know why, but for me --max-count 2 doesnt work)
this is how you can get list with latest 2 tag names in reverse chronological order, works perfectly on git 1.8.4. For earlier versions of git(like 1.7.*), there is no "tag: " string in output - just delete last sed call
If you want more than 2 latest tags - change this "sed 2q" to "sed 5q" or whatever you need
Then you can easily parse every tag name to variable or so.
You should be able to "MINUS" or "EXCEPT" depending on the flavor of SQL used by your DBMS.
select * from tableA
minus
select * from tableB
If the query returns no rows then the data is exactly the same.
We had the same issue.
The parent pom file was available in our local repository, but maven still unsuccessfully tried to download it from the central repository, or from the relativePath (there were no files in the relative path).
Turns out, there was a file called "_remote.repositories" in the local repository, which was causing this behavior. After deleting all the files with this name from the complete local repository, we could build our modules.
Try... csv download.
<?php
mysql_connect('hostname', 'username', 'password');
mysql_select_db('dbname');
$qry = mysql_query("SELECT * FROM tablename");
$data = "";
while($row = mysql_fetch_array($qry)) {
$data .= $row['field1'].",".$row['field2'].",".$row['field3'].",".$row['field4']."\n";
}
header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename="filename.csv"');
echo $data; exit();
?>
Use JOIN to join the subqueries and use ON to say where the rows from each subquery must match:
SELECT T1.col_a, T1.col_b, T2.col_c
FROM (SELECT col_a, col_b, ...etc...) AS T1
JOIN (SELECT col_a, col_c, ...etc...) AS T2
ON T1.col_a = T2.col_a
If there are some values of col_a that are in T1 but not in T2, you can use a LEFT OUTER JOIN instead.
Silly workaround that always works.
$state.go("otherState").then(function(){
$state.go("wantedState")
});
some people have suggested the "visited", but the visited links remain in the browsers cache, so the next time your user visits the page, the link will have the second image.. i dont know it that's the desired effect you want. Anyway you coul mix JS and CSS:
<style>
.off{
color:red;
}
.on{
color:green;
}
</style>
<a href="" class="off" onclick="this.className='on';return false;">Foo</a>
using the onclick event, you can change (or toggle maybe?) the class name of the element. In this example i change the text color but you could also change the background image.
Good Luck
You mean fast enumeration? You question is very unclear.
A normal for loop would look a bit like this:
unsigned int i, cnt = [someArray count];
for(i = 0; i < cnt; i++)
{
// do loop stuff
id someObject = [someArray objectAtIndex:i];
}
And a loop with fast enumeration, which is optimized by the compiler, would look like this:
for(id someObject in someArray)
{
// do stuff with object
}
Keep in mind that you cannot change the array you are using in fast enumeration, thus no deleting nor adding when using fast enumeration
Every class in Java have a constructor ( a constructor is a method which is called when a new object is created, which initializes the fields of the class variables ). So when you are creating an instance of the class, constructor method is called while creating the object and all the data values are initialized at that time.
For object of integer array type all values in the array are initialized to 0(zero) in the constructor method. Similarly for object of boolean array, all values are initialized to false.
So Java is initializing the array by running its constructor method while creating the object
In a nutshell Javascript Closures allow a function to access a variable that is declared in a lexical-parent function.
Let's see a more detailed explanation. To understand closures it is important to understand how JavaScript scopes variables.
Scopes
In JavaScript scopes are defined with functions. Every function defines a new scope.
Consider the following example;
function f()
{//begin of scope f
var foo='hello'; //foo is declared in scope f
for(var i=0;i<2;i++){//i is declared in scope f
//the for loop is not a function, therefore we are still in scope f
var bar = 'Am I accessible?';//bar is declared in scope f
console.log(foo);
}
console.log(i);
console.log(bar);
}//end of scope f
calling f prints
hello
hello
2
Am I Accessible?
Let's now consider the case we have a function g
defined within another function f
.
function f()
{//begin of scope f
function g()
{//being of scope g
/*...*/
}//end of scope g
/*...*/
}//end of scope f
We will call f
the lexical parent of g
.
As explained before we now have 2 scopes; the scope f
and the scope g
.
But one scope is "within" the other scope, so is the scope of the child function part of the scope of the parent function? What happens with the variables declared in the scope of the parent function; will I be able to access them from the scope of the child function? That's exactly where closures step in.
Closures
In JavaScript the function g
can not only access any variables declared in scope g
but also access any variables declared in the scope of the parent function f
.
Consider following;
function f()//lexical parent function
{//begin of scope f
var foo='hello'; //foo declared in scope f
function g()
{//being of scope g
var bar='bla'; //bar declared in scope g
console.log(foo);
}//end of scope g
g();
console.log(bar);
}//end of scope f
calling f prints
hello
undefined
Let's look at the line console.log(foo);
. At this point we are in scope g
and we try to access the variable foo
that is declared in scope f
. But as stated before we can access any variable declared in a lexical parent function which is the case here; g
is the lexical parent of f
. Therefore hello
is printed.
Let's now look at the line console.log(bar);
. At this point we are in scope f
and we try to access the variable bar
that is declared in scope g
. bar
is not declared in the current scope and the function g
is not the parent of f
, therefore bar
is undefined
Actually we can also access the variables declared in the scope of a lexical "grand parent" function. Therefore if there would be a function h
defined within the function g
function f()
{//begin of scope f
function g()
{//being of scope g
function h()
{//being of scope h
/*...*/
}//end of scope h
/*...*/
}//end of scope g
/*...*/
}//end of scope f
then h
would be able to access all the variables declared in the scope of function h
, g
, and f
. This is done with closures. In JavaScript closures allows us to access any variable declared in the lexical parent function, in the lexical grand parent function, in the lexical grand-grand parent function, etc.
This can be seen as a scope chain; scope of current function -> scope of lexical parent function -> scope of lexical grand parent function -> ...
until the last parent function that has no lexical parent.
The window object
Actually the chain doesn't stop at the last parent function. There is one more special scope; the global scope. Every variable not declared in a function is considered to be declared in the global scope. The global scope has two specialities;
window
object.Therefore there are exactly two ways of declaring a variable foo
in the global scope; either by not declaring it in a function or by setting the property foo
of the window object.
Both attempts uses closures
Now that you have read a more detailed explanation it may now be apparent that both solutions uses closures. But to be sure, let's make a proof.
Let's create a new Programming Language; JavaScript-No-Closure. As the name suggests, JavaScript-No-Closure is identical to JavaScript except it doesn't support Closures.
In other words;
var foo = 'hello';
function f(){console.log(foo)};
f();
//JavaScript-No-Closure prints undefined
//JavaSript prints hello
Alright, let's see what happens with the first solution with JavaScript-No-Closure;
for(var i = 0; i < 10; i++) {
(function(){
var i2 = i;
setTimeout(function(){
console.log(i2); //i2 is undefined in JavaScript-No-Closure
}, 1000)
})();
}
therefore this will print undefined
10 times in JavaScript-No-Closure.
Hence the first solution uses closure.
Let's look at the second solution;
for(var i = 0; i < 10; i++) {
setTimeout((function(i2){
return function() {
console.log(i2); //i2 is undefined in JavaScript-No-Closure
}
})(i), 1000);
}
therefore this will print undefined
10 times in JavaScript-No-Closure.
Both solutions uses closures.
Edit: It is assumed that these 3 code snippets are not defined in the global scope. Otherwise the variables foo
and i
would be bind to the window
object and therefore accessible through the window
object in both JavaScript and JavaScript-No-Closure.
What if your lists contain duplicates like this:
v1 = ['s', 'h', 'e', 'e', 'p']
v2 = ['s', 's', 'h']
Sets do not contain duplicates. So, the following line returns True.
set(v2).issubset(v1)
To count for duplicates, you can use the code:
v1 = sorted(v1)
v2 = sorted(v2)
def is_subseq(v2, v1):
"""Check whether v2 is a subsequence of v1."""
it = iter(v1)
return all(c in it for c in v2)
So, the following line returns False.
is_subseq(v2, v1)
yourContext.Entry(yourEntity).Reload();
since your over
div doesn't have a positioning, the z-index doesn't know where and how to position it (and with respect to what?). Just change your over div's position to relative, so there is no side effects on that div and then the under div will obey to your will.
here is your example on jsfiddle: Fiddle
edit: I see someone already mentioned this answer!
Consider using Joda Time. I love this library and wish it would replace the current horrible mess that are the existing Java Date and Calendar classes. It's date handling done right.
EDIT: It's not 2009 any more, and Java 8's been out for ages. Use Java 8's built in java.time classes which are based on Joda Time, as Basil Bourque mentions above. In this case you'll want the Period class, and here's Oracle's tutorial on how to use it.
Remember, you are NOT allowed to do this.
class foo():
def print_hello(self):
print("Hello") # This next line will produce an ERROR!
self.print_hello() # <---- it calls a class function, inside a class,
# but outside a class function. Not allowed.
You must call a class function from either outside the class, or from within a function in that class.
There is an explicit cast on CString to LPCTSTR, so you can do (provided unicode is not specified):
CString str;
// ....
const char* cstr = (LPCTSTR)str;
On line 10 there's a space between s
and t
. It should be one word: stylesheet
.
You can find your created database, named <your-database-name>
in
//data/data/<Your-Application-Package-Name>/databases/<your-database-name>
Pull it out using File explorer and rename it to have .db3 extension to use it in SQLiteExplorer
Use File explorer of DDMS to navigate to emulator directory.
You are grouping by month only, you have to add YEAR() to the group by
Iterative:
Math.factorial=n=>{for(var o=n;n>1;)o*=--n;return o};
Recursive:
Math.factorial=n=>n>1?n--*Math.fac(n):1;
Precalculated:
(_=>{let f=[],i=0;for(;i<171;i++)f[i]=(n=>{for(var o=n;n>1;)o*=--n;return o})(i);Math.factorial=n=>{n=Math.round(n);return n<171?f[n]:Infinity}})();
https://code.sololearn.com/Wj4rlA27C9fD. Here I might post more solutions.
The root directory of a web application has a special significance and certain content can be present on in that folder. It can have a special file called as “Global.asax”. ASP.Net framework uses the content in the global.asax and creates a class at runtime which is inherited from HttpApplication. During the lifetime of an application, ASP.NET maintains a pool of Global.asax derived HttpApplication instances. When an application receives an http request, the ASP.Net page framework assigns one of these instances to process that request. That instance is responsible for managing the entire lifetime of the request it is assigned to and the instance can only be reused after the request has been completed when it is returned to the pool. The instance members in Global.asax cannot be used for sharing data across requests but static member can be. Global.asax can contain the event handlers of HttpApplication object and some other important methods which would execute at various points in a web application
A better pyramid can be printed this way:
The Pattern is $ $$$ $$$$$ $$$$$$$ $$$$$$$$$ $$$$$$$$$$$
public static void main(String agrs[]) {
System.out.println("The Pattern is");
int size = 11; //use only odd numbers here
for (int i = 1; i <= size; i=i+2) {
int spaceCount = (size - i)/2;
for(int j = 0; j< size; j++) {
if(j < spaceCount || j >= (size - spaceCount)) {
System.out.print(" ");
} else {
System.out.print("$");
}
}
System.out.println();
}
}
Happens when you have T_XXX
token in unexpected place, unbalanced (superfluous) parentheses, use of short tag without activating it in php.ini, and many more.
Related Questions:
For further help see:
There's actually a pretty good implementation of a class decorator here:
https://github.com/agiliq/Django-parsley/blob/master/parsley/decorators.py
I actually think this is a pretty interesting implementation. Because it subclasses the class it decorates, it will behave exactly like this class in things like isinstance
checks.
It has an added benefit: it's not uncommon for the __init__
statement in a custom django Form to make modifications or additions to self.fields
so it's better for changes to self.fields
to happen after all of __init__
has run for the class in question.
Very clever.
However, in your class you actually want the decoration to alter the constructor, which I don't think is a good use case for a class decorator.
Well... so many good answers but i wanna to add more on it. A brief look on Inner class in Java- Java allows us to define a class within another class and Being able to nest classes in this way has certain advantages:
It can hide(It increases encapsulation) the class from other classes - especially relevant if the class is only being used by the class it is contained within. In this case there is no need for the outside world to know about it.
It can make code more maintainable as the classes are logically grouped together around where they are needed.
The inner class has access to the instance variables and methods of its containing class.
We have mainly three types of Inner Classes
Some of the important points to be remember
Let`s try to see the above concepts practically_
public class MyInnerClass {
public static void main(String args[]) throws InterruptedException {
// direct access to inner class method
new MyInnerClass.StaticInnerClass().staticInnerClassMethod();
// static inner class reference object
StaticInnerClass staticInnerclass = new StaticInnerClass();
staticInnerclass.staticInnerClassMethod();
// access local inner class
LocalInnerClass localInnerClass = new MyInnerClass().new LocalInnerClass();
localInnerClass.localInnerClassMethod();
/*
* Pay attention to the opening curly braces and the fact that there's a
* semicolon at the very end, once the anonymous class is created:
*/
/*
AnonymousClass anonymousClass = new AnonymousClass() {
// your code goes here...
};*/
}
// static inner class
static class StaticInnerClass {
public void staticInnerClassMethod() {
System.out.println("Hay... from Static Inner class!");
}
}
// local inner class
class LocalInnerClass {
public void localInnerClassMethod() {
System.out.println("Hay... from local Inner class!");
}
}
}
I hope this will helps to everyone. Please refer for more
Based on the answer of massimo virgilio, I've also managed to do it with slf4j-log4j using introspection. HTH.
Logger LOG = LoggerFactory.getLogger(MyOwnClass.class);
org.apache.logging.slf4j.Log4jLogger LOGGER = (org.apache.logging.slf4j.Log4jLogger) LOG;
try {
Class loggerIntrospected = LOGGER.getClass();
Field fields[] = loggerIntrospected.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
String fieldName = fields[i].getName();
if (fieldName.equals("logger")) {
fields[i].setAccessible(true);
org.apache.logging.log4j.core.Logger loggerImpl = (org.apache.logging.log4j.core.Logger) fields[i].get(LOGGER);
loggerImpl.setLevel(Level.DEBUG);
}
}
} catch (Exception e) {
System.out.println("ERROR :" + e.getMessage());
}
I find this code and is resolve my problem.
http://arcware.net/setting-http-header-authorization-for-web-services/
protected override WebRequest GetWebRequest(Uri uri)
{
// Assuming authValue is set from somewhere, such as the config file
HttpWebRequest request = (HttpWebRequest)base.GetWebRequest(uri);
request.Headers.Add("Authorization", string.Format("Basic {0}", authValue));
return request;
}
If you're using jQuery versions 1.4.3+:
$('selector').click(false);
If not:
$('selector').click(function(){return false;});
I've implemented a MultipleAnswer
class that helps me to stub different answers in every call. Here the piece of code:
private final class MultipleAnswer<T> implements Answer<T> {
private final ArrayList<Answer<T>> mAnswers;
MultipleAnswer(Answer<T>... answer) {
mAnswers = new ArrayList<>();
mAnswers.addAll(Arrays.asList(answer));
}
@Override
public T answer(InvocationOnMock invocation) throws Throwable {
return mAnswers.remove(0).answer(invocation);
}
}
The simple answer to your question is that there is no Annotation-Inheritance in Java. However, there is a way to use the Spring annotations in a way that I think will help solve your problem.
@RequestMapping is supported at both the type level and at the method level.
When you put @RequestMapping
at the type level, most of the attributes are 'inherited' for each method in that class. This is mentioned in the Spring reference documentation. Look at the api docs for details on how each attribute is handled when adding @RequestMapping
to a type. I've summarized this for each attribute below:
name
: Value at Type level is concatenated with value at method level using '#' as a separator.value
: Value at Type level is inherited by method.path
: Value at Type level is inherited by method.method
: Value at Type level is inherited by method.params
: Value at Type level is inherited by method.headers
: Value at Type level is inherited by method.consumes
: Value at Type level is overridden by method.produces
: Value at Type level is overridden by method.Here is a brief example Controller that showcases how you could use this:
package com.example;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping(path = "/",
consumes = MediaType.APPLICATION_JSON_VALUE,
produces = MediaType.APPLICATION_JSON_VALUE,
method = {RequestMethod.GET, RequestMethod.POST})
public class JsonProducingEndpoint {
private FooService fooService;
@RequestMapping(path = "/foo", method = RequestMethod.POST)
public String postAFoo(@RequestBody ThisIsAFoo theFoo) {
fooService.saveTheFoo(theFoo);
return "http://myservice.com/foo/1";
}
@RequestMapping(path = "/foo/{id}", method = RequestMethod.GET)
public ThisIsAFoo getAFoo(@PathVariable String id) {
ThisIsAFoo foo = fooService.getAFoo(id);
return foo;
}
@RequestMapping(path = "/foo/{id}", produces = MediaType.APPLICATION_XML_VALUE, method = RequestMethod.GET)
public ThisIsAFooXML getAFooXml(@PathVariable String id) {
ThisIsAFooXML foo = fooService.getAFoo(id);
return foo;
}
}
list1 = ['a','b','c','d','e','f','g','h','i']
list2 = [0,1,1,0,1,2,2,0,1]
output=[]
cur_loclist = []
To get unique values present in list2
list_set = set(list2)
To find the loc of the index in list2
list_str = ''.join(str(s) for s in list2)
Location of index in list2
is tracked using cur_loclist
[0, 3, 7, 1, 2, 4, 8, 5, 6]
for i in list_set:
cur_loc = list_str.find(str(i))
while cur_loc >= 0:
cur_loclist.append(cur_loc)
cur_loc = list_str.find(str(i),cur_loc+1)
print(cur_loclist)
for i in range(0,len(cur_loclist)):
output.append(list1[cur_loclist[i]])
print(output)
Use std::setprecision
:
std::cout << std::setprecision (15) << 3.14159265358979 << std::endl;
Quick note: if you're also using coord_flip()
to flip the x and the y axis, you won't be able to set range limits using coord_cartesian()
because those two functions are exclusive (see here).
Fortunately, this is an easy fix; set your limits within coord_flip()
like so:
p + coord_flip(ylim = c(3,5), xlim = c(100, 400))
This just alters the visible range (i.e. doesn't remove data points).
Not to beat a dead horse, but I was searching for a solution, ended up here, and was myself not satisfied with the options, not least for some reason I wasn't able to get the provided solutions here to work well for me. (Likely due to errors on my part...) But I've been playing with flexbox and here's something I did get to work for myself.
Some of the settings are hard-wired, but only for purposes of demonstration. I'd think this solution ought to work in just about any modern browser. Just remove/adjust the fixed settings for the .flex-parent class, adjust colors/text/stuff and (I hope) you'll be as happy as I am with this approach.
HTML:
.flex-parent {_x000D_
display: flex;_x000D_
width: 300px;_x000D_
height: 20px;_x000D_
align-items: center;_x000D_
}_x000D_
_x000D_
.flex-child-edge {_x000D_
flex-grow: 2;_x000D_
height: 1px;_x000D_
background-color: #000;_x000D_
border: 1px #000 solid;_x000D_
}_x000D_
.flex-child-text {_x000D_
flex-basis: auto;_x000D_
flex-grow: 0;_x000D_
margin: 0px 5px 0px 5px;_x000D_
text-align: center;_x000D_
}
_x000D_
<div class="flex-parent">_x000D_
<div class="flex-child-edge"></div>_x000D_
<div class="flex-child-text">I found this simpler!</div>_x000D_
<div class="flex-child-edge"></div>_x000D_
</div>
_x000D_
I also saved my solution here: https://jsfiddle.net/Wellspring/wupj1y1a/1/
Now a days(year 2020) you can handle this using mocha configuration file:
Step 1: Create .mocharc.js file at the root location of your application
Step 2: Add below code in mocha config file:
'use strict';
module.exports = {
spec: 'src/app/**/*.test.js'
};
For More option in config file refer this link: https://github.com/mochajs/mocha/blob/master/example/config/.mocharc.js
And very nice and clean solution in koltin from com.nhaarman.mockito_kotlin
verify(mock).execute(argThat {
this.param = expected
})
Just try to add exit;
at the end of your PHP script.
Eclipse gives you an error/warning because you are trying to use internal classes that are specific to a JDK vendor and not part of the public API. Jakarta Commons provides its own implementation of base64 codecs, which of course reside in a different package. Delete those imports and let Eclipse import the proper Commons classs for you.
You can change your second condition to check only the span element:
...and contains(div/span, 'someText')]
If the span isn't always inside another div you can also use
...and contains(.//span, 'someText')]
This searches for the span anywhere inside the div.
Sounds like mssql jdbc is buffering the entire resultset for you. You can add a connect string parameter saying selectMode=cursor or responseBuffering=adaptive. If you are on version 2.0+ of the 2005 mssql jdbc driver then response buffering should default to adaptive.
You could instantiate the values from a dictionary if you wanted different values for each column & you don't mind making a dictionary on the line before.
>>> import pandas as pd
>>> import numpy as np
>>> df = pd.DataFrame({
'col_1': [0, 1, 2, 3],
'col_2': [4, 5, 6, 7]
})
>>> df
col_1 col_2
0 0 4
1 1 5
2 2 6
3 3 7
>>> cols = {
'column_new_1':np.nan,
'column_new_2':'dogs',
'column_new_3': 3
}
>>> df[list(cols)] = pd.DataFrame(data={k:[v]*len(df) for k,v in cols.items()})
>>> df
col_1 col_2 column_new_1 column_new_2 column_new_3
0 0 4 NaN dogs 3
1 1 5 NaN dogs 3
2 2 6 NaN dogs 3
3 3 7 NaN dogs 3
Not necessarily better than the accepted answer, but it's another approach not yet listed.
What is REST
REST stands for representational state transfer, it's actually an architectural style for creating Web API which treats everything(data or functionality) as recourse. It expects; exposing resources through URI and responding in multiple formats and representational transfer of state of the resources in stateless manner. Here I am talking about two things:
REST can use SOAP web services because it is a concept and can use any protocol like HTTP, SOAP.SOAP uses services interfaces to expose the business logic. REST uses URI to expose business logic.
REST is not REST without HATEOAS. This means that a client only knows the entry point URI and the resources are supposed to return links the client should follow. Those fancy documentation generators that give URI patterns for everything you can do in a REST API miss the point completely. They are not only documenting something that's supposed to be following the standard, but when you do that, you're coupling the client to one particular moment in the evolution of the API, and any changes on the API have to be documented and applied, or it will break.
HATEOAS, an abbreviation for Hypermedia As The Engine Of Application State, is a constraint of the REST application architecture that distinguishes it from most other network application architectures. The principle is that a client interacts with a network application entirely through hypermedia provided dynamically by application servers. A REST client needs no prior knowledge about how to interact with any particular application or server beyond a generic understanding of hypermedia. By contrast, in some service-oriented architectures (SOA), clients and servers interact through a fixed interface shared through documentation or an interface description language (IDL).
Here is the code for the functions that will do the work
-- To Base64 string
CREATE FUNCTION [dbo].[fn_str_TO_BASE64]
(
@STRING NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
RETURN (
SELECT
CAST(N'' AS XML).value(
'xs:base64Binary(xs:hexBinary(sql:column("bin")))'
, 'NVARCHAR(MAX)'
) Base64Encoding
FROM (
SELECT CAST(@STRING AS VARBINARY(MAX)) AS bin
) AS bin_sql_server_temp
)
END
GO
-- From Base64 string
CREATE FUNCTION [dbo].[fn_str_FROM_BASE64]
(
@BASE64_STRING NVARCHAR(MAX)
)
RETURNS NVARCHAR(MAX)
AS
BEGIN
RETURN (
SELECT
CAST(
CAST(N'' AS XML).value('xs:base64Binary(sql:variable("@BASE64_STRING"))', 'VARBINARY(MAX)')
AS NVARCHAR(MAX)
) UTF8Encoding
)
END
Example of usage:
DECLARE @CHAR NVARCHAR(256) = N'e.g., ???? ????? or ? ??????'
SELECT [dbo].[fn_str_FROM_BASE64]([dbo].[fn_str_TO_BASE64](@CHAR)) as converted
If you are using the LaunchScreen.storyboard you can obtain the same view controller and present it: (remember to set the storyboard id, for example "LaunchScreen")
func applicationDidBecomeActive(application: UIApplication) {
let storyboard = UIStoryboard(name: "LaunchScreen", bundle: nil)
let vc = storyboard.instantiateViewControllerWithIdentifier("LaunchScreen")
self.window!.rootViewController!.presentViewController(vc, animated: false, completion: nil)
}
SWIFT 4
let storyboard = UIStoryboard(name: "LaunchScreen", bundle: nil)
let vc = storyboard.instantiateViewController(withIdentifier: "LaunchScreen")
self.window!.rootViewController!.present(vc, animated: false, completion: nil)
In case this is useful to anyone I had this same issue. I was bringing in a footer into a web page via jQuery. Inside that footer were some Google scripts for ads and retargeting. I had to move those scripts from the footer and place them directly in the page and that eliminated the notice.
Since you didn't mention the version of Eclipse, I advice you to download the latest version of Eclipse Luna
which comes with Java 8 support by default.
The reason you might not be getting any results is because you might not be having the J2EE environment setup in your Eclipse IDE. Follow these steps to solve the problem.
Hope this helps.
table {
width: 100%;
th, td {
width: 1%;
}
}
SCSS syntax
library(lubridate)
if your date format is like this '04/24/2017 05:35:00'then change it like below
prods.all$Date2<-gsub("/","-",prods.all$Date2)
then change the date format
parse_date_time(prods.all$Date2, orders="mdy hms")
http://callmenick.com/2014/02/18/create-an-animated-resizing-header-on-scroll/
This link has a great tutorial with source code that you can play with, showing how to make elements within the header smaller as well as the header itself.
------SOLVED------
in this case you want to check two type of count for two cace
case 1:
if result contain only one record other word select single row from database using ->first()
if(count($result)){
...record is exist true...
}
case 2:
if result contain set of multiple row other word using ->get() or ->all()
if($result->count()) {
...record is exist true...
}
Based on Mark's answer above (and Geo's comment), I created a two liner version to remove all ASCII exception cases from a string. Provided for people searching for this answer (as I did).
using System.Text;
// Create encoder with a replacing encoder fallback
var encoder = ASCIIEncoding.GetEncoding("us-ascii",
new EncoderReplacementFallback(string.Empty),
new DecoderExceptionFallback());
string cleanString = encoder.GetString(encoder.GetBytes(dirtyString));
NO. It's not possible to change height of a select dropdown because that property is browser specific.
However if you want that functionality, then there are many options. You can use bootstrap dropdown-menu
and define it's max-height
property. Something like this.
$('.dropdown-menu').on( 'click', 'a', function() {_x000D_
var text = $(this).html();_x000D_
var htmlText = text + ' <span class="caret"></span>';_x000D_
$(this).closest('.dropdown').find('.dropdown-toggle').html(htmlText);_x000D_
});
_x000D_
.dropdown-menu {_x000D_
max-height: 146px;_x000D_
overflow: scroll;_x000D_
overflow-x: hidden;_x000D_
margin-top: 0px;_x000D_
}_x000D_
_x000D_
.caret {_x000D_
float: right;_x000D_
margin-top: 5%;_x000D_
}_x000D_
_x000D_
#menu1 {_x000D_
width: 160px; _x000D_
text-align: left;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
<div class="container" style="margin:10px">_x000D_
<div class="dropdown">_x000D_
<button class="btn btn-default dropdown-toggle" type="button" id="menu1" data-toggle="dropdown">Tutorials_x000D_
<span class="caret"></span></button>_x000D_
<ul class="dropdown-menu" role="menu" aria-labelledby="menu1">_x000D_
<li><a href="#">HTML</a></li>_x000D_
<li><a href="#">CSS</a></li>_x000D_
<li><a href="#">JavaScript</a></li>_x000D_
<li><a href="#">About Us</a></li>_x000D_
<li><a href="#">HTML</a></li>_x000D_
<li><a href="#">CSS</a></li>_x000D_
<li><a href="#">JavaScript</a></li>_x000D_
<li><a href="#">About Us</a></li>_x000D_
<li><a href="#">HTML</a></li>_x000D_
<li><a href="#">CSS</a></li>_x000D_
<li><a href="#">JavaScript</a></li>_x000D_
<li><a href="#">About Us</a></li>_x000D_
<li><a href="#">HTML</a></li>_x000D_
<li><a href="#">CSS</a></li>_x000D_
<li><a href="#">JavaScript</a></li>_x000D_
<li><a href="#">About Us</a></li>_x000D_
<li><a href="#">HTML</a></li>_x000D_
<li><a href="#">CSS</a></li>_x000D_
<li><a href="#">JavaScript</a></li>_x000D_
<li><a href="#">About Us</a></li>_x000D_
<li><a href="#">HTML</a></li>_x000D_
<li><a href="#">CSS</a></li>_x000D_
<li><a href="#">JavaScript</a></li>_x000D_
<li><a href="#">About Us</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>
_x000D_
Let's try this
public static void main(String args[]) {
Calendar cal = GregorianCalendar.getInstance();
Date today = cal.getTime();
DateFormat df7 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
String str7 = df7.format(today);
System.out.println("String in yyyy-MM-dd format is: " + str7);
} catch (Exception ex) {
ex.printStackTrace();
}
}
Or a utility function
public String convertDateToString(Date date, String format) {
String dateStr = null;
DateFormat df = new SimpleDateFormat(format);
try {
dateStr = df.format(date);
} catch (Exception ex) {
ex.printStackTrace();
}
return dateStr;
}
Removing the name from your binding will make it apply to all endpoints, and should produce the desired results. As so:
<services>
<service name="Service.IService">
<clear />
<endpoint binding="basicHttpBinding" contract="Service.IService" />
</service>
</services>
<bindings>
<basicHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647">
<readerQuotas maxDepth="32" maxStringContentLength="2147483647"
maxArrayLength="16348" maxBytesPerRead="4096" maxNameTableCharCount="16384" />
</binding>
</basicHttpBinding>
<webHttpBinding>
<binding maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" />
</webHttpBinding>
</bindings>
Also note that I removed the bindingConfiguration
attribute from the endpoint node. Otherwise you would get an exception.
This same solution was found here : Problem with large requests in WCF
here describes the process well. However, some of the characters that didn't fit in latin space are gone forever. UTF-8 is a SUPERSET of latin1. Not the reverse. Most will fit in single byte space, but any undefined ones will not (check a list of latin1 - not all 256 characters are defined, depending on mysql's latin1 definition)
As it turns out, my suspicions were right. The audience aud
claim in a JWT is meant to refer to the Resource Servers that should accept the token.
As this post simply puts it:
The audience of a token is the intended recipient of the token.
The audience value is a string -- typically, the base address of the resource being accessed, such as
https://contoso.com
.
The client_id
in OAuth refers to the client application that will be requesting resources from the Resource Server.
The Client app (e.g. your iOS app) will request a JWT from your Authentication Server. In doing so, it passes it's client_id
and client_secret
along with any user credentials that may be required. The Authorization Server validates the client using the client_id
and client_secret
and returns a JWT.
The JWT will contain an aud
claim that specifies which Resource Servers the JWT is valid for. If the aud
contains www.myfunwebapp.com
, but the client app tries to use the JWT on www.supersecretwebapp.com
, then access will be denied because that Resource Server will see that the JWT was not meant for it.
I don't think there is a good analogy that could highlight the two important characteristics as opposed to an array: 1. efficient to insert after current item and 2. inefficient to find a specific item by index.
There's nothing like that because normally people don't deal with very large number of items where you need to insert or locate specific items. For example, if you have a bag of sand, that would be hundreds of millions of grains, but you don't need to locate a specific grain, and the order of grains isn't important.
When you deal with smaller collections, you can locate the needed item visually, or, in case of books in a library, you will have a dictinary-like organization.
The closest analogy is having a blind man who goes through linked items like links of chain, beads on a necklace, train cars, etc. He may be looking for specific item or needing to insert an item after current one. It might be good to add that the blind man can go through them very quickly, e.g. one million beads per second, but can only feel one link at a time, and cannot see the whole chain or part of it.
Note that this analogy is similar to a double-linked list, I can't think of a similar analogy with singly linked one, because having a physical connection implies ability to backtrack.
What you want to do is separate the content of the table from the header of the table.
You want only the <th>
elements to be scrolled.
You can easily define this separation in HTML with the <tbody>
and the <thead>
elements.
Now the header and the body of the table are still connected to each other, they will still have the same width (and same scroll properties). Now to let them not 'work' as a table anymore you can set the display: block
. This way <thead>
and <tbody>
are separated.
table tbody, table thead
{
display: block;
}
Now you can set the scroll to the body of the table:
table tbody
{
overflow: auto;
height: 100px;
}
And last, because the <thead>
doesn't share the same width as the body anymore, you should set a static width to the header of the table:
th
{
width: 72px;
}
You should also set a static width for <td>
. This solves the issue of the unaligned columns.
td
{
width: 72px;
}
<tr>
element, that includes the header row:
<tr>
<th>head1</th>
<th>head2</th>
<th>head3</th>
<th>head4</th>
</tr>
I hope this is what you meant.
Addendum
If you would like to have more control over the column widths, have them to vary in width between each other, and course keep the header and body columns aligned, you can use the following example:
table th:nth-child(1), td:nth-child(1) { min-width: 50px; max-width: 50px; }
table th:nth-child(2), td:nth-child(2) { min-width: 100px; max-width: 100px; }
table th:nth-child(3), td:nth-child(3) { min-width: 150px; max-width: 150px; }
table th:nth-child(4), td:nth-child(4) { min-width: 200px; max-width: 200px; }
Actually the lombok is working (if you run the project even with the IDE red alerts, you will see the project will run without error), but the IDE is not recognizing all the resources generated by the lombok annotations. So you have to install the lombok plugin, that's all!
You will have to use some sort of network sniffer if you want to get at this sort of data and you're likely to run into the same problem (pulling out the relevant data from the overall network traffic) with those that you do now with Wireshark.
Have you tried the Generate Scripts
(Right click, tasks, generate scripts) option in SQL Management Studio? Does that produce what you mean by a "SQL File"?
Happened upon this post as I was looking for the same functionality this could possibly do what the guy wanted. Take the original date and replace the time part
DateTime dayOpen = DateTime.Parse(processDay.ToShortDateString() + " 05:00 AM");
The Windows shell (assuming you're using CMD.exe) uses %ProgramFiles% to point to the Program Files folder, no matter where it is. Since the default Windows file opener accounts for environment variables like this, if the program was well-written, it should support this.
Also, it could be worth using relative addresses. If the program you're using is installed correctly, it should already be in the Program Files folder, so you could just refer to the configuration file as .\config_file.txt if its in the same directory as the program, or ..\other_program\config_file.txt if its in a directory different than the other program. This would apply not only on Windows but on almost every modern operating system, and will work properly if you have the "Start In" box properly set, or you run it directly from its folder.
OK, I got the icons because I wrote in menu.xml android:showAsAction="ifRoom"
instead of app:showAsAction="ifRoom"
since i am using v7 library.
However the title is coming at center of extended toolbar. How to make it appear at the top?
I just wanted to add the fix I found for this issue. I'm not sure why this worked. I had the correct version of jstl (1.2) and also the correct version of servlet-api (2.5)
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
I also had the correct address in my page as suggested in this thread, which is
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
What fixed this issue for me was removing the scope tag from my xml file in the pom for my jstl 1.2 dependency. Again not sure why that fixed it but just in case someone is doing the spring with JPA and Hibernate tutorial on pluralsight and has their pom setup this way, try removing the scope tag and see if that fixes it. Like I said it worked for me.
UPDATE
Now it's available:
https://marketplace.visualstudio.com/items?itemName=donjayamanne.githistory
Until now it isn't supported, but you can follow the thread for it: GitHub
On redis.conf
line ~235
let's try to change config like this
- stop-writes-on-bgsave-error yes
+ stop-writes-on-bgsave-error no
a.update(b)
Will add keys and values from b to a, overwriting if there's already a value for a key.
Do a row div.
Like this:
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">_x000D_
<div class="grid">_x000D_
<div class="row">_x000D_
<div class="col-lg-3 col-md-3 col-sm-3 col-xs-12 bg-success">Under me should be a DIV</div>_x000D_
<div class="col-lg-6 col-md-6 col-sm-5 col-xs-12 bg-danger">Under me should be a DIV</div>_x000D_
</div>_x000D_
<div class="row">_x000D_
<div class="col-lg-3 col-md-3 col-sm-4 col-xs-12 bg-warning">I am the last DIV</div>_x000D_
</div>_x000D_
</div>
_x000D_
It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories.
It's abbreviated because C compilers at the dawn of time didn't support more than 8 characters in symbols.
I had similar issue before and in my case the file was in another machine so i have mapped network drive z to the folder location where my file is then i created a context in tomcat so in my web project i could access the HTML file via context
I'm using Ubuntu. I spent a whole morning fixing this, tried all different solutions, when I type go version, it's still there, really annoying... Finally this worked for me, hope this will help!
sudo apt-get remove golang-go
sudo apt-get remove --auto-remove golang-go
Use project root in terminal like this:-/Users/rajnish/Desktop/RankProjects/ProjectCloud
After that enter this command ./gradlew clean
It will work.
The constraint is generally applied recursively to every subtree. That is, the tree is only balanced if:
According to this, the next tree is balanced:
A
/ \
B C
/ / \
D E F
/
G
The next one is not balanced because the subtrees of C differ by 2 in their height:
A
/ \
B C <-- difference = 2
/ /
D E
/
G
That said, the specific constraint of the first point depends on the type of tree. The one listed above is the typical for AVL trees.
Red-black trees, for instance, impose a softer constraint.
If it instead returned Option[QueueObject]
you could use a construct like getObject.foreach { QueueManager.add }
. You can wrap it right inline with Option(getObject).foreach ...
because Option[QueueObject](null)
is None
.
You can also use below code which helps me:
select convert(numeric(10,2), column_name) as Total from TABLE_NAME
where Total
is alias of the field you want.
When your website is served by only one web server, for each client-server pair, a session object is created and remains in the memory of the web server. All the requests from the client go to this web server and update this session object. If some data needs to be stored in the session object over the period of interaction, it is stored in this session object and stays there as long as the session exists.
However, if your website is served by multiple web servers which sit behind a load balancer, the load balancer decides which actual (physical) web-server should each request go to. For example, if there are 3 web servers A, B and C behind the load balancer, it is possible that www.mywebsite.com/index.jsp is served from server A, www.mywebsite.com/login.jsp is served from server B and www.mywebsite.com/accoutdetails.php are served from server C.
Now, if the requests are being served from (physically) 3 different servers, each server has created a session object for you and because these session objects sit on three independent boxes, there's no direct way of one knowing what is there in the session object of the other. In order to synchronize between these server sessions, you may have to write/read the session data into a layer which is common to all - like a DB. Now writing and reading data to/from a db for this use-case may not be a good idea. Now, here comes the role of sticky-session.
If the load balancer is instructed to use sticky sessions, all of your interactions will happen with the same physical server, even though other servers are present. Thus, your session object will be the same throughout your entire interaction with this website.
To summarize, In case of Sticky Sessions, all your requests will be directed to the same physical web server while in case of a non-sticky loadbalancer may choose any webserver to serve your requests.
As an example, you may read about Amazon's Elastic Load Balancer and sticky sessions here : http://aws.typepad.com/aws/2010/04/new-elastic-load-balancing-feature-sticky-sessions.html
Your expression works if you add parentheses:
>>> y[(1 < x) & (x < 5)]
array(['o', 'o', 'a'],
dtype='|S1')
The easiest way to pass additional data is to add the data to the existing ViewData for the view as @Joel Martinez notes. However, if you don't want to pollute your ViewData, RenderPartial has a method that takes three arguments as well as the two-argument version you show. The third argument is a ViewDataDictionary. You can construct a separate ViewDataDictionary just for your partial containing just the extra data that you want to pass in.
change image captcha refresh
html:
<img id="captcha_img" src="http://localhost/captcha.php" />
jquery:
$("#captcha_img").click(function()
{
var capt_rand=Math.floor((Math.random() * 9999) + 1);
$("#captcha_img").attr("src","http://localhost/captcha.php?" + capt_rand);
});
Margin is usually used to create a space between the element itself and its surround.
for example I use it when I'm building a navbar to make it sticks to the edges of the screen and for no white gap.
I usually use when I've an element inside a border, <div>
or something similar, and I want to decrease its size but at the time I want to keep the distance or the margin between the other elements around it.
So briefly, it's situational; it depends on what you are trying to do.
I had exactly the same problem and found the solution eventually. My query runs like:
$result = mysqli_query($link,'SELECT * FROM clients WHERE ' . $sql_where . ' AND ' . $sql_where2 . ' ORDER BY acconame ASC ');
In order to display the sql command, all I had to do was to create a variable ($resultstring) with the exact same content as my query and then echo it, like this:<?php echo $resultstring = 'SELECT * FROM clients WHERE ' . $sql_where . ' AND ' . $sql_where2 . ' ORDER BY acconame ASC '; ?>
It works!
Mark F's solution is awesome but it's not supported by old browsers. Kennebec's solution is awesome and supported by old browsers but doesn't support regex.
So, if you're looking for a solution that splits your string only once, that is supported by old browsers and supports regex, here's my solution:
String.prototype.splitOnce = function(regex)_x000D_
{_x000D_
var match = this.match(regex);_x000D_
if(match)_x000D_
{_x000D_
var match_i = this.indexOf(match[0]);_x000D_
_x000D_
return [this.substring(0, match_i),_x000D_
this.substring(match_i + match[0].length)];_x000D_
}_x000D_
else_x000D_
{ return [this, ""]; }_x000D_
}_x000D_
_x000D_
var str = "something/////another thing///again";_x000D_
_x000D_
alert(str.splitOnce(/\/+/)[1]);
_x000D_
NO,but there are some other options to implement default value. There are some good blog posts on the subject, but here are some specific examples.
// Both parameters are optional, use empty string for default value
func Concat1(a string, b int) string {
if a == "" {
a = "default-a"
}
if b == 0 {
b = 5
}
return fmt.Sprintf("%s%d", a, b)
}
// a is required, b is optional.
// Only the first value in b_optional will be used.
func Concat2(a string, b_optional ...int) string {
b := 5
if len(b_optional) > 0 {
b = b_optional[0]
}
return fmt.Sprintf("%s%d", a, b)
}
// A declarative default value syntax
// Empty values will be replaced with defaults
type Parameters struct {
A string `default:"default-a"` // this only works with strings
B string // default is 5
}
func Concat3(prm Parameters) string {
typ := reflect.TypeOf(prm)
if prm.A == "" {
f, _ := typ.FieldByName("A")
prm.A = f.Tag.Get("default")
}
if prm.B == 0 {
prm.B = 5
}
return fmt.Sprintf("%s%d", prm.A, prm.B)
}
func Concat4(args ...interface{}) string {
a := "default-a"
b := 5
for _, arg := range args {
switch t := arg.(type) {
case string:
a = t
case int:
b = t
default:
panic("Unknown argument")
}
}
return fmt.Sprintf("%s%d", a, b)
}
That's a tricky one... Your storage letter must be capical. For example "C:\..."
Most of these solutions depend on there being an odd number of items so that you can take the middle item and center it. What if you have an even number of items that you still want to be evenly distributed? Here's a more general solution. This category will evenly distribute any number of items along either the vertical or horizontal axis.
Example usage to vertically distribute 4 labels within their superview:
[self.view addConstraints:
[NSLayoutConstraint constraintsForEvenDistributionOfItems:@[label1, label2, label3, label4]
relativeToCenterOfItem:self.view
vertically:YES]];
NSLayoutConstraint+EvenDistribution.h
@interface NSLayoutConstraint (EvenDistribution)
/**
* Returns constraints that will cause a set of views to be evenly distributed horizontally
* or vertically relative to the center of another item. This is used to maintain an even
* distribution of subviews even when the superview is resized.
*/
+ (NSArray *) constraintsForEvenDistributionOfItems:(NSArray *)views
relativeToCenterOfItem:(id)toView
vertically:(BOOL)vertically;
@end
NSLayoutConstraint+EvenDistribution.m
@implementation NSLayoutConstraint (EvenDistribution)
+(NSArray *)constraintsForEvenDistributionOfItems:(NSArray *)views
relativeToCenterOfItem:(id)toView vertically:(BOOL)vertically
{
NSMutableArray *constraints = [NSMutableArray new];
NSLayoutAttribute attr = vertically ? NSLayoutAttributeCenterY : NSLayoutAttributeCenterX;
for (NSUInteger i = 0; i < [views count]; i++) {
id view = views[i];
CGFloat multiplier = (2*i + 2) / (CGFloat)([views count] + 1);
NSLayoutConstraint *constraint = [NSLayoutConstraint constraintWithItem:view
attribute:attr
relatedBy:NSLayoutRelationEqual
toItem:toView
attribute:attr
multiplier:multiplier
constant:0];
[constraints addObject:constraint];
}
return constraints;
}
@end
Set both :focusable
and :focusableInTouchMode
to true and call requestFocus
. It does the trick.
return RedirectToAction("ProductImageManager","Index", new { id=id });
Here is an invalid parameters order, should be an action first
AND
ensure your routing table is correct
You can commit in the current branch, checkout to another branch, and finally cherry-pick that commit (in lieu of merge).
var fd = new FormData();
var file_data = $('input[type="file"]')[0].files; // for multiple files
for(var i = 0;i<file_data.length;i++){
fd.append("file_"+i, file_data[i]);
}
var other_data = $('form').serializeArray();
$.each(other_data,function(key,input){
fd.append(input.name,input.value);
});
$.ajax({
url: 'test.php',
data: fd,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
console.log(data);
}
});
Added a for
loop and changed .serialize()
to .serializeArray()
for object reference in a .each()
to append to the FormData
.
As an addition about the core of Mac OS X, Finder had not been written in Objective-C prior to Snow Leopard. In Snow Leopard it was written in Cocoa, Objective-C
Extension methods I commonly use to solve this problem:
public static string RemoveAfter(this string value, string character)
{
int index = value.IndexOf(character);
if (index > 0)
{
value = value.Substring(0, index);
}
return value;
}
public static string RemoveBefore(this string value, string character)
{
int index = value.IndexOf(character);
if (index > 0)
{
value = value.Substring(index + 1);
}
return value;
}
Merger two image png and jpg/png [Image Masking]
//URL or Local path
$src_url = '1.png';
$dest_url = '2.jpg';
$src = imagecreatefrompng($src_url);
$dest1 = imagecreatefromjpeg($dest_url);
//if you want to make same size
list($width, $height) = getimagesize($dest_url);
list($newWidth, $newHeight) = getimagesize($src_url);
$dest = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled($dest, $dest1, 0, 0, 0, 0, $newWidth, $newHeight, $width, $height);
list($src_w, $src_h) = getimagesize($src_url);
//merger with same size
$this->imagecopymerge_alpha($dest, $src, 0, 0, 0, 0, $src_w, $src_h, 100);
//show output on browser
header('Content-Type: image/png');
imagejpeg($dest);
function imagecopymerge_alpha($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $pct)
{
$cut = imagecreatetruecolor($src_w, $src_h);
imagecopy($cut, $dst_im, 0, 0, $dst_x, $dst_y, $src_w, $src_h);
imagecopy($cut, $src_im, 0, 0, $src_x, $src_y, $src_w, $src_h);
imagecopymerge($dst_im, $cut, $dst_x, $dst_y, 0, 0, $src_w, $src_h, $pct);
}
If you want to keep it simple go ahead and try this out.
$page_number = mysqli_escape_string($con, $_GET['page']);
$count_per_page = 20;
$next_offset = $page_number * $count_per_page;
$cat =mysqli_query($con, "SELECT * FROM categories LIMIT $count_per_page OFFSET $next_offset");
while ($row = mysqli_fetch_array($cat))
$count = $row[0];
The rest is up to you. If you have result comming from two tables i suggest you try a different approach.
You 100% have an error in an XML-file, but the XML verification does not show you the error. This is the reason why you need to check your XML files first!
Text nodes cannot have margins or any other style applied to them, so anything you need style applied to must be in an element. If you want some of the text inside of your element to be styled differently, wrap it in a span
or div
, for example.
If you're using scss for your styles you can use a mixin to help generate the code. Your styles will quickly get out of hand if you put all the properties every time.
This is a very simple example - really nothing more than a proof of concept, you can extend this with multiple properties and rules as needed.
@mixin mat-table-columns($columns)
{
.mat-column-
{
@each $colName, $props in $columns {
$width: map-get($props, 'width');
&#{$colName}
{
flex: $width;
min-width: $width;
@if map-has-key($props, 'color')
{
color: map-get($props, 'color');
}
}
}
}
}
Then in your component where your table is defined you just do this:
@include mat-table-columns((
orderid: (width: 6rem, color: gray),
date: (width: 9rem),
items: (width: 20rem)
));
This generates something like this:
.mat-column-orderid[_ngcontent-c15] {
flex: 6rem;
min-width: 6rem;
color: gray; }
.mat-column-date[_ngcontent-c15] {
flex: 9rem;
min-width: 9rem; }
In this version width
becomes flex: value; min-width: value
.
For your specific example you could add wrap: true
or something like that as a new parameter.
SciChart for Android is a relative newcomer, but brings extremely fast high performance real-time charting to the Android platform.
SciChart is a commercial control but available under royalty free distribution / per developer licensing. There is also free licensing available for educational use with some conditions.
Some useful links can be found below:
Disclosure: I am the tech lead on the SciChart project!
Let's go over the basics: "Accessor" and "Mutator" are just fancy names fot a getter and a setter. A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.
So first you need to set up a class with some variables to get/set:
public class IDCard
{
private String mName;
private String mFileName;
private int mID;
}
But oh no! If you instantiate this class the default values for these variables will be meaningless. B.T.W. "instantiate" is a fancy word for doing:
IDCard test = new IDCard();
So - let's set up a default constructor, this is the method being called when you "instantiate" a class.
public IDCard()
{
mName = "";
mFileName = "";
mID = -1;
}
But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:
public IDCard(String name, int ID, String filename)
{
mName = name;
mID = ID;
mFileName = filename;
}
Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:
public String getName()
{
return mName;
}
public void setName( String name )
{
mName = name;
}
Nice. Now we can access mName
. Add the rest of the accessors and mutators and you're now a certified Java newbie.
Good luck.
The modulus operator takes a division statement and returns whatever is left over from that calculation, the "remaining" data, so to speak, such as 13 / 5 = 2. Which means, there is 3 left over, or remaining from that calculation. Why? because 2 * 5 = 10. Thus, 13 - 10 = 3.
The modulus operator does all that calculation for you, 13 % 5 = 3.
Great then. Let's create a simple function that takes an array and prints our an ordered listview/list inside a div tag.
Step 1: Let's say you have an div with "contentSectionID" id.<div id="contentSectionID"></div>
Step 2: We then create our javascript function that returns a list component and takes in an array:
function createList(spacecrafts){
var listView=document.createElement('ol');
for(var i=0;i<spacecrafts.length;i++)
{
var listViewItem=document.createElement('li');
listViewItem.appendChild(document.createTextNode(spacecrafts[i]));
listView.appendChild(listViewItem);
}
return listView;
}
Step 3: Finally we select our div and create a listview in it:
document.getElementById("contentSectionID").appendChild(createList(myArr));
Another possibility is too many threads. We just ran into this error message when running a test harness against an app that uses a thread pool. We used
watch -n 5 -d "ps -eL <java_pid> | wc -l"
to watch the ongoing count of Linux native threads running within the given Java process ID. After this hit about 1,000 (for us--YMMV), we started getting the error message you mention.
Donning asbestos longjohns...
Yesterday my title with Packt Publications, Reactive Programming with JavaScript. It isn't really a Node.js-centric title; early chapters are intended to cover theory, and later code-heavy chapters cover practice. Because I didn't really think it would be appropriate to fail to give readers a webserver, Node.js seemed by far the obvious choice. The case was closed before it was even opened.
I could have given a very rosy view of my experience with Node.js. Instead I was honest about good points and bad points I encountered.
Let me include a few quotes that are relevant here:
Warning: Node.js and its ecosystem are hot--hot enough to burn you badly!
When I was a teacher’s assistant in math, one of the non-obvious suggestions I was told was not to tell a student that something was “easy.” The reason was somewhat obvious in retrospect: if you tell people something is easy, someone who doesn’t see a solution may end up feeling (even more) stupid, because not only do they not get how to solve the problem, but the problem they are too stupid to understand is an easy one!
There are gotchas that don’t just annoy people coming from Python / Django, which immediately reloads the source if you change anything. With Node.js, the default behavior is that if you make one change, the old version continues to be active until the end of time or until you manually stop and restart the server. This inappropriate behavior doesn’t just annoy Pythonistas; it also irritates native Node.js users who provide various workarounds. The StackOverflow question “Auto-reload of files in Node.js” has, at the time of this writing, over 200 upvotes and 19 answers; an edit directs the user to a nanny script, node-supervisor, with homepage at http://tinyurl.com/reactjs-node-supervisor. This problem affords new users with great opportunity to feel stupid because they thought they had fixed the problem, but the old, buggy behavior is completely unchanged. And it is easy to forget to bounce the server; I have done so multiple times. And the message I would like to give is, “No, you’re not stupid because this behavior of Node.js bit your back; it’s just that the designers of Node.js saw no reason to provide appropriate behavior here. Do try to cope with it, perhaps taking a little help from node-supervisor or another solution, but please don’t walk away feeling that you’re stupid. You’re not the one with the problem; the problem is in Node.js’s default behavior.”
This section, after some debate, was left in, precisely because I don't want to give an impression of “It’s easy.” I cut my hands repeatedly while getting things to work, and I don’t want to smooth over difficulties and set you up to believe that getting Node.js and its ecosystem to function well is a straightforward matter and if it’s not straightforward for you too, you don’t know what you’re doing. If you don’t run into obnoxious difficulties using Node.js, that’s wonderful. If you do, I would hope that you don’t walk away feeling, “I’m stupid—there must be something wrong with me.” You’re not stupid if you experience nasty surprises dealing with Node.js. It’s not you! It’s Node.js and its ecosystem!
The Appendix, which I did not really want after the rising crescendo in the last chapters and the conclusion, talks about what I was able to find in the ecosystem, and provided a workaround for moronic literalism:
Another database that seemed like a perfect fit, and may yet be redeemable, is a server-side implementation of the HTML5 key-value store. This approach has the cardinal advantage of an API that most good front-end developers understand well enough. For that matter, it’s also an API that most not-so-good front-end developers understand well enough. But with the node-localstorage package, while dictionary-syntax access is not offered (you want to use localStorage.setItem(key, value) or localStorage.getItem(key), not localStorage[key]), the full localStorage semantics are implemented, including a default 5MB quota—WHY? Do server-side JavaScript developers need to be protected from themselves?
For client-side database capabilities, a 5MB quota per website is really a generous and useful amount of breathing room to let developers work with it. You could set a much lower quota and still offer developers an immeasurable improvement over limping along with cookie management. A 5MB limit doesn’t lend itself very quickly to Big Data client-side processing, but there is a really quite generous allowance that resourceful developers can use to do a lot. But on the other hand, 5MB is not a particularly large portion of most disks purchased any time recently, meaning that if you and a website disagree about what is reasonable use of disk space, or some site is simply hoggish, it does not really cost you much and you are in no danger of a swamped hard drive unless your hard drive was already too full. Maybe we would be better off if the balance were a little less or a little more, but overall it’s a decent solution to address the intrinsic tension for a client-side context.
However, it might gently be pointed out that when you are the one writing code for your server, you don’t need any additional protection from making your database more than a tolerable 5MB in size. Most developers will neither need nor want tools acting as a nanny and protecting them from storing more than 5MB of server-side data. And the 5MB quota that is a golden balancing act on the client-side is rather a bit silly on a Node.js server. (And, for a database for multiple users such as is covered in this Appendix, it might be pointed out, slightly painfully, that that’s not 5MB per user account unless you create a separate database on disk for each user account; that’s 5MB shared between all user accounts together. That could get painful if you go viral!) The documentation states that the quota is customizable, but an email a week ago to the developer asking how to change the quota is unanswered, as was the StackOverflow question asking the same. The only answer I have been able to find is in the Github CoffeeScript source, where it is listed as an optional second integer argument to a constructor. So that’s easy enough, and you could specify a quota equal to a disk or partition size. But besides porting a feature that does not make sense, the tool’s author has failed completely to follow a very standard convention of interpreting 0 as meaning “unlimited” for a variable or function where an integer is to specify a maximum limit for some resource use. The best thing to do with this misfeature is probably to specify that the quota is Infinity:
if (typeof localStorage === 'undefined' || localStorage === null)
{
var LocalStorage = require('node-localstorage').LocalStorage;
localStorage = new LocalStorage(__dirname + '/localStorage',
Infinity);
}
Swapping two comments in order:
People needlessly shot themselves in the foot constantly using JavaScript as a whole, and part of JavaScript being made respectable language was a Douglas Crockford saying in essence, “JavaScript as a language has some really good parts and some really bad parts. Here are the good parts. Just forget that anything else is there.” Perhaps the hot Node.js ecosystem will grow its own “Douglas Crockford,” who will say, “The Node.js ecosystem is a coding Wild West, but there are some real gems to be found. Here’s a roadmap. Here are the areas to avoid at almost any cost. Here are the areas with some of the richest paydirt to be found in ANY language or environment.”
Perhaps someone else can take those words as a challenge, and follow Crockford’s lead and write up “the good parts” and / or “the better parts” for Node.js and its ecosystem. I’d buy a copy!
And given the degree of enthusiasm and sheer work-hours on all projects, it may be warranted in a year, or two, or three, to sharply temper any remarks about an immature ecosystem made at the time of this writing. It really may make sense in five years to say, “The 2015 Node.js ecosystem had several minefields. The 2020 Node.js ecosystem has multiple paradises.”
http://www.tohtml.com/ created syntax highlighted HTML code for lots of languages. It might be what you're looking for.
DO not use the below method to send the data using ajax call
data: '{"jewellerId":"' + filter + '","locale":"' + locale + '"}'
If by mistake user enter special character like single quote or double quote the ajax call fails due to wrong string.
Use below method to call the Web service without any issue
var parameter = {
jewellerId: filter,
locale : locale
};
data: JSON.stringify(parameter)
In above parameter is the name of javascript object and stringify it when passing it to the data attribute of the ajax call.
Here is a pure Java
solution actually:
public static long getFreePhysicalMemory()
{
com.sun.management.OperatingSystemMXBean bean =
(com.sun.management.OperatingSystemMXBean)
java.lang.management.ManagementFactory.getOperatingSystemMXBean();
return bean.getFreePhysicalMemorySize();
}
Here is how you set the cookie with JavaScript:
below code has been taken from https://www.w3schools.com/js/js_cookies.asp
function setCookie(cname, cvalue, exdays) { var d = new Date(); d.setTime(d.getTime() + (exdays*24*60*60*1000)); var expires = "expires="+ d.toUTCString(); document.cookie = cname + "=" + cvalue + ";" + expires + ";path=/"; }
now you can get the cookie with below function:
function getCookie(cname) { var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for(var i = 0; i <ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; }
And finally this is how you check the cookie:
function checkCookie() { var username = getCookie("username"); if (username != "") { alert("Welcome again " + username); } else { username = prompt("Please enter your name:", ""); if (username != "" && username != null) { setCookie("username", username, 365); } } }
If you want to delete the cookie just set the expires parameter to a passed date:
document.cookie = "username=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
The ng-if
directive removes the content from the page and ng-show/ng-hide
uses the CSS display
property to hide content.
This is useful in case you want to use :first-child
and :last-child
pseudo selectors to style.
Here you go with:
from b in _dbContext.Burden
join bl in _dbContext.BurdenLookups on
new { Organization_Type = b.Organization_Type_ID, Cost_Type = b.Cost_Type_ID } equals
new { Organization_Type = bl.Organization_Type_ID, Cost_Type = bl.Cost_Type_ID }
There is no standard C (or C++) way to enumerate files in a directory.
Under Windows you can use the FindFirstFile/FindNextFile functions to enumerate all entries in a directory. Under Linux/OSX use the opendir/readdir/closedir functions.
When I started learning Spring Security, then I overrided the method userDetailsService() as in below code snippet:
@Configuration
@EnableWebSecurity
public class ApplicationSecurityConfiguration extends WebSecurityConfigurerAdapter{
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/", "/index").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
@Override
@Bean
public UserDetailsService userDetailsService() {
List<UserDetails> users= new ArrayList<UserDetails>();
users.add(User.withDefaultPasswordEncoder().username("admin").password("nimda").roles("USER","ADMIN").build());
users.add(User.withDefaultPasswordEncoder().username("Spring").password("Security").roles("USER").build());
return new InMemoryUserDetailsManager(users);
}
}
So we can log in to the application using the above-mentioned creds. (e.g. admin/nimda)
Note: This we should not use in production.
Abstract Factory: A factory of factories; a factory that groups the individual but related/dependent factories together without specifying their concrete classes. Abstract Factory Example
Factory: It provides a way to delegate the instantiation logic to child classes. Factory Pattern Example
I believe that phrase should have been worded as follows:
bcrypt has salts built into the generated hashes to prevent rainbow table attacks.
The bcrypt
utility itself does not appear to maintain a list of salts. Rather, salts are generated randomly and appended to the output of the function so that they are remembered later on (according to the Java implementation of bcrypt
). Put another way, the "hash" generated by bcrypt
is not just the hash. Rather, it is the hash and the salt concatenated.
Based on the answers by @James and @Jyotirmoy Bhattacharya I came up with this solution:
zx <- replicate (5, rnorm(50))
zx_means <- (colMeans(zx, na.rm = TRUE))
boxplot(zx, horizontal = FALSE, outline = FALSE)
points(zx_means, pch = 22, col = "darkgrey", lwd = 7)
(See this post for more details)
If you would like to add points to horizontal box plots, please see this post.
My prompt includes:
rsync
-style user@host:pathname
for copy-paste goodnessExample:
To do this, add the following to your ~/.bashrc
:
#
# Set the prompt #
#
# Select git info displayed, see /usr/share/git/completion/git-prompt.sh for more
export GIT_PS1_SHOWDIRTYSTATE=1 # '*'=unstaged, '+'=staged
export GIT_PS1_SHOWSTASHSTATE=1 # '$'=stashed
export GIT_PS1_SHOWUNTRACKEDFILES=1 # '%'=untracked
export GIT_PS1_SHOWUPSTREAM="verbose" # 'u='=no difference, 'u+1'=ahead by 1 commit
export GIT_PS1_STATESEPARATOR='' # No space between branch and index status
export GIT_PS1_DESCRIBE_STYLE="describe" # detached HEAD style:
# contains relative to newer annotated tag (v1.6.3.2~35)
# branch relative to newer tag or branch (master~4)
# describe relative to older annotated tag (v1.6.3.1-13-gdd42c2f)
# default exactly eatching tag
# Check if we support colours
__colour_enabled() {
local -i colors=$(tput colors 2>/dev/null)
[[ $? -eq 0 ]] && [[ $colors -gt 2 ]]
}
unset __colourise_prompt && __colour_enabled && __colourise_prompt=1
__set_bash_prompt()
{
local exit="$?" # Save the exit status of the last command
# PS1 is made from $PreGitPS1 + <git-status> + $PostGitPS1
local PreGitPS1="${debian_chroot:+($debian_chroot)}"
local PostGitPS1=""
if [[ $__colourise_prompt ]]; then
export GIT_PS1_SHOWCOLORHINTS=1
# Wrap the colour codes between \[ and \], so that
# bash counts the correct number of characters for line wrapping:
local Red='\[\e[0;31m\]'; local BRed='\[\e[1;31m\]'
local Gre='\[\e[0;32m\]'; local BGre='\[\e[1;32m\]'
local Yel='\[\e[0;33m\]'; local BYel='\[\e[1;33m\]'
local Blu='\[\e[0;34m\]'; local BBlu='\[\e[1;34m\]'
local Mag='\[\e[0;35m\]'; local BMag='\[\e[1;35m\]'
local Cya='\[\e[0;36m\]'; local BCya='\[\e[1;36m\]'
local Whi='\[\e[0;37m\]'; local BWhi='\[\e[1;37m\]'
local None='\[\e[0m\]' # Return to default colour
# No username and bright colour if root
if [[ ${EUID} == 0 ]]; then
PreGitPS1+="$BRed\h "
else
PreGitPS1+="$Red\u@\h$None:"
fi
PreGitPS1+="$Blu\w$None"
else # No colour
# Sets prompt like: ravi@boxy:~/prj/sample_app
unset GIT_PS1_SHOWCOLORHINTS
PreGitPS1="${debian_chroot:+($debian_chroot)}\u@\h:\w"
fi
# Now build the part after git's status
# Highlight non-standard exit codes
if [[ $exit != 0 ]]; then
PostGitPS1="$Red[$exit]"
fi
# Change colour of prompt if root
if [[ ${EUID} == 0 ]]; then
PostGitPS1+="$BRed"'\$ '"$None"
else
PostGitPS1+="$Mag"'\$ '"$None"
fi
# Set PS1 from $PreGitPS1 + <git-status> + $PostGitPS1
__git_ps1 "$PreGitPS1" "$PostGitPS1" '(%s)'
# echo '$PS1='"$PS1" # debug
# defaut Linux Mint 17.2 user prompt:
# PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[01;34m\] \w\[\033[00m\] $(__git_ps1 "(%s)") \$ '
}
# This tells bash to reinterpret PS1 after every command, which we
# need because __git_ps1 will return different text and colors
PROMPT_COMMAND=__set_bash_prompt
I found it in this location:
C:\Users\amitsinha02\AppData\Local\Android\sdk\platform-tools
If you have a _Layout.cshtml view like this
<html>
<body>
@RenderBody()
@RenderSection("scripts", required: false)
</body>
</html>
then you can have an index.cshtml content view like this
@section scripts {
<script type="text/javascript">alert('hello');</script>
}
the required indicates whether or not the view using the layout page must have a scripts section
My understanding is that this is actually very simple:
So, to work through some of your examples:
function f(a,b,c) {
// Argument a is re-assigned to a new value.
// The object or primitive referenced by the original a is unchanged.
a = 3;
// Calling b.push changes its properties - it adds
// a new property b[b.length] with the value "foo".
// So the object referenced by b has been changed.
b.push("foo");
// The "first" property of argument c has been changed.
// So the object referenced by c has been changed (unless c is a primitive)
c.first = false;
}
var x = 4;
var y = ["eeny", "miny", "mo"];
var z = {first: true};
f(x,y,z);
console.log(x, y, z.first); // 4, ["eeny", "miny", "mo", "foo"], false
Example 2:
var a = ["1", "2", {foo:"bar"}];
var b = a[1]; // b is now "2";
var c = a[2]; // c now references {foo:"bar"}
a[1] = "4"; // a is now ["1", "4", {foo:"bar"}]; b still has the value
// it had at the time of assignment
a[2] = "5"; // a is now ["1", "4", "5"]; c still has the value
// it had at the time of assignment, i.e. a reference to
// the object {foo:"bar"}
console.log(b, c.foo); // "2" "bar"
It appears it's not possible to actually use the "value" of a select in any meaningful way as a normal HTML form element and also hook it up to Angular in the approved way with ng-options. As a compromise, I ended up having to put a hidden input alongside my select and have it track the same model as my select, like this (all very much simplified from real production code for brevity):
HTML:
<select ng-model="profile" ng-options="o.id as o.name for o in profiles" name="something_i_dont_care_about">
</select>
<input name="profile_id" type="text" style="margin-left:-10000px;" ng-model="profile"/>
Javascript:
App.controller('ConnectCtrl',function ConnectCtrl($scope) {
$scope.profiles = [{id:'xyz', name:'a profile'},{id:'abc', name:'another profile'}];
$scope.profile = -1;
}
Then, in my server-side code I just looked for params[:profile_id]
(this happened to be a Rails app, but the same principle applies anywhere). Because the hidden input tracks the same model as the select, they stay in sync automagically (no additional javascript necessary). This is the cool part of Angular. It almost makes up for what it does to the value attribute as a side effect.
Interestingly, I found this technique only worked with input tags that were not hidden (which is why I had to use the margin-left:-10000px; trick to move the input off the page). These two variations did not work:
<input name="profile_id" type="text" style="display:none;" ng-model="profile"/>
and
<input name="profile_id" type="hidden" ng-model="profile"/>
I feel like that must mean I'm missing something. It seems too weird for it to be a problem with Angular.
The Java 7 Files utility type is useful for working with files:
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.io.IOException;
import java.util.*;
public class WriteReadUtf8 {
public static void main(String[] args) throws IOException {
List<String> lines = Arrays.asList("These", "are", "lines");
Path textFile = Paths.get("foo.txt");
Files.write(textFile, lines, StandardCharsets.UTF_8);
List<String> read = Files.readAllLines(textFile, StandardCharsets.UTF_8);
System.out.println(lines.equals(read));
}
}
The Java 8 version allows you to omit the Charset argument - the methods default to UTF-8.
Easiest solution, works if you have already a tag or not, and removes it automatically so it wont keep adding equal tags, have fun
function changeURL(tag)
{
if(window.location.href.indexOf("?") > -1) {
if(window.location.href.indexOf("&"+tag) > -1){
var url = window.location.href.replace("&"+tag,"")+"&"+tag;
}
else
{
var url = window.location.href+"&"+tag;
}
}else{
if(window.location.href.indexOf("?"+tag) > -1){
var url = window.location.href.replace("?"+tag,"")+"?"+tag;
}
else
{
var url = window.location.href+"?"+tag;
}
}
window.location = url;
}
THEN
changeURL("i=updated");
Since this answer still gets voted up, I want to point out that you should almost never need to look in the header files. If you want to write reliable code, you're much better served by looking in the standard. A better question than "how is off_t
defined on my machine" is "how is off_t
defined by the standard?". Following the standard means that your code will work today and tomorrow, on any machine.
In this case, off_t
isn't defined by the C standard. It's part of the POSIX standard, which you can browse here.
Unfortunately, off_t
isn't very rigorously defined. All I could find to define it is on the page on sys/types.h
:
blkcnt_t
andoff_t
shall be signed integer types.
This means that you can't be sure how big it is. If you're using GNU C, you can use the instructions in the answer below to ensure that it's 64 bits. Or better, you can convert to a standards defined size before putting it on the wire. This is how projects like Google's Protocol Buffers work (although that is a C++ project).
So, I think "where do I find the definition in my header files" isn't the best question. But, for completeness here's the answer:
On my machine (and most machines using glibc) you'll find the definition in bits/types.h
(as a comment says at the top, never directly include this file), but it's obscured a bit in a bunch of macros. An alternative to trying to unravel them is to look at the preprocessor output:
#include <stdio.h>
#include <sys/types.h>
int main(void) {
off_t blah;
return 0;
}
And then:
$ gcc -E sizes.c | grep __off_t
typedef long int __off_t;
....
However, if you want to know the size of something, you can always use the sizeof()
operator.
Edit: Just saw the part of your question about the __
. This answer has a good discussion. The key point is that names starting with __
are reserved for the implementation (so you shouldn't start your own definitions with __
).
Update
Flutter now has a Visibility widget. To implement your own solution start with the below code.
Make a widget yourself.
show/hide
class ShowWhen extends StatelessWidget {
final Widget child;
final bool condition;
ShowWhen({this.child, this.condition});
@override
Widget build(BuildContext context) {
return Opacity(opacity: this.condition ? 1.0 : 0.0, child: this.child);
}
}
show/remove
class RenderWhen extends StatelessWidget {
final Widget child;
final bool condition;
RenderWhen({this.child, this.show});
@override
Widget build(BuildContext context) {
return this.condition ? this.child : Container();
}
}
By the way, does any one have a better name for the widgets above?
More Reads
Python 2 or Python 3 API reference:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
The file argument must be an object with a
write(string)
method; if it is not present orNone
,sys.stdout
will be used. Since printed arguments are converted to text strings,print()
cannot be used with binary mode file objects. For these, usefile.write(...)
instead.
Since file object normally contains write()
method, all you need to do is to pass a file object into its argument.
with open('file.txt', 'w') as f:
print('hello world', file=f)
with open('file.txt', 'a') as f:
print('hello world', file=f)
I was moving data directory on a cloned server and having troubles to login as postgres. Resetting postgres password like this worked for me.
root# su postgres
postgres$ psql -U postgres
psql (9.3.6)
Type "help" for help.
postgres=#\password
Enter new password:
Enter it again:
postgres=#
A bit late for probable answer, might help new people. In case you have multiple instances of database:
mongoimport --host <host_name>:<host_port> --db <database_name> --collection <collection_name> --file <path_to_dump_file> -u <my_user> -p <my_pass>
Assuming credentials needed, otherwise remove this option.
Here is a simple long-polling example in PHP by Erik Dubbelboer using the Content-type: multipart/x-mixed-replace
header:
<?
header('Content-type: multipart/x-mixed-replace; boundary=endofsection');
// Keep in mind that the empty line is important to separate the headers
// from the content.
echo 'Content-type: text/plain
After 5 seconds this will go away and a cat will appear...
--endofsection
';
flush(); // Don't forget to flush the content to the browser.
sleep(5);
echo 'Content-type: image/jpg
';
$stream = fopen('cat.jpg', 'rb');
fpassthru($stream);
fclose($stream);
echo '
--endofsection
';
And here is a demo:
Recently I faced a similar problem. I was using the sublime editor. it's not an issue with the code but with the editor.
Below change in the preference settings worked for me.
Sublime Text menu -> Preferences -> Settings: Syntax-Specific:
{
"tab_size": 4,
"translate_tabs_to_spaces": true
}
a much more handy solution for your reference, it works perfect in all of my projects:
change your first line from
.navbar.navbar-fixed-top
to
.navbar.navbar-default.navbar-static-top
Math.Ceiling
always rounds up (towards the ceiling)
Math.Floor
always rounds down (towards to floor)
what you are after is simply
Math.Round
which rounds as per this post
Angular will automatically update a component when it detects a variable change .
So all you have to do for it to "refresh" is ensure that the header has a reference to the new data. This could be via a subscription within header.component.ts
or via an @Input
variable...
an example...
main.html
<app-header [header-data]="headerData"></app-header>
main.component.ts
public headerData:int = 0;
ngOnInit(){
setInterval(()=>{this.headerData++;}, 250);
}
header.html
<p>{{data}}</p>
header.ts
@Input('header-data') data;
In the above example, the header will recieve the new data every 250ms and thus update the component.
For more information about Angular's lifecycle hooks, see: https://angular.io/guide/lifecycle-hooks
You can always use the ( <condition> ? <value if true> : <value if false> )
syntax (it's called the ternary operator - thanks to Mark for remining me :) ).
If <condition>
is true, the statement would be evaluated as <value if true>
. If not, it would be evaluated as <value if false>
For instance:
$fourteen = 14;
$twelve = 12;
echo "Fourteen is ".($fourteen > $twelve ? "more than" : "not more than")." twelve";
This is the same as:
$fourteen = 14;
$twelve = 12;
if($fourteen > 12) {
echo "Fourteen is more than twelve";
}else{
echo "Fourteen is not more than twelve";
}
I solved this by going to the App Store and installing Xcode.
It was a pretty large 11GB install, so this is probably overkill. But, as a last resort, it seems to have solve my issues. In the middle of the installation (well around 10GB), Mac OS told me there was an update to Command Line Tools for Xcode. Performing this installation won't fix anything until Xcode is fully installed.
Once the install is done, it should start working (after you accept the license agreement).