Would like to thank you for some excellent replies. @AR., your a star and it works perfectly. I had noticed last night that the Excel.exe
was not closing; so I did some research and found out about how to release the COM objects. Here is my final code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.IO;
using Excel;
namespace testExcelconsoleApp
{
class Program
{
private String fileLoc = @"C:\temp\test.xls";
static void Main(string[] args)
{
Program p = new Program();
p.createExcel();
}
private void createExcel()
{
Excel.Application excelApp = null;
Excel.Workbook workbook = null;
Excel.Sheets sheets = null;
Excel.Worksheet newSheet = null;
try
{
FileInfo file = new FileInfo(fileLoc);
if (file.Exists)
{
excelApp = new Excel.Application();
workbook = excelApp.Workbooks.Open(fileLoc, 0, false, 5, "", "",
false, XlPlatform.xlWindows, "",
true, false, 0, true, false, false);
sheets = workbook.Sheets;
//check columns exist
foreach (Excel.Worksheet sheet in sheets)
{
Console.WriteLine(sheet.Name);
sheet.Select(Type.Missing);
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
}
newSheet = (Worksheet)sheets.Add(sheets[1], Type.Missing, Type.Missing, Type.Missing);
newSheet.Name = "My New Sheet";
newSheet.Cells[1, 1] = "BOO!";
workbook.Save();
workbook.Close(null, null, null);
excelApp.Quit();
}
}
finally
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(newSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(sheets);
System.Runtime.InteropServices.Marshal.ReleaseComObject(workbook);
System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
newSheet = null;
sheets = null;
workbook = null;
excelApp = null;
GC.Collect();
}
}
}
}
Thank you for all your help.
Add reference > Browse > C: > Windows > assembly > GAC > Microsoft.Office.Interop.Excel > 12.0.0.0_wasd.. > Microsoft.Office.Interop.Excel.dll
Use this One
((Excel.Range)oSheet.Cells[1, 1]).EntireColumn.ColumnWidth = 10;
You could use the ExcelStorage Class of the FileHelpers library, it's very easy and simple... you will need Excel 2000 or later installed on the machine.
The FileHelpers is a free and easy to use .NET library to import/export data from fixed length or delimited records in files, strings or streams.
Reading Datetime value From Excel sheet : Try this will be work.
string sDate = (xlRange.Cells[4, 3] as Excel.Range).Value2.ToString();
double date = double.Parse(sDate);
var dateTime = DateTime.FromOADate(date).ToString("MMMM dd, yyyy");
You could output them to a .csv file and open the file in excel. Is that direct enough?
I have used Excel.dll library which is:
The documentation available over here: https://exceldatareader.codeplex.com/
Strongly recommendable.
I too encountered the same scenario and found out two solutions after googling for several times. Hope this helps.
Way 01:
Before trying to open the file in Excel, find it in Windows' File Explorer. Right-click the file and select Properties. At the bottom of the General tab, click the Unblock button. Once you unblock a file, Windows should remember and Excel should not ask you again. This option is available for some file types, but not others. If you don't have an Unblock button, use Way 2.
Way 02:
This option is better if you usually store your downloaded Excel files in one folder. In Excel, click File » Options » Trust Center » Trust Center Settings » Trusted Locations. Click Add new location. Browse to the folder where you store your Excel files, select Subfolders of this location are also trusted, and click OK.
Hope this help
private bool isDate(Range cell)
{
if (cell.NumberFormat.ToString().Contains("/yy"))
{
return true;
}
return false;
}
isDate(worksheet.Cells[irow, icol])
MS Office Interop is slow and even Microsoft does not recommend Interop usage on server side and cannot be use to import large Excel files. For more details see why not to use OLE Automation from Microsoft point of view.
Instead, you can use any Excel library, like EasyXLS for example. This is a code sample that shows how to read the Excel file:
ExcelDocument workbook = new ExcelDocument();
DataSet ds = workbook.easy_ReadXLSActiveSheet_AsDataSet("excel.xls");
DataTable dataTable = ds.Tables[0];
If your Excel file has multiple sheets or for importing only ranges of cells (for better performances) take a look to more code samples on how to import Excel to DataTable in C# using EasyXLS.
The layout for Switch widget is something like this.
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:gravity="right"
android:text="All"
android:textStyle="bold"
android:textColor="@color/black"
android:textSize="20dp"
android:id="@+id/list_toggle" />
</LinearLayout>
In the Activity class, you can code by two ways. Depends on the use you can code.
First Way
public class ActivityClass extends Activity implements CompoundButton.OnCheckedChangeListener {
Switch list_toggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.return_vehicle);
list_toggle=(Switch)findViewById(R.id.list_toggle);
list_toggle.setOnCheckedChangeListener(this);
}
}
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(isChecked) {
list_toggle.setText("Only Today's"); //To change the text near to switch
Log.d("You are :", "Checked");
}
else {
list_toggle.setText("All List"); //To change the text near to switch
Log.d("You are :", " Not Checked");
}
}
Second way
public class ActivityClass extends Activity {
Switch list_toggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.return_vehicle);
list_toggle=(Switch)findViewById(R.id.list_toggle);
list_toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
list_toggle.setText("Only Today's"); //To change the text near to switch
Log.d("You are :", "Checked");
}
else {
list_toggle.setText("All List"); //To change the text near to switch
Log.d("You are :", " Not Checked");
}
}
});
}
}
Just like with nextSibling and nextElementSibling, just remember that, properties with "element" in their name always returns Element
or null
. Properties without can return any other kind of node.
console.log(document.body.parentNode, "is body's parent node"); // returns <html>
console.log(document.body.parentElement, "is body's parent element"); // returns <html>
var html = document.body.parentElement;
console.log(html.parentNode, "is html's parent node"); // returns document
console.log(html.parentElement, "is html's parent element"); // returns null
in response to mattlant's reply - sharepoint will work well as a version control only if the version control feature is turned on in the document library. in addition be aware that any code that calls other files by relative paths wont work. and finally any links to external files will break when a file is saved in sharepoint.
use this code
SELECT *
FROM paypal_ipn_orders
GROUP BY payer_email
HAVING COUNT( payer_email) >1
Thanks for the above codes! - I tried several options and this was the ticket. I had problems in that preventDefault was preventing scrolling on the ipad - I am now testing for draggable items and it works great so far.
if (event.target.id == 'draggable_item' ) {
event.preventDefault();
}
You can refer below example for getting a comma separated string array from list.
Example:
List<string> testList= new List<string>();
testList.Add("Apple"); // Add string 1
testList.Add("Banana"); // 2
testList.Add("Mango"); // 3
testList.Add("Blue Berry"); // 4
testList.Add("Water Melon"); // 5
string JoinDataString = string.Join(",", testList.ToArray());
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
And then install wget
with brew and also enable openressl
for TLS support
brew install wget --with-libressl
It worked perfectly for me.
It looks like your syntax for unset is invalid, and the lack of reindexing might cause trouble in the future. See: the section on PHP arrays.
The correct syntax is shown above. Also keep in mind array-values for reindexing, so you don't ever index something you previously deleted.
enum Orientations
{
None, North, East, South, West
}
private Orientations? _orientation { get; set; }
public Orientations? Orientation
{
get
{
return _orientation ?? Orientations.None;
}
set
{
_orientation = value;
}
}
If you set the property to null will return Orientations.None on get. The property _orientation is null by default.
I did not found the maven or configure menus but found the following button that solved my problem:
I had same requirement.
I have used the below way to get it.
I had session scoped bean.
@ManagedBean(name="mb")
@SessionScopedpublic
class ManagedBean {
--------
}
I have used the below code in my servlet doPost() method.
ManagedBean mb = (ManagedBean) request.getSession().getAttribute("mb");
it solved my problem.
I had similar problem. Got message in js
Resource interpreted as Document but transferred with MIME type text/csv
But I also got message in chrome console
Mixed Content: The site at 'https://my-site/' was loaded over a secure connection, but the file at 'https://my-site/Download?id=99a50c7b' was redirected through an insecure connection. This file should be served over HTTPS. This download has been blocked
It says here that you need to use an secure connection (but scheme is https in message already, strangely...).
The problem is that href for file downloading builded on server side. And this href used http in my case.
So I changed scheme to https when build href for file downloading.
If you are using ES6 Classes and ControllerAs
syntax, you need to do something slightly different.
See the snippet below and note that vm
is the ControllerAs
value of the parent Controller as used in the parent HTML
myApp.directive('name', function() {
return {
// no scope definition
link : function(scope, element, attrs, ngModel) {
scope.vm.func(...)
This will work for actual paths on the file system if you're not talking the URL string.
var path = document.location.pathname;
var directory = path.substring(path.indexOf('/'), path.lastIndexOf('/'));
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: "AnotherViewController")
self.navigationController?.pushViewController(controller, animated: true)
}
}
import UIKit
class AnotherViewController: UIViewController {
var name : String!
deinit {
print("Deint AnotherViewController")
}
override func viewDidLoad() {
super.viewDidLoad()
print(CFGetRetainCount(self))
/*
When you test please comment out or vice versa
*/
// // Should not use unowned here. Because unowned is used where not deallocated. or gurranted object alive. If you immediate click back button app will crash here. Though there will no retain cycles
// clouser(string: "") { [unowned self] (boolValue) in
// self.name = "some"
// }
//
//
// // There will be a retain cycle. because viewcontroller has a strong refference to this clouser and as well as clouser (self.name) has a strong refferennce to the viewcontroller. Deint AnotherViewController will not print
// clouser(string: "") { (boolValue) in
// self.name = "some"
// }
//
//
// // no retain cycle here. because viewcontroller has a strong refference to this clouser. But clouser (self.name) has a weak refferennce to the viewcontroller. Deint AnotherViewController will print. As we forcefully made viewcontroller weak so its now optional type. migh be nil. and we added a ? (self?)
//
// clouser(string: "") { [weak self] (boolValue) in
// self?.name = "some"
// }
// no retain cycle here. because viewcontroller has a strong refference to this clouser. But clouser nos refference to the viewcontroller. Deint AnotherViewController will print. As we forcefully made viewcontroller weak so its now optional type. migh be nil. and we added a ? (self?)
clouser(string: "") { (boolValue) in
print("some")
print(CFGetRetainCount(self))
}
}
func clouser(string: String, completion: @escaping (Bool) -> ()) {
// some heavy task
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
completion(true)
}
}
}
If you do not sure about
[unowned self]
then use[weak self]
AppDomain.CurrentDomain.BaseDirectory
is probably the most useful for accessing files whose location is relative to the application install directory.
In an ASP.NET application, this will be the application root directory, not the bin subfolder - which is probably what you usually want. In a client application, it will be the directory containing the main executable.
In a VSTO 2005 application, it will be the directory containing the VSTO managed assemblies for your application, not, say, the path to the Excel executable.
The others may return different directories depending on your environment - for example see @Vimvq1987's answer.
CodeBase
is the place where a file was found and can be a URL beginning with http://. In which case Location
will probably be the assembly download cache. CodeBase is not guaranteed to be set for assemblies in the GAC.
UPDATE
These days (.NET Core, .NET Standard 1.3+ or .NET Framework 4.6+) it's better to use AppContext.BaseDirectory
rather than AppDomain.CurrentDomain.BaseDirectory
. Both are equivalent, but multiple AppDomains are no longer supported.
str1 = "Hello"
str2 = "World"
newstr = " ".join((str1, str2))
That joins str1 and str2 with a space as separators. You can also do "".join(str1, str2, ...)
. str.join()
takes an iterable, so you'd have to put the strings in a list or a tuple.
That's about as efficient as it gets for a builtin method.
Even though you can't think of a use of it right now, you can bet there has to be a use for it. Here is an unimaginative sample:
With else
:
a = [1,2,3]
try:
something = a[2]
except:
print "out of bounds"
else:
print something
Without else
:
try:
something = a[2]
except:
print "out of bounds"
if "something" in locals():
print something
Here you have the variable something
defined if no error is thrown. You can remove this outside the try
block, but then it requires some messy detection if a variable is defined.
You can also map the share to a local drive as follows:
net use X: "\\servername\share" /user:morgan password
I ran into similar/same error message. In my case, I did not have the target DOM node which is to render the ReactJS component defined. Ensure the HTML target node is well defined with appropriate "id" or "name", along with other HTML attributes (suitable for your design need)
For Mac:
Quick Text Search: Shift + Cmd + L
All other search (like File Search, Git Search, Java Search etc): Ctrl + H
In addition to Oleiade, see the spec on zero values:
When memory is allocated to store a value, either through a declaration or a call of make or new, and no explicit initialization is provided, the memory is given a default initialization. Each element of such a value is set to the zero value for its type: false for booleans, 0 for integers, 0.0 for floats, "" for strings, and nil for pointers, functions, interfaces, slices, channels, and maps. This initialization is done recursively, so for instance each element of an array of structs will have its fields zeroed if no value is specified.
As you can see, nil
is not the zero value for every type but only for pointers, functions, interfaces, slices, channels and maps. This is the reason why config == nil
is an error and
&config == nil
is not.
To check whether your struct is uninitialized you'd have to check every member for its
respective zero value (e.g. host == ""
, port == 0
, etc.) or have a private field which
is set by an internal initialization method. Example:
type Config struct {
Host string
Port float64
setup bool
}
func NewConfig(host string, port float64) *Config {
return &Config{host, port, true}
}
func (c *Config) Initialized() bool { return c != nil && c.setup }
It is bad practice to perform network operations on the main thread, which is why you are seeing the NetworkOnMainThreadException
. It is prevented by the policy. If you really must do it for testing, put the following in your OnCreate:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Please remember that is is very bad practice to do this, and should ideally move your network code to an AsyncTask
or a Thread
.
Make server output on First of all
SET SERVEROUTPUT on
then
Go to the DBMS Output window (View->DBMS Output)
then Press Ctrl+N for connecting server
<input type="file" @change="onFileChange" class="input upload-input" ref="inputFile"/>
onFileChange(e) {
//upload file and then delete it from input
self.$refs.inputFile.value = ''
}
Assuming that end_date
and start_date
are both of class ActiveSupport::TimeWithZone
in Rails, then you can use:
(end_date.to_date - start_date.to_date).to_i
Lets assume you created a Ubuntu VM on your local machine. It's IP address is 192.168.1.104.
You login into VM, and installed Kubernetes. Then you created a pod where nginx image running on it.
1- If you want to access this nginx pod inside your VM, you will create a ClusterIP bound to that pod for example:
$ kubectl expose deployment nginxapp --name=nginxclusterip --port=80 --target-port=8080
Then on your browser you can type ip address of nginxclusterip with port 80, like:
2- If you want to access this nginx pod from your host machine, you will need to expose your deployment with NodePort. For example:
$ kubectl expose deployment nginxapp --name=nginxnodeport --port=80 --target-port=8080 --type=NodePort
Now from your host machine you can access to nginx like:
In my dashboard they appear as:
Below is a diagram shows basic relationship.
You can use the Apache Commons StringUtils.substring(String str, int start, int end)
static method, which is also null safe.
And here my version of finding N random unique numbers using HashSet. Looks pretty simple, since HashSet can contain only different items. It's interesting - would it be faster then using List or Shuffler?
using System;
using System.Collections.Generic;
namespace ConsoleApplication1
{
class RnDHash
{
static void Main()
{
HashSet<int> rndIndexes = new HashSet<int>();
Random rng = new Random();
int maxNumber;
Console.Write("Please input Max number: ");
maxNumber = int.Parse(Console.ReadLine());
int iter = 0;
while (rndIndexes.Count != maxNumber)
{
int index = rng.Next(maxNumber);
rndIndexes.Add(index);
iter++;
}
Console.WriteLine("Random numbers were found in {0} iterations: ", iter);
foreach (int num in rndIndexes)
{
Console.WriteLine(num);
}
Console.ReadKey();
}
}
}
LINQ defines an extension method that is perfect for solving this exact problem:
using System.Linq;
...
bool has = list.Any(cus => cus.FirstName == "John");
make sure you reference System.Core.dll, that's where LINQ lives.
your validation should be occur before your event suppose you are going to submit your form.
anyway if you want this on onchange, so here is code.
function valid(id)
{
var textVal=document.getElementById(id).value;
if (!textVal.match(/\S/))
{
alert("Field is blank");
return false;
}
else
{
return true;
}
}
In responsive.less, you can comment out the line that imports responsive-1200px-min.less.
// Large desktops
@import "responsive-1200px-min.less";
Like so:
// Large desktops
// @import "responsive-1200px-min.less";
Just a small addition to Jeff Bowman's excellent answer, as I found this question when searching for a solution to one of my own problems:
If a call to a method matches more than one mock's when
trained calls, the order of the when
calls is important, and should be from the most wider to the most specific. Starting from one of Jeff's examples:
when(foo.quux(anyInt(), anyInt())).thenReturn(true);
when(foo.quux(anyInt(), eq(5))).thenReturn(false);
is the order that ensures the (probably) desired result:
foo.quux(3 /*any int*/, 8 /*any other int than 5*/) //returns true
foo.quux(2 /*any int*/, 5) //returns false
If you inverse the when calls then the result would always be true
.
Java Web Start is a good technology for installing Java rich clients off the internet direct to the end user's desktop (whether the OS is Windows, Mac or *nix). It comes complete with desktop integration and automatic updates, among many other goodies.
For more information on JWS, see the JWS info page.
(Tested on Oracle 11g
)
About AS
:
AS
is optional.AS
shouldn't be added, otherwise it's an error.About double quote
:
e.g
-- 'AS' is optional for result column
select (1+1) as result from dual;
select (1+1) result from dual;
-- 'AS' shouldn't be used for table name
select 'hi' from dual d;
-- Adding double quotes for alias name is optional, but valid for both result column & table name,
select (1+1) as "result" from dual;
select (1+1) "result" from dual;
select 'hi' from dual "d";
There is a way to paste an nbsp
- open CharMap and copy character 160. However, in this case I'd probably space it out with padding, like this:
.breadcrumbs a:before { content: '>'; padding-right: .5em; }
You might need to set the breadcrumbs display:inline-block
or something, though.
Don't overuse Vue.component()
, it registers components globally. You can create file, name it MyTask.vue, export there Vue object
https://vuejs.org/v2/guide/single-file-components.html
and then import in your main file, and don't forget to register it:
new Vue({
...
components: { myTask }
...
})
On Bootstrap 4 you can use:
<p class="font-weight-bold">Bold text.</p>
<p class="font-weight-normal">Normal weight text.</p>
<p class="font-weight-light">Light weight text.</p>
In Typescript 3.5+:
interface TypographyProps {
variant: string
fontSize: number
}
type TypographyPropsMinusVariant = Omit<TypographyProps, "variant">
The verbose
configuration option might allow you to see what you want. There is an example in the documentation.
NOTE: Read the comments below: The verbose config options doesn't seem to be available anymore.
Just try this.
<asp:TextBox ID="tb" onkeypress="javascript:return false;" width="50px" runat="server"></asp:TextBox>
This won't allow any characters to be entered inside the TextBox.
In Python 3.1+ you can specify multiple context expressions, and they will be processed as if multiple with
statements were nested:
with A() as a, B() as b:
suite
is equivalent to
with A() as a:
with B() as b:
suite
This also means that you can use the alias from the first expression in the second (useful when working with db connections/cursors):
with get_conn() as conn, conn.cursor() as cursor:
cursor.execute(sql)
Use select setval('payments_id_seq', 21, true);
setval
contains 3 parameters:
sequence_name
nextval
The use of true or false in 3rd parameter of setval is as follows:
SELECT setval('payments_id_seq', 21); // Next nextval will return 22
SELECT setval('payments_id_seq', 21, true); // Same as above
SELECT setval('payments_id_seq', 21, false); // Next nextval will return 21
The better way to avoid hard-coding of sequence name, next sequence value and to handle empty column table correctly, you can use the below way:
SELECT setval(pg_get_serial_sequence('table_name', 'id'), coalesce(max(id), 0)+1 , false) FROM table_name;
where table_name
is the name of the table, id
is the primary key
of the table
use
sudo pip install virtualenv
You have a permission denied error. This states your current user does not have the root permissions.So run the command as a super user.
C++ has no specific feature to do that. However, if you use a std::vector instead of an array (as you probably should do) then you can specify a value to initialise the vector with.
std::vector <char> v( 100, 42 );
creates a vector of size 100 with all values initialised to 42.
Try this:
umount -f <absolute pathname to the mount point>
Example:
umount -f /Users/plummie/Documents/stanford
If that doesn't work, try the same command as root:
sudo umount -f ...
if ( getActivity().getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH)) {
CameraManager cameraManager=(CameraManager) getActivity().getSystemService(Context.CAMERA_SERVICE);
try {
String cameraId = cameraManager.getCameraIdList()[0];
cameraManager.setTorchMode(cameraId,true);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
Ok. I found a program buried deep in other files from the beginning of the year that does what I want. I can't really comment on the suggestions offered because I'm not an experienced spim or low level programmer.Here it is:
.text
.globl __start
__start:
la $a0,str1 #Load and print string asking for string
li $v0,4
syscall
li $v0,8 #take in input
la $a0, buffer #load byte space into address
li $a1, 20 # allot the byte space for string
move $t0,$a0 #save string to t0
syscall
la $a0,str2 #load and print "you wrote" string
li $v0,4
syscall
la $a0, buffer #reload byte space to primary address
move $a0,$t0 # primary address = t0 address (load pointer)
li $v0,4 # print string
syscall
li $v0,10 #end program
syscall
.data
buffer: .space 20
str1: .asciiz "Enter string(max 20 chars): "
str2: .asciiz "You wrote:\n"
###############################
#Output:
#Enter string(max 20 chars): qwerty 123
#You wrote:
#qwerty 123
#Enter string(max 20 chars): new world oreddeYou wrote:
# new world oredde //lol special character
###############################
I think it is good to categorize relations like this
When to use eager loading
When to use lazy loading
Note: like Transcendent said there may be disposal problem with lazy loading.
You could also just use regular expressions to accomplish a slightly simpler job if this is enough for you (e.g. as seen in [1]).
They are build in into javascript so you can use them without any libraries.
function isValidDate(dateString) {
var regEx = /^\d{4}-\d{2}-\d{2}$/;
return dateString.match(regEx) != null;
}
would be a function to check if the given string is four numbers - two numbers - two numbers (almost yyyy-mm-dd). But you can do even more with more complex expressions, e.g. check [2].
isValidDate("23-03-2012") // false
isValidDate("1987-12-24") // true
isValidDate("22-03-1981") // false
isValidDate("0000-00-00") // true
You haven't provided enough context to provide an accurate answer (i.e. how do you want to handle identical keys in multiple dicts?)
One answer is to iterate the list, and attempt to get 'd'
mylist = [{'a': 1, 'b': 2}, {'c': 3, 'd': 4}, {'e': 5, 'f': 6}]
myvalues = [i['d'] for i in mylist if 'd' in i]
Another answer is to access the dict directly (by list index), though you have to know that the key is present
mylist[1]['d']
Go to run as and choose Run Configurations
-> Common
and in the Standard Input and Output you can choose a File also.
In angularjs you can create the UI part, service, Directives and all the part of angularjs which represent the UI. It is nice technology to work on.
As any one who new into this technology and want to authenticate the "User" then i suggest to do it with the power of c# web api. for that you can use the OAuth specification which will help you to built a strong security mechanism to authenticate the user. once you build the WebApi with OAuth you need to call that api for token:
var _login = function (loginData) {_x000D_
_x000D_
var data = "grant_type=password&username=" + loginData.userName + "&password=" + loginData.password;_x000D_
_x000D_
var deferred = $q.defer();_x000D_
_x000D_
$http.post(serviceBase + 'token', data, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }).success(function (response) {_x000D_
_x000D_
localStorageService.set('authorizationData', { token: response.access_token, userName: loginData.userName });_x000D_
_x000D_
_authentication.isAuth = true;_x000D_
_authentication.userName = loginData.userName;_x000D_
_x000D_
deferred.resolve(response);_x000D_
_x000D_
}).error(function (err, status) {_x000D_
_logOut();_x000D_
deferred.reject(err);_x000D_
});_x000D_
_x000D_
return deferred.promise;_x000D_
_x000D_
};_x000D_
_x000D_
and once you get the token then you request the resources from angularjs with the help of Token and access the resource which kept secure in web Api with OAuth specification.
Please have a look into the below article for more help:-
With:
global index_add_counter
You are not defining, just declaring so it's like saying there is a global index_add_counter
variable elsewhere, and not create a global called index_add_counter
. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global
keyword and initialize your variable:
index_add_counter = 0
Now you can import it with:
from app import index_add_counter
The construction:
global index_add_counter
is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:
index_add_counter = 0
def test():
global index_add_counter # means: in this scope, use the global name
print(index_add_counter)
You can accomplish what you want with either:
docker run -t -d <image-name>
or
docker run -i -d <image-name>
or
docker run -it -d <image-name>
The command parameter as suggested by other answers (i.e. tail -f /dev/null) is completely optional, and is NOT required to get your container to stay running in the background.
Also note the Docker documentation suggests that combining -i and -t options will cause it to behave like a shell.
See:
Using Node.js
sync mode:
var fs = require("fs");
var text = fs.readFileSync("./mytext.txt");
var textByLine = text.split("\n")
async mode:
var fs = require("fs");
fs.readFile("./mytext.txt", function(text){
var textByLine = text.split("\n")
});
UPDATE
As of at least Node 6, readFileSync
returns a Buffer
, so it must first be converted to a string in order for split
to work:
var text = fs.readFileSync("./mytext.txt").toString('utf-8');
Or
var text = fs.readFileSync("./mytext.txt", "utf-8");
in the first you don't define the type that will be held and linked within your arraylist construct
this is the preferred method to do so, you define the type of list and the ide will handle the rest
in the third one you will better just define List for shorter code
If you don't want to assign identifier to the hidden field; you can use name or class with selector like:
$('input[name=hiddenfieldname]').val();
or with assigned class:
$('input.hiddenfieldclass').val();
In Swift 3.x, you can set highlighted image when button is selected in the following way:
// Normal state
button.setImage(UIImage(named: "normalImage"), for: .normal)
// Highlighted state (before button is selected)
button.setImage(UIImage(named: "pressedImage"), for: .highlighted)
// Selected state
button.setImage(UIImage(named: "selectedImage"), for: .selected)
// Highlighted state (after button is selected)
button.setImage(UIImage(named: "pressedAfterBeingSelectedImage"),
for: UIControlState.selected.union(.highlighted))
"Just set the MaxSelectionCount
to 1 so that users cannot select more than one day. Then in the SelectionRange.Start.ToString()
. There is nothing available to show the selection of only one day." - Justin Etheredge
From here.
The problem:
java.lang.ClassNotFoundException: org.glassfish.jersey.servlet.ServletContainer
indicates that you try to use the Jersey 2.x servlet, but you are supplying the Jersey 1.x libs.
For Jersey 1.x you have to do it like this:
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>
com.sun.jersey.spi.container.servlet.ServletContainer
</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>sample.hello.resources</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/rest/*</url-pattern>
</servlet-mapping>
For more information check the Jersey 1.x documentation.
If you instead want to use Jersey 2.x then you'll have to supply the Jersey 2.x libs. In a maven based project you can use the following:
<dependency>
<groupId>org.glassfish.jersey.containers</groupId>
<artifactId>jersey-container-servlet</artifactId>
<version>2.xx</version>
</dependency>
<!-- if you are using Jersey client specific features without the server side -->
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.xx</version>
</dependency>
For Jersey 2.x you don't need to setup anything in your web.xml
, it is sufficient to supply a class similar to this:
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Application;
@ApplicationPath("rest")
public class ApplicationConfig extends Application {
}
For more information, check the Jersey documentation.
See also:
I have to make an application which shows the Contact no of the SIM card that is being used in the cell. For that I need to use Telephony Manager class. Can i get details on its usage?
Yes, You have to use Telephony Manager;If at all you not found the contact no. of user; You can get Sim Serial Number of Sim Card and Imei No. of Android Device by using the same Telephony Manager Class...
Add permission:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Import:
import android.telephony.TelephonyManager;
Use the below code:
TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
// get IMEI
imei = tm.getDeviceId();
// get SimSerialNumber
simSerialNumber = tm.getSimSerialNumber();
I am doing it like this:
let lastActionTaken = new Date().getTime();
function checkLastAction() {
let now = new Date().getTime();
if (now - lastActionTaken > 1000 * 60 * 60) window.location.reload();
else lastActionTaken = now;
}
window.addEventListener("mousemove", checkLastAction);
window.addEventListener("touchstart", checkLastAction);
window.addEventListener("keydown", checkLastAction);
This will reload the page as soon as the user moves their mouse, hits a key or touches a touchscreen if it has been inactive for 1 hour. Also, this takes care of the focus
as well, so if a user is moving their mouse in a different program and then come back to this window
it will reload, which is good because the point is to not have old data being shown.
You can use Trim
if you want to remove from start and end.
string stringWithoutNewLine = "\n\nHello\n\n".Trim();
Define a class like this :
public class myclass {
string id ;
string title ;
string content;
}
public class program {
public void Main () {
List<myclass> objlist = new List<myclass> () ;
foreach (var value in objlist) {
TextBox1.Text = value.id ;
TextBox2.Text= value.title;
TextBox3.Text= value.content ;
}
}
}
I tried to draw a sketch and you can improve it in many ways. Instead of defining class "myclass", you can define struct.
How can I convert tabs to spaces in every file of a directory (possibly recursively)?
This is usually not what you want.
Do you want to do this for png images? PDF files? The .git directory? Your
Makefile
(which requires tabs)? A 5GB SQL dump?
You could, in theory, pass a whole lot of exlude options to find
or whatever
else you're using; but this is fragile, and will break as soon as you add other
binary files.
What you want, is at least:
expand
does this, sed
doesn't).As far as I know, there is no "standard" Unix utility that can do this, and it's not very easy to do with a shell one-liner, so a script is needed.
A while ago I created a little script called
sanitize_files which does exactly
that. It also fixes some other common stuff like replacing \r\n
with \n
,
adding a trailing \n
, etc.
You can find a simplified script without the extra features and command-line arguments below, but I recommend you use the above script as it's more likely to receive bugfixes and other updated than this post.
I would also like to point out, in response to some of the other answers here,
that using shell globbing is not a robust way of doing this, because sooner
or later you'll end up with more files than will fit in ARG_MAX
(on modern
Linux systems it's 128k, which may seem a lot, but sooner or later it's not
enough).
#!/usr/bin/env python
#
# http://code.arp242.net/sanitize_files
#
import os, re, sys
def is_binary(data):
return data.find(b'\000') >= 0
def should_ignore(path):
keep = [
# VCS systems
'.git/', '.hg/' '.svn/' 'CVS/',
# These files have significant whitespace/tabs, and cannot be edited
# safely
# TODO: there are probably more of these files..
'Makefile', 'BSDmakefile', 'GNUmakefile', 'Gemfile.lock'
]
for k in keep:
if '/%s' % k in path:
return True
return False
def run(files):
indent_find = b'\t'
indent_replace = b' ' * indent_width
for f in files:
if should_ignore(f):
print('Ignoring %s' % f)
continue
try:
size = os.stat(f).st_size
# Unresolvable symlink, just ignore those
except FileNotFoundError as exc:
print('%s is unresolvable, skipping (%s)' % (f, exc))
continue
if size == 0: continue
if size > 1024 ** 2:
print("Skipping `%s' because it's over 1MiB" % f)
continue
try:
data = open(f, 'rb').read()
except (OSError, PermissionError) as exc:
print("Error: Unable to read `%s': %s" % (f, exc))
continue
if is_binary(data):
print("Skipping `%s' because it looks binary" % f)
continue
data = data.split(b'\n')
fixed_indent = False
for i, line in enumerate(data):
# Fix indentation
repl_count = 0
while line.startswith(indent_find):
fixed_indent = True
repl_count += 1
line = line.replace(indent_find, b'', 1)
if repl_count > 0:
line = indent_replace * repl_count + line
data = list(filter(lambda x: x is not None, data))
try:
open(f, 'wb').write(b'\n'.join(data))
except (OSError, PermissionError) as exc:
print("Error: Unable to write to `%s': %s" % (f, exc))
if __name__ == '__main__':
allfiles = []
for root, dirs, files in os.walk(os.getcwd()):
for f in files:
p = '%s/%s' % (root, f)
if do_add:
allfiles.append(p)
run(allfiles)
return true not work
return false working
found = false;
query = "foo";
$('.items').each(function()
{
if($(this).text() == query)
{
found = true;
return false;
}
});
Try switching your JVM to eclipse openj9. Its gonna use way less memory. I swapped it and its using 600Mb constantly.
I like to check if it isset and if it's empty in a ternary operator.
// POST variable check
$userID = (isset( $_POST['userID'] ) && !empty( $_POST['userID'] )) ? $_POST['userID'] : null;
$line = (isset( $_POST['line'] ) && !empty( $_POST['line'] )) ? $_POST['line'] : null;
$message = (isset( $_POST['message'] ) && !empty( $_POST['message'] )) ? $_POST['message'] : null;
$source = (isset( $_POST['source'] ) && !empty( $_POST['source'] )) ? $_POST['source'] : null;
$version = (isset( $_POST['version'] ) && !empty( $_POST['version'] )) ? $_POST['version'] : null;
$release = (isset( $_POST['release'] ) && !empty( $_POST['release'] )) ? $_POST['release'] : null;
ChangeDetectorRef.detectChanges() - similar to $scope.$digest() -- i.e., check only this component and its children
You could do something like this:
i={'foo':'bar', 'baz':'huh?'}
keys=i.keys() #in python 3, you'll need `list(i.keys())`
values=i.values()
print keys[values.index("bar")] #'foo'
However, any time you change your dictionary, you'll need to update your keys,values because dictionaries are not ordered in versions of Python prior to 3.7. In these versions, any time you insert a new key/value pair, the order you thought you had goes away and is replaced by a new (more or less random) order. Therefore, asking for the index in a dictionary doesn't make sense.
As of Python 3.6, for the CPython implementation of Python, dictionaries remember the order of items inserted. As of Python 3.7+ dictionaries are ordered by order of insertion.
Also note that what you're asking is probably not what you actually want. There is no guarantee that the inverse mapping in a dictionary is unique. In other words, you could have the following dictionary:
d={'i':1, 'j':1}
In that case, it is impossible to know whether you want i
or j
and in fact no answer here will be able to tell you which ('i'
or 'j'
) will be picked (again, because dictionaries are unordered). What do you want to happen in that situation? You could get a list of acceptable keys ... but I'm guessing your fundamental understanding of dictionaries isn't quite right.
Using javascript seems to be unnecessary if you choose CSS3.
By using :before
selector, you can do this in two lines of CSS. (no script involved).
Another advantage of this approach is that it does not rely on <label>
tag and works even it is missing.
Note: in browsers without CSS3 support, checkboxes will look normal. (backward compatible).
input[type=checkbox]:before { content:""; display:inline-block; width:12px; height:12px; background:red; }
input[type=checkbox]:checked:before { background:green; }?
You can see a demo here: http://jsfiddle.net/hqZt6/1/
and this one with images:
For joins, I strongly prefer query-syntax for all the details that are happily hidden (not the least of which are the transparent identifiers involved with the intermediate projections along the way that are apparent in the dot-syntax equivalent). However, you asked regarding Lambdas which I think you have everything you need - you just need to put it all together.
var categorizedProducts = product
.Join(productcategory, p => p.Id, pc => pc.ProdId, (p, pc) => new { p, pc })
.Join(category, ppc => ppc.pc.CatId, c => c.Id, (ppc, c) => new { ppc, c })
.Select(m => new {
ProdId = m.ppc.p.Id, // or m.ppc.pc.ProdId
CatId = m.c.CatId
// other assignments
});
If you need to, you can save the join into a local variable and reuse it later, however lacking other details to the contrary, I see no reason to introduce the local variable.
Also, you could throw the Select
into the last lambda of the second Join
(again, provided there are no other operations that depend on the join results) which would give:
var categorizedProducts = product
.Join(productcategory, p => p.Id, pc => pc.ProdId, (p, pc) => new { p, pc })
.Join(category, ppc => ppc.pc.CatId, c => c.Id, (ppc, c) => new {
ProdId = ppc.p.Id, // or ppc.pc.ProdId
CatId = c.CatId
// other assignments
});
...and making a last attempt to sell you on query syntax, this would look like this:
var categorizedProducts =
from p in product
join pc in productcategory on p.Id equals pc.ProdId
join c in category on pc.CatId equals c.Id
select new {
ProdId = p.Id, // or pc.ProdId
CatId = c.CatId
// other assignments
};
Your hands may be tied on whether query-syntax is available. I know some shops have such mandates - often based on the notion that query-syntax is somewhat more limited than dot-syntax. There are other reasons, like "why should I learn a second syntax if I can do everything and more in dot-syntax?" As this last part shows - there are details that query-syntax hides that can make it well worth embracing with the improvement to readability it brings: all those intermediate projections and identifiers you have to cook-up are happily not front-and-center-stage in the query-syntax version - they are background fluff. Off my soap-box now - anyhow, thanks for the question. :)
Converting to another palette is a far superior way to do this. There's a reason they do that: other palettes are 'perceptual' - that is, they put similar seeming colors close together, and adjusting one variable changes the color in a predictable manner. None of that is true for RGB, where there's no obvious relationship between colors that "go well together".
You need to define static variables in a translation unit, unless they are of integral types.
In your header:
private:
static const char *SOMETHING;
static const int MyInt = 8; // would be ok
In the .cpp file:
const char *YourClass::SOMETHING = "something";
C++ standard, 9.4.2/4:
If a static data member is of const integral or const enumeration type, its declaration in the class definition can specify a constant-initializer which shall be an integral constant expression. In that case, the member can appear in integral constant expressions within its scope. The member shall still be defined in a namespace scope if it is used in the program and the namespace scope definition shall not contain an initializer.
@Html.EditorFor(x => x.Remember)
Will generate:
<input id="Remember" type="checkbox" value="true" name="Remember" />
<input type="hidden" value="false" name="Remember" />
How does it work:
checkbox
remains unchecked, the form submits only the hidden
value (false)true
for the model's bool
property<input id="Remember" name="Remember" type="checkbox" value="@Model.Remember" />
This will always send the default value, if checked.
This error can occur for lots of reasons, and the last time, I solved it by modifying the Reference.svcmap
file, and changing how the WSDL file is referenced.
Throwing exception:
<MetadataSource Address="C:\Users\Me\Repo\Service.wsdl" Protocol="file" SourceId="1" />
<MetadataFile FileName="Service.wsdl" ... SourceUrl="file:///C:/Users/Me/Repo/Service.wsdl" />
Working fine:
<MetadataSource Address="https://server.domain/path/Service.wsdl" Protocol="http" SourceId="1" />
<MetadataFile FileName="Service.wsdl" ... SourceUrl="https://server.domain/path/Service.wsdl" />
This seems weird, but I have reproduced it. This was in a console application on .NET 4.5 and 4.7, as well as a .NET WebAPI site on 4.7.
It’s about time someone provides the modern answer. The modern solution uses java.time, the modern Java date and time API. The classes SimpleDateFormat
and Date
used in the question and in a couple of the other answers are poorly designed and long outdated, the former in particular notoriously troublesome. TimeZone
is poorly designed to. I recommend you avoid those.
ZoneId utc = ZoneId.of("Etc/UTC");
DateTimeFormatter targetFormatter = DateTimeFormatter.ofPattern(
"MM/dd/yyyy hh:mm:ss a zzz", Locale.ENGLISH);
String itsAlarmDttm = "2013-10-22T01:37:56";
ZonedDateTime utcDateTime = LocalDateTime.parse(itsAlarmDttm)
.atZone(ZoneId.systemDefault())
.withZoneSameInstant(utc);
String formatterUtcDateTime = utcDateTime.format(targetFormatter);
System.out.println(formatterUtcDateTime);
When running in my time zone, Europe/Copenhagen, the output is:
10/21/2013 11:37:56 PM UTC
I have assumed that the string you got was in the default time zone of your JVM, a fragile assumption since that default setting can be changed at any time from another part of your program or another programming running in the same JVM. If you can, instead specify time zone explicitly, for example ZoneId.of("Europe/Podgorica")
or ZoneId.of("Asia/Kolkata")
.
I am exploiting the fact that you string is in ISO 8601 format, the format the the modern classes parse as their default, that is, without any explicit formatter.
I am using a ZonedDateTime
for the result date-time because it allows us to format it with UTC
in the formatted string to eliminate any and all doubt. For other purposes one would typically have wanted an OffsetDateTime
or an Instant
instead.
If you're trying to insert in to last_accessed_on
, which is a DateTime2
, then your issue is with the fact that you are converting it to a varchar
in a format that SQL doesn't understand.
If you modify your code to this, it should work, note the format of your date has been changed to: YYYY-MM-DD hh:mm:ss:
UPDATE student_queues
SET Deleted=0,
last_accessed_by='raja',
last_accessed_on=CONVERT(datetime2,'2014-07-23 09:37:00')
WHERE std_id IN ('2144-384-11564') AND reject_details='REJECT'
Or if you want to use CAST
, replace with:
CAST('2014-07-23 09:37:00.000' AS datetime2)
This is using the SQL ISO Date Format.
Even though you may have a head appending it may not work in all browsers. This was the only method I found to work consistently.
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
document.write('<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"><\/script>');
}
</script>
First, ensure that your version of Eclipse and JDK match, either both 64-bit or both 32-bit (you can't mix-and-match 32-bit with 64-bit).
Second, the -vm argument in eclipse.ini
should point to the java executable. See
http://wiki.eclipse.org/Eclipse.ini for examples.
If you're unsure of what version (64-bit or 32-bit) of Eclipse you have installed, you can determine that a few different ways. See How to find out if an installed Eclipse is 32 or 64 bit version?
The question didn't ask which is fastest, but to add to the sed answer, -n '1p' is badly performing as the pattern space is still scanned on large files. Out of curiosity I found that 'head' wins over sed narrowly:
# best:
head -n1 $bigfile >/dev/null
# a bit slower than head (I saw about 10% difference):
sed '1q' $bigfile >/dev/null
# VERY slow:
sed -n '1p' $bigfile >/dev/null
A compiler is a special program that processes statements written in a particular programming language and turns them into machine language or "code" that a computer's processor uses
SQL stands for Structured Query Language, and is the basis for which all Relational Database Management Systems allow the user to add, remove, update, or select records. Things like MySQ are the actual Management Systems which allow you to store and retrieve your data, whereas SQL is the actual language to do so.
The basic SQL is somewhat universal - Selects usually look the same, Inserts, Updates, Deletes, etc. Once you get beyond the basics, the commands and abilities of your individual Databases vary, and this is where you get people who are Oracle experts, MySQL, SQL Server, etc.
Basically, MySQL is one of many books holding everything, and SQL is how you go about reading that book.
You can just use the error function that's built in to the math library, as stated on their website.
In angular (or any other framework), you can load using http get I use it something like this:
this.http.get(<path_to_your_json_file))
.success((data) => console.log(data));
Hope this helps.
The array is being re-indexed when you do a .splice()
, which means you'll skip over an index when one is removed, and your cached .length
is obsolete.
To fix it, you'd either need to decrement i
after a .splice()
, or simply iterate in reverse...
var i = Auction.auctions.length
while (i--) {
...
if (...) {
Auction.auctions.splice(i, 1);
}
}
This way the re-indexing doesn't affect the next item in the iteration, since the indexing affects only the items from the current point to the end of the Array, and the next item in the iteration is lower than the current point.
Anybody facing problemn while creating jniLibs cpp is shown ..just add ndk ..
Good solutions explained pretty well here. But Here is one more.
Create your own CustomContextWrapper
class extending ContextWrapper
and use it to change Locale setting for the complete application.
Here is a GIST with usage.
And then call the CustomContextWrapper
with saved locale identifier e.g. 'hi'
for Hindi language in activity lifecycle method attachBaseContext
. Usage here:
@Override
protected void attachBaseContext(Context newBase) {
// fetch from shared preference also save the same when applying. Default here is en = English
String language = MyPreferenceUtil.getInstance().getString("saved_locale", "en");
super.attachBaseContext(MyContextWrapper.wrap(newBase, language));
}
While getting the permanent access token I followed above 5 steps as Donut mentioned. However in the 5th step while generating permanent access token its returning the long lived access token(Which is valid for 2 months) not permanent access token(which never expires). what I noticed is the current version of Graph API is V2.5. If you trying to get the permanent access token with V2.5 its giving long lived access token.Try to make API call with V2.2(if you are not able to change version in the graph api explorer,hit the API call https://graph.facebook.com/v2.2/{account_id}/accounts?access_token={long_lived_access_token} in the new tab with V2.2) then you will get the permanent access token(Which never expires)
There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :
Option Explicit
DIM fso
Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists("C:\Program Files\conf")) Then
WScript.Echo("File exists!")
WScript.Quit()
Else
WScript.Echo("File does not exist!")
End If
WScript.Quit()
This gives me the best result:
Intent intent;
if (android.os.Build.MANUFACTURER.equalsIgnoreCase("samsung")) {
intent = new Intent("com.sec.android.app.myfiles.PICK_DATA");
intent.putExtra("CONTENT_TYPE", "*/*");
intent.addCategory(Intent.CATEGORY_DEFAULT);
} else {
String[] mimeTypes =
{"application/msword", "application/vnd.openxmlformats-officedocument.wordprocessingml.document", // .doc & .docx
"application/vnd.ms-powerpoint", "application/vnd.openxmlformats-officedocument.presentationml.presentation", // .ppt & .pptx
"application/vnd.ms-excel", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", // .xls & .xlsx
"text/plain",
"application/pdf",
"application/zip", "application/vnd.android.package-archive"};
intent = new Intent(Intent.ACTION_GET_CONTENT); // or ACTION_OPEN_DOCUMENT
intent.setType("*/*");
intent.putExtra(Intent.EXTRA_MIME_TYPES, mimeTypes);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
}
Try including this decorator on your dispatch code
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt
@method_decorator(csrf_exempt, name='dispatch')
def dispatch(self, request, *args, **kwargs):
return super(LessonUploadWorkView,self).dispatch(request,*args,**kwargs)
Other answers may not work if your key contains special chars - Guide$CLASSMETADATA][1]
for instance. Wrapping each key into quotes will ensure they get properly deleted:
redis-cli --scan --pattern sf_* | awk '{print $1}' | sed "s/^/'/;s/$/'/" | xargs redis-cli del
I would advise against using """
for multi line comments!
Here is a simple example to highlight what might be considered an unexpected behavior:
print('{}\n{}'.format(
'I am a string',
"""
Some people consider me a
multi-line comment, but
"""
'clearly I am also a string'
)
)
Now have a look at the output:
I am a string
Some people consider me a
multi-line comment, but
clearly I am also a string
The multi line string was not treated as comment, but it was concatenated with 'clearly I'm also a string'
to form a single string.
If you want to comment multiple lines do so according to PEP 8 guidelines:
print('{}\n{}'.format(
'I am a string',
# Some people consider me a
# multi-line comment, but
'clearly I am also a string'
)
)
Output:
I am a string
clearly I am also a string
From v2.0 many users are using path, but we can use either path or url. For example in django 2.1.1 mapping to functions through url can be done as follows
from django.contrib import admin
from django.urls import path
from django.contrib.auth import login
from posts.views import post_home
from django.conf.urls import url
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^posts/$', post_home, name='post_home'),
]
where posts is an application & post_home is a function in views.py
Your error appears when you have modified a file and the branch that you are switching to has changes for this file too (from latest merge point).
Your options, as I see it, are - commit, and then amend this commit with extra changes (you can modify commits in git, as long as they're not push
ed); or - use stash:
git stash save your-file-name
git checkout master
# do whatever you had to do with master
git checkout staging
git stash pop
git stash save
will create stash that contains your changes, but it isn't associated with any commit or even branch. git stash pop
will apply latest stash entry to your current branch, restoring saved changes and removing it from stash.
If you want the correct answer according to the latest Unicode standard, you should use icu4j.
UCharacter.toTitleCase(Locale.US, "hello world", null, 0);
Note that this is locale sensitive.
For a minimum API level of 15, you'd want to use AppCompatActivity
. So for example, your MainActivity
would look like this:
public class MainActivity extends AppCompatActivity {
....
....
}
To use the AppCompatActivity
, make sure you have the Google Support Library downloaded (you can check this in your Tools -> Android -> SDK manager). Then just include the gradle dependency in your app's gradle.build file:
compile 'com.android.support:appcompat-v7:22:2.0'
You can use this AppCompat
as your main Activity
, which can then be used to launch Fragments or other Activities (this depends on what kind of app you're building).
The BigNerdRanch book is a good resource, but yeah, it's outdated. Read it for general information on how Android works, but don't expect the specific classes they use to be up to date.
Go to build path in eclipse, then click order and export, then check the library/jar, and then click the up button to move it to the top of the list to compile it first.
When you add the const
keyword to a method the this
pointer will essentially become a pointer to const
object, and you cannot therefore change any member data. (Unless you use mutable
, more on that later).
The const
keyword is part of the functions signature which means that you can implement two similar methods, one which is called when the object is const
, and one that isn't.
#include <iostream>
class MyClass
{
private:
int counter;
public:
void Foo()
{
std::cout << "Foo" << std::endl;
}
void Foo() const
{
std::cout << "Foo const" << std::endl;
}
};
int main()
{
MyClass cc;
const MyClass& ccc = cc;
cc.Foo();
ccc.Foo();
}
This will output
Foo
Foo const
In the non-const method you can change the instance members, which you cannot do in the const
version. If you change the method declaration in the above example to the code below you will get some errors.
void Foo()
{
counter++; //this works
std::cout << "Foo" << std::endl;
}
void Foo() const
{
counter++; //this will not compile
std::cout << "Foo const" << std::endl;
}
This is not completely true, because you can mark a member as mutable
and a const
method can then change it. It's mostly used for internal counters and stuff. The solution for that would be the below code.
#include <iostream>
class MyClass
{
private:
mutable int counter;
public:
MyClass() : counter(0) {}
void Foo()
{
counter++;
std::cout << "Foo" << std::endl;
}
void Foo() const
{
counter++; // This works because counter is `mutable`
std::cout << "Foo const" << std::endl;
}
int GetInvocations() const
{
return counter;
}
};
int main(void)
{
MyClass cc;
const MyClass& ccc = cc;
cc.Foo();
ccc.Foo();
std::cout << "Foo has been invoked " << ccc.GetInvocations() << " times" << std::endl;
}
which would output
Foo
Foo const
Foo has been invoked 2 times
check your image cmd
using the command docker inspect image_name
. The output might be like this:
"Cmd": [
"/bin/bash",
"-c",
"#(nop) ",
"CMD [\"/bin/bash\"]"
],
So use the command docker exec -it container_id /bin/bash
. If your cmd
output is different like this:
"Cmd": [
"/bin/sh",
"-c",
"#(nop) ",
"CMD [\"/bin/sh\"]"
],
Use /bin/sh
instead of /bin/bash
in the command above.
It seems like you're using C++ with a C library and therefore you need to work with const char *
.
I suggest wrapping those const char *
into std::string
:
const char *a = "hello ";
const char *b = "world";
std::string c = a;
std::string d = b;
cout << c + d;
Andrey's answer (the highest voted at the time of writing) is slightly incorrect. I would have added this as comment but I am not reputable enough.
In Andrey's answer:
char[] chars = {'c', 'h', 'a', 'r', 's'}
byte[] bytes = Charset.forName("UTF-8").encode(CharBuffer.wrap(chars)).array();
the call to array() may not return the desired value, for example:
char[] c = "aaaaaaaaaa".toCharArray();
System.out.println(Arrays.toString(Charset.forName("UTF-8").encode(CharBuffer.wrap(c)).array()));
output:
[97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 0]
As can be seen a zero byte has been added. To avoid this use the following:
char[] c = "aaaaaaaaaa".toCharArray();
ByteBuffer bb = Charset.forName("UTF-8").encode(CharBuffer.wrap(c));
byte[] b = new byte[bb.remaining()];
bb.get(b);
System.out.println(Arrays.toString(b));
output:
[97, 97, 97, 97, 97, 97, 97, 97, 97, 97]
As the answer also alluded to using passwords it might be worth blanking out the array that backs the ByteBuffer (accessed via the array() function):
ByteBuffer bb = Charset.forName("UTF-8").encode(CharBuffer.wrap(c));
byte[] b = new byte[bb.remaining()];
bb.get(b);
blankOutByteArray(bb.array());
System.out.println(Arrays.toString(b));
It can be cleaner to add an extension to FileManager for this kind of awkward call, for tidiness if nothing else. Something like:
extension FileManager {
static var documentDir : URL {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
}
}
Instead of this iconv solution:
$str = iconv('UTF-8', 'windows-1252', $str);
You could use the following:
$str = mb_convert_encoding($str, "UTF-8", "Windows-1252");
See: How to convert Windows-1252 characters to values in php?
intList = Array.ConvertAll(stringList, int.Parse).ToList();
This may be old, but I may as well write what I've learned down. So anyway I did it this way.
---------->
Before you start, make sure the Apache rewrites module is enabled and then follow the steps below.
1) Log-in to your Magento administration area then go to System > Configuration > Web.
2) Navigate to the Unsecure and Secure tabs. Make sure the Unsecured and Secure - Base Url options have your domain name within it, and do not leave the forward slash off at the end of the URL. Example: http://www.yourdomain.co.uk/
3) While still on the Web page, navigate to Search Engine Optimisation tab and select YES underneath the Use Web Server Rewrites option.
4) Navigate to the Secure tab again (if not already on it) and select Yes on the Use Secure URLs in Front-End option.
5) Now go to the root of your Magento website folder and use this code for your .htaccess:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
Save the .htaccess and replace the original file. (PLEASE MAKE SURE TO BACKUP YOUR ORIGINAL .htaccess FILE BEFORE MESSING WITH IT!!!)
6) Now go to System > Cache Management and select all fields and make sure the Actions dropdown is set on Refresh, then submit. (This will of-course refresh the Cache.)
---------->
If this did not work please follow these extra steps.
7) Go to System > Configuration > web again. This time look for the Current Configuration Scope and select your website from the dropdown menu. (This is of course, it is set to Default Config)
8) Make sure the Unsecure and Secure fields contain the same domain as the previous Default Config file.
9) Navigate to the Search Engines Optimisation tab and select Yes underneath the Use Web Server Rewrites section.
10) Once the URLs are the same, and the rewrite is enabled save that page, then go back and make sure they are all checked as default, then save again if needed.
11) Repeat step 6.
Now your index.php problem should be fixed and all should be well!!!
I hope this helps, and good luck.
Not really an answer to the specific question, but if there are others, like me, who are getting this error in fastAPI and end up here:
It is probably because your route response has a value that can't be JSON serialised by jsonable_encoder
. For me it was WKBElement: https://github.com/tiangolo/fastapi/issues/2366
Like in the issue, I ended up just removing the value from the output.
I usually use padding to resolve this issue. The padding will be added when border disappears and removed when border appears. Sample code:
.good-border {
padding: 1px;
}
.good-border:hover {
padding: 0px;
border: 1px solid blue;
}
View my full sample code on JSFiddle: https://jsfiddle.net/3t7vyebt/4/
I think what he is trying to say is to use the
getContentPane().setBackground(Color.the_Color_you_want_here)
but if u want to set the color to any other then the JFrame, you use the object.setBackground(Color.the_Color_you_want_here)
Eg:
jPanel.setbackground(Color.BLUE)
Using map (halfdanrump's answer) is best for me, though haven't timed it...
But if you go for a dictionary, and if you have a big_dict:
so e.g.:
big_dict = {'a':1,'b':2,'c':3,................................................}
req = ['a','c','w']
{k:big_dict.get(k,None) for k in req )
# or
{k:big_dict[k] for k in req if k in big_dict)
Note that in the converse case, that the req is big, but my_dict is small, you should loop through my_dict instead.
In general, we are doing an intersection and the complexity of the problem is O(min(len(dict)),min(len(req))). Python's own implementation of intersection considers the size of the two sets, so it seems optimal. Also, being in c and part of the core library, is probably faster than most not optimized python statements. Therefore, a solution that I would consider is:
dict = {'a':1,'b':2,'c':3,................................................}
req = ['a','c','w',...................]
{k:dic[k] for k in set(req).intersection(dict.keys())}
It moves the critical operation inside python's c code and will work for all cases.
Add XAttribute
in the constructor of the XElement
, like
new XElement("Conn", new XAttribute("Server", comboBox1.Text));
You can also add multiple attributes or elements via the constructor
new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));
or you can use the Add-Method of the XElement
to add attributes
XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);
I'd say there isn't any portable and 100% reliable way due to dangling alias
es. For example:
alias john='ls --color'
alias paul='george -F'
alias george='ls -h'
alias ringo=/
Of course, only the last one is problematic (no offence to Ringo!). But all of them are valid alias
es from the point of view of command -v
.
In order to reject dangling ones like ringo
, we have to parse the output of the shell built-in alias
command and recurse into them (command -v
isn't a superior to alias
here.) There isn't any portable solution for it, and even a Bash-specific solution is rather tedious.
Note that a solution like this will unconditionally reject alias ls='ls -F'
:
test() { command -v $1 | grep -qv alias }
Specify the optional selector to target what you want:
jQuery(this).parent('li').addClass('yourClass');
Or:
jQuery(this).parents('li').addClass('yourClass');
As it is announced in jQuery 1.11.0/2.1.0 Beta 2 Released
the source map comment will be removed so the issue will not appear in newer versions of jQuery
.
Here is the official announcement:
One of the changes we’ve made in this beta is to remove the sourcemap comment. Sourcemaps have proven to be a very problematic and puzzling thing to developers, generating scores of confused questions on forums like StackOverflow and causing users to think jQuery itself was broken.
Anyway, if you need to use a source map, it still be available:
We’ll still be generating and distributing sourcemaps, but you will need to add the appropriate sourcemap comment at the end of the minified file if the browser does not support manually associating map files (currently, none do). If you generate your own jQuery file using the custom build process, the sourcemap comment will be present in the minified file and the map is generated; you can either leave it in and use sourcemaps or edit it out and ignore the map file entirely.
Here you can find more details about the changes.
Here you can find confirmation that with the jQuery 1.11.0/2.1.0 Released
the source-map comment in the minified file is removed.
Previous answers got you list of torch.Size Here is how to get list of ints
listofints = [int(x) for x in tensor.shape]
You can read the nice post Swift & Cocoapods. Basically, we need to create a bridging header file and put all Objective-C headers there. And then we need to reference it from our build settings. After that, we can use the Objective-C code.
let manager = AFHTTPRequestOperationManager()
manager.GET(
"http://example.com/resources.json",
parameters: nil,
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
println("JSON: " + responseObject.description)
},
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
println("Error: " + error.localizedDescription)
})
Also have a look at Apple's document Using Swift with Cocoa and Objective-C as well.
What about running the google-drive-ftp-adapter application in your local pc and then connect your filezilla client to that application? The google-drive-ftp-adapter application is not an online service, but its an alternative solution to connect to google drive through ftp.
The google-drive-ftp-adapter is an open source application hosted in github and it is a kind of standalone ftp-server java application that connects to your google drive in behalf of you, acting as a bridge (or adapter) between your ftp client and the google drive service. Once you have running the google-drive-ftp adapter, you can connect your preferred FTP client to the google-drive-ftp-adapter ftp server in your localhost (or wherever the app is running, like in a remote machine) to manage your files.
I use it in conjunction with beyond compare to synchronize my local files against the ones I have in the google drive and it serves well for the purpose.
This is the current github link hosting the google-drive-ftp-adapter repository: https://github.com/andresoviedo/google-drive-ftp-adapter
It's totally subjective. I omit the redundant public
modifier as it seems like clutter. As mentioned by others - consistency is the key to this decision.
It's interesting to note that the C# language designers decided to enforce this. Declaring an interface method as public in C# is actually a compile error. Consistency is probably not important across languages though, so I guess this is not really directly relevant to Java.
Use vanilla js, example
document.cookie = `referral_key=hello;max-age=604800;domain=example.com`
Read more at: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie
Press F8 for temporarily freezing / unfreezing JS (with DevTools open).
This is very useful for debugging UI issues on elements that may lose focus if you click or press anything outside of that element. (Chrome 71.0.3578.98, Ubuntu 18.10)
The difference between XML and JSON is that XML is a meta-language/markup language and JSON is a lightweight data-interchange. That is, XML syntax is designed specifically to have no inherent semantics. Particular element names don't mean anything until a particular processing application processes them in a particular way. By contrast, JSON syntax has specific semantics built in stuff between {} is an object, stuff between [] is an array, etc.
A JSON parser, therefore, knows exactly what every JSON document means. An XML parser only knows how to separate markup from data. To deal with the meaning of an XML document, you have to write additional code.
To illustrate the point, let me borrow Guffa's example:
{ "persons": [
{
"name": "Ford Prefect",
"gender": "male"
},
{
"name": "Arthur Dent",
"gender": "male"
},
{
"name": "Tricia McMillan",
"gender": "female"
} ] }
The XML equivalent he gives is not really the same thing since while the JSON example is semantically complete, the XML would require to be interpreted in a particular way to have the same effect. In effect, the JSON is an example uses an established markup language of which the semantics are already known, whereas the XML example creates a brand new markup language without any predefined semantics.
A better XML equivalent would be to define a (fictitious) XJSON language with the same semantics as JSON, but using XML syntax. It might look something like this:
<xjson>
<object>
<name>persons</name>
<value>
<array>
<object>
<value>Ford Prefect</value>
<gender>male</gender>
</object>
<object>
<value>Arthur Dent</value>
<gender>male</gender>
</object>
<object>
<value>Tricia McMillan</value>
<gender>female</gender>
</object>
</array>
</value>
</object>
</xjson>
Once you wrote an XJSON processor, it could do exactly what JSON processor does, for all the types of data that JSON can represent, and you could translate data losslessly between JSON and XJSON.
So, to complain that XML does not have the same semantics as JSON is to miss the point. XML syntax is semantics-free by design. The point is to provide an underlying syntax that can be used to create markup languages with any semantics you want. This makes XML great for making up ad-hoc data and document formats, because you don't have to build parsers for them, you just have to write a processor for them.
But the downside of XML is that the syntax is verbose. For any given markup language you want to create, you can come up with a much more succinct syntax that expresses the particular semantics of your particular language. Thus JSON syntax is much more compact than my hypothetical XJSON above.
If follows that for really widely used data formats, the extra time required to create a unique syntax and write a parser for that syntax is offset by the greater succinctness and more intuitive syntax of the custom markup language. It also follows that it often makes more sense to use JSON, with its established semantics, than to make up lots of XML markup languages for which you then need to implement semantics.
It also follows that it makes sense to prototype certain types of languages and protocols in XML, but, once the language or protocol comes into common use, to think about creating a more compact and expressive custom syntax.
It is interesting, as a side note, that SGML recognized this and provided a mechanism for specifying reduced markup for an SGML document. Thus you could actually write an SGML DTD for JSON syntax that would allow a JSON document to be read by an SGML parser. XML removed this capability, which means that, today, if you want a more compact syntax for a specific markup language, you have to leave XML behind, as JSON does.
I was facing this similiar problem and did not want to use header() to redirect to another page.
Solution:
Use $_POST = array();
to reset the $_POST
array at the top of the form, along with the code used to process the form.
The error or success messages can be conditionally added after the form. Hope this helps :)
I needed to download and install the Windows 8.0 (and not 8.1) SDK to make the error disappear on my TeamCity server.
https://developer.microsoft.com/en-us/windows/downloads/windows-8-sdk
I couldn't get the suggestion above at https://stackoverflow.com/a/20956456/1019307 to work. This worked for me though. For a file secondstring-20030401.jar
that I stored in a libs/
directory in the root of the project:
repositories {
mavenCentral()
// Not everything is available in a Maven/Gradle repository. Use a local 'libs/' directory for these.
flatDir {
dirs 'libs'
}
}
...
compile name: 'secondstring-20030401'
Strangely, I didn't find anything about legends and labels in the Chart.js documentation. It seems like you can't do it with chart.js alone.
I used https://github.com/bebraw/Chart.js.legend which is extremely light, to generate the legends.
SELECT
DB_NAME (database_id) as [Database Name],
name as [Database File Name],
[Type] = CASE WHEN Type_Desc = 'ROWS' THEN 'Data File(s)'
WHEN Type_Desc = 'LOG' THEN 'Log File(s)'
ELSE Type_Desc END,
size*8/1024 as 'Size (MB)',
physical_name as [Database_File_Location]
FROM sys.master_files
ORDER BY 1,3
Output
Database Name Database File Name Type Size (MB) Database_File_Location
--------------------------- ------------------------------- ------------------- ----------- ---------------------------------------------------------------
AdventureWorksDW2017 AdventureWorksDW2017 Data File(s) 136 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\AdventureWorksDW2017.mdf
AdventureWorksDW2017 AdventureWorksDW2017_log Log File(s) 72 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\AdventureWorksDW2017_log.ldf
DBA_Admin DBA_Admin Data File(s) 8 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\DBA_Admin.mdf
DBA_Admin DBA_Admin_log Log File(s) 8 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\DBA_Admin_log.ldf
EventNotifications EventNotifications Data File(s) 8 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\EventNotifications.mdf
EventNotifications EventNotifications_log Log File(s) 8 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\EventNotifications_log.ldf
master master Data File(s) 4 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\master.mdf
master mastlog Log File(s) 2 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\mastlog.ldf
model modeldev Data File(s) 8 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\model.mdf
model modellog Log File(s) 8 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\modellog.ldf
msdb MSDBData Data File(s) 19 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\MSDBData.mdf
msdb MSDBLog Log File(s) 13 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\MSDBLog.ldf
tempdb temp2 Data File(s) 8 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\tempdb_mssql_2.ndf
tempdb temp3 Data File(s) 8 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\tempdb_mssql_3.ndf
tempdb temp4 Data File(s) 8 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\tempdb_mssql_4.ndf
tempdb tempdev Data File(s) 8 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\tempdb.mdf
tempdb templog Log File(s) 8 E:\MSSQL14.MSSQLSERVER\MSSQL\DATA\templog.ldf
Here is another version of weighted_choice that uses numpy. Pass in the weights vector and it will return an array of 0's containing a 1 indicating which bin was chosen. The code defaults to just making a single draw but you can pass in the number of draws to be made and the counts per bin drawn will be returned.
If the weights vector does not sum to 1, it will be normalized so that it does.
import numpy as np
def weighted_choice(weights, n=1):
if np.sum(weights)!=1:
weights = weights/np.sum(weights)
draws = np.random.random_sample(size=n)
weights = np.cumsum(weights)
weights = np.insert(weights,0,0.0)
counts = np.histogram(draws, bins=weights)
return(counts[0])
select empid,empname,managename,[Management ],cityname
from employees inner join Managment
on employees.manageid = Managment.ManageId
inner join CITY on employees.Cityid=CITY.CityId
id name managename managment cityname
----------------------------------------
1 islam hamza it cairo
Have you tried using JavaScriptSerializer
?
There's also DataContractJsonSerializer
The previous answers are correct but remember to use the name attribute in the input fields (html form) or you won't get anything. Example:
<input type="text" id="username" /> <!-- won't work -->
<input type="text" name="username" /> <!-- will work -->
<input type="text" name="username" id="username" /> <!-- will work too -->
All this code is HTML valid, but using getParameter(java.lang.String) you will need the name attribute been set in all parameters you want to receive.
You can try doing this.
function scrollDetect(){_x000D_
var lastScroll = 0;_x000D_
_x000D_
window.onscroll = function() {_x000D_
let currentScroll = document.documentElement.scrollTop || document.body.scrollTop; // Get Current Scroll Value_x000D_
_x000D_
if (currentScroll > 0 && lastScroll <= currentScroll){_x000D_
lastScroll = currentScroll;_x000D_
document.getElementById("scrollLoc").innerHTML = "Scrolling DOWN";_x000D_
}else{_x000D_
lastScroll = currentScroll;_x000D_
document.getElementById("scrollLoc").innerHTML = "Scrolling UP";_x000D_
}_x000D_
};_x000D_
}_x000D_
_x000D_
_x000D_
scrollDetect();
_x000D_
html,body{_x000D_
height:100%;_x000D_
width:100%;_x000D_
margin:0;_x000D_
padding:0;_x000D_
}_x000D_
_x000D_
.cont{_x000D_
height:100%;_x000D_
width:100%;_x000D_
}_x000D_
_x000D_
.item{_x000D_
margin:0;_x000D_
padding:0;_x000D_
height:100%;_x000D_
width:100%;_x000D_
background: #ffad33;_x000D_
}_x000D_
_x000D_
.red{_x000D_
background: red;_x000D_
}_x000D_
_x000D_
p{_x000D_
position:fixed;_x000D_
font-size:25px;_x000D_
top:5%;_x000D_
left:5%;_x000D_
}
_x000D_
<div class="cont">_x000D_
<div class="item"></div>_x000D_
<div class="item red"></div>_x000D_
<p id="scrollLoc">0</p>_x000D_
</div>
_x000D_
Here is another base R solution. We can use read.table
but since it accepts only one-byte sep
argument and here we have multi-byte separator we can use gsub
to replace the multibyte separator to any one-byte separator and use that as sep
argument in read.table
cbind(before[1], read.table(text = gsub('_and_', '\t', before$type),
sep = "\t", col.names = paste0("type_", 1:2)))
# attr type_1 type_2
#1 1 foo bar
#2 30 foo bar_2
#3 4 foo bar
#4 6 foo bar_2
In this case, we can also make it shorter by replacing it with default sep
argument so we don't have to mention it explicitly
cbind(before[1], read.table(text = gsub('_and_', ' ', before$type),
col.names = paste0("type_", 1:2)))
Yes.
invalidateOptionsMenu()
when you want to hide the option. This will call onCreateOptionsMenu()
.onCreateOptionsMenu()
, check for the flag/condition and show or
hide it the following way:MenuItem item = menu.findItem(R.id.menu_Done); if (flag/condition)) { item.setVisible(false); } else { }
Another way to resolve this problem is:
Let's assume:
path_to_driver_directory = C:\Work\drivers\
driver = IEDriverServer.exe
When getting messsage about path you can always add path_to_driver_directory containing driver to the PATH environment variable. Check: http://java.com/en/download/help/path.xml
Then simply check in cmd window if driver is available - just run cmd in any location and type name of driver.
If everything works fine then you get:
C:\Users\A>IEDriverServer.exe
Started InternetExplorerDriver server (32-bit)
2.28.0.0
Listening on port 5555
Thats it.
The read
method returns a sequence of bytes as a string. To convert from a string byte-sequence to binary data, use the built-in struct
module: http://docs.python.org/library/struct.html.
import struct
print(struct.unpack('i', fin.read(4)))
Note that unpack
always returns a tuple, so struct.unpack('i', fin.read(4))[0]
gives the integer value that you are after.
You should probably use the format string '<i'
(< is a modifier that indicates little-endian byte-order and standard size and alignment - the default is to use the platform's byte ordering, size and alignment). According to the BMP format spec, the bytes should be written in Intel/little-endian byte order.
use Select().Distinct()
for example
DBContext db = new DBContext();
var data= db.User_Food_UserIntakeFood .Select( ).Distinct();
GetDetailsOf()
Method - Retrieves details about an item in a folder. For example, its size, type, or the time of its last modification. File Properties may vary based on the Windows-OS
version.
List<string> arrHeaders = new List<string>();
Shell shell = new ShellClass();
Folder rFolder = shell.NameSpace(_rootPath);
FolderItem rFiles = rFolder.ParseName(filename);
for (int i = 0; i < short.MaxValue; i++)
{
string value = rFolder.GetDetailsOf(rFiles, i).Trim();
arrHeaders.Add(value);
}
It's and old post, but it's new for me. So, it is straight forward! In this part of the code:
public boolean onNavigationItemSelected(MenuItem item) {
} , I bound an ImageView to the LinearLayout, which contains the ImageView from the example, listed below. Mind: it's the same code you get when you start a new project, and choose the template "Navigation Drawer Activity":
<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:src="@android:drawable/sym_def_app_icon" />
I gave the LinearLayout and ID, inside nav_header_main.xml (in my case I chose 'navigation_header_container' , so it went this way:
LinearLayout lV = (LinearLayout) findViewById(R.id.navigation_header_container);
ivCloseDrawer = (ImageView) lV.findViewById(R.id.imageView);
ivCloseDrawer.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
drawer.closeDrawer(GravityCompat.START);
}
});
Note: I have a private ImageView ivCloseDrawer declared at the top, before onCreate (MainActivity).
It worked fine! Hope it helps, Best Regards.
You haven't defined struct stasher_file
by your first definition. What you have defined is an nameless struct type and a variable stasher_file
of that type. Since there's no definition for such type as struct stasher_file
in your code, the compiler complains about incomplete type.
In order to define struct stasher_file
, you should have done it as follows
struct stasher_file {
char name[32];
int size;
int start;
int popularity;
};
Note where the stasher_file
name is placed in the definition.
There is a problem in your query..
statement =con.prepareStatement("SELECT * from employee WHERE userID = "+"''"+userID);
ResultSet rs = statement.executeQuery();
You are using Prepare Statement.. So you need to set your parameter using statement.setInt()
or statement.setString()
depending upon what is the type of your userId
Replace it with: -
statement =con.prepareStatement("SELECT * from employee WHERE userID = :userId");
statement.setString(userId, userID);
ResultSet rs = statement.executeQuery();
Or, you can use ?
in place of named value - :userId
..
statement =con.prepareStatement("SELECT * from employee WHERE userID = ?");
statement.setString(1, userID);
You could import csv then loop through all the CSV files reading them into a list. Then write the list back out to disk.
import csv
rows = []
for f in (file1, file2, ...):
reader = csv.reader(open("f", "rb"))
for row in reader:
rows.append(row)
writer = csv.writer(open("some.csv", "wb"))
writer.writerows("\n".join(rows))
The above is not very robust as it has no error handling nor does it close any open files. This should work whether or not the the individual files have one or more rows of CSV data in them. Also I did not run this code, but it should give you an idea of what to do.
This site has great examples check it out
// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);
String.Format("{0:y yy yyy yyyy}", dt); // "8 08 008 2008" year
String.Format("{0:M MM MMM MMMM}", dt); // "3 03 Mar March" month
String.Format("{0:d dd ddd dddd}", dt); // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}", dt); // "4 04 16 16" hour 12/24
String.Format("{0:m mm}", dt); // "5 05" minute
String.Format("{0:s ss}", dt); // "7 07" second
String.Format("{0:f ff fff ffff}", dt); // "1 12 123 1230" sec.fraction
String.Format("{0:F FF FFF FFFF}", dt); // "1 12 123 123" without zeroes
String.Format("{0:t tt}", dt); // "P PM" A.M. or P.M.
String.Format("{0:z zz zzz}", dt); // "-6 -06 -06:00" time zone
// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}", dt); // "3/9/2008"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"
// day/month names
String.Format("{0:ddd, MMM d, yyyy}", dt); // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt); // "Sunday, March 9, 2008"
// two/four digit year
String.Format("{0:MM/dd/yy}", dt); // "03/09/08"
String.Format("{0:MM/dd/yyyy}", dt); // "03/09/2008"
Standard DateTime Formatting
String.Format("{0:t}", dt); // "4:05 PM" ShortTime
String.Format("{0:d}", dt); // "3/9/2008" ShortDate
String.Format("{0:T}", dt); // "4:05:07 PM" LongTime
String.Format("{0:D}", dt); // "Sunday, March 09, 2008" LongDate
String.Format("{0:f}", dt); // "Sunday, March 09, 2008 4:05 PM" LongDate+ShortTime
String.Format("{0:F}", dt); // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt); // "3/9/2008 4:05 PM" ShortDate+ShortTime
String.Format("{0:G}", dt); // "3/9/2008 4:05:07 PM" ShortDate+LongTime
String.Format("{0:m}", dt); // "March 09" MonthDay
String.Format("{0:y}", dt); // "March, 2008" YearMonth
String.Format("{0:r}", dt); // "Sun, 09 Mar 2008 16:05:07 GMT" RFC1123
String.Format("{0:s}", dt); // "2008-03-09T16:05:07" SortableDateTime
String.Format("{0:u}", dt); // "2008-03-09 16:05:07Z" UniversalSortableDateTime
/*
Specifier DateTimeFormatInfo property Pattern value (for en-US culture)
t ShortTimePattern h:mm tt
d ShortDatePattern M/d/yyyy
T LongTimePattern h:mm:ss tt
D LongDatePattern dddd, MMMM dd, yyyy
f (combination of D and t) dddd, MMMM dd, yyyy h:mm tt
F FullDateTimePattern dddd, MMMM dd, yyyy h:mm:ss tt
g (combination of d and t) M/d/yyyy h:mm tt
G (combination of d and T) M/d/yyyy h:mm:ss tt
m, M MonthDayPattern MMMM dd
y, Y YearMonthPattern MMMM, yyyy
r, R RFC1123Pattern ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
s SortableDateTimePattern yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
u UniversalSortableDateTimePattern yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)
(*) = culture independent
*/
Update using c# 6 string interpolation format
// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);
$"{dt:y yy yyy yyyy}"; // "8 08 008 2008" year
$"{dt:M MM MMM MMMM}"; // "3 03 Mar March" month
$"{dt:d dd ddd dddd}"; // "9 09 Sun Sunday" day
$"{dt:h hh H HH}"; // "4 04 16 16" hour 12/24
$"{dt:m mm}"; // "5 05" minute
$"{dt:s ss}"; // "7 07" second
$"{dt:f ff fff ffff}"; // "1 12 123 1230" sec.fraction
$"{dt:F FF FFF FFFF}"; // "1 12 123 123" without zeroes
$"{dt:t tt}"; // "P PM" A.M. or P.M.
$"{dt:z zz zzz}"; // "-6 -06 -06:00" time zone
// month/day numbers without/with leading zeroes
$"{dt:M/d/yyyy}"; // "3/9/2008"
$"{dt:MM/dd/yyyy}"; // "03/09/2008"
// day/month names
$"{dt:ddd, MMM d, yyyy}"; // "Sun, Mar 9, 2008"
$"{dt:dddd, MMMM d, yyyy}"; // "Sunday, March 9, 2008"
// two/four digit year
$"{dt:MM/dd/yy}"; // "03/09/08"
$"{dt:MM/dd/yyyy}"; // "03/09/2008"
There are several problems.
One is of style; always capitalize class names. This is a universally observed Java convention. Failing to do so confuses other programmers.
Secondly, the line
System.out.println(boolean isLeapYear);
is a syntax error. Delete it.
Thirdly.
You never call the function from your main routine. That is why you never see any reply to the input.
"Subscript out of range" indicates that you've tried to access an element from a collection that doesn't exist. Is there a "Sheet1" in your workbook? If not, you'll need to change that to the name of the worksheet you want to protect.
do adb pull \sdcard\log.txt C:Users\admin\Desktop
You could try to sort descending "sort LastWriteTime -Descending" and then "select -first 1." Not sure which one is faster
new Handler().postDelayed(new Runnable() {
public void run() {
// do something...
}
}, 100);
There are some great solutions here, but I'll like to take it one step further regarding the local file.
In a scenario when Google does fail, it should load a local source but maybe a physical file on the server isn't necessarily the best option. I bring this up because I'm currently implementing the same solution, only I want to fall back to a local file that gets generated by a data source.
My reasons for this is that I want to have some piece of mind when it comes to keeping track of what I load from Google vs. what I have on the local server. If I want to change versions, I'll want to keep my local copy synced with what I'm trying to load from Google. In an environment where there are many developers, I think the best approach would be to automate this process so that all one would have to do is change a version number in a configuration file.
Here's my proposed solution that should work in theory:
In theory, if my code is written properly, all I would need to do is change the version number in my app config then viola! You have a fallback solution which is automated, and you don't have to maintain physical files on your server.
What does everyone think? Maybe this is overkill, but it could be an elegant method of maintaining your AJAX libraries.
Acorn
time1
is the key of the most outer dictionary, eg, feb2012
. So then you're trying to index the string, but you can only do this with integers. I think what you wanted was:
for info in courses[time1][course]:
As you're going through each dictionary, you must add another nest.
Unfortunatelly, today (September 2018) you can not find cross-browser solution for client side file writing.
For example: in some browser like a Chrome we have today this possibility and we can write with FileSystemFileEntry.createWriter() with client side call, but according to the docu:
This feature is obsolete. Although it may still work in some browsers, its use is discouraged since it could be removed at any time. Try to avoid using it.
For IE (but not MS Edge) we could use ActiveX too, but this is only for this client.
If you want update your JSON file cross-browser you have to use server and client side together.
On client side you can make a request to the server and then you have to read the response from server. Or you could read a file with FileReader too. For the cross-browser writing to the file you have to have some server (see below on server part).
var xhr = new XMLHttpRequest(),
jsonArr,
method = "GET",
jsonRequestURL = "SOME_PATH/jsonFile/";
xhr.open(method, jsonRequestURL, true);
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
// we convert your JSON into JavaScript object
jsonArr = JSON.parse(xhr.responseText);
// we add new value:
jsonArr.push({"nissan": "sentra", "color": "green"});
// we send with new request the updated JSON file to the server:
xhr.open("POST", jsonRequestURL, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
// if you want to handle the POST response write (in this case you do not need it):
// xhr.onreadystatechange = function(){ /* handle POST response */ };
xhr.send("jsonTxt="+JSON.stringify(jsonArr));
// but on this place you have to have a server for write updated JSON to the file
}
};
xhr.send(null);
You can use a lot of different servers, but I would like to write about PHP and Node.js servers.
By using searching machine you could find "free PHP Web Hosting*" or "free Node.js Web Hosting". For PHP server I would recommend 000webhost.com and for Node.js I would recommend to see and to read this list.
PHP server side script solution
The PHP script for reading and writing from JSON file:
<?php
// This PHP script must be in "SOME_PATH/jsonFile/index.php"
$file = 'jsonFile.txt';
if($_SERVER['REQUEST_METHOD'] === 'POST')
// or if(!empty($_POST))
{
file_put_contents($file, $_POST["jsonTxt"]);
//may be some error handeling if you want
}
else if($_SERVER['REQUEST_METHOD'] === 'GET')
// or else if(!empty($_GET))
{
echo file_get_contents($file);
//may be some error handeling if you want
}
?>
Node.js server side script solution
I think that Node.js is a little bit complex for beginner. This is not normal JavaScript like in browser. Before you start with Node.js I would recommend to read one from two books:
The Node.js script for reading and writing from JSON file:
var http = require("http"),
fs = require("fs"),
port = 8080,
pathToJSONFile = '/SOME_PATH/jsonFile.txt';
http.createServer(function(request, response)
{
if(request.method == 'GET')
{
response.writeHead(200, {"Content-Type": "application/json"});
response.write(fs.readFile(pathToJSONFile, 'utf8'));
response.end();
}
else if(request.method == 'POST')
{
var body = [];
request.on('data', function(chunk)
{
body.push(chunk);
});
request.on('end', function()
{
body = Buffer.concat(body).toString();
var myJSONdata = body.split("=")[1];
fs.writeFileSync(pathToJSONFile, myJSONdata); //default: 'utf8'
});
}
}).listen(port);
Related links for Node.js:
function Do-SendKeys {
param (
$SENDKEYS,
$WINDOWTITLE
)
$wshell = New-Object -ComObject wscript.shell;
IF ($WINDOWTITLE) {$wshell.AppActivate($WINDOWTITLE)}
Sleep 1
IF ($SENDKEYS) {$wshell.SendKeys($SENDKEYS)}
}
Do-SendKeys -WINDOWTITLE Print -SENDKEYS '{TAB}{TAB}'
Do-SendKeys -WINDOWTITLE Print
Do-SendKeys -SENDKEYS '%{f4}'
You are going to need to call the SmsManager
class. You are probably going to need to use the STATUS_ON_ICC_READ
constant and maybe put what you get there into your apps local db so that you can keep track of what you have already read vs the new stuff for your app to parse through.
BUT bear in mind that you have to declare the use of the class in your manifest, so users will see that you have access to their SMS called out in the permissions dialogue they get when they install. Seeing SMS access is unusual and could put some users off. Good luck.
You can stop the 2-line separation in the output by using
with open('t.ini') as f:
for line in f:
print line.strip()
if 'str' in line:
break
I know this is a very old question but I post this solution in case it helps somebody. I recently met this problem and google led me here. The answer here helps me to understand the problem but there are still issues due to my parameter combination. What eventually solves my problem is curl to C# converter. It is a very powerful tool and supports most of the parameters for Curl. The code it generates is almost immediately runnable.
Yes there is a difference.
The Runtime.exec(String)
method takes a single command string that it splits into a command and a sequence of arguments.
The ProcessBuilder
constructor takes a (varargs) array of strings. The first string is the command name and the rest of them are the arguments. (There is an alternative constructor that takes a list of strings, but none that takes a single string consisting of the command and arguments.)
So what you are telling ProcessBuilder to do is to execute a "command" whose name has spaces and other junk in it. Of course, the operating system can't find a command with that name, and the command execution fails.
For any char with ord($char) < 16 you get a HEX back which is only 1 long. You forgot to add 0 padding.
This should solve it:
<?php
function strToHex($string){
$hex = '';
for ($i=0; $i<strlen($string); $i++){
$ord = ord($string[$i]);
$hexCode = dechex($ord);
$hex .= substr('0'.$hexCode, -2);
}
return strToUpper($hex);
}
function hexToStr($hex){
$string='';
for ($i=0; $i < strlen($hex)-1; $i+=2){
$string .= chr(hexdec($hex[$i].$hex[$i+1]));
}
return $string;
}
// Tests
header('Content-Type: text/plain');
function test($expected, $actual, $success) {
if($expected !== $actual) {
echo "Expected: '$expected'\n";
echo "Actual: '$actual'\n";
echo "\n";
$success = false;
}
return $success;
}
$success = true;
$success = test('00', strToHex(hexToStr('00')), $success);
$success = test('FF', strToHex(hexToStr('FF')), $success);
$success = test('000102FF', strToHex(hexToStr('000102FF')), $success);
$success = test('???§P?§P ?§T?§?', hexToStr(strToHex('???§P?§P ?§T?§?')), $success);
echo $success ? "Success" : "\nFailed";
I think it depends on how you installed python. Note that you can have multiple installs of python, I do on my machine. However, if you install via an msi of a version of python 2.2 or above, I believe it creates a registry key like so:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\Python.exe
which gives this value on my machine:
C:\Python25\Python.exe
You just read the registry key to get the location.
However, you can install python via an xcopy like model that you can have in an arbitrary place, and you just have to know where it is installed.
If you want to access members of the collection by one of their properties, you might consider using a Dictionary<T>
or KeyedCollection<T>
instead. This way you don't have to search for the item you're looking for.
Otherwise, you could at least do this:
foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments)
{
if (spAssignment.Member.Name == shortName)
{
workspace.RoleAssignments.Remove(spAssignment);
break;
}
}
It seems impossible to prevent spinners from appearing in Opera. As a temporary workaround, you can make room for the spinners. As far as I can tell, the following CSS adds just enough padding, only in Opera:
noindex:-o-prefocus,
input[type=number] {
padding-right: 1.2em;
}
You either have to make the method Shared
or use an instance of the class General
:
Dim gen = New General()
gen.updateDynamics(get_prospect.dynamicsID)
or
General.updateDynamics(get_prospect.dynamicsID)
Public Shared Sub updateDynamics(dynID As Int32)
' ... '
End Sub
A clear understanding of these terms(JVM, JDK, JRE) are essential to grasp their usage and differences.
JVM Java Virtual Machine (JVM) is a run-time system that executes Java bytecode. The JVM is like a virtual computer that can execute a set of compiled instructions and manipulate memory locations. When a Java compiler compiles source code, it generates a highly optimized set of instructions called bytecode in a .class file. The JVM interprets these bytecode instructions and converts them to machine-specific code for execution.
JDK The Java Development Kit (JDK) is a software development environment that you can use to develop and execute Java applications. It includes the JRE and a set of programming tools, such as a Java compiler, interpreter, appletviewer, and document viewer. The JDK is implemented through the Java SE, Java EE, or Java ME platforms.
JRE The Java Runtime Environment (JRE) is a part of the JDK that includes a JVM, core classes, and several libraries that support application development. Though the JRE is available as part of the JDK, you can also download and use it separately.
For complete understanding you can see my Blog : Jdk Jre Jvm and differences
A few other good references on those topics:
I use the index as a checkpoint.
When I'm about to make a change that might go awry — when I want to explore some direction that I'm not sure if I can follow through on or even whether it's a good idea, such as a conceptually demanding refactoring or changing a representation type — I checkpoint my work into the index.
If this is the first change I've made since my last commit, then I can use the local repository as a checkpoint, but often I've got one conceptual change that I'm implementing as a set of little steps.
I want to checkpoint after each step, but save the commit until I've gotten back to working, tested code.
Notes:
the workspace is the directory tree of (source) files that you see and edit.
The index is a single, large, binary file in
<baseOfRepo>/.git/index
, which lists all files in the current branch, their sha1 checksums, time stamps and the file name -- it is not another directory with a copy of files in it.The local repository is a hidden directory (
.git
) including anobjects
directory containing all versions of every file in the repo (local branches and copies of remote branches) as a compressed "blob" file.Don't think of the four 'disks' represented in the image above as separate copies of the repo files.
They are basically named references for Git commits. There are two major types of refs: tags and heads.
- Tags are fixed references that mark a specific point in history, for example v2.6.29.
- On the contrary, heads are always moved to reflect the current position of project development.
(note: as commented by Timo Huovinen, those arrows are not what the commits point to, it's the workflow order, basically showing arrows as 1 -> 2 -> 3 -> 4
where 1
is the first commit and 4
is the last)
Now we know what is happening in the project.
But to know what is happening right here, right now there is a special reference called HEAD. It serves two major purposes:
- it tells Git which commit to take files from when you checkout, and
- it tells Git where to put new commits when you commit.
When you run
git checkout ref
it pointsHEAD
to the ref you’ve designated and extracts files from it. When you rungit commit
it creates a new commit object, which becomes a child of currentHEAD
. NormallyHEAD
points to one of the heads, so everything works out just fine.
These are the ways :
1. /proc/meminfo
MemTotal: 8152200 kB
MemFree: 760808 kB
You can write a code or script to parse it.
2. Use sysconf by using below macros
sysconf (_SC_PHYS_PAGES) * sysconf (_SC_PAGESIZE);
3. By using sysinfo system call
int sysinfo(struct sysinfo *info);
struct sysinfo { .
.
unsigned long totalram; /*Total memory size to use */
unsigned long freeram; /* Available memory size*/
.
.
};
logger
logs to syslog facilities. If you want the message to go to a particular file you have to modify the syslog configuration accordingly. You could add a line like this:
local7.* -/var/log/mycustomlog
and restart syslog. Then you can log like this:
logger -p local7.info "information message"
logger -p local7.err "error message"
and the messages will appear in the desired logfile with the correct log level.
Without making changes to the syslog configuration you could use logger
like this:
logger -s "foo bar" >> /var/log/mycustomlog
That would instruct logger
to print the message to STDERR as well (in addition to logging it to syslog), so you could redirect STDERR to a file. However, it would be utterly pointless, because the message is already logged via syslog anyway (with the default priority user.notice
).
IIFE (Immediately invoked function expression) is a function which executes as soon as the script loads and goes away.
Consider the function below written in a file named iife.js
(function(){
console.log("Hello Stackoverflow!");
})();
This code above will execute as soon as you load iife.js and will print 'Hello Stackoverflow!' on the developer tools' console.
For a Detailed explanation see Immediately-Invoked Function Expression (IIFE)
Like this:
#include <vector>
// ...
std::vector<std::vector<int>> A(dimension, std::vector<int>(dimension));
(Pre-C++11 you need to leave whitespace between the angled brackets.)
The provider is bundled with PowerShell>=6.0.
If all you need is a way to install a package from a file, just grab the .msi installer for the latest version from the github releases page, copy it over to the machine, install it and use it.
curl -X PUT -T "/path/to/file" "http://myputserver.com/puturl.tmp"
obj={};
$.each(obj, function (key, value) {
console.log(key+ ' : ' + value); //push the object value
});
for (var i in obj) {
nameList += "" + obj[i] + "";//display the object value
}
$("id/class").html($(nameList).length);//display the length of object.
The NVARCHAR2 datatype was introduced by Oracle for databases that want to use Unicode for some columns while keeping another character set for the rest of the database (which uses VARCHAR2). The NVARCHAR2 is a Unicode-only datatype.
One reason you may want to use NVARCHAR2 might be that your DB uses a non-Unicode character set and you still want to be able to store Unicode data for some columns without changing the primary character set. Another reason might be that you want to use two Unicode character set (AL32UTF8 for data that comes mostly from western Europe, AL16UTF16 for data that comes mostly from Asia for example) because different character sets won't store the same data equally efficiently.
Both columns in your example (Unicode VARCHAR2(10 CHAR)
and NVARCHAR2(10)
) would be able to store the same data, however the byte storage will be different. Some strings may be stored more efficiently in one or the other.
Note also that some features won't work with NVARCHAR2, see this SO question:
Observer pattern is used when there is one-to-many relationship between objects such as if one object is modified, its dependent objects are to be notified automatically.
Because python checks in the directories in sequential order starting at the first directory in sys.path
list, till it find the .py
file it was looking for.
Ideally, the current directory or the directory of the script is the first always the first element in the list, unless you modify it, like you did. From documentation -
As initialized upon program startup, the first item of this list, path[0], is the directory containing the script that was used to invoke the Python interpreter. If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input), path[0] is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result of PYTHONPATH.
So, most probably, you had a .py
file with the same name as the module you were trying to import from, in the current directory (where the script was being run from).
Also, a thing to note about ImportError
s , lets say the import error says -
ImportError: No module named main
- it doesn't mean the main.py
is overwritten, no if that was overwritten we would not be having issues trying to read it. Its some module above this that got overwritten with a .py
or some other file.
Example -
My directory structure looks like -
- test
- shared
- __init__.py
- phtest.py
- testmain.py
Now From testmain.py
, I call from shared import phtest
, it works fine.
Now lets say I introduce a shared.py in test
directory` , example -
- test
- shared
- __init__.py
- phtest.py
- testmain.py
- shared.py
Now when I try to do from shared import phtest
from testmain.py
, I will get the error -
ImportError: cannot import name 'phtest'
As you can see above, the file that is causing the issue is shared.py
, not phtest.py
.
Here is the full code with no errors
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
#map-canvas
{
height: 400px;
width: 500px;
}
</style>
</script>
<script type="text/javascript">
function initialize() {
var myLatLng = new google.maps.LatLng( 17.3850, 78.4867 ),
myOptions = {
zoom: 5,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map( document.getElementById( 'map-canvas' ), myOptions ),
marker = new google.maps.Marker( {icon: {
url: 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png',
// This marker is 20 pixels wide by 32 pixels high.
size: new google.maps.Size(20, 32),
// The origin for this image is (0, 0).
origin: new google.maps.Point(0, 0),
// The anchor for this image is the base of the flagpole at (0, 32).
anchor: new google.maps.Point(0, 32)
}, position: myLatLng, map: map} );
marker.setMap( map );
moveBus( map, marker );
}
function moveBus( map, marker ) {
setTimeout(() => {
marker.setPosition( new google.maps.LatLng( 12.3850, 77.4867 ) );
map.panTo( new google.maps.LatLng( 17.3850, 78.4867 ) );
}, 1000)
};
</script>
</head>
<body onload="initialize()">
<script type="text/javascript">
//moveBus();
</script>
<script src="http://maps.googleapis.com/maps/api/js?sensor=AIzaSyB-W_sLy7VzaQNdckkY4V5r980wDR9ldP4"></script>
<div id="map-canvas" style="height: 500px; width: 500px;"></div>
</body>
</html>
Use column-width property of css like below
<ul style="column-width:135px">
To get camelCase
ES5
var camalize = function camalize(str) {
return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, function(match, chr)
{
return chr.toUpperCase();
});
}
ES6
var camalize = function camalize(str) {
return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase());
}
To get CamelSentenceCase or PascalCase
var camelSentence = function camelSentence(str) {
return (" " + str).toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, function(match, chr)
{
return chr.toUpperCase();
});
}
Note :
For those language with accents. Do include À-ÖØ-öø-ÿ
with the regex as following
.replace(/[^a-zA-ZÀ-ÖØ-öø-ÿ0-9]+(.)/g
Just for kicks, since this Q&A does seem to be about syntax microanalysis, a tiny tiny modification of André Alçada Padez's suggestion(s):
(and of course accounting for the pre-IE9 shim/shiv/polyfill he's included)
if (~[foo, bar].indexOf(foobar)) {
// pretty
}
SAP is notoriously bad at making these downloads available... or in an easily accessible location so hopefully this link still works by the time you read this answer.
< original link no longer active >
http://scn.sap.com/docs/DOC-7824 Updated Link 2/6/13:
https://wiki.scn.sap.com/wiki/display/BOBJ/Crystal+Reports%2C+Developer+for+Visual+Studio+Downloads - "Updated 10/31/2017"
http://www.crystalreports.com/crvs/confirm/ - "Updated 10/31/2017"
Use \b
for word boundaries:
sed -i 's/\boldtext\b/newtext/g' <file>
this is my case
startActivityForResult(intent, PICK_IMAGE_REQUEST);
I defined two request code PICK_IMAGE_REQUEST
and SCAN_BARCODE_REQUEST
with the same value, eg.
static final int BARCODE_SCAN_REQUEST = 1;
static final int PICK_IMAGE_REQUEST = 1;
this could also causes the problem
In C++, it is also possible to use meta programming and variadic templates. The following post shows how to do it: Programmatically create static arrays at compile time in C++.
You can set picturebox's SizeMode
property to PictureSizeMode.Zoom
, this will increase the size of smaller images or decrease the size of larger images to fill the PictureBox
My guess is that if there would be edge cases such as extra or missing spaces, this expression with less boundaries might also be an option:
^\s*\[\s*([^\s\r\n:]+)\s*:\s*"([^"]*)"\s*([^\s\r\n:]+)\s*:\s*"([^"]*)"\s*\]\s*$
If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
const regex = /^\s*\[\s*([^\s\r\n:]+)\s*:\s*"([^"]*)"\s*([^\s\r\n:]+)\s*:\s*"([^"]*)"\s*\]\s*$/gm;_x000D_
const str = `[description:"aoeu" uuid:"123sth"]_x000D_
[description : "aoeu" uuid: "123sth"]_x000D_
[ description : "aoeu" uuid: "123sth" ]_x000D_
[ description : "aoeu" uuid : "123sth" ]_x000D_
[ description : "aoeu"uuid : "123sth" ] `;_x000D_
let m;_x000D_
_x000D_
while ((m = regex.exec(str)) !== null) {_x000D_
// This is necessary to avoid infinite loops with zero-width matches_x000D_
if (m.index === regex.lastIndex) {_x000D_
regex.lastIndex++;_x000D_
}_x000D_
_x000D_
// The result can be accessed through the `m`-variable._x000D_
m.forEach((match, groupIndex) => {_x000D_
console.log(`Found match, group ${groupIndex}: ${match}`);_x000D_
});_x000D_
}
_x000D_
jex.im visualizes regular expressions:
Had the very same problem, then I remembered that for security reasons ASP doesn't expose the entire error or stack trace when accessing your site/service remotely, same as not being able to test a .asmx
web service remotely, so I remoted into the sever and monitored my dev tools, and only then did I get the notorious message "Could not load file or assembly 'Newtonsoft.Json, Version=3.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'
or one of its dep...".
So log on the server and debug from there.
java.io.IOException: Connection reset by peer
In my case, the problem was with PUT requests (GET and POST were passing successfully).
Communication went through VPN tunnel and ssh connection. And there was a firewall with default restrictions on PUT requests... PUT requests haven't been passing throughout, to the server...
Problem was solved after exception was added to the firewall for my IP address.
A simple way of reading variables from a text file using the standard library:
# Get vars from conf file
var = {}
with open("myvars.conf") as conf:
for line in conf:
if ":" in line:
name, value = line.split(":")
var[name] = str(value).rstrip()
globals().update(var)
Tested on a Huawei P20:
Reinstall Google Play: (Source)
Restart device.
Note: before finding this solution, I followed the instructions from some of the other answers here: removed my Google account from my device and added it again, cleared data and cache from various google play apps. This may or may not be necessary; feedback is welcome.
i use this code for navbar on bootstrap 3.2.0, the image should be at most 50px high, or else it will bleed the standard bs navbar.
Notice that i purposely do not use the class='navbar-brand' as that introduces padding on the image
<div class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="" href="/"><img src='img/anyWidthx50.png'/></a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse navbar-ex1-collapse">
<ul class="nav navbar-nav">
<li class="active"><a href="#">Active Link</a></li>
<li><a href="#">More Links</a></li>
</ul>
</div><!-- /.navbar-collapse -->
</div>
</div>
This is the correct way.
>>> x = [ ['0,0', '0,1'], ['1,0', '1,1'], ['2,0', '2,1'] ]
>>> for i in range(len(x)):
for j in range(len(x[i])):
print(x[i][j])
0,0
0,1
1,0
1,1
2,0
2,1
>>>
You could try to override the value returned, rather than setting it. The method is declared as { get }, so just provide a getter:
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
If you set this conditionally, you'll need to call setNeedsStatusBarAppearanceUpdate()
so it'll animate the change when you're ready
Only justification for moving your application to 64 bit is need for more memory in applications like large databases or ERP applications with at least 100s of concurrent users where 2 GB limit will be exceeded fairly quickly when applications cache for better performance. This is case specially on Windows OS where integer and long is still 32 bit (they have new variable _int64. Only pointers are 64 bit. In fact WOW64 is highly optimised on Windows x64 so that 32 bit applications run with low penalty on 64 bit Windows OS. My experience on Windows x64 is 32 bit application version run 10-15% faster than 64 bit since in former case at least for proprietary memory databases you can use pointer arithmatic for maintaining b-tree (most processor intensive part of database systems). Compuatation intensive applications which require large decimals for highest accuracy not afforded by double on 32-64 bit operating system. These applications can use _int64 in natively instead of software emulation. Of course large disk based databases will also show improvement over 32 bit simply due to ability to use large memory for caching query plans and so on.
@{ bool testVar = ((bool)item.testVar ? true : false); }
@Html.DisplayFor(modelItem => testVar)
select id,phno,case gender
when 'G' then 'M'
when 'L' then 'F'
else
'No gender'
end
as gender
from contacts
Try one of this solutions:
1. The browser fails to load the compressed script
This is usually the case if you get the error on IE6, but not on other browsers.
The Script Resource Handler – ScriptResource.axd compresses the scripts before returning them to the browser. In pre-RTM releases, the handler did it all the time for all browsers, and it wasn’t configurable. There is an issue in one of the components of IE6 that prevents it from loading compressed scripts correctly. See KB article here. In RTM builds, we’ve made two fixes for this. One, we don’t compress if IE6 is the browser client. Two, we’ve now made compression configurable. Here’s how you can toggle the web.config.
How do you fix it? First, make sure you are using the AJAX Extensions 1.0 RTM release. That alone should be enough. You can also try turning off compression by editing your web.config to have the following:
<system.web.extensions>
<scripting>
<scriptResourceHandler enableCompression="false" enableCaching="true" />
</scripting>
</system.web.extensions>
2. The required configuration for ScriptResourceHandler doesn’t exist for the web.config for your application
Make sure your web.config contains the entries from the default web.config file provided with the extensions install. (default location: C:\Program Files\Microsoft ASP.NET\ASP.NET 2.0 AJAX Extensions\v1.0.61025)
3. The virtual directory you are using for your web, isn’t correctly marked as an application (thus the configuration isn’t getting loaded) - This would happen for IIS webs.
Make sure that you are using a Web Application, and not just a Virtual Directory
4. ScriptResource.axd requests return 404
This usually points to a mis-configuration of ASP.NET as a whole. On a default installation of ASP.NET, any web request to a resource ending in .axd is passed from IIS to ASP.NET via an isapi mapping. Additionally the mapping is configured to not check if the file exists. If that mapping does not exist, or the check if file exists isn't disabled, then IIS will attempt to find the physical file ScriptResource.axd, won't find it, and return 404.
You can check to see if this is the problem by coipy/pasting the full url to ScriptResource.axd from here, and seeing what it returns
<script src="/MyWebApp/ScriptResource.axd?[snip - long query string]" type="text/javascript"></script>
How do you fix this? If ASP.NET isn't properly installed at all, you can run the "aspnet_regiis.exe" command line tool to fix it up. It's located in C:\WINDOWS\Microsoft.Net\Framework\v2.0.50727. You can run "aspnet_regiis -i -enable", which does the full registration of ASP.NET with IIS and makes sure the ISAPI is enabled in IIS6. You can also run "aspnet_regiis -s w3svc/1/root/MyWebApp" to only fix up the registration for your web application.
5. Resolving the "Sys is undefined" error in ASP.NET AJAX RTM under IIS 7
Put this entry under <system.webServer/><handlers/>
:
<add name="ScriptResource" preCondition="integratedMode" verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
and remove the one under <system.web/><httpHandlers/>
.
References: http://weblogs.asp.net/chrisri/demystifying-sys-is-undefined http://geekswithblogs.net/lorint/archive/2007/03/28/110161.aspx
This one solved my issue which is SELinux setting:
chcon -R -t httpd_sys_content_t /home/*