Further to Karl Anderson solution, you could put your parameters into session information and then clear them after response.TransmitFile(Server.MapPath( Session(currentSessionItemName)));
.
See MSDN page HttpSessionState.Add Method (String, Object) for more information on sessions.
Have you looked at the samples provided with EPPlus?
This one shows you how to create a file http://epplus.codeplex.com/wikipage?title=ContentSheetExample
This one shows you how to use it to stream back a file http://epplus.codeplex.com/wikipage?title=WebapplicationExample
This is how we use the package to generate a file.
var newFile = new FileInfo(ExportFileName);
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{
// do work here
xlPackage.Save();
}
Just a slight addition to the above solution if you are having problem with downloaded file's name...
Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");
This will return the exact file name even if it contains spaces or other characters.
I think the reason may be that mock object libraries typically create mocks by dynamically creating classes at runtime (using cglib). This means they either implement an interface at runtime (that's what EasyMock does if I'm not mistaken), or they inherit from the class to mock (that's what Mockito does if I'm not mistaken). Both approaches do not work for static members, since you can't override them using inheritance.
The only way to mock statics is to modify a class' byte code at runtime, which I suppose is a little more involved than inheritance.
That's my guess at it, for what it's worth...
An "if" is not a loop. Just use the break inside the "if" and it will break out of the "while".
If you ever need to use genuine nested loops, Java has the concept of a labeled break. You can put a label before a loop, and then use the name of the label is the argument to break. It will break outside of the labeled loop.
For Python 3.6, you can use the f-strings new feature to convert to string and it's faster compared to str() function. It is used like this:
age = 45
strAge = f'{age}'
Python provides the str() function for that reason.
digit = 10
print(type(digit)) # Will show <class 'int'>
convertedDigit = str(digit)
print(type(convertedDigit)) # Will show <class 'str'>
For a more detailed answer, you can check this article: Converting Python Int to String and Python String to Int
The only thing that worked for me:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().anyRequest().permitAll();
}
and
security.ignored=/**
Could be that the properties part is redundant or can be done in code, but had no time to experiment. Anyway is temporary.
Sorry to tell you screencap
just a simple command, only accept few arguments, but none of them can save time for you, here is the -h
help output.
$ adb shell screencap -h
usage: screencap [-hp] [-d display-id] [FILENAME]
-h: this message
-p: save the file as a png.
-d: specify the display id to capture, default 0.
If FILENAME ends with .png it will be saved as a png.
If FILENAME is not given, the results will be printed to stdout.
Besides the command screencap
, there is another command screenshot
, I don't know why screenshot
was removed from Android 5.0
, but it's avaiable below Android 4.4
, you can check the source from here. I didn't make my comparison which is faster between these two commands, but you can give your try in your real environment and make the final decision.
From documentation:
You cannot insert the values
TRUE
andFALSE
into a database column. You cannot select or fetch column values into aBOOLEAN
variable. Functions called from aSQL
query cannot take anyBOOLEAN
parameters. Neither can built-inSQL
functions such asTO_CHAR
; to representBOOLEAN
values in output, you must useIF-THEN
orCASE
constructs to translateBOOLEAN
values into some other type, such as0
or1
,'Y'
or'N'
,'true'
or'false'
, and so on.
You will need to make a wrapper function that takes an SQL
datatype and use it instead.
The specification for 'mailto' body says:
The body of a message is simply lines of US-ASCII characters. The only two limitations on the body are as follows:
- CR and LF MUST only occur together as CRLF; they MUST NOT appear independently in the body.
- Lines of characters in the body MUST be limited to 998 characters, and SHOULD be limited to 78 characters, excluding the CRLF.
https://tools.ietf.org/html/rfc5322#section-2.3
Generally nowadays most email clients are good at autolinking, but not all do, due to security concerns. You can likely find some work-arounds, but it won't necessarily work universally.
I've recently developed the Release Candidate Maven plugin that solves this exact problem so that you don't have to resort to any hacky shell scripts and parsing the output of the maven-help-plugin
.
For example, to print the version of your Maven project to a terminal, run:
mvn com.smartcodeltd:release-candidate-maven-plugin:LATEST:version
which gives output similar to maven-help-plugin
:
[INFO] Detected version: '1.0.0-SNAPSHOT'
1.0.0-SNAPSHOT
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
However, you can also specify an arbitrary output format (so that the version could be picked up from the log by a CI server such as TeamCity):
mvn com.smartcodeltd:release-candidate-maven-plugin:LATEST:version \
-DoutputTemplate="##teamcity[setParameter name='env.PROJECT_VERSION' value='{{ version }}']"
Which results in:
[INFO] Detected version: '1.0.0-SNAPSHOT'
##teamcity[setParameter name='env.PROJECT_VERSION' value='1.0.0-SNAPSHOT']
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
To save the output to a file (so that a CI server such as Jenkins could use it):
mvn com.smartcodeltd:release-candidate-maven-plugin:LATEST:version \
-DoutputTemplate="PROJECT_VERSION={{ version }}" \
-DoutputUri="file://\${project.basedir}/version.properties"
The resulting version.properties
file will look as follows:
PROJECT_VERSION=1.0.0-SNAPSHOT
On top of all the above, Release Candidate also allows you to set the version of your project (which is something you'd probably do on your CI server) based on the API version you've defined in your POM.
If you'd like to see an example of Release Candidate being used as part of the Maven lifecycle, have a look at the pom.xml
of my other open-source project - Build Monitor for Jenkins.
As specified by the top answer, I used the following in the code behind the button control.
Private Sub btnClose_Click()
Unload Me
End Sub
In doing so, it will not attempt to unload a control, but rather will unload the user form where the button control resides. The "Me" keyword refers to the user form object even when called from a control on the user form. If you are getting errors with this technique, there are a couple of possible reasons.
You could be entering the code in the wrong place (such as a separate module)
You might be using an older version of Office. I'm using Office 2013. I've noticed that VBA changes over time.
From my experience, the use of the the DoCmd.... method is more specific to the macro features in MS Access, but not commonly used in Excel VBA.
Under normal (out of the box) conditions, the code above should work just fine.
You can access component one's method from component two..
componentOne
ngOnInit() {}
public testCall(){
alert("I am here..");
}
componentTwo
import { oneComponent } from '../one.component';
@Component({
providers:[oneComponent ],
selector: 'app-two',
templateUrl: ...
}
constructor(private comp: oneComponent ) { }
public callMe(): void {
this.comp.testCall();
}
componentTwo html file
<button (click)="callMe()">click</button>
const mapObject = (obj = {}, mapper) =>
Object.entries(obj).reduce(
(acc, [key, val]) => ({ ...acc, [key]: mapper(val) }),
{},
);
Here are few examples from PostgreSQL-9.5
Display list:
\df+
\dy+
Display Definition:
postgres=# \sf
function name is required
postgres=# \sf pg_reload_conf()
CREATE OR REPLACE FUNCTION pg_catalog.pg_reload_conf()
RETURNS boolean
LANGUAGE internal
STRICT
AS $function$pg_reload_conf$function$
postgres=# \sf pg_encoding_to_char
CREATE OR REPLACE FUNCTION pg_catalog.pg_encoding_to_char(integer)
RETURNS name
LANGUAGE internal
STABLE STRICT
AS $function$PG_encoding_to_char$function$
Use ffmpeg + ffserver. It works!!! You can get a config file for ffserver from ffmpeg.org and accordingly set the values.
I believe telnet 74.255.12.25 8089
. Why don't u try both
see docs: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.insert.html
using loc = 0 will insert at the beginning
df.insert(loc, column, value)
df = pd.DataFrame({'B': [1, 2, 3], 'C': [4, 5, 6]})
df
Out:
B C
0 1 4
1 2 5
2 3 6
idx = 0
new_col = [7, 8, 9] # can be a list, a Series, an array or a scalar
df.insert(loc=idx, column='A', value=new_col)
df
Out:
A B C
0 7 1 4
1 8 2 5
2 9 3 6
In order to get the image view with the proper size and in the center, you should use the following approach:
let width = 120 // choose the image width
let height = 20 // choose the image height
let titleView = UIView(frame: CGRect(x: 0, y: 0, width: view.bounds.width, height: 44)) //44 is the standard size of the top bar
let imageView = UIImageView(frame: CGRect(x: (view.bounds.width - width)/2, y: (44 - height)/2, width: width, height: height))
imageView.contentMode = .scaleAspectFit //choose other if it makes sense
imageView.image = UIImage(named: "your_image_name")
titleView.addSubview(imageView)
navigationItem.titleView = titleView
$(document).ready(function(){
$('.lbOn').click();
});
Suppose this would work too.
pip install worked for me, and it failed with a permission issue, which was resolved when I used
sudo pip install pandas
I see that the best sudo workaround is from /tmp: Is it acceptable and safe to run pip install under sudo?
In Python 3.2+, you can use int.to_bytes:
>>> n = 1245427
>>> n.to_bytes((n.bit_length() + 7) // 8, 'big') or b'\0'
b'\x13\x00\xf3'
>>> (1245427).to_bytes(3, byteorder='big')
b'\x13\x00\xf3'
To connect Excel to Access using VBA is very useful I use it in my profession everyday. The connection string I use is according to the program found in the link below. The program can be automated to do multiple connections or tasks in on shot but the basic connection code looks the same. Good luck!
you have to declare current date into variables like this
$(function() {
var date = new Date();
var currentMonth = date.getMonth();
var currentDate = date.getDate();
var currentYear = date.getFullYear();
$('#datepicker').datepicker({
minDate: new Date(currentYear, currentMonth, currentDate)
});
})
In Entity Framework Core (EF.core
) you can use .ThenInclude
for including next levels.
var blogs = context.Blogs
.Include(blog => blog.Posts)
.ThenInclude(post => post.Author)
.ToList();
More information: https://docs.microsoft.com/en-us/ef/core/querying/related-data
Note:
Say you need multiple ThenInclude()
on blog.Posts
, just repeat the Include(blog => blog.Posts)
and do another ThenInclude(post => post.Other)
.
var blogs = context.Blogs
.Include(blog => blog.Posts)
.ThenInclude(post => post.Author)
.Include(blog => blog.Posts)
.ThenInclude(post => post.Other)
.ToList();
You want to become familiar with parseInt()
and toString()
.
And useful in your toolkit will be to look at a variable to find out what type it is—typeof
:
<script type="text/javascript">
/**
* print out the value and the type of the variable passed in
*/
function printWithType(val) {
document.write('<pre>');
document.write(val);
document.write(' ');
document.writeln(typeof val);
document.write('</pre>');
}
var a = "1", b = "2", c = "3", result;
// Step (1) Concatenate "1", "2", "3" into "123"
// - concatenation operator is just "+", as long
// as all the items are strings, this works
result = a + b + c;
printWithType(result); //123 string
// - If they were not strings you could do
result = a.toString() + b.toString() + c.toString();
printWithType(result); // 123 string
// Step (2) Convert "123" into 123
result = parseInt(result,10);
printWithType(result); // 123 number
// Step (3) Add 123 + 100 = 223
result = result + 100;
printWithType(result); // 223 number
// Step (4) Convert 223 into "223"
result = result.toString(); //
printWithType(result); // 223 string
// If you concatenate a number with a
// blank string, you get a string
result = result + "";
printWithType(result); //223 string
</script>
I had teh same problem and spend many hours find diferent solutions, and now I join all the comments in this post.I hope it, will be helpfull, my answer was correctly tested on Internet Explorer 11, Chrome and FireFox.
HTML :
<a href="#" class="btn btn-default" file-name="'fileName.extension'" ng-click="getFile()" file-download="myBlobObject"><i class="fa fa-file-excel-o"></i></a>
DIRECTIVE :
directive('fileDownload',function(){
return{
restrict:'A',
scope:{
fileDownload:'=',
fileName:'=',
},
link:function(scope,elem,atrs){
scope.$watch('fileDownload',function(newValue, oldValue){
if(newValue!=undefined && newValue!=null){
console.debug('Downloading a new file');
var isFirefox = typeof InstallTrigger !== 'undefined';
var isSafari = Object.prototype.toString.call(window.HTMLElement).indexOf('Constructor') > 0;
var isIE = /*@cc_on!@*/false || !!document.documentMode;
var isEdge = !isIE && !!window.StyleMedia;
var isChrome = !!window.chrome && !!window.chrome.webstore;
var isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;
var isBlink = (isChrome || isOpera) && !!window.CSS;
if(isFirefox || isIE || isChrome){
if(isChrome){
console.log('Manage Google Chrome download');
var url = window.URL || window.webkitURL;
var fileURL = url.createObjectURL(scope.fileDownload);
var downloadLink = angular.element('<a></a>');//create a new <a> tag element
downloadLink.attr('href',fileURL);
downloadLink.attr('download',scope.fileName);
downloadLink.attr('target','_self');
downloadLink[0].click();//call click function
url.revokeObjectURL(fileURL);//revoke the object from URL
}
if(isIE){
console.log('Manage IE download>10');
window.navigator.msSaveOrOpenBlob(scope.fileDownload,scope.fileName);
}
if(isFirefox){
console.log('Manage Mozilla Firefox download');
var url = window.URL || window.webkitURL;
var fileURL = url.createObjectURL(scope.fileDownload);
var a=elem[0];//recover the <a> tag from directive
a.href=fileURL;
a.download=scope.fileName;
a.target='_self';
a.click();//we call click function
}
}else{
alert('SORRY YOUR BROWSER IS NOT COMPATIBLE');
}
}
});
}
}
})
IN CONTROLLER:
$scope.myBlobObject=undefined;
$scope.getFile=function(){
console.log('download started, you can show a wating animation');
serviceAsPromise.getStream({param1:'data1',param1:'data2', ...})
.then(function(data){//is important that the data was returned as Aray Buffer
console.log('Stream download complete, stop animation!');
$scope.myBlobObject=new Blob([data],{ type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
},function(fail){
console.log('Download Error, stop animation and show error message');
$scope.myBlobObject=[];
});
};
IN SERVICE:
function getStream(params){
console.log("RUNNING");
var deferred = $q.defer();
$http({
url:'../downloadURL/',
method:"PUT",//you can use also GET or POST
data:params,
headers:{'Content-type': 'application/json'},
responseType : 'arraybuffer',//THIS IS IMPORTANT
})
.success(function (data) {
console.debug("SUCCESS");
deferred.resolve(data);
}).error(function (data) {
console.error("ERROR");
deferred.reject(data);
});
return deferred.promise;
};
BACKEND(on SPRING):
@RequestMapping(value = "/downloadURL/", method = RequestMethod.PUT)
public void downloadExcel(HttpServletResponse response,
@RequestBody Map<String,String> spParams
) throws IOException {
OutputStream outStream=null;
outStream = response.getOutputStream();//is important manage the exceptions here
ObjectThatWritesOnOutputStream myWriter= new ObjectThatWritesOnOutputStream();// note that this object doesn exist on JAVA,
ObjectThatWritesOnOutputStream.write(outStream);//you can configure more things here
outStream.flush();
return;
}
VARCHAR means that it's a variable-length character, so it's only going to take as much space as is necessary. But if you knew something about the underlying structure, it may make sense to restrict VARCHAR to some maximum amount.
For instance, if you were storing comments from the user, you may limit the comment field to only 4000 characters; if so, it doesn't really make any sense to make the sql table have a field that's larger than VARCHAR(4000).
I was able to piece together a number of different sources for this answer:
...
<repository>
<id>atlassian</id>
<name>Atlassian Repo</name>
<url>https://maven.atlassian.com/content/repositories/atlassian-public</url>
</repository>
...
<dependency>
<groupId>com.atlassian.maven.plugins</groupId>
<artifactId>maven-upload-plugin</artifactId>
<version>1.1</version>
</dependency>
...
<plugin>
<groupId>com.atlassian.maven.plugins</groupId>
<artifactId>maven-upload-plugin</artifactId>
<version>1.1</version>
<configuration>
<serverId>jira-repo</serverId>
<resourceSrc>
${project.build.directory}/${project.build.finalName}.${project.packaging}
</resourceSrc>
<resourceDest>opt/jira/webapps</resourceDest> <!-- note: no leading slash -->
<url>scp://root@jira</url>
</configuration>
</plugin>
...
From ~/.m2/settings.xml
:
...
<servers>
<server>
<id>jira-repo</id>
<username>myusername</username>
<password>mypassword</password>
</server>
</servers>
...
Then run the command: (the -X is for debug)
mvn -X upload:upload
Use FileUtils from Apache commons.
listFiles
public static Collection<File> listFiles(File directory,
String[] extensions,
boolean recursive)
Finds files within a given directory (and optionally its subdirectories) which match an array of extensions.
Parameters:
directory - the directory to search in
extensions - an array of extensions, ex. {"java","xml"}. If this parameter is null, all files are returned.
recursive - if true all subdirectories are searched as well
Returns:
an collection of java.io.File with the matching files
Since the Logical Address space is 32-bit long that means program size is 2^32 bytes i.e. 4GB. Now we have the page size of 4KB i.e.2^12 bytes.Thus the number of pages in program are 2^20.(no. of pages in program = program size/page size).Now the size of page table entry is 4 byte hence the size of page table is 2^20*4 = 4MB(size of page table = no. of pages in program * page table entry size). Hence 4MB space is required in Memory to store the page table.
public static void showCustomAlertDialog(Context context, String name,
String id, String desc, String fromDate, String toDate,
String resions) {
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
context);
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.dialog, null);
alertDialogBuilder.setView(view);
alertDialogBuilder.setCancelable(false);
final AlertDialog dialog = alertDialogBuilder.create();
dialog.show();
txt_empId = (TextView) view.findViewById(R.id.txt_dialog_empcode);
txt_empName = (TextView) view.findViewById(R.id.txt_dialog_empname);
txt_desc = (TextView) view.findViewById(R.id.txt_dialog_desc);
txt_startDate = (TextView) view.findViewById(R.id.txt_dialog_startDate);
txt_resions = (TextView) view.findViewById(R.id.txt_dialog_endDate);
txt_empId.setTypeface(Utils.setLightTypeface(context));
txt_empName.setTypeface(Utils.setLightTypeface(context));
txt_desc.setTypeface(Utils.setLightTypeface(context));
txt_startDate.setTypeface(Utils.setLightTypeface(context));
txt_resions.setTypeface(Utils.setLightTypeface(context));
txt_empId.setText(id);
txt_empName.setText(name);
txt_desc.setText(desc);
txt_startDate.setText(fromDate + "\t to \t" + toDate);
txt_resions.setText(resions);
btn_accept = (Button) view.findViewById(R.id.btn_dialog_accept);
btn_reject = (Button) view.findViewById(R.id.btn_dialog_reject);
btn_cancel = (Button) view.findViewById(R.id.btn_dialog_cancel);
btn_accept.setTypeface(Utils.setBoldTypeface(context));
btn_reject.setTypeface(Utils.setBoldTypeface(context));
btn_cancel.setTypeface(Utils.setBoldTypeface(context));
btn_cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
}
Functions from .py file (can (of course) be in different directory) can be simply imported by writing directories first and then the file name without .py extension:
from directory_name.file_name import function_name
And later be used: function_name()
If you have properties specific to the view, and not related to the DB/Service/Data store, it is a good practice to use ViewModels. Say, you want to leave a checkbox selected based on a DB field (or two) but the DB field itself isn't a boolean. While it is possible to create these properties in the Model itself and keep it hidden from the binding to data, you may not want to clutter the Model depending on the amount of such fields and transactions.
If there are too few view-specific data and/or transformations, you can use the Model itself
You can use each()
$('#id-submit').click(function () {
$(":input").each(function(){
this.value = this.value.toUpperCase();
});
});
My way of testing this is quite simple, within each abstractUnitTest.java
. I simply create a class in the abstractUnitTest.java that extend the abstract class. And test it that way.
Look at the link, there is an answer for your question.
Sending Email in Android using JavaMail API without using the default/built-in app
They have wrapped most stuff need to solve your problem, one of the tests looks like this:
String filename = CSSURLEmbedderTest.class.getResource("folder.png").getPath().replace("%20", " ");
String code = "background: url(folder.png);";
StringWriter writer = new StringWriter();
embedder = new CSSURLEmbedder(new StringReader(code), true);
embedder.embedImages(writer, filename.substring(0, filename.lastIndexOf("/")+1));
String result = writer.toString();
assertEquals("background: url(" + folderDataURI + ");", result);
\n
is used for Unix systems (including Linux, and OSX).
\r\n
is mainly used on Windows.
\r
is used on really old Macs.
PHP_EOL
constant is used instead of these characters for portability between platforms.
I had the same problem. I changed the localhost parameter in the mysqli object to '127.0.0.1' instead of writing 'localhost'. It worked; I’m not sure how or why.
$db_connection = new mysqli("127.0.0.1","root","","db_name");
Hope it helps.
@larowlan great sample code. With the new GitHub API V3, the curl statement needs to be updated. Also, the login is no longer required:
curl https://api.github.com/repos/$2/$3 2> /dev/null | grep size | tr -dc '[:digit:]'
For example:
curl https://api.github.com/repos/dotnet/roslyn 2> /dev/null | grep size | tr -dc '[:digit:]'
returns 931668
(in KB), which is almost a GB.
I used Andrew's script but added a piece before the printPage() function is called. The iframe needs focus, otherwise it will still print the parent frame in IE.
function printIframe(id)
{
var iframe = document.frames ? document.frames[id] : document.getElementById(id);
var ifWin = iframe.contentWindow || iframe;
iframe.focus();
ifWin.printPage();
return false;
}
Don't thank me though, it was Andrew who wrote this. I just made a tweak =P
Delete entire node "Element" (inside "Connections" tree) from XML file, used by version 18 or higher.
C:\Users\%username%\AppData\Roaming\Microsoft\SQL Server Management Studio\18.0\UserSettings.xml
I came across the same problem, but I wasn't enamoured by any of the solutions I found here. So, I wrote one that iterates over the characters of the string using a matcher to find and replace the escape sequences. This solution assumes properly formatted input. That is, it happily skips over nonsensical escapes, and it decodes Unicode escapes for line feed and carriage return (which otherwise cannot appear in a character literal or a string literal, due to the definition of such literals and the order of translation phases for Java source). Apologies, the code is a bit packed for brevity.
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Decoder {
// The encoded character of each character escape.
// This array functions as the keys of a sorted map, from encoded characters to decoded characters.
static final char[] ENCODED_ESCAPES = { '\"', '\'', '\\', 'b', 'f', 'n', 'r', 't' };
// The decoded character of each character escape.
// This array functions as the values of a sorted map, from encoded characters to decoded characters.
static final char[] DECODED_ESCAPES = { '\"', '\'', '\\', '\b', '\f', '\n', '\r', '\t' };
// A pattern that matches an escape.
// What follows the escape indicator is captured by group 1=character 2=octal 3=Unicode.
static final Pattern PATTERN = Pattern.compile("\\\\(?:(b|t|n|f|r|\\\"|\\\'|\\\\)|((?:[0-3]?[0-7])?[0-7])|u+(\\p{XDigit}{4}))");
public static CharSequence decodeString(CharSequence encodedString) {
Matcher matcher = PATTERN.matcher(encodedString);
StringBuffer decodedString = new StringBuffer();
// Find each escape of the encoded string in succession.
while (matcher.find()) {
char ch;
if (matcher.start(1) >= 0) {
// Decode a character escape.
ch = DECODED_ESCAPES[Arrays.binarySearch(ENCODED_ESCAPES, matcher.group(1).charAt(0))];
} else if (matcher.start(2) >= 0) {
// Decode an octal escape.
ch = (char)(Integer.parseInt(matcher.group(2), 8));
} else /* if (matcher.start(3) >= 0) */ {
// Decode a Unicode escape.
ch = (char)(Integer.parseInt(matcher.group(3), 16));
}
// Replace the escape with the decoded character.
matcher.appendReplacement(decodedString, Matcher.quoteReplacement(String.valueOf(ch)));
}
// Append the remainder of the encoded string to the decoded string.
// The remainder is the longest suffix of the encoded string such that the suffix contains no escapes.
matcher.appendTail(decodedString);
return decodedString;
}
public static void main(String... args) {
System.out.println(decodeString(args[0]));
}
}
I should note that Apache Commons Lang3 doesn't seem to suffer the weaknesses indicated in the accepted solution. That is, StringEscapeUtils
seems to handle octal escapes and multiple u
characters of Unicode escapes. That means unless you have some burning reason to avoid Apache Commons, you should probably use it rather than my solution (or any other solution here).
In case you do not want to use Asset Catalog, you can add an iOS 7 icon for an old app by creating a 120x120 .png image. Name it Icon-120.png
and drag in to the project.
Under TARGET > Your App > Info > Icon files, add one more entry in the Target Properties:
I tested on Xcode 5 and an app was submitted without the missing retina icon warning.
Method 1:
function functABC(){
$.ajax({
url: 'myPage.php',
data: {id: id},
success: function(data) {
return data;
},
complete: function(){
// do the job here
}
});
}
var response = functABC();
Method 2
function functABC(){
$.ajax({
url: 'myPage.php',
data: {id: id},
async: false,
success: function(data) {
return data;
}
});
// do the job here
}
a = [[1,'aa',3,12,'a','b','c','s'],[],[],[1,'aa',7,80,'d','g','f',''],[9,None,11,12,13,14,15,'k']]
b=[]
for lng in range(len(a)):
if(len(a[lng])>=1):b.append(a[lng])
a=b
print(a)
Output:
[[1,'aa',3,12,'a','b','c','s'],[1,'aa',7,80,'d','g','f',''],[9,None,11,12,13,14,15,'k']]
You need to use a regular expression, so that you can specify the global (g) flag:
var s = 'some+multi+word+string'.replace(/\+/g, ' ');
(I removed the $()
around the string, as replace
is not a jQuery method, so that won't work at all.)
You can think of O(log N) intuitively by saying the time is proportional to the number of digits in N.
If an operation performs constant time work on each digit or bit of an input, the whole operation will take time proportional to the number of digits or bits in the input, not the magnitude of the input; thus, O(log N) rather than O(N).
If an operation makes a series of constant time decisions each of which halves (reduces by a factor of 3, 4, 5..) the size of the input to be considered, the whole will take time proportional to log base 2 (base 3, base 4, base 5...) of the size N of the input, rather than being O(N).
And so on.
I experienced this condition when I had installed Oracle version 12 client 32 bit client connected to an Oracle 12 Server running on windows. Although both of Oracle-source and SqlServer-destination are NOT Unicode, I kept getting this message, as if the oracle columns were Unicode. I solved the problem inserting a data conversion box, and selecting type DT-STR (not unicode) for varchar2 fields and DT-WSTR (unicode) for numeric fields, then I've dropped the 'COPY OF' from the output field name. Note that I kept getting the error because I had connected the source box arrow with the conversion box BEFORE setting the convertion types. So I had to switch source box and this cleaned all the errors in the destination box.
Try using this instead:
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
It's bit hard to navigate Google's api but here is the relevant documentation.
One thing I had trouble finding was how to go in the other direction. From coordinates to an address. Here is the code I neded upp using. Please not that I also use jquery.
$.each(results[0].address_components, function(){
$("#CreateDialog").find('input[name="'+ this.types+'"]').attr('value', this.long_name);
});
What I'm doing is to loop through all the returned address_components
and test if their types match any input element names I have in a form. And if they do I set the value of the element to the address_components
value.
If you're only interrested in the whole formated address then you can follow Google's example
What I usually do is:
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'
):
do_something
this way the closing brace and colon visually mark the end of our condition.
You need make your Contact classes implement Comparable, and then implement the compareTo(Contact)
method. That way, the Collections.sort will be able to sort them for you. Per the page I linked to, compareTo 'returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.'
For example, if you wanted to sort by name (A to Z), your class would look like this:
public class Contact implements Comparable<Contact> {
private String name;
// all the other attributes and methods
public compareTo(Contact other) {
return this.name.compareTo(other.name);
}
}
I favor field accessors. The code is much cleaner. All the annotations can be placed in one section of a class and the code is much easier to read.
I found another problem with property accessors: if you have getXYZ methods on your class that are NOT annotated as being associated with persistent properties, hibernate generates sql to attempt to get those properties, resulting in some very confusing error messages. Two hours wasted. I did not write this code; I have always used field accessors in the past and have never run into this issue.
Hibernate versions used in this app:
<!-- hibernate -->
<hibernate-core.version>3.3.2.GA</hibernate-core.version>
<hibernate-annotations.version>3.4.0.GA</hibernate-annotations.version>
<hibernate-commons-annotations.version>3.1.0.GA</hibernate-commons-annotations.version>
<hibernate-entitymanager.version>3.4.0.GA</hibernate-entitymanager.version>
In C, int
, char
, long
, etc. are all integers.
They typically have different memory sizes and thus different ranges as in INT_MIN
to INT_MAX
. char
and arrays of char
are often used to store characters and strings. Integers are stored in many types: int
being the most popular for a balance of speed, size and range.
ASCII is by far the most popular character encoding, but others exist. The ASCII code for an 'A' is 65, 'a' is 97, '\n' is 10, etc. ASCII data is most often stored in a char
variable. If the C environment is using ASCII encoding, the following all store the same value into the integer variable.
int i1 = 'a';
int i2 = 97;
char c1 = 'a';
char c2 = 97;
To convert an int
to a char
, simple assign:
int i3 = 'b';
int i4 = i3;
char c3;
char c4;
c3 = i3;
// To avoid a potential compiler warning, use a cast `char`.
c4 = (char) i4;
This warning comes up because int
typically has a greater range than char
and so some loss-of-information may occur. By using the cast (char)
, the potential loss of info is explicitly directed.
To print the value of an integer:
printf("<%c>\n", c3); // prints <b>
// Printing a `char` as an integer is less common but do-able
printf("<%d>\n", c3); // prints <98>
// Printing an `int` as a character is less common but do-able.
// The value is converted to an `unsigned char` and then printed.
printf("<%c>\n", i3); // prints <b>
printf("<%d>\n", i3); // prints <98>
There are additional issues about printing such as using %hhu
or casting when printing an unsigned char
, but leave that for later. There is a lot to printf()
.
For simple structures you can either use memcpy
like you do, or just assign from one to the other:
RTCclk = RTCclkBuffert;
The compiler will create code to copy the structure for you.
An important note about the copying: It's a shallow copy, just like with memcpy
. That means if you have e.g. a structure containing pointers, it's only the actual pointers that will be copied and not what they point to, so after the copy you will have two pointers pointing to the same memory.
I use this with a daily cron job to check if I should send an email on the first day of any given month to my affiliates. It's a few more lines than the other answers but solid as a rock.
//is this the first day of the month?
$date = date('Y-m-d');
$pieces = explode("-", $date);
$day = $pieces[2];
//if it's not the first day then stop
if($day != "01") {
echo "error - it's not the first of the month today";
exit;
}
You can easily get what you want by adding the line in ax:
ax.plot([], [], '-r', label = 'temp')
or
ax.plot(np.nan, '-r', label = 'temp')
This would plot nothing but add a label to legend of ax.
I think this is a much easier way. It's not necessary to track lines automatically when you have only a few lines in the second axes, as fixing by hand like above would be quite easy. Anyway, it depends on what you need.
The whole code is as below:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')
time = np.arange(22.)
temp = 20*np.random.rand(22)
Swdown = 10*np.random.randn(22)+40
Rn = 40*np.random.rand(22)
fig = plt.figure()
ax = fig.add_subplot(111)
ax2 = ax.twinx()
#---------- look at below -----------
ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')
ax2.plot(time, temp, '-r') # The true line in ax2
ax.plot(np.nan, '-r', label = 'temp') # Make an agent in ax
ax.legend(loc=0)
#---------------done-----------------
ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()
The plot is as below:
Update: add a better version:
ax.plot(np.nan, '-r', label = 'temp')
This will do nothing while plot(0, 0)
may change the axis range.
One extra example for scatter
ax.scatter([], [], s=100, label = 'temp') # Make an agent in ax
ax2.scatter(time, temp, s=10) # The true scatter in ax2
ax.legend(loc=1, framealpha=1)
Leave off the quotes
$cmd &
$othercmd &
eg:
nicholas@nick-win7 /tmp
$ cat test
#!/bin/bash
cmd="ls -la"
$cmd &
nicholas@nick-win7 /tmp
$ ./test
nicholas@nick-win7 /tmp
$ total 6
drwxrwxrwt+ 1 nicholas root 0 2010-09-10 20:44 .
drwxr-xr-x+ 1 nicholas root 4096 2010-09-10 14:40 ..
-rwxrwxrwx 1 nicholas None 35 2010-09-10 20:44 test
-rwxr-xr-x 1 nicholas None 41 2010-09-10 20:43 test~
Just for the sake of completeness: there are IPv4-mapped IPv6 addresses, where you can embed an IPv4 address in an IPv6 address (may not be supported by every IPv6 equipment).
Example: I run a server on my machine, which can be accessed via http://127.0.0.1:19983/solr
. If I access it via an IPv4-mapped IPv6 address then I access it via http://[::ffff:127.0.0.1]:19983/solr
(which will be converted to http://[::ffff:7f00:1]:19983/solr
)
You need to add in the seconds, too:
unsigned long time_in_micros = 1000000 * tv.tv_sec + tv.tv_usec;
Note that this will only last for about 232/106 =~ 4295 seconds, or roughly 71 minutes though (on a typical 32-bit system).
I just got this after creating a new Objective-C project in Xcode 10, after I added a Core Data model file to the project.
I found two ways to fix this:
The model contains a "contents" file with this line:
<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="14460.32" systemVersion="17G5019" minimumToolsVersion="Automatic" sourceLanguage="Swift" userDefinedModelVersionIdentifier="">
In there is a sourceLanguage="Swift"
entry. Change it to sourceLanguage="Objective-C"
and the error goes away.
To find the "contents" file, right click on the .xcdatamodeld
in Xcode and do "Show in Finder". Right-click on the actual (Finder) file and do "Show Package Contents"
Also: Changing the model's language will stop Xcode from generating managed object subclass files in Swift.
An update:
As of Laravel 5.3 doing this in a single step is possible; the firstOrCreate
method now accepts an optional second array as an argument.
The first array argument is the array on which the fields/values are matched, and the second array is the additional fields to use in the creation of the model if no match is found via matching the fields/values in the first array:
If you are doing simple manipulation and can tie yourself to xlsx then you can look into manipulating the XML yourself. I have done it and found it to be faster than grokking the excel libs.
There are also 3rd party libs that can be easier to use... and can be used on the server which MS's can't.
You can get the path via fp.name
. Example:
>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'
You might need os.path.basename
if you want only the file name:
>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'
File object docs (for Python 2) here.
Lookarounds are zero width assertions. They check for a regex (towards right or left of the current position - based on ahead or behind), succeeds or fails when a match is found (based on if it is positive or negative) and discards the matched portion. They don't consume any character - the matching for regex following them (if any), will start at the same cursor position.
Read regular-expression.info for more details.
Syntax:
(?=REGEX_1)REGEX_2
Match only if REGEX_1 matches; after matching REGEX_1, the match is discarded and searching for REGEX_2 starts at the same position.
example:
(?=[a-z0-9]{4}$)[a-z]{1,2}[0-9]{2,3}
REGEX_1 is [a-z0-9]{4}$
which matches four alphanumeric chars followed by end of line.
REGEX_2 is [a-z]{1,2}[0-9]{2,3}
which matches one or two letters followed by two or three digits.
REGEX_1 makes sure that the length of string is indeed 4, but doesn't consume any characters so that search for REGEX_2 starts at the same location. Now REGEX_2 makes sure that the string matches some other rules. Without look-ahead it would match strings of length three or five.
Syntax:
(?!REGEX_1)REGEX_2
Match only if REGEX_1 does not match; after checking REGEX_1, the search for REGEX_2 starts at the same position.
example:
(?!.*\bFWORD\b)\w{10,30}$
The look-ahead part checks for the FWORD
in the string and fails if it finds it. If it doesn't find FWORD
, the look-ahead succeeds and the following part verifies that the string's length is between 10 and 30 and that it contains only word characters a-zA-Z0-9_
Look-behind is similar to look-ahead: it just looks behind the current cursor position. Some regex flavors like javascript doesn't support look-behind assertions. And most flavors that support it (PHP, Python etc) require that look-behind portion to have a fixed length.
As @swanliu pointed out it is due to a bad connection.
However before adjusting the server timing and client timeout , I would first try and use a better connection pooling strategy.
Hibernate itself admits that its connection pooling strategy is minimal
Hibernate's own connection pooling algorithm is, however, quite rudimentary. It is intended to help you get started and is not intended for use in a production system, or even for performance testing. You should use a third party pool for best performance and stability. Just replace the hibernate.connection.pool_size property with connection pool specific settings. This will turn off Hibernate's internal pool. For example, you might like to use c3p0.
As stated in Reference : http://docs.jboss.org/hibernate/core/3.3/reference/en/html/session-configuration.html
I personally use C3P0
. however there are other alternatives available including DBCP
.
Check out
Below is a minimal configuration of C3P0 used in my application:
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="c3p0.acquire_increment">1</property>
<property name="c3p0.idle_test_period">100</property> <!-- seconds -->
<property name="c3p0.max_size">100</property>
<property name="c3p0.max_statements">0</property>
<property name="c3p0.min_size">10</property>
<property name="c3p0.timeout">1800</property> <!-- seconds -->
By default, pools will never expire Connections. If you wish Connections to be expired over time in order to maintain "freshness", set maxIdleTime and/or maxConnectionAge. maxIdleTime defines how many seconds a Connection should be permitted to go unused before being culled from the pool. maxConnectionAge forces the pool to cull any Connections that were acquired from the database more than the set number of seconds in the past.
As stated in Reference : http://www.mchange.com/projects/c3p0/index.html#managing_pool_size
Edit:
I updated the configuration file (Reference), as I had just copy pasted the one for my project earlier.
The timeout should ideally solve the problem, If that doesn't work for you there is an expensive solution which I think you could have a look at:
Create a file “c3p0.properties” which must be in the root of the classpath (i.e. no way to override it for particular parts of the application). (Reference)
# c3p0.properties
c3p0.testConnectionOnCheckout=true
With this configuration each connection is tested before being used. It however might affect the performance of the site.
Try this
SELECT DATEADD(day, DATEDIFF(day, 0, GETDATE()), '03:30:00')
$dir = "mytheme/images/myimages";
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
$files[] = $filename;
}
$images=preg_grep ('/\.jpg$/i', $files);
Very fast because you only scan the needed directory.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Case_example_1
{
class Program
{
static void Main(string[] args)
{
Char ch;
Console.WriteLine("Enter a character");
ch =Convert.ToChar(Console.ReadLine());
switch (ch)
{
case 'a':
case 'e':
case 'i':
case 'o':
case 'u':
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
Console.WriteLine("Character is alphabet");
break;
default:
Console.WriteLine("Character is constant");
break;
}
Console.ReadLine();
}
}
}
If you want to round a number, you can obtain different results depending on: how you use the Math.Round() function (if for a round-up or round-down), you're working with doubles and/or floats numbers, and you apply the midpoint rounding. Especially, when using with operations inside of it or the variable to round comes from an operation. Let's say, you want to multiply these two numbers: 0.75 * 0.95 = 0.7125. Right? Not in C#
Let's see what happens if you want to round to the 3rd decimal:
double result = 0.75d * 0.95d; // result = 0.71249999999999991
double result = 0.75f * 0.95f; // result = 0.71249997615814209
result = Math.Round(result, 3, MidpointRounding.ToEven); // result = 0.712. Ok
result = Math.Round(result, 3, MidpointRounding.AwayFromZero); // result = 0.712. Should be 0.713
As you see, the first Round() is correct if you want to round down the midpoint. But the second Round() it's wrong if you want to round up.
This applies to negative numbers:
double result = -0.75 * 0.95; //result = -0.71249999999999991
result = Math.Round(result, 3, MidpointRounding.ToEven); // result = -0.712. Ok
result = Math.Round(result, 3, MidpointRounding.AwayFromZero); // result = -0.712. Should be -0.713
So, IMHO, you should create your own wrap function for Math.Round() that fit your requirements. I created a function in which, the parameter 'roundUp=true' means to round to next greater number. That is: 0.7125 rounds to 0.713 and -0.7125 rounds to -0.712 (because -0.712 > -0.713). This is the function I created and works for any number of decimals:
double Redondea(double value, int precision, bool roundUp = true)
{
if ((decimal)value == 0.0m)
return 0.0;
double corrector = 1 / Math.Pow(10, precision + 2);
if ((decimal)value < 0.0m)
{
if (roundUp)
return Math.Round(value, precision, MidpointRounding.ToEven);
else
return Math.Round(value - corrector, precision, MidpointRounding.AwayFromZero);
}
else
{
if (roundUp)
return Math.Round(value + corrector, precision, MidpointRounding.AwayFromZero);
else
return Math.Round(value, precision, MidpointRounding.ToEven);
}
}
The variable 'corrector' is for fixing the inaccuracy of operating with floating or double numbers.
Adding a <Context>
tag in the <Host>
tag in server.xml
for Tomcat 6 will resolve the problem.
If you use path=""
empty you can use a URL like http://localhost/first.do
.
In the context tag set attributes docBase="E:\struts-ITRCbook\myStrutsbook"
and reloadable="true"
, then end the context tag.
It should look something like this:
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true"
xmlValidation="false" xmlNamespaceAware="false">
<Context path="" docBase="E:\struts-ITRCbook\myStrutsbook" reloadable="true">
</Context>
</Host>
You seem a bit confused as to how numpy arrays work behind the scenes. Each item in an array must be the same size.
The string representation of a float doesn't work this way. For example, repr(1.3)
yields '1.3'
, but repr(1.33)
yields '1.3300000000000001'
.
A accurate string representation of a floating point number produces a variable length string.
Because numpy arrays consist of elements that are all the same size, numpy requires you to specify the length of the strings within the array when you're using string arrays.
If you use x.astype('str')
, it will always convert things to an array of strings of length 1.
For example, using x = np.array(1.344566)
, x.astype('str')
yields '1'
!
You need to be more explict and use the '|Sx'
dtype syntax, where x
is the length of the string for each element of the array.
For example, use x.astype('|S10')
to convert the array to strings of length 10.
Even better, just avoid using numpy arrays of strings altogether. It's usually a bad idea, and there's no reason I can see from your description of your problem to use them in the first place...
in web app java spring what worked for me
cron="0 0/30 * * * ?"
This will trigger on for example 10:00AM then 10:30AM etc...
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task.xsd">
<beans profile="cron">
<bean id="executorService" class="java.util.concurrent.Executors" factory-method="newFixedThreadPool">
<beans:constructor-arg value="5" />
</bean>
<task:executor id="threadPoolTaskExecutor" pool-size="5" />
<task:annotation-driven executor="executorService" />
<beans:bean id="expireCronJob" class="com.cron.ExpireCron"/>
<task:scheduler id="serverScheduler" pool-size="5"/>
<task:scheduled-tasks scheduler="serverScheduler">
<task:scheduled ref="expireCronJob" method="runTask" cron="0 0/30 * * * ?"/> <!-- every thirty minute -->
</task:scheduled-tasks>
</beans>
</beans>
I dont know why but this is working on my local develop and production, but other changes if i made i have to be careful because it may work local and on develop but not on production
Bitstorm has the best jquery color animation plugin I've seen. It's an improvement to the jquery color project. It also supports rgba.
Currently (Laravel 5.4) the way to achieve this is:
$model = new Model();
$model->created_at = Carbon::now();
$model->save(['timestamps' => false]);
If you want to catch the focus event dynamiclly on every input on your component :
import { AfterViewInit, Component, ElementRef } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit {
constructor(private el: ElementRef) {
}
ngAfterViewInit() {
// document.getElementsByTagName('input') : to gell all Docuement imputs
const inputList = [].slice.call((<HTMLElement>this.el.nativeElement).getElementsByTagName('input'));
inputList.forEach((input: HTMLElement) => {
input.addEventListener('focus', () => {
input.setAttribute('placeholder', 'focused');
});
input.addEventListener('blur', () => {
input.removeAttribute('placeholder');
});
});
}
}
Checkout the full code here : https://stackblitz.com/edit/angular-93jdir
This is simpler to read:
IF "%ID%"=="0" REM do something
IF "%ID%"=="1" REM do something else
IF "%ID%"=="2" REM do another thing
IF %ID% GTR 2 REM default case...
In your view template, set a default value:
f.text_field :password, :value => "password"
In your Javascript (assuming jquery here):
$(document).ready(function() {
//add a handler to remove the text
});
My Java version was the 1.6 and I found that was using 1.7 with CDI however after that I changed the Java version to 1.7 and import the package javax.faces.bean.ManagedBean and everything worked.
Thanks @PM77-1
It is best to use native dictionaries and arrays because they have been optimized for use with swift. That being said you can use NS... classes in swift and I think this situation warrants that. Here is how you would implement it:
var path = NSBundle.mainBundle().pathForResource("Config", ofType: "plist")
var dict = NSDictionary(contentsOfFile: path)
So far (in my opinion) this is the easiest and most efficient way to access a plist, but in the future I expect that apple will add more functionality (such as using plist) into native dictionaries.
Let's say you have a master
branch with files/directories:
> git branch
master
> ls -la # (files and dirs which you may keep in master)
.git
directory1
directory2
file_1
..
file_n
git checkout —orphan new_branch_name
ls -la |awk '{print $9}' |grep -v git |xargs -I _ rm -rf ./_
git rm -rf .
touch new_file
git add new_file
git commit -m 'added first file in the new branch'
git push origin new_branch_name
In step 2, we simply remove all the files locally to avoid confusion with the files on your new branch and those ones you keep in master
branch.
Then, we unlink all those files in step 3. Finally, step 4 and after are working with our new empty branch.
Once you're done, you can easily switch between your branches:
git checkout master
git checkout new_branch
A simpler approach like the one Ioannis Filippidis do :
import matplotlib.pyplot as plt
import numpy as np
# evenly sampled time at 200ms intervals
tMin=-1 ;tMax=10
t = np.arange(tMin, tMax, 0.1)
# red dashes, blue points default
plt.plot(t, 22*t, 'r--', t, t**2, 'b')
factor=3/4 ;offset=20 # text position in view
textPosition=[(tMax+tMin)*factor,22*(tMax+tMin)*factor]
plt.text(textPosition[0],textPosition[1]+offset,'22 t',color='red',fontsize=20)
textPosition=[(tMax+tMin)*factor,((tMax+tMin)*factor)**2+20]
plt.text(textPosition[0],textPosition[1]+offset, 't^2', bbox=dict(facecolor='blue', alpha=0.5),fontsize=20)
plt.show()
The first is easiest(involves less typing), and it is guaranteed to work, all members will be set to 0
[Ref 1].
The second is more readable.
The choice depends on user preference or the one which your coding standard mandates.
[Ref 1] Reference C99 Standard 6.7.8.21:
If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration.
Good Read:
C and C++ : Partial initialization of automatic structure
Unless you write your own Homescreen launcher or use an existing one from Goolge Play, there's "no way" to resize icons.
Well, "no way" does not mean its impossible:
Use it in conjunction with pipefail
.
set -e
set -o pipefail
-e (errexit): Abort the script at the first error, when a command exits with non-zero status (except in until or while loops, if-tests, and list constructs)
-o pipefail: Causes a pipeline to return the exit status of the last command in the pipe that returned a non-zero return value.
I solved it easily via running these codes:
npm uninstall mongodb --save
npm install [email protected] --save
Happy Coding!
the answers are a bit incomplete, 3 things you have to do
in php.ini of your php installation (note: depending if you want it for CLI, apache, or nginx, find the right php.ini to manipulate. For nginx it is usually located in /etc/php/7.1/fpm
where 7.1 depends on your version. For apache usually /etc/php/7.1/apache2
)
post_max_size=500M
upload_max_filesize=500M
memory_limit=900M
or set other values. Restart/reload apache if you have apache installed or php-fpm for nginx if you use nginx.
Add the css
<style type="text/css">
textarea
{
border:1px solid #999999
width:99%;
margin:5px 0;
padding:1%;
}
</style>
Perhaps create a shared Fruit
interface that provides isDecayed. fruits
is now of type Fruit[]
so the type can be explicit. Like this:
interface Fruit {
isDecayed: boolean;
}
interface Apple extends Fruit {
color: string;
}
interface Pear extends Fruit {
weight: number;
}
interface FruitBasket {
apples: Apple[];
pears: Pear[];
}
const fruitBasket: FruitBasket = { apples: [], pears: [] };
const key: keyof FruitBasket = Math.random() > 0.5 ? 'apples': 'pears';
const fruits: Fruit[] = fruitBasket[key];
const freshFruits = fruits.filter((fruit) => !fruit.isDecayed);
You can pass program arguments on the command line and get them in your Java app like this:
public static void main(String[] args) {
String pathToXml = args[0];
....
}
Alternatively you pass a system property by changing the command line to:
java -Dpath-to-xml=enwiki-20111007-pages-articles.xml -jar wiki2txt
and your main class to:
public static void main(String[] args) {
String pathToXml = System.getProperty("path-to-xml");
....
}
Off course an old question. But I have a simple solution where no need of Looping, CTE, Table variables etc.
DECLARE @MyVar datetime = '1/1/2010'
SELECT @MyVar
SELECT DATEADD (DD,NUMBER,@MyVar)
FROM master.dbo.spt_values
WHERE TYPE='P' AND NUMBER BETWEEN 0 AND 4
ORDER BY NUMBER
Note : spt_values
is a Mircrosoft's undocumented table. It has numbers for every type. Its not suggestible to use as it can be removed in any new versions of sql server without prior information, since it is undocumented. But we can use it as quick workaround in some scenario's like above.
This is another one
$("#header ul li").last().html('<li> Menu 5 </li>');
If you do a
sudo yum list | grep python3
you will see that while they don't have a "python3" package, they do have a "python34" package, or a more recent release, such as "python36". Installing it is as easy as:
sudo yum install python34 python34-pip
Short answer: You can't.
Long answer: You could use a modal to display a popup with the image you need.
You can refer to this as an example to a modal.
To change only the second column of a table use the following:
General Case:
table td + td{ /* this will go to the 2nd column of a table directly */
background:red
}
Your case:
.countTable table table td + td{
background: red
}
Note: this works for all browsers (Modern and old ones) that's why I added my answer to an old question
Simplyfing for the begginers:
If you want to select an element immediatly after another element you use the +
selector.
For example:
div + p
The "+" element selects all <p>
elements that are placed immediately after <div>
elements
If you want to learn more about selectors use this table
Yes, you can find out element by data attribute.
element = $('a[data-item-id="stand-out"]');
If you want to call a bash script using python, here is a simple method to load a file from a folder in S3 bucket to a local folder (in a Linux machine) :
import boto3
import subprocess
import os
###TOEDIT###
my_bucket_name = "your_my_bucket_name"
bucket_folder_name = "your_bucket_folder_name"
local_folder_path = "your_local_folder_path"
###TOEDIT###
# 1.Load thes list of files existing in the bucket folder
FILES_NAMES = []
s3 = boto3.resource('s3')
my_bucket = s3.Bucket('{}'.format(my_bucket_name))
for object_summary in my_bucket.objects.filter(Prefix="{}/".format(bucket_folder_name)):
# print(object_summary.key)
FILES_NAMES.append(object_summary.key)
# 2.List only new files that do not exist in local folder (to not copy everything!)
new_filenames = list(set(FILES_NAMES )-set(os.listdir(local_folder_path)))
# 3.Time to load files in your destination folder
for new_filename in new_filenames:
upload_S3files_CMD = """aws s3 cp s3://{}/{}/{} {}""".format(my_bucket_name,bucket_folder_name,new_filename ,local_folder_path)
subprocess_call = subprocess.call([upload_S3files_CMD], shell=True)
if subprocess_call != 0:
print("ALERT: loading files not working correctly, please re-check new loaded files")
JQuery version:
$('yourInputSelectorHere').val("<script>alert('test');<\/script>")
To get rid of the fixed height property you can set it to the default value:
height: auto;
In .NET4.5
, MVC 5
no need for widgets.
Javascript:
object in JS:
mechanism that does post.
$('.button-green-large').click(function() {
$.ajax({
url: 'Quote',
type: "POST",
dataType: "json",
data: JSON.stringify(document.selectedProduct),
contentType: 'application/json; charset=utf-8',
});
});
C#
Objects:
public class WillsQuoteViewModel
{
public string Product { get; set; }
public List<ClaimedFee> ClaimedFees { get; set; }
}
public partial class ClaimedFee //Generated by EF6
{
public long Id { get; set; }
public long JourneyId { get; set; }
public string Title { get; set; }
public decimal Net { get; set; }
public decimal Vat { get; set; }
public string Type { get; set; }
public virtual Journey Journey { get; set; }
}
Controller:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Quote(WillsQuoteViewModel data)
{
....
}
Object received:
Hope this saves you some time.
FYI, I have used UI_USER_INTERFACE_IDIOM()
for my app written in Swift. The app can be compiled well with XCode 6.3.1 without any warning on that command, runs well on Simulator (with any selected devices) and on all my real devices (iPhone, iPad) with iOS versions from 7.1 to 8.3.
However, the app crashed on Apple reviewers' devices (and was refused). That took me few days to detect the problem with few more re-uploads to iTunes Connect.
Now I use UIDevice.currentDevice().userInterfaceIdiom
instead and my app can survive from such crashes.
By default, it begins by processing the first target that does not begin with a .
aka the default goal; to do that, it may have to process other targets - specifically, ones the first target depends on.
The GNU Make Manual covers all this stuff, and is a surprisingly easy and informative read.
It was talked about it a lot already, u can find even on Wiki the reasons...
And I hear more and more Java programmers that try to convince people that Java is not slow, it is not slow for drawing a widget on the screen and drawing some ASCII characters on the widget, to receive and send data through network(And it is recommended to use it in this cases(network data manipulation) instead of C/C++)... But it is damn slow when it comes to serious stuff like math calculations, memory allocation/manipulation and a lot of this good stuff.
I remember an article on MIT site where they show what C/C++ can do if u use the language and compiler features: A matrix multiplier(2 matrices), 1 implementation in Java and 1 implementation in C/C++, with C/C++ features and appropriate compiler optimisations activated, the C/C++ implementation was ~296 260 times faster than the Java implementation.
I hope you understand now why people use C/C++ instead of Java in games, imagine Crysis in Java, there would not be any computer in this world which could handle that... + Garbage collection works ok for Widgets which just destroyed an image but it's still cached in there and needs to be cleaned but not for games, for sure, u will have even more lags on every garbage collection activation.
Edit: Because somebody asked for the article, here, I searched in the web archive to get that, I hope you are satisfied...MIT Case Study
And to add, no, Java for gaming is still an awful idea. Just a few days ago a big company that I will not name started rewriting their game client from Java to C++ because a very simple game(In terms of Graphics) was lagging and heating i7 Laptops with powerful nVidia GT 5xx and 6xx generation video cards(not only nVidia, the point here is that this powerful cards that can handle on Max settings most of the new games and can't handle this game) and the memory consumption was ~2.5 - 2.6 GB Ram. For such simple graphics it needs a beast of a machine.
Faced with the same problem I created a simple jQuery plugin http://xypaul.github.io/radioimg.js/
It works using hidden radio buttons and labels containing images as shown below.
<input type="radio" style="display: none;" id="a" />
<label for="a">
<img class="" />
</label>
As many said - this version
int maxAge = context.Persons.Max(p => p.Age);
throws an exception when table is empty.
Use
int maxAge = context.Persons.Max(x => (int?)x.Age) ?? 0;
or
int maxAge = context.Persons.Select(x => x.Age).DefaultIfEmpty(0).Max()
your list comphresnion will, work but will return list of None because append return None:
demo:
>>> a=[]
>>> [ a.append(x) for x in range(10) ]
[None, None, None, None, None, None, None, None, None, None]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
better way to use it like this:
>>> a= [ x for x in range(10) ]
>>> a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
python >= 2.6,
if we write such as
if A:
will generate warning as,
FutureWarning: The behavior of this method will change in future versions. Use specific 'len(elem)' or 'elem is not None' test instead.
So we can use
if A is not None:
Globally, disabling the back button is indeed bad practice. But, in certain situations, the back button functionality doesn't make sense.
Here's one way to prevent unwanted navigation between pages:
Top page (file top.php
):
<?php
session_start();
$_SESSION[pid]++;
echo "top page $_SESSION[pid]";
echo "<BR><a href='secondary.php?pid=$_SESSION[pid]'>secondary page</a>";
?>
Secondary page (file secondary.php
):
<?php
session_start();
if ($_SESSION[pid] != $_GET[pid])
header("location: top.php");
else {
echo "secondary page $_SESSION[pid]";
echo "<BR><a href='top.php'>top</a>";
}
?>
The effect is to allow navigating from the top page forward to the secondary page and back (e.g. Cancel) using your own links. But, after returning to the top page the browser back button is prevented from navigating to the secondary page.
I landed here because I needed to rate-limit http.request (~10k aggregation queries to elastic search to build an analytical report). The following just choked my machine.
for (item in set) {
http.request(... + item + ...);
}
My URLs are very simple so this may not trivially apply to the original question but I think it's both potentially applicable and worth writing here for readers that land here with issues similar to mine and who want a trivial JavaScript no-library solution.
My job wasn't order dependent and my first approach to bodging this was to wrap it in a shell script to chunk it (because I'm new to JavaScript). That was functional but not satisfactory. My JavaScript resolution in the end was to do the following:
var stack=[];
stack.push('BOTTOM');
function get_top() {
var top = stack.pop();
if (top != 'BOTTOM')
collect(top);
}
function collect(item) {
http.request( ... + item + ...
result.on('end', function() {
...
get_top();
});
);
}
for (item in set) {
stack.push(item);
}
get_top();
It looks like mutual recursion between collect and get_top. I'm not sure it is in effect because the system is asynchronous and the function collect completes with a callback stashed for the event at on.('end'.
I think it is general enough to apply to the original question. If, like my scenario, the sequence/set is known, all URLs/keys can be pushed on the stack in one step. If they are calculated as you go, the on('end' function can push the next url on the stack just before get_top(). If anything, the result has less nesting and might be easier to refactor when the API you're calling changes.
I realise this is effectively equivalent to the @generalhenry's simple recursive version above (so I upvoted that!)
You would usually use map for that kind of thing.
buttonsListArr = initialArr.map(buttonInfo => (
<Button ... key={buttonInfo[0]}>{buttonInfo[1]}</Button>
);
(key is a necessary prop whenever you do mapping in React. The key needs to be a unique identifier for the generated component)
As a side, I would use an object instead of an array. I find it looks nicer:
initialArr = [
{
id: 1,
color: "blue",
text: "text1"
},
{
id: 2,
color: "red",
text: "text2"
},
];
buttonsListArr = initialArr.map(buttonInfo => (
<Button ... key={buttonInfo.id}>{buttonInfo.text}</Button>
);
You'll find one in
http://commons.apache.org/lang/
It's called
org.apache.commons.lang.time.StopWatch
But it roughly does the same as yours. If you're in for more precision, use
System.nanoTime()
See also this question here:
An alternative answer that uses today()
method to calculate current date and then subtracts one using timedelta()
. Rest of the steps remain the same.
https://docs.python.org/3.7/library/datetime.html#timedelta-objects
from datetime import date, timedelta
today = date.today()
yesterday = today - timedelta(days = 1)
print(today)
print(yesterday)
Output:
2019-06-14
2019-06-13
For Ubuntu/Linux
Step 1: Find the process id that is using the port 8080
netstat -lnp | grep 8080
or
ps -aef | grep tomcat
Step 2: Kill the process using process id in above result
kill -9 process_id
For Windows
Step 1: Find the process id
netstat -ano | findstr 8080
Step 2: Open command prompt as administrator and kill the process
taskkill /F /pid 1088
In my case port 8005 was already in use so I used the same above steps.
If you absolutely must use input
, try this:
background-image: url(...);
background-repeat: no-repeat;
background-position: <left|right>;
padding-<left|right>: <width of image>px;
It's usually a little easier to use a button
with an img
inside:
<button type="submit"><img> Text</button>
However the browser implementations of button
for submitting are inconsistent, as well as the fact that all button values are sent when button
is used - which kills the "what button clicked" detection in a multi-submit form.
Yes. You can loop through an object using for loop. Here is an example
var myObj = {_x000D_
abc: 'ABC',_x000D_
bca: 'BCA',_x000D_
zzz: 'ZZZ',_x000D_
xxx: 'XXX',_x000D_
ccc: 'CCC',_x000D_
}_x000D_
_x000D_
var k = Object.keys (myObj);_x000D_
for (var i = 0; i < k.length; i++) {_x000D_
console.log (k[i] + ": " + myObj[k[i]]);_x000D_
}
_x000D_
NOTE: the example mentioned above will only work in IE9+. See Objec.keys browser support here.
This code will output current time in HH:MM:SS format in console, it takes into account GMT timezones.
var currentTime = Date.now()
var GMT = -(new Date()).getTimezoneOffset()/60;
var totalSeconds = Math.floor(currentTime/1000);
seconds = ('0' + totalSeconds % 60).slice(-2);
var totalMinutes = Math.floor(totalSeconds/60);
minutes = ('0' + totalMinutes % 60).slice(-2);
var totalHours = Math.floor(totalMinutes/60);
hours = ('0' + (totalHours+GMT) % 24).slice(-2);
var timeDisplay = hours + ":" + minutes + ":" + seconds;
console.log(timeDisplay);
//Output is: 11:16:55
Here is a sample I wrote shows how I parse a json and mess every number inside it:
public class JsonParser {
public static Object parseAndMess(Object object) throws IOException {
String json = JsonUtil.toJson(object);
JsonNode jsonNode = parseAndMess(json);
if(null != jsonNode)
return JsonUtil.toObject(jsonNode, object.getClass());
return null;
}
public static JsonNode parseAndMess(String json) throws IOException {
JsonNode rootNode = parse(json);
return mess(rootNode, new Random());
}
private static JsonNode parse(String json) throws IOException {
JsonFactory factory = new JsonFactory();
ObjectMapper mapper = new ObjectMapper(factory);
JsonNode rootNode = mapper.readTree(json);
return rootNode;
}
private static JsonNode mess(JsonNode rootNode, Random rand) throws IOException {
if (rootNode instanceof ObjectNode) {
Iterator<Map.Entry<String, JsonNode>> fieldsIterator = rootNode.fields();
while (fieldsIterator.hasNext()) {
Map.Entry<String, JsonNode> field = fieldsIterator.next();
replaceObjectNode((ObjectNode) rootNode, field, rand);
}
} else if (rootNode instanceof ArrayNode) {
ArrayNode arrayNode = ((ArrayNode) rootNode);
replaceArrayNode(arrayNode, rand);
}
return rootNode;
}
private static void replaceObjectNode(ObjectNode rootNode, Map.Entry<String, JsonNode> field, Random rand)
throws IOException {
JsonNode childNode = field.getValue();
if (childNode instanceof IntNode) {
(rootNode).put(field.getKey(), rand.nextInt(1000));
} else if (childNode instanceof LongNode) {
(rootNode).put(field.getKey(), rand.nextInt(1000000));
} else if (childNode instanceof FloatNode) {
(rootNode).put(field.getKey(), format(rand.nextFloat()));
} else if (childNode instanceof DoubleNode) {
(rootNode).put(field.getKey(), format(rand.nextFloat()));
} else {
mess(childNode, rand);
}
}
private static void replaceArrayNode(ArrayNode arrayNode, Random rand) throws IOException {
int arrayLength = arrayNode.size();
if(arrayLength == 0)
return;
if (arrayNode.get(0) instanceof IntNode) {
for (int i = 0; i < arrayLength; i++) {
arrayNode.set(i, new IntNode(rand.nextInt(10000)));
}
} else if (arrayNode.get(0) instanceof LongNode) {
arrayNode.removeAll();
for (int i = 0; i < arrayLength; i++) {
arrayNode.add(rand.nextInt(1000000));
}
} else if (arrayNode.get(0) instanceof FloatNode) {
arrayNode.removeAll();
for (int i = 0; i < arrayLength; i++) {
arrayNode.add(format(rand.nextFloat()));
}
} else if (arrayNode.get(0) instanceof DoubleNode) {
arrayNode.removeAll();
for (int i = 0; i < arrayLength; i++) {
arrayNode.add(format(rand.nextFloat()));
}
} else {
for (int i = 0; i < arrayLength; i++) {
mess(arrayNode.get(i), rand);
}
}
}
public static void print(JsonNode rootNode) throws IOException {
System.out.println(rootNode.toString());
}
private static double format(float a) {
return Math.round(a * 10000.0) / 100.0;
}
}
The fix is to modify your EDMX file, using the XML editor, and change the value of ProviderManifestToken from 2012 to 2008. I found that on line 7 in my EDMX file. After saving that change, the paging SQL will be generated using the “old”, SQL Server 2008 compatible syntax.
My apologies for posting an answer on this very old thread. Posting it for the people like me, I solved this issue today.
You might not have been started your application with the right parameters.
Those are the simple problems when I have faced "Connection refused" error.
You have two versions of mysql using the same port. 3306. Change the port.
How to change the mysql port for xampp?
Code:
Password = your_password
port = 3306 ---> 3307
socket = "/ xampp / mysql / mysql.sock"
and here also
Code:
The MySQL server
[ mysqld ]
port = 3306 ---> 3307
socket = "/ xampp / mysql / mysql.sock"
2. Start mysql service
Note that in general, Mockito does allow throwing checked exceptions so long as the exception is declared in the message signature. For instance, given
class BarException extends Exception {
// this is a checked exception
}
interface Foo {
Bar frob() throws BarException
}
it's legal to write:
Foo foo = mock(Foo.class);
when(foo.frob()).thenThrow(BarException.class)
However, if you throw a checked exception not declared in the method signature, e.g.
class QuxException extends Exception {
// a different checked exception
}
Foo foo = mock(Foo.class);
when(foo.frob()).thenThrow(QuxException.class)
Mockito will fail at runtime with the somewhat misleading, generic message:
Checked exception is invalid for this method!
Invalid: QuxException
This may lead you to believe that checked exceptions in general are unsupported, but in fact Mockito is only trying to tell you that this checked exception isn't valid for this method.
well, just a quick and dirty suggestion for simple 1-level directory structure without spaces, [edit] and for directories containing only ONE type of files that I found useful (at some point from http://www.pcreview.co.uk/forums/can-check-if-folder-empty-bat-file-t1468868.html):
for /f %a in ('dir /ad/b') do if not exist %a\*.xml echo %a Empty
/ad : shows only directory entries
/b : use bare format (just names)
[edit] using plain asterisk to check for ANY file (%a\* above) won't work, thanks for correction
therefore, deleting would be:
for /f %a in ('dir /ad/b') do if not exist %a\*.xml rmdir %a
Foreign keys work by joining a column to a unique key in another table, and that unique key must be defined as some form of unique index, be it the primary key, or some other unique index.
At the moment, the only unique index you have is a compound one on ISBN, Title
which is your primary key.
There are a number of options open to you, depending on exactly what BookTitle holds and the relationship of the data within it.
I would hazard a guess that the ISBN is unique for each row in BookTitle. ON the assumption this is the case, then change your primary key to be only on ISBN, and change BookCopy so that instead of Title you have ISBN and join on that.
If you need to keep your primary key as ISBN, Title
then you either need to store the ISBN in BookCopy as well as the Title, and foreign key on both columns, OR you need to create a unique index on BookTitle(Title) as a distinct index.
More generally, you need to make sure that the column or columns you have in your REFERENCES
clause match exactly a unique index in the parent table: in your case it fails because you do not have a single unique index on Title
alone.
You can use unset
:
unset($array['key-here']);
Example:
$array = array("key1" => "value1", "key2" => "value2");
print_r($array);
unset($array['key1']);
print_r($array);
unset($array['key2']);
print_r($array);
Output:
Array
(
[key1] => value1
[key2] => value2
)
Array
(
[key2] => value2
)
Array
(
)
It is possible to write like this:
elif var1 in [80, 443] or 1024 < var1 < 65535
This way you check if var1 appears in that a list, then you make just 1 check, didn't repeat the "var1" one extra time, and looks clear:
if var1 in [80, 443] or 1024 < var1 < 65535:
print 'good'
else:
print 'bad'
....:
good
Layout changes can occur whenever any of the following events happens in a view:
a. The size of a view’s bounds rectangle changes.
b. An interface orientation change occurs, which usually triggers a change in the root view’s bounds rectangle.
c. The set of Core Animation sublayers associated with the view’s layer changes and requires layout.
d. Your application forces layout to occur by calling thesetNeedsLayout
orlayoutIfNeeded
method of a view.
e. Your application forces layout by calling thesetNeedsLayout
method of the view’s underlying layer object.
I use this and it works right
@Id
@GeneratedValue(generator = "SEC_ODON", strategy = GenerationType.SEQUENCE)
@SequenceGenerator(name = "SEC_ODON", sequenceName = "SO.SEC_ODON",allocationSize=1)
@Column(name="ID_ODON", unique=true, nullable=false, precision=10, scale=0)
public Long getIdOdon() {
return this.idOdon;
}
Go to Synaptic package manager. Reload -> Search for python -> select the python package you want -> Submit -> Install Works for me ;)
Exactly, the package you need to install is python-dev.
In addition to the answer, $ yarn cache clean
removes all libraries from cache. If you want to remove a specific lib's cache run $ yarn cache dir
to get the right yarn cache directory path for your OS, then $ cd
to that directory and remove the folder with the name
+ version
of the lib you want to cleanup.
Another method without having to update your Python code at all, would be to redirect via the console.
Basically, have your Python script print()
as usual, then call the script from the command line and use command line redirection. Like this:
$ python ./myscript.py > output.txt
Your output.txt
file will now contain all output from your Python script.
Edit:
To address the comment; for Windows, change the forward-slash to a backslash.
(i.e. .\myscript.py
)
It sort of depends on what you mean by "convert".
If you have a series of characters that represents an integer, like "123456", then there are two typical ways to do that in C: Use a special-purpose conversion like atoi() or strtol(), or the general-purpose sscanf(). C++ (which is really a different language masquerading as an upgrade) adds a third, stringstreams.
If you mean you want the exact bit pattern in one of your int
variables to be treated as a char
, that's easier. In C the different integer types are really more of a state of mind than actual separate "types". Just start using it where char
s are asked for, and you should be OK. You might need an explicit conversion to make the compiler quit whining on occasion, but all that should do is drop any extra bits past 256.
You can do this replacing position:absolute;
by position:fixed;
.
In Intent, you can directly put Uri. You don't need to convert the Uri to string and convert back again to Uri.
Look at this simple approach.
// put uri to intent
intent.setData(imageUri);
And to get Uri back from intent:
// Get Uri from Intent
Uri imageUri=getIntent().getData();
<script>
var url= "http://www.google.com";
window.location = url;
</script>
First create the file you want, with any editor like vi r gedit. And save with. Py extension.In that the first line should be
If you are a intellij IDE user, you can use shortcut key Alt+Enter
and then choose Wrap with Center
and then add textAlign: TextAlign.center
The actual walk through the directories works as you have coded it. If you replace the contents of the inner loop with a simple print
statement you can see that each file is found:
import os
rootdir = 'C:/Users/sid/Desktop/test'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
print os.path.join(subdir, file)
If you still get errors when running the above, please provide the error message.
Updated for Python3
import os
rootdir = 'C:/Users/sid/Desktop/test'
for subdir, dirs, files in os.walk(rootdir):
for file in files:
print(os.path.join(subdir, file))
#define NAME(x) printf("Hello " #x);
main(){
NAME(Ian)
}
//will print: Hello Ian
Use the third party dateutil library:
from dateutil import parser
parser.parse("Aug 28 1999 12:00AM") # datetime.datetime(1999, 8, 28, 0, 0)
It can handle most date formats, including the one you need to parse. It's more convenient than strptime
as it can guess the correct format most of the time.
It's very useful for writing tests, where readability is more important than performance.
You can install it with:
pip install python-dateutil
Another alternative is to use capturing sub-expressions with the regular expression functions regmatches
and regexec
.
# the original example
x <- 'hello stackoverflow'
# grab the substrings
myStrings <- regmatches(x, regexec('(^.)(.*)', x))
This returns the entire string, the first character, and the "popped" result in a list of length 1.
myStrings
[[1]]
[1] "hello stackoverflow" "h" "ello stackoverflow"
which is equivalent to list(c(x, substr(x, 1, 1), substr(x, 2, nchar(x))))
. That is, it contains the super set of the desired elements as well as the full string.
Adding sapply
will allow this method to work for a character vector of length > 1.
# a slightly more interesting example
xx <- c('hello stackoverflow', 'right back', 'at yah')
# grab the substrings
myStrings <- regmatches(x, regexec('(^.)(.*)', xx))
This returns a list with the matched full string as the first element and the matching subexpressions captured by ()
as the following elements. So in the regular expression '(^.)(.*)'
, (^.)
matches the first character and (.*)
matches the remaining characters.
myStrings
[[1]]
[1] "hello stackoverflow" "h" "ello stackoverflow"
[[2]]
[1] "right back" "r" "ight back"
[[3]]
[1] "at yah" "a" "t yah"
Now, we can use the trusty sapply
+ [
method to pull out the desired substrings.
myFirstStrings <- sapply(myStrings, "[", 2)
myFirstStrings
[1] "h" "r" "a"
mySecondStrings <- sapply(myStrings, "[", 3)
mySecondStrings
[1] "ello stackoverflow" "ight back" "t yah"
Now google chrome has introduce new feature. By Using this feature You can edit you code in chrome browse. (Permanent change on code location)
For that Press F12 --> Source Tab -- (right side) --> File System - in that please select your location of code. and then chrome browser will ask you permission and after that code will be sink with green color. and you can modify your code and it will also reflect on you code location (It means it will Permanent change)
Thanks
%3A
and %2F
are URL encoded characters. Use this java code to convert them back into :
and /
String decoded = java.net.URLDecoder.decode(url, "UTF-8");
You probably have allProviders
typed as object[]
as well. And property country
does not exist on object
. If you don't care about typing, you can declare both allProviders
and countryProviders
as Array<any>
:
let countryProviders: Array<any>;
let allProviders: Array<any>;
If you do want static type checking. You can create an interface for the structure and use it:
interface Provider {
region: string,
country: string,
locale: string,
company: string
}
let countryProviders: Array<Provider>;
let allProviders: Array<Provider>;
I've ran into the same problem. The question here is that play-java-jpa artifact (javaJpa key in the build.sbt file) depends on a different version of the spec (version 2.0 -> "org.hibernate.javax.persistence" % "hibernate-jpa-2.0-api" % "1.0.1.Final")
.
When you added hibernate-entitymanager 4.3 this brought the newer spec (2.1) and a different factory provider for the entitymanager. Basically you ended up having both jars in the classpath as transitive dependencies.
Edit your build.sbt file like this and it will temporarily fix you problem until play releases a new version of the jpa plugin for the newer api dependency.
libraryDependencies ++= Seq(
javaJdbc,
javaJpa.exclude("org.hibernate.javax.persistence", "hibernate-jpa-2.0-api"),
"org.hibernate" % "hibernate-entitymanager" % "4.3.0.Final"
)
This is for play 2.2.x
. In previous versions there were some differences in the build files.
In the meantime, a time-window capability was added. See this link.
In [1]: df = DataFrame({'B': range(5)})
In [2]: df.index = [Timestamp('20130101 09:00:00'),
...: Timestamp('20130101 09:00:02'),
...: Timestamp('20130101 09:00:03'),
...: Timestamp('20130101 09:00:05'),
...: Timestamp('20130101 09:00:06')]
In [3]: df
Out[3]:
B
2013-01-01 09:00:00 0
2013-01-01 09:00:02 1
2013-01-01 09:00:03 2
2013-01-01 09:00:05 3
2013-01-01 09:00:06 4
In [4]: df.rolling(2, min_periods=1).sum()
Out[4]:
B
2013-01-01 09:00:00 0.0
2013-01-01 09:00:02 1.0
2013-01-01 09:00:03 3.0
2013-01-01 09:00:05 5.0
2013-01-01 09:00:06 7.0
In [5]: df.rolling('2s', min_periods=1).sum()
Out[5]:
B
2013-01-01 09:00:00 0.0
2013-01-01 09:00:02 1.0
2013-01-01 09:00:03 3.0
2013-01-01 09:00:05 3.0
2013-01-01 09:00:06 7.0
In all versions of MySQL, simply alias the aggregate in the SELECT list, and order by the alias:
SELECT COUNT(id) AS theCount, `Tag` from `images-tags`
GROUP BY `Tag`
ORDER BY theCount DESC
LIMIT 20
Assuming you are using Windows forms, you could allow the user to select a row and in the delete key click event. It is recommended that you allow the user to select 1 row only and not a group of rows (myDataGridView.MultiSelect = false)
Private Sub pbtnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click
If myDataGridView.SelectedRows.Count > 0 Then
'you may want to add a confirmation message, and if the user confirms delete
myDataGridView.Rows.Remove(myDataGridView.SelectedRows(0))
Else
MessageBox.Show("Select 1 row before you hit Delete")
End If
End Sub
Note that this will not delete the row form the database until you perform the delete in the database.
I got this error after upgrading from Visual Studio 2013 to 2015. After a bit of searching and trying various fixes I found the problem can be resolved by removing the following from web.config:
<staticContent>
<mimeMap fileExtension=".less" mimeType="text/css" />
</staticContent >
Apparently staticContent is deprecated now?
Edit 1
This sort of prevented IIS from serving .json files when the program was deployed. If you do this you're supposed to re-add .json (application/json) to the mime types of your site in IIS. Here is some more info: http://www.iis.net/configreference/system.webserver/staticcontent/mimemap
Edit 2
I noticed that in my situation the above edit 1 solution only works temporarily. Once I redeploy the entry gets removed. So, I moved the mimeMap XML into Web.Release.config
. Works fine now.
You have to run 'bibtex':
latex paper.tex
bibtex paper
latex paper.tex
latex paper.tex
dvipdf paper.dvi
You should use partial views. I use the following approach:
Use a view model so you're not passing your domain models to your views:
public class EditPersonViewModel
{
public int Id { get; set; } // this is only used to retrieve record from Db
public string Name { get; set; }
public string Age { get; set; }
}
In your PersonController:
[HttpGet] // this action result returns the partial containing the modal
public ActionResult EditPerson(int id)
{
var viewModel = new EditPersonViewModel();
viewModel.Id = id;
return PartialView("_EditPersonPartial", viewModel);
}
[HttpPost] // this action takes the viewModel from the modal
public ActionResult EditPerson(EditPersonViewModel viewModel)
{
if (ModelState.IsValid)
{
var toUpdate = personRepo.Find(viewModel.Id);
toUpdate.Name = viewModel.Name;
toUpdate.Age = viewModel.Age;
personRepo.InsertOrUpdate(toUpdate);
personRepo.Save();
return View("Index");
}
}
Next create a partial view called _EditPersonPartial
. This contains the modal header, body and footer. It also contains the Ajax form. It's strongly typed and takes in our view model.
@model Namespace.ViewModels.EditPersonViewModel
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Edit group member</h3>
</div>
<div>
@using (Ajax.BeginForm("EditPerson", "Person", FormMethod.Post,
new AjaxOptions
{
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
UpdateTargetId = "list-of-people"
}))
{
@Html.ValidationSummary()
@Html.AntiForgeryToken()
<div class="modal-body">
@Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Name)
@Html.Bootstrap().ControlGroup().TextBoxFor(x => x.Age)
</div>
<div class="modal-footer">
<button class="btn btn-inverse" type="submit">Save</button>
</div>
}
Now somewhere in your application, say another partial _peoplePartial.cshtml etc:
<div>
@foreach(var person in Model.People)
{
<button class="btn btn-primary edit-person" data-id="@person.PersonId">Edit</button>
}
</div>
// this is the modal definition
<div class="modal hide fade in" id="edit-person">
<div id="edit-person-container"></div>
</div>
<script type="text/javascript">
$(document).ready(function () {
$('.edit-person').click(function () {
var url = "/Person/EditPerson"; // the url to the controller
var id = $(this).attr('data-id'); // the id that's given to each button in the list
$.get(url + '/' + id, function (data) {
$('#edit-person-container').html(data);
$('#edit-person').modal('show');
});
});
});
</script>
TLDR:
CREATE TABLE MyTable(
a int NOT NULL
,b smallint NOT NULL index IX_indexName nonclustered
,c smallint NOT NULL
,d smallint NOT NULL
,e smallint NOT NULL
)
Details
As per T-SQL CREATE TABLE documentation, in 2014 the column definition supports defining an index:
<column_definition> ::=
column_name <data_type>
...
[ <column_index> ]
and <column_index> grammar is defined as:
<column_index> ::=
INDEX index_name [ CLUSTERED | NONCLUSTERED ]
[ WITH ( <index_option> [ ,... n ] ) ]
[ ON { partition_scheme_name (column_name )
| filegroup_name
| default
}
]
[ FILESTREAM_ON { filestream_filegroup_name | partition_scheme_name | "NULL" } ]
So a lot of what you can do as a separate statement can be done inline. I noticed include
is not an option in this grammar so some things are not possible.
CREATE TABLE MyTable(
a int NOT NULL
,b smallint NOT NULL index IX_indexName nonclustered
,c smallint NOT NULL
,d smallint NOT NULL
,e smallint NOT NULL
)
You can also have inline indexes defined as another line after columns, but within the create table statement, and this allows multiple columns in the index, but still no include
clause:
< table_index > ::=
{
{
INDEX index_name [ CLUSTERED | NONCLUSTERED ]
(column_name [ ASC | DESC ] [ ,... n ] )
| INDEX index_name CLUSTERED COLUMNSTORE
| INDEX index_name [ NONCLUSTERED ] COLUMNSTORE (column_name [ ,... n ] )
}
[ WITH ( <index_option> [ ,... n ] ) ]
[ ON { partition_scheme_name (column_name )
| filegroup_name
| default
}
]
[ FILESTREAM_ON { filestream_filegroup_name | partition_scheme_name | "NULL" } ]
}
For example here we add an index on both columns c and d:
CREATE TABLE MyTable(
a int NOT NULL
,b smallint NOT NULL index IX_MyTable_b nonclustered
,c smallint NOT NULL
,d smallint NOT NULL
,e smallint NOT NULL
,index IX_MyTable_c_d nonclustered (c,d)
)
More than likely your method declaration is incorrect. Make sure the methods parameter is of type String array (String[]) and not simply String and that you use double quotes around your strings in the array declaration.
private String[] stringArray = {"a","b","c","d","e","f","g","h","t","k","k","k"};
public void myMethod(String[] myArray) {}
Try BeanComparator from Apache Commons.
import org.apache.commons.beanutils.BeanComparator;
BeanComparator fieldComparator = new BeanComparator("fruitName");
Collections.sort(fruits, fieldComparator);
It works like this:
String item = "http://www.youtube.com/embed/";
String ss = "your url";
ss = ss.substring(ss.indexOf("v=") + 2);
item += ss;
DisplayMetrics metrics = getResources().getDisplayMetrics();
int w1 = (int) (metrics.widthPixels / metrics.density), h1 = w1 * 3 / 5;
wv.getSettings().setJavaScriptEnabled(true);
wv.setWebChromeClient(chromeClient);
wv.getSettings().setPluginsEnabled(true);
try {
wv.loadData(
"<html><body><iframe class=\"youtube-player\" type=\"text/html5\" width=\""
+ (w1 - 20)
+ "\" height=\""
+ h1
+ "\" src=\""
+ item
+ "\" frameborder=\"0\"\"allowfullscreen\"></iframe></body></html>",
"text/html5", "utf-8");
} catch (Exception e) {
e.printStackTrace();
}
private WebChromeClient chromeClient = new WebChromeClient() {
@Override
public void onShowCustomView(View view, CustomViewCallback callback) {
super.onShowCustomView(view, callback);
if (view instanceof FrameLayout) {
FrameLayout frame = (FrameLayout) view;
if (frame.getFocusedChild() instanceof VideoView) {
VideoView video = (VideoView) frame.getFocusedChild();
frame.removeView(video);
video.start();
}
}
}
};
Restart IntelliJ and reimport the Project and import it as maven. It should work then. The error occurs because IntelliJ keeps track of module through .iml files so any changes in these files can cause this error. Reimporting the project regenerates the .iml file so generally, it solves the error.
Move the queue to self instead of as an argument to your functions package
and send
Even more simple, pass the $event
object to ng-click
to access the event properties. As an example:
<a ng-click="clickEvent($event)" class="exampleClass" id="exampleID" data="exampleData" href="">Click Me</a>
Within your clickEvent() = function(obj) {}
function you can access the data
value like this:
var dataValue = obj.target.attributes.data.value;
Which would return exampleData
.
Here's a full jsFiddle.
You might want to add:
-webkit-appearance: none;
if you need it looking consistent on Mobile Safari...
To remove borders between cells, while retaining the border around the table, add the attribute rules=none
to the table
tag.
There is no way in HTML to achieve the rendering specified in the last figure of the question. There are various tricky workarounds that are based on using some other markup structure.
In the Windows command prompt you can use "tree /F" to view a tree of the current folder and all descending files & folders.
In File Explorer under Windows 8.1:
tree /f > tree.txt
and press EnterYou now have an editable tree structure file.
This works for versions of Windows from Windows XP to Windows 8.1.
When you say multiple queries do you mean multiple SQL statements as in:
UPDATE table1 SET a=b WHERE c;
UPDATE table2 SET a=b WHERE d;
UPDATE table3 SET a=b WHERE e;
Or multiple query function calls as in:
mySqlQuery(UPDATE table1 SET a=b WHERE c;)
mySqlQuery(UPDATE table2 SET a=b WHERE d;)
mySqlQuery(UPDATE table3 SET a=b WHERE e;)
The former can all be done using a single mySqlQuery call if that is what you wanted to achieve, simply call the mySqlQuery function in the following manner:
mySqlQuery(UPDATE table1 SET a=b WHERE c; UPDATE table2 SET a=b WHERE d; UPDATE table3 SET a=b WHERE e;)
This will execute all three queries with one mySqlQuery() call.
If you want to do this, you need to save it in a variable first. So you don't need to use id to query this element every time.
var el = $("#page_navigation1");
$("#add").click(function(){
el.attr("id","page_navigation1");
});
$("#remove").click(function(){
el.removeAttr("id");
});
What solves my problem: I am using 64 bit Windows 7, so I thought I could install 64 bit Wamp. After I Installed the 32-bit version the error does not appear. So something in the developing process at Wamp went wrong...
Just subtract the string address from what strchr returns:
char *string = "qwerty";
char *e;
int index;
e = strchr(string, 'e');
index = (int)(e - string);
Note that the result is zero based, so in above example it will be 2.
In Angular 7, the following simple example would work (assuming dictionary is in a variable called d
):
my.component.ts:
keys: string[] = []; // declaration of class member 'keys'
// component code ...
this.keys = Object.keys(d);
my.component.html: (will display list of key:value pairs)
<ul *ngFor="let key of keys">
{{key}}: {{d[key]}}
</ul>
Instead of:
DOCS="/cygdrive/c/Users/my\ dir/Documents"
Try:
DOCS="/cygdrive/c/Users/my dir/Documents"
This should work on any POSIX system.
The default in the php.ini for the session.gc_maxlifetime
directive (the "gc" is for garbage collection) is 1440 seconds or 24 minutes. See the Session Runtime Configuation page in the manual:
http://www.php.net/manual/en/session.configuration.php
You can change this constant in the php.ini or .httpd.conf files if you have access to them, or in the local .htaccess file on your web site. To set the timeout to one hour using the .htaccess method, add this line to the .htaccess file in the root directory of the site:
php_value session.gc_maxlifetime "3600"
Be careful if you are on a shared host or if you host more than one site where you have not changed the default. The default session location is the /tmp directory, and the garbage collection routine will run every 24 minutes for these other sites (and wipe out your sessions in the process, regardless of how long they should be kept). See the note on the manual page or this site for a better explanation.
The answer to this is to move your sessions to another directory using session.save_path. This also helps prevent bad guys from hijacking your visitors' sessions from the default /tmp directory.
My code is:
s=["9"]*int(input())
for I in range(len(s)):
while not set(s[I])<=set('01'):s[i]=input(i)
print(bin(sum([int(x,2)for x in s]))[2:])
It is a binary adder but I don't think the range len or the inside can be replaced to make it smaller/better.
from numpy import array
a = array( [1,2,3] )
b = array( [3,2,1] )
print a + b
gives array([4,4,4])
.
Function marr(arr1 As Variant, arr2 As Variant) As Variant
Dim item As Variant
For Each item In arr1
i = i + 1
Next item
For Each item In arr2
i = i + 1
Next item
ReDim MergeData(0 To i)
i = 1
For Each item In arr1
MergeData(i) = item
i = i + 1
Next item
For Each item In arr2
MergeData(i) = item
i = i + 1
Next item
marr = MergeData
End Function
Here's a slghtly different take using javascript's native confirm functionality and a custom Angular directive. It's super flexible and pretty lightweight:
Usage:
<button (hrsAreYouSure) (then)="confirm(arg1)" (else)="cancel(arg2)">
This will execute confirm if user presses Ok on the confirmation dialog, or cancel if they
hit Cancel
</button>
Directive:
import {Directive, ElementRef, EventEmitter, Inject, OnInit, Output} from '@angular/core';
@Directive({
selector: '[hrsAreYouSure]'
})
export class AreYouSureDirective implements OnInit {
@Output() then = new EventEmitter<boolean>();
@Output() else = new EventEmitter<boolean>();
constructor(@Inject(ElementRef) private element: ElementRef) { }
ngOnInit(): void {
const directive = this;
this.element.nativeElement.onclick = function() {
const result = confirm('Are you sure?');
if (result) {
directive.then.emit(true);
} else {
directive.else.emit(true);
}
};
}
}
I was using the following:
from module import Foo
foo_instance = Foo()
but to get rid of circular reference
I did the following and it worked:
import module.foo
foo_instance = foo.Foo()
It depends.
When you commit to sending output to stdout
, you're basically leaving it up to the user to decide where that output should go.
If you use printf(...)
(or the equivalent fprintf(stdout, ...)
), you're sending the output to stdout
, but where that actually ends up can depend on how I invoke your program.
If I launch your program from my console like this, I'll see output on my console:
$ prog
Hello, World! # <-- output is here on my console
However, I might launch the program like this, producing no output on the console:
$ prog > hello.txt
but I would now have a file "hello.txt" with the text "Hello, World!" inside, thanks to the shell's redirection feature.
Who knows – I might even hook up some other device and the output could go there. The point is that when you decide to print to stdout
(e.g. by using printf()
), then you won't exactly know where it will go until you see how the process is launched or used.
Tested on Angular 11. I need an extra object 'typeSelected'. Pay attention I'm not using [(ngValue)] as other answers do :
HTML
<mat-select formControlName="type" [(value)]="typeSelected" [compareWith]="typeComparation">
<mat-option *ngFor="let myType of allSurveysTypes" [value]="myType">
{{myType.title}}
</mat-option>
</mat-select>
CODE
// declaration
typeSelected: SurveyType;
...
// assigning variable 'type' of object 'survey' to 'typeSelected'
this.typeSelected = survey?.type;
...
// function to compare SurveyType objects
typeComparation = ( option, value ) => {
if (option && value) {
return option.id === value.id;
}
}
It opens a popup to select the fields for which getter/setter methods to be generated. Select the fields and click on "Generate" button.
More of a novelty, but it's clever...
Top 10 commands used:
$ history | awk '{print $2}' | awk 'BEGIN {FS="|"}{print $1}' | sort | uniq -c | sort -nr | head
Sample output:
242 git
83 rake
43 cd
33 ss
24 ls
15 rsg
11 cap
10 dig
9 ping
3 vi
Too many overly-complicated answers. Just make a TableData tag that spans how many rows you want it to using rowspan. Then use the right-border for the actual bar.
Example:
<td rowspan="5" style="border-right-color: #000000; border-right-width: thin; border-right-style: solid"> </td>
<td rowspan="5"> </td>
Ensure that the " " in the second line runs the same amount of lines as the first. so that there's proper spacing between both.
This technique has served me rather well with my time in HTML5.
Hope this can help you!
<input type="button" id="left" value="left" />
<input type="button" id="right" value="right" />
<img src="https://www.google.com/images/srpr/logo3w.png" id="image">
<script>
var angle = 0;
$('#left').on('click', function () {
angle -= 90;
$("#image").rotate(angle);
});
$('#right').on('click', function () {
angle += 90;
$("#image").rotate(angle);
});
</script>
It means you're trying to call something that isn't a function
const foo = 'string'
foo() // error
CREATE TABLE car(Id int identity(1,1), PersonId int, CarId int)
INSERT INTO car(PersonId,CarId)
VALUES(1,2),(1,3),(1,2),(2,4)
--SELECT * FROM car
;WITH CTE as(
SELECT ROW_NUMBER() over (PARTITION BY personid,carid order by personid,carid) as rn,Id,PersonID,CarId from car)
DELETE FROM car where Id in(SELECT Id FROM CTE WHERE rn>1)
Finally, I found the solution to my problem.
I looked into the Magento system log file (var/log/system.log). There I saw the exact error.
The error is as below:-
Recoverable Error: Argument 1 passed to Mage_Core_Model_Store::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in YOUR_PATH\app\code\core\Mage\Core\Model\App.php on line 555 and defined in YOUR_PATH\app\code\core\Mage\Core\Model\Store.php on line 285
Recoverable Error: Argument 1 passed to Mage_Core_Model_Store_Group::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in YOUR_PATH\app\code\core\Mage\Core\Model\App.php on line 575 and defined in YOUR_PATH\app\code\core\Mage\Core\Model\Store\Group.php on line 227
Actually, I had this error before. But, error display message like Error: 404 Not Found
was new to me.
The reason for this error is that store_id
and website_id
for admin should be set to 0 (zero). But, when you import database to new server, somehow these values are not set to 0.
Open PhpMyAdmin and run the following query in your database:-
SET FOREIGN_KEY_CHECKS=0;
UPDATE `core_store` SET store_id = 0 WHERE code='admin';
UPDATE `core_store_group` SET group_id = 0 WHERE name='Default';
UPDATE `core_website` SET website_id = 0 WHERE code='admin';
UPDATE `customer_group` SET customer_group_id = 0 WHERE customer_group_code='NOT LOGGED IN';
SET FOREIGN_KEY_CHECKS=1;
I have written about this problem and solution over here:-
Magento: Solution to "Error: 404 Not Found" in Admin Login Page
When you log in to your developer account, you can find a link at the bottom of the download section for Xcode that says "Looking for an older version of Xcode?". In there you can find download links to older versions of Xcode and other developer tools
If you are using Sql Server 2005 you can use table valued functions. You can call these directly and pass paramters, whilst treating them as if they were tables.
For more info check out Table-Valued User-Defined Functions
Clone is broken, so dont use it.
THE CLONE METHOD of the Object class is a somewhat magical method that does what no pure Java method could ever do: It produces an identical copy of its object. It has been present in the primordial Object superclass since the Beta-release days of the Java compiler*; and it, like all ancient magic, requires the appropriate incantation to prevent the spell from unexpectedly backfiring
Prefer a method that copies the object
Foo copyFoo (Foo foo){
Foo f = new Foo();
//for all properties in FOo
f.set(foo.get());
return f;
}
Read more http://adtmag.com/articles/2000/01/18/effective-javaeffective-cloning.aspx
&wmode=opaque
didn't work for me (chrome 10) but &wmode=transparent
cleared the issue right up.
If you don't know the main activity, then the package name can be used to launch the application.
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.package.address");
if (launchIntent != null) {
startActivity(launchIntent);//null pointer check in case package name was not found
}
I needed to load the settings file synchronously, and this was my solution:
export function InitConfig(config: AppConfig) { return () => config.load(); }
import { Injectable } from '@angular/core';
@Injectable()
export class AppConfig {
Settings: ISettings;
constructor() { }
load() {
return new Promise((resolve) => {
this.Settings = this.httpGet('assets/clientsettings.json');
resolve(true);
});
}
httpGet(theUrl): ISettings {
const xmlHttp = new XMLHttpRequest();
xmlHttp.open( 'GET', theUrl, false ); // false for synchronous request
xmlHttp.send( null );
return JSON.parse(xmlHttp.responseText);
}
}
This is then provided as a app_initializer which is loaded before the rest of the application.
app.module.ts
{
provide: APP_INITIALIZER,
useFactory: InitConfig,
deps: [AppConfig],
multi: true
},
If there is a primary key like "id" you have to exclude it for example my php table has: id, col2,col3,col4 columns. id is primary key so if I run this code:
INSERT INTO php (SELECT * FROM php);
I probably get this error:
#1062 - Duplicate entry '1' for key 'PRIMARY'
So here is the solution, I excluded "id" key:
INSERT INTO php ( col2,col3,col4) (SELECT col2,col3,col4 FROM php2);
So my new php table has all php2 table rows anymore.
In C++ copying the object means cloning. There is no any special cloning in the language.
As the standard suggests, after copying you should have 2 identical copies of the same object.
There are 2 types of copying: copy constructor when you create object on a non initialized space and copy operator where you need to release the old state of the object (that is expected to be valid) before setting the new state.
This is due to spring-config.xml is not in classpath.
Add complete path of spring-config.xml to your classpath.
Also write command you execute to run your project. You can check classpath in command.
Reading quickly through the source it seems that you're not far off. The following link should help (I did something similar but for FTP). For a file send from server to client, you start off with a file instance and an array of bytes. You then read the File into the byte array and write the byte array to the OutputStream which corresponds with the InputStream on the client's side.
http://www.rgagnon.com/javadetails/java-0542.html
Edit: Here's a working ultra-minimalistic file sender and receiver. Make sure you understand what the code is doing on both sides.
package filesendtest;
import java.io.*;
import java.net.*;
class TCPServer {
private final static String fileToSend = "C:\\test1.pdf";
public static void main(String args[]) {
while (true) {
ServerSocket welcomeSocket = null;
Socket connectionSocket = null;
BufferedOutputStream outToClient = null;
try {
welcomeSocket = new ServerSocket(3248);
connectionSocket = welcomeSocket.accept();
outToClient = new BufferedOutputStream(connectionSocket.getOutputStream());
} catch (IOException ex) {
// Do exception handling
}
if (outToClient != null) {
File myFile = new File( fileToSend );
byte[] mybytearray = new byte[(int) myFile.length()];
FileInputStream fis = null;
try {
fis = new FileInputStream(myFile);
} catch (FileNotFoundException ex) {
// Do exception handling
}
BufferedInputStream bis = new BufferedInputStream(fis);
try {
bis.read(mybytearray, 0, mybytearray.length);
outToClient.write(mybytearray, 0, mybytearray.length);
outToClient.flush();
outToClient.close();
connectionSocket.close();
// File sent, exit the main method
return;
} catch (IOException ex) {
// Do exception handling
}
}
}
}
}
package filesendtest;
import java.io.*;
import java.io.ByteArrayOutputStream;
import java.net.*;
class TCPClient {
private final static String serverIP = "127.0.0.1";
private final static int serverPort = 3248;
private final static String fileOutput = "C:\\testout.pdf";
public static void main(String args[]) {
byte[] aByte = new byte[1];
int bytesRead;
Socket clientSocket = null;
InputStream is = null;
try {
clientSocket = new Socket( serverIP , serverPort );
is = clientSocket.getInputStream();
} catch (IOException ex) {
// Do exception handling
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (is != null) {
FileOutputStream fos = null;
BufferedOutputStream bos = null;
try {
fos = new FileOutputStream( fileOutput );
bos = new BufferedOutputStream(fos);
bytesRead = is.read(aByte, 0, aByte.length);
do {
baos.write(aByte);
bytesRead = is.read(aByte);
} while (bytesRead != -1);
bos.write(baos.toByteArray());
bos.flush();
bos.close();
clientSocket.close();
} catch (IOException ex) {
// Do exception handling
}
}
}
}
Related
Byte array of unknown length in java
Edit: The following could be used to fingerprint small files before and after transfer (use SHA if you feel it's necessary):
public static String md5String(File file) {
try {
InputStream fin = new FileInputStream(file);
java.security.MessageDigest md5er = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int read;
do {
read = fin.read(buffer);
if (read > 0) {
md5er.update(buffer, 0, read);
}
} while (read != -1);
fin.close();
byte[] digest = md5er.digest();
if (digest == null) {
return null;
}
String strDigest = "0x";
for (int i = 0; i < digest.length; i++) {
strDigest += Integer.toString((digest[i] & 0xff)
+ 0x100, 16).substring(1).toUpperCase();
}
return strDigest;
} catch (Exception e) {
return null;
}
}
Previous answers are correct: adding the line...
Response.AddHeader("Content-Disposition", "inline; filename=[filename]");
...will causing multiple Content-Disposition headers to be sent down to the browser. This happens b/c FileContentResult
internally applies the header if you supply it with a file name. An alternative, and pretty simple, solution is to simply create a subclass of FileContentResult
and override its ExecuteResult()
method. Here's an example that instantiates an instance of the System.Net.Mime.ContentDisposition
class (the same object used in the internal FileContentResult
implementation) and passes it into the new class:
public class FileContentResultWithContentDisposition : FileContentResult
{
private const string ContentDispositionHeaderName = "Content-Disposition";
public FileContentResultWithContentDisposition(byte[] fileContents, string contentType, ContentDisposition contentDisposition)
: base(fileContents, contentType)
{
// check for null or invalid ctor arguments
ContentDisposition = contentDisposition;
}
public ContentDisposition ContentDisposition { get; private set; }
public override void ExecuteResult(ControllerContext context)
{
// check for null or invalid method argument
ContentDisposition.FileName = ContentDisposition.FileName ?? FileDownloadName;
var response = context.HttpContext.Response;
response.ContentType = ContentType;
response.AddHeader(ContentDispositionHeaderName, ContentDisposition.ToString());
WriteFile(response);
}
}
In your Controller
, or in a base Controller
, you can write a simple helper to instantiate a FileContentResultWithContentDisposition
and then call it from your action method, like so:
protected virtual FileContentResult File(byte[] fileContents, string contentType, ContentDisposition contentDisposition)
{
var result = new FileContentResultWithContentDisposition(fileContents, contentType, contentDisposition);
return result;
}
public ActionResult Report()
{
// get a reference to your document or file
// in this example the report exposes properties for
// the byte[] data and content-type of the document
var report = ...
return File(report.Data, report.ContentType, new ContentDisposition {
Inline = true,
FileName = report.FileName
});
}
Now the file will be sent to the browser with the file name you choose and with a content-disposition header of "inline; filename=[filename]".
I hope that helps!
Dont know if this is good to anyone, but search all these dlls:
You find them in C:\Windows\assembly\GAC_MSIL\...
, and then put them in the references of your project.
For each of them say: local copy, and check for 32 or 64 bit solution.
My solution to do this from the GUI:
Create a shortcut to the program you want to run;
Edit the shortcut's properties;
Change the TARGET
field to %COMSPEC% /C "START "" "PROGRAMNAME""
;
Change the RUN
field to minimized.
Ready! See how you like it...
PS: Program parameters can be inserted in between the two final quotation marks; the PROGRAMNAME
string can be either a filename, a relative or an absolute path -- if you put in an absolute path and erase the drive letter and semicolon, then this will work in a thumbdrive no matter what letter the host computer assigns to it... (also, if you place the shortcut in the same folder and precede the program filename in PROGRAMNAME
with the %CD%
variable, paths will always match; same trick can be used in START IN
field).
May be?
result.map(&:attributes)
If you need symbols keys:
result.map { |r| r.attributes.symbolize_keys }
Why not just use the EmailAttribute
?
[Email(ErrorMessage = "Bad email")]
public string Email { get; set; }
Not possible but if you try CTE, this would be the code:
ALTER VIEW [dbo].[VW_PuntosDeControlDeExpediente]
AS
WITH TEMP (RefLocal, IdPuntoControl, Descripcion)
AS
(
SELECT
EX.RefLocal
, PV.IdPuntoControl
, PV.Descripcion
FROM [dbo].[PuntosDeControl] AS PV
INNER JOIN [dbo].[Vertidos] AS VR ON VR.IdVertido = PV.IdVertido
INNER JOIN [dbo].[ExpedientesMF] AS MF ON MF.IdExpedienteMF = VR.IdExpedienteMF
INNER JOIN [dbo].[Expedientes] AS EX ON EX.IdExpediente = MF.IdExpediente
)
SELECT
Q1.[RefLocal]
, [IdPuntoControl] = ( SELECT MAX(IdPuntoControl) FROM TEMP WHERE [RefLocal] = Q1.[RefLocal] AND [Descripcion] = Q1.[Descripcion] )
, Q1.[Descripcion]
FROM TEMP AS Q1
GROUP BY Q1.[RefLocal], Q1.[Descripcion]
GO
float b = (float)Math.ceil(a);
or
float b = (float)Math.round(a);
Depending on whether you meant "round to the nearest whole number" (round) or "round up" (ceil).
Beware of loss of precision in converting a double to a float, but that shouldn't be an issue here.
Why are you jQuery-ifying a vanilla JavaScript array? Use standard JavaScript!
var ary = ['first', 'second', 'third', 'fourth', 'fifth'];
alert(ary[0]);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
You are disabling only on document.ready
and this happens only once when DOM
is ready but you need to disable
in keyup event too when textbox gets empty. Also change $(this).val.length
to $(this).val().length
$(document).ready(function(){
$('.sendButton').attr('disabled',true);
$('#message').keyup(function(){
if($(this).val().length !=0)
$('.sendButton').attr('disabled', false);
else
$('.sendButton').attr('disabled',true);
})
});
Or you can use conditional operator instead of if statement. also use prop instead of attr as attribute is not recommended by jQuery 1.6 and above for disabled, checked etc.
As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. To retrieve and change DOM properties such as the checked, selected, or disabled state of form elements, use the .prop() method, jQuery docs
$(document).ready(function(){
$('.sendButton').prop('disabled',true);
$('#message').keyup(function(){
$('.sendButton').prop('disabled', this.value == "" ? true : false);
})
});