You don't actually have SDK version 7.0A installed? That's a problem you'll need to fix. Look in the VS2010 install log files to see what went wrong. The SDK should be present in c:\program files\microsoft sdks\windows\7.0a and the listed registry key must be present as well. Running with the 6.0a version of sgen.exe isn't okay, it is bound to use the wrong compiler.
Break-down:
8
says that you want to show 8 digits0
that you want to prefix with 0
's instead of just blank spacesx
that you want to print in lower-case hexadecimal.Quick example (thanks to Grijesh Chauhan):
#include <stdio.h>
int main() {
int data = 29;
printf("%x\n", data); // just print data
printf("%0x\n", data); // just print data ('0' on its own has no effect)
printf("%8x\n", data); // print in 8 width and pad with blank spaces
printf("%08x\n", data); // print in 8 width and pad with 0's
return 0;
}
Output:
1d
1d
1d
0000001d
Also see http://www.cplusplus.com/reference/cstdio/printf/ for reference.
JPA doesn't provide any specification on mapping annotations to select fetch strategy. In general, related entities can be fetched in any one of the ways given below
So SELECT
and JOIN
are two extremes and SUBSELECT
falls in between. One can choose suitable strategy based on her/his domain model.
By default SELECT
is used by both JPA/EclipseLink and Hibernate. This can be overridden by using:
@Fetch(FetchMode.JOIN)
@Fetch(FetchMode.SUBSELECT)
in Hibernate. It also allows to set SELECT
mode explicitly using @Fetch(FetchMode.SELECT)
which can be tuned by using batch size e.g. @BatchSize(size=10)
.
Corresponding annotations in EclipseLink are:
@JoinFetch
@BatchFetch
Try this. Here is the code to get the sheet names in order.
private Dictionary<int, string> GetExcelSheetNames(string fileName)
{
Excel.Application _excel = null;
Excel.Workbook _workBook = null;
Dictionary<int, string> excelSheets = new Dictionary<int, string>();
try
{
object missing = Type.Missing;
object readOnly = true;
Excel.XlFileFormat.xlWorkbookNormal
_excel = new Excel.ApplicationClass();
_excel.Visible = false;
_workBook = _excel.Workbooks.Open(fileName, 0, readOnly, 5, missing,
missing, true, Excel.XlPlatform.xlWindows, "\\t", false, false, 0, true, true, missing);
if (_workBook != null)
{
int index = 0;
foreach (Excel.Worksheet sheet in _workBook.Sheets)
{
// Can get sheet names in order they are in workbook
excelSheets.Add(++index, sheet.Name);
}
}
}
catch (Exception e)
{
return null;
}
finally
{
if (_excel != null)
{
if (_workBook != null)
_workBook.Close(false, Type.Missing, Type.Missing);
_excel.Application.Quit();
}
_excel = null;
_workBook = null;
}
return excelSheets;
}
From Google OAuth2.0 for Client documentation,
Ignore the chrome warning. There is no standard MIME type for OTF fonts.
font/opentype may silence the warning, but that doesn't make it the "right" thing to do.
Arguably, you're better off making one up, e.g. with "application/x-opentype" because at least "application" is a registered content type, while "font" is not.
Update: OTF remains a problem, but WOFF grew an IANA MIME type of application/font-woff in January 2013.
Update 2: OTF has grown a MIME type: application/font-sfnt In March 2013. This type also applies to .ttf
can't you use a
System.out.printf("%n%,d",int name);
The comma in the printf
should add the commas into the %d
inter.
Not positive about it, but works for me.
In the receiving activity
Bundle extras = getIntent().getExtras();
String userName;
if (extras != null) {
userName = extras.getString("name");
// and get whatever type user account id is
}
This is not possible the way you are trying it. The Jackson unmarshalling works on the compiled java code after type erasure. So your
public @ResponseBody ModelMap setTest(@RequestBody List<TestS> refunds, ModelMap map)
is really only
public @ResponseBody ModelMap setTest(@RequestBody List refunds, ModelMap map)
(no generics in the list arg).
The default type Jackson creates when unmarshalling a List
is a LinkedHashMap
.
As mentioned by @Saint you can circumvent this by creating your own type for the list like so:
class TestSList extends ArrayList<TestS> { }
and then modifying your controller signature to
public @ResponseBody ModelMap setTest(@RequestBody TestSList refunds, ModelMap map) {
Unfortunately, git branch -a
and git branch -r
do not show you all remote branches, if you haven't executed a "git fetch".
git remote show origin
works consistently all the time. Also git show-ref
shows all references in the Git repository. However, it works just like the git branch
command.
Try the Apache POI HSSF. Here's an example on how to read an excel file:
try {
POIFSFileSystem fs = new POIFSFileSystem(new FileInputStream(file));
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = wb.getSheetAt(0);
HSSFRow row;
HSSFCell cell;
int rows; // No of rows
rows = sheet.getPhysicalNumberOfRows();
int cols = 0; // No of columns
int tmp = 0;
// This trick ensures that we get the data properly even if it doesn't start from first few rows
for(int i = 0; i < 10 || i < rows; i++) {
row = sheet.getRow(i);
if(row != null) {
tmp = sheet.getRow(i).getPhysicalNumberOfCells();
if(tmp > cols) cols = tmp;
}
}
for(int r = 0; r < rows; r++) {
row = sheet.getRow(r);
if(row != null) {
for(int c = 0; c < cols; c++) {
cell = row.getCell((short)c);
if(cell != null) {
// Your code here
}
}
}
}
} catch(Exception ioe) {
ioe.printStackTrace();
}
On the documentation page you also have examples of how to write to excel files.
Put this code somewhere in your C++ project:
#ifdef _DEBUG
TCHAR version[50];
sprintf(&version[0], "Version = %d", _MSC_VER);
MessageBox(NULL, (LPCTSTR)szMsg, "Visual Studio", MB_OK | MB_ICONINFORMATION);
#endif
Note that _MSC_VER
symbol is Microsoft specific. Here you can find a list of Visual Studio versions with the value for _MSC_VER
for each version.
Seems like it can be one of a thousand things.
For me, I was initially pushing master and develop (master had no changes) via SourceTree. Changing this to develop only worked.
Simply floating both elements left achieves the same result.
div {
background:yellow;
vertical-align:middle;
margin:10px;
}
a {
background-color:#FFF;
width:20px;
height:20px;
display:inline-block;
border:solid black 1px;
float:left;
}
span {
background:red;
display:inline-block;
float:left;
}
Just a note of a peculiarity I faced:
Consider:
db server: 192.168.0.101
web server: 192.168.0.102
If you have a user defined in mysql.user as 'user'@'192.168.0.102'
with password1 and another 'user'@'192.168.0.%'
with password2,
then,
if you try to connect to the db server from the web server as 'user' with password2,
it will result in an 'Access denied' error because the single IP 'user'@'192.168.0.102'
authentication is used over the wildcard 'user'@'192.168.0.%'
authentication.
Place this line before the closing script tag,writing from memory:
window.onload = GetTimeZoneOffset;
i think the question is how to call the javascript function on pageload
Add this line before main function:
void swapCase (char* name);
int main()
{
...
swapCase(name); // swapCase prototype should be known at this point
...
}
This is called forward declaration: compiler needs to know function prototype when function call is compiled.
dummyElem.focus() where dummyElem is a hidden object (e.g. has negative zIndex)?
Handles either type of line break
str.replace(new RegExp('\r?\n','g'), '<br />');
Active mode: -server initiates the connection.
Passive mode: -client initiates the connection.
Note :- Certainly in python-3x you need to use Range function It works to generate numbers on demand, standard method to use Range function to make a list of consecutive numbers is
x=list(range(10))
#"list"_will_make_all_numbers_generated_by_range_in_a_list
#number_in_range_(10)_is_an_option_you_can_change_as_you_want
print (x)
#Output_is_ [0,1,2,3,4,5,6,7,8,9]
Also if you want to make an function to generate a list of consecutive numbers by using Range function watch this code !
def consecutive_numbers(n) :
list=[i for i in range(n)]
return (list)
print(consecutive_numbers(10))
Good Luck!
This error can typically occur when you have a typo in the branch name.
For example you're on the branch adminstration
and you want to invoke:
git push origin administration
.
Notice that you're on the branch without second i
letter: admin(i)stration
, that's why git prevents you from pushing to a different branch!
Try this:
private void comboBox1_KeyDown(object sender, KeyEventArgs e)
{
// comboBox1 is readonly
e.SuppressKeyPress = true;
}
In summary:
The ApplicationContext includes all functionality of the BeanFactory. It is generally recommended to use the former.
There are some limited situations such as in a Mobile application, where memory consumption might be critical.
In that scenarios, It can be justifiable to use the more lightweight BeanFactory. However, in the most enterprise applications, the ApplicationContext is what you will want to use.
For more, see my blog post:
Take a closer look at the ?axis
documentation. If you look at the description of the labels
argument, you'll see that it is:
"a logical value specifying whether (numerical) annotations are
to be made at the tickmarks,"
So, just change it to true, and you'll get your tick labels.
x <- seq(10,200,10)
y <- runif(x)
plot(x,y,xaxt='n')
axis(side = 1, at = x,labels = T)
# Since TRUE is the default for labels, you can just use axis(side=1,at=x)
Be careful that if you don't stretch your window width, then R might not be able to write all your labels in. Play with the window width and you'll see what I mean.
It's too bad that you had such trouble finding documentation! What were your search terms? Try typing r axis
into Google, and the first link you will get is that Quick R page that I mentioned earlier. Scroll down to "Axes", and you'll get a very nice little guide on how to do it. You should probably check there first for any plotting questions, it will be faster than waiting for a SO reply.
You could use eventlet. It lets you write what appears to be synchronous code, but have it operate asynchronously over the network.
Here's an example of a super minimal crawler:
urls = ["http://www.google.com/intl/en_ALL/images/logo.gif",
"https://wiki.secondlife.com/w/images/secondlife.jpg",
"http://us.i1.yimg.com/us.yimg.com/i/ww/beta/y3.gif"]
import eventlet
from eventlet.green import urllib2
def fetch(url):
return urllib2.urlopen(url).read()
pool = eventlet.GreenPool()
for body in pool.imap(fetch, urls):
print "got body", len(body)
I also got a similar error but in my case it was Error:java: invalid source release: 11... So I just changed all the annotations of java 11 to java 8 and even if the annotation was java 8, I just leaved it like that. I hope it helps you to fix the issue.
This is item A.1 in the RMI FAQ. You need to either fix your /etc/hosts file or set the java.rmi.server.hostname
property at the server.
The optimizer often cannot use the relational algebra to transform the problem when a cursor method is used. Often a cursor is a great way to solve a problem, but SQL is a declarative language, and there is a lot of information in the database, from constraints, to statistics and indexes which mean that the optimizer has a lot of options to solve the problem, whereas a cursor pretty much explicitly directs the solution.
As said elsewhere on here, proguard is good, but what might not be known is that there is also a third-party maven plugin for it here http://pyx4me.com/pyx4me-maven-plugins/proguard-maven-plugin/...I've used them both together and they're very good.
According to the above,i found three ways to solve the problem.
AnotherMongoDocument._id.toString()
JSON.stringify(AnotherMongoDocument._id)
results.userId.equals(AnotherMongoDocument._id)
We can mock list properly for foreach loop. Please find below code snippet and explanation.
This is my actual class method where I want to create test case by mocking list.
this.nameList
is a list object.
public void setOptions(){
// ....
for (String str : this.nameList) {
str = "-"+str;
}
// ....
}
The foreach loop internally works on iterator, so here we crated mock of iterator.
Mockito framework has facility to return pair of values on particular method call by using Mockito.when().thenReturn()
, i.e. on hasNext()
we pass 1st true and on second call false, so that our loop will continue only two times. On next()
we just return actual return value.
@Test
public void testSetOptions(){
// ...
Iterator<SampleFilter> itr = Mockito.mock(Iterator.class);
Mockito.when(itr.hasNext()).thenReturn(true, false);
Mockito.when(itr.next()).thenReturn(Mockito.any(String.class);
List mockNameList = Mockito.mock(List.class);
Mockito.when(mockNameList.iterator()).thenReturn(itr);
// ...
}
In this way we can avoid sending actual list to test by using mock of list.
Short answer: No.
But you might be able to do it with a bit of filthing. If you open up a test page (with GET) then evaluate some JavaScript on that page you should be able to replicate a POST request. See JavaScript post request like a form submit to see how you can replicate a POST request in JavaScript.
Hope this helps.
The call to time(NULL)
returns the current calendar time (seconds since Jan 1, 1970). See this reference for details. Ordinarily, if you pass in a pointer to a time_t
variable, that pointer variable will point to the current time.
you can use command line query and execute in mssql:
exec xp_cmdshell 'ipconfig'
you are describing a Problem, which I would try to solve with the VLOOKUP function rather than using VBA.
You should always consider a non-vba solution first.
Here are some application examples of VLOOKUP (or SVERWEIS in German, as i know it):
http://www.youtube.com/watch?v=RCLUM0UMLXo
http://office.microsoft.com/en-us/excel-help/vlookup-HP005209335.aspx
If you have to make it as a macro, you could use VLOOKUP as an application function - a quick solution with slow performance - or you will have to make a simillar function yourself.
If it has to be the latter, then there is need for more details on your specification, regarding performance questions.
You could copy any range to an array, loop through this array and check for your value, then copy this value to any other range. This is how i would solve this as a vba-function.
This would look something like that:
Public Sub CopyFilter()
Dim wks As Worksheet
Dim avarTemp() As Variant
'go through each worksheet
For Each wks In ThisWorkbook.Worksheets
avarTemp = wks.UsedRange
For i = LBound(avarTemp, 1) To UBound(avarTemp, 1)
'check in the first column in each row
If avarTemp(i, LBound(avarTemp, 2)) = "XYZ" Then
'copy cell
targetWks.Cells(1, 1) = avarTemp(i, LBound(avarTemp, 2))
End If
Next i
Next wks
End Sub
Ok, now i have something nice which could come in handy for myself:
Public Function FILTER(ByRef rng As Range, ByRef lngIndex As Long) As Variant
Dim avarTemp() As Variant
Dim avarResult() As Variant
Dim i As Long
avarTemp = rng
ReDim avarResult(0)
For i = LBound(avarTemp, 1) To UBound(avarTemp, 1)
If avarTemp(i, 1) = "active" Then
avarResult(UBound(avarResult)) = avarTemp(i, lngIndex)
'expand our result array
ReDim Preserve avarResult(UBound(avarResult) + 1)
End If
Next i
FILTER = avarResult
End Function
You can use it in your Worksheet like this =FILTER(Tabelle1!A:C;2) or with =INDEX(FILTER(Tabelle1!A:C;2);3) to specify the result row. I am sure someone could extend this to include the index functionality into FILTER or knows how to return a range like object - maybe I could too, but not today ;)
You can also do,
getDefaultProps: ->
firstName: 'Rails'
lastName: 'React'
now access, those constant (default value) using
@props.firstName
@props.lastName
Hope this help!!!.
I have found a way to make your application run well when the device reboots, please follow the steps below to be successful.
AndroidManifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="pack.saltriver" android:versionCode="1" android:versionName="1.0">
<uses-permission
android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".UIBootReceiver" android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<service android:name=".class_Service" />
</application>
UIBootReceiver
public class UIBootReceiver extends BroadcastReceiver {
private static final String TAG = "UIBootReceiver";
@Override
public void onReceive(Context context, Intent arg1)
{
Toast.makeText(context, "started", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context,class_Service.class);
context.startService(intent);
}
}
This is asking permission to not need to manage battery saving for this app so you can run in the background stably.
Declare this code in onCreate () of MainActivity class:
Intent myIntent = new Intent();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
myIntent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
myIntent.setData(Uri.parse("package:" +
DeviceMovingSpeed.this.getPackageName()));
}
startActivity(myIntent);
Had a need for similar functionality myself, so after much hair pulling I came up with the function below
/**
* Fetches angle relative to screen centre point
* where 3 O'Clock is 0 and 12 O'Clock is 270 degrees
*
* @param screenPoint
* @return angle in degress from 0-360.
*/
public double getAngle(Point screenPoint) {
double dx = screenPoint.getX() - mCentreX;
// Minus to correct for coord re-mapping
double dy = -(screenPoint.getY() - mCentreY);
double inRads = Math.atan2(dy, dx);
// We need to map to coord system when 0 degree is at 3 O'clock, 270 at 12 O'clock
if (inRads < 0)
inRads = Math.abs(inRads);
else
inRads = 2 * Math.PI - inRads;
return Math.toDegrees(inRads);
}
The easiest way seems to be subtracting the second number from the first:
var numericArray:Array<number> = [2,3,4,1,5,8,11];
var sorrtedArray:Array<number> = numericArray.sort((n1,n2) => n1 - n2);
DateTime dt = DateTime.ParseExact(yourObject.ToString(), "MM/dd/yyyy hh:mm:ss tt", CultureInfo.InvariantCulture);
string s = dt.ToString("dd/M/yyyy", CultureInfo.InvariantCulture);
You may need to format
the out put as follows.
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date convertedCurrentDate = sdf.parse("2013-09-18");
String date=sdf.format(convertedCurrentDate );
System.out.println(date);
Use
String convertedCurrentDate =sdf.format(sdf.parse("2013-09-18"));
Output:
2013-09-18
For everybody that falls off google, in here, this is the fix for VSCode 1.40 (2019):
Open the global settings.json: File > Preferences > Settings
Then select the tab 'User', open the section 'Extensions', click on 'C/C++'. Then scroll the right panel till you find a 'Edit in settings.json' button.
Last, you add the "C_Cpp.default.includePath" section. The code provided there is from my own system (Windows 7). You can use it as a base for your own libraries paths. (Remember to change the YOUR USERNAME
to your correct system (my case windows) username)
(edit info: There is a problem with the recursion of my approach. VSCode doesn't like multiple definitions for the same thing. I solved it with "C_Cpp.intelliSenseEngine": "Tag Parser"
)
the code before line 7, on the settings.json has nothing to do with arduino or includePath. You may not copy that...
JSON section to add to settings.json:
"C_Cpp.default.includePath": [
"C:/Program Files (x86)/Arduino/libraries/**",
"C:/Program Files (x86)/Arduino/hardware/arduino/avr/cores/arduino/**",
"C:/Program Files (x86)/Arduino/hardware/tools/avr/avr/include/**",
"C:/Program Files (x86)/Arduino/hardware/tools/avr/lib/gcc/avr/5.4.0/include/**",
"C:/Program Files (x86)/Arduino/hardware/arduino/avr/variants/standard/**",
"C:/Users/<YOUR USERNAME>/.platformio/packages/framework-arduinoavr/**",
"C:/Users/<YOUR USERNAME>/Documents/Arduino/libraries/**",
"{$workspaceFolder}/libraries/**",
"{$workspaceFolder}/**"
],
"C_Cpp.intelliSenseEngine": "Tag Parser"
You can use "ELSE IF" using conditional operator in expression language as below:
<p:outputLabel value="#{transaction.status.equals('PNDNG')?'Pending':
transaction.status.equals('RJCTD')?'Rejected':
transaction.status.equals('CNFRMD')?'Confirmed':
transaction.status.equals('PSTD')?'Posted':''}"/>
Use pyplot.text()
(import matplotlib.pyplot as plt
)
import matplotlib.pyplot as plt
x=[1,2,3]
y=[9,8,7]
plt.plot(x,y)
for a,b in zip(x, y):
plt.text(a, b, str(b))
plt.show()
In the box is working on being able to convert android projects to iOS
So, the idea is to convert character numbers (in single quotes, e.g. '8') to integer expression. For instance char c = '8'; int i = c - '0' //would yield integer 8; And sum up all the converted numbers by the principle that 908=9*100+0*10+8, which is done in a loop.
char t[5] = {'-', '9', '0', '8', '\0'}; //Should be terminated properly.
int s = 1;
int i = -1;
int res = 0;
if (c[0] == '-') {
s = -1;
i = 0;
}
while (c[++i] != '\0') { //iterate until the array end
res = res*10 + (c[i] - '0'); //generating the integer according to read parsed numbers.
}
res = res*s; //answer: -908
In your MakeFile or CMakeLists.txt you can set CMAKE_CXX_FLAGS as below:
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/path/to/your/folder")
Be aware that there are problems using .NET/C# and any COM port higher than COM9.
See: HOWTO: Specify Serial Ports Larger than COM9
There is a workaround in the format: "\\.\COM10" that is supported in the underlying CreateFile method, but .NET prevents using that workaround format; neither the SerialPort constructor nor the PortName property will allow a port name that begins with "\"
I've been struggling to get reliable communications to COM10 in C#/.NET. As an example, if I have a device on COM9 and COM10, traffic intended for COM10 goes to the device on COM9! If I remove the device on COM9, COM10 traffic goes to the device on COM10.
I still haven't figured how to use the handle returned by CreateFile to create a C#/.NET style SerialPort object, if I knew how to do that, then I think I could use COM10+ just fine from C#.
Assuming you have the public keys inside X.509 certificates, and assuming they are RSA keys, then for each public key, do
openssl x509 -in certfile -modulus -noout
For each private key, do
openssl rsa -in keyfile -modulus -noout
Then match the keys by modulus.
For me the main difference was the declaration of the function....
INSTEAD OF
function initMap() {
...
}
THIS WORKED
window.initMap = function () {
...
}
I think you will want to use ThreadSafeClientConnManager.
You can see how it works here: http://foo.jasonhudgins.com/2009/08/http-connection-reuse-in-android.html
Or in the AndroidHttpClient
which uses it internally.
If you already know size of the char*, use this instead
char* data = ...;
int size = ...;
std::string myString(data, size);
This doesn't use strlen.
EDIT: If string variable already exists, use assign():
std::string myString;
char* data = ...;
int size = ...;
myString.assign(data, size);
Why do you have the brackets around digit
?
It should be
NSLog("%@", digit);
You're also missing an =
in the first line...
NSString *digit = [[sender titlelabel] text];
You can do this with SQL Server Management Studio.
? Right click the table design and go to Relationships and choose the foreign key on the left-side pane and in the right-side pane, expand the menu "INSERT and UPDATE specification" and select "Cascade" as Delete Rule.
Why not both?
string ReplacementString = "";
Regex.Replace(strin.Replace(System.Environment.NewLine, ReplacementString), @"(\r\n?|\n)", ReplacementString);
Note: Replace strin
with the name of your input string.
Solution for me.
Step: 1
<a onclick="exportAsExcel()">Export to excel</a>
Step: 2
I'm using file-saver lib.
Read more: https://www.npmjs.com/package/file-saver
npm i file-saver
Step: 3
let FileSaver = require('file-saver'); // path to file-saver
function exportAsExcel() {
let dataBlob = '...kAAAAFAAIcmtzaGVldHMvc2hlZXQxLnhtbFBLBQYAAAAACQAJAD8CAADdGAAAAAA='; // If have ; You should be split get blob data only
this.downloadFile(dataBlob);
}
function downloadFile(blobContent){
let blob = new Blob([base64toBlob(blobContent, 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet')], {});
FileSaver.saveAs(blob, 'report.xlsx');
}
function base64toBlob(base64Data, contentType) {
contentType = contentType || '';
let sliceSize = 1024;
let byteCharacters = atob(base64Data);
let bytesLength = byteCharacters.length;
let slicesCount = Math.ceil(bytesLength / sliceSize);
let byteArrays = new Array(slicesCount);
for (let sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
let begin = sliceIndex * sliceSize;
let end = Math.min(begin + sliceSize, bytesLength);
let bytes = new Array(end - begin);
for (var offset = begin, i = 0; offset < end; ++i, ++offset) {
bytes[i] = byteCharacters[offset].charCodeAt(0);
}
byteArrays[sliceIndex] = new Uint8Array(bytes);
}
return new Blob(byteArrays, { type: contentType });
}
Work for me. ^^
Uncheck "Size Classes" checkbox works for me as well, but you could also add the missing constraints in the interface builder. Just use the built-in function if you don't want to add the constraints on your own. Using constraints is - in my opinion - the better way because the layout is independent from the device (iPhone or iPad).
Here ya go:
viewNoteDateMonth.text = [[displayDate objectAtIndex:2] uppercaseString];
Btw:
"april"
is lowercase
? [NSString lowercaseString]
"APRIL"
is UPPERCASE
? [NSString uppercaseString]
"April May"
is Capitalized/Word Caps
? [NSString capitalizedString]
"April may"
is Sentence caps
? (method missing; see workaround below)
Hence what you want is called "uppercase", not "capitalized". ;)
As for "Sentence Caps" one has to keep in mind that usually "Sentence" means "entire string". If you wish for real sentences use the second method, below, otherwise the first:
@interface NSString ()
- (NSString *)sentenceCapitalizedString; // sentence == entire string
- (NSString *)realSentenceCapitalizedString; // sentence == real sentences
@end
@implementation NSString
- (NSString *)sentenceCapitalizedString {
if (![self length]) {
return [NSString string];
}
NSString *uppercase = [[self substringToIndex:1] uppercaseString];
NSString *lowercase = [[self substringFromIndex:1] lowercaseString];
return [uppercase stringByAppendingString:lowercase];
}
- (NSString *)realSentenceCapitalizedString {
__block NSMutableString *mutableSelf = [NSMutableString stringWithString:self];
[self enumerateSubstringsInRange:NSMakeRange(0, [self length])
options:NSStringEnumerationBySentences
usingBlock:^(NSString *sentence, NSRange sentenceRange, NSRange enclosingRange, BOOL *stop) {
[mutableSelf replaceCharactersInRange:sentenceRange withString:[sentence sentenceCapitalizedString]];
}];
return [NSString stringWithString:mutableSelf]; // or just return mutableSelf.
}
@end
After show table, above the table ( +options ) Hyperlink is there.
Use an EmptyDataTemplate like below. When your DataSource has no records, you will see your grid with headers, and the literal text or HTML that is inside the EmptyDataTemplate tags.
<asp:GridView ID="gvResults" AutoGenerateColumns="False" HeaderStyle-CssClass="tableheader" runat="server">
<EmptyDataTemplate>
<asp:Label ID="lblEmptySearch" runat="server">No Results Found</asp:Label>
</EmptyDataTemplate>
<Columns>
<asp:BoundField DataField="ItemId" HeaderText="ID" />
<asp:BoundField DataField="Description" HeaderText="Description" />
...
</Columns>
</asp:GridView>
You can create a config class witch static properties
class Config
{
static $dbHost = 'localhost';
static $dbUsername = 'user';
static $dbPassword = 'pass';
}
then you can simple use it:
Config::$dbHost
Sometimes in my projects I use a design pattern SINGLETON to access configuration data. It's very comfortable in use.
Why?
For example you have 2 data source in your project. And you can choose witch of them is enabled.
Somewhere in config file you choose:
$dataSource = 'mysql' // or 'json'
When you change source whole app shoud switch to new data source, work fine and dont need change in code.
Example:
Config:
class Config
{
// ....
static $dataSource = 'mysql';
/ .....
}
Singleton class:
class AppConfig
{
private static $instance;
private $dataSource;
private function __construct()
{
$this->init();
}
private function init()
{
switch (Config::$dataSource)
{
case 'mysql':
$this->dataSource = new StorageMysql();
break;
case 'json':
$this->dataSource = new StorageJson();
break;
default:
$this->dataSource = new StorageMysql();
}
}
public static function getInstance()
{
if (empty(self::$instance)) {
self::$instance = new self();
}
return self::$instance;
}
public function getDataSource()
{
return $this->dataSource;
}
}
... and somewhere in your code (eg. in some service class):
$container->getItemsLoader(AppConfig::getInstance()->getDataSource()) // getItemsLoader need Object of specific data source class by dependency injection
We can obtain an AppConfig object from any place in the system and always get the same copy (thanks to static). The init () method of the class is called In the constructor, which guarantees only one execution. Init() body checks The value of the config $dataSource, and create new object of specific data source class. Now our script can get object and operate on it, not knowing even which specific implementation actually exists.
In command mode: : + 1 will take you to first line
You can't have this discussion without bringing up type systems.
The main features of functional programming include functions as first-class values, currying, immutable values, etc. It doesn't seem obvious to me that OO design patterns are approximating any of those features.
That's because these features don't address the same issues that OOP does... they are alternatives to imperative programming. The FP answer to OOP lies in the type systems of ML and Haskell... specifically sum types, abstract data types, ML modules, and Haskell typeclasses.
But of course there are still design patterns which are not solved by FP languages. What is the FP equivalent of a singleton? (Disregarding for a moment that singletons are generally a terrible pattern to use)
The first thing typeclasses do is eliminate the need for singletons.
You could go through the list of 23 and eliminate more, but I don't have time to right now.
i was having the same problem. and the problem was caused because i was listening to port 8080, on 2 listeners.
setMaxListeners()
works fine, but i would not recommend it.
the correct way is to, check your code for extra listeners, remove the listener or change the port number on which you are listening, this fixed my problem.
$JAVA_HOME/bin/java -version says 'Permission Denied'
If you cannot access or run code, it which be ignored if added to your path. You need to make it accessible and runnable or get a copy of your own.
Do an
ls -ld $JAVA_HOME $JAVA_HOME/bin $JAVA_HOME/bin/java
to see why you cannot access or run this program,.
What exactly do you want to know?
The shared library soname? That's part of the filename, libstdc++.so.6
, or shown by readelf -d /usr/lib64/libstdc++.so.6 | grep soname
.
The minor revision number? You should be able to get that by simply checking what the symlink points to:
$ ls -l /usr/lib/libstdc++.so.6
lrwxrwxrwx. 1 root root 19 Mar 23 09:43 /usr/lib/libstdc++.so.6 -> libstdc++.so.6.0.16
That tells you it's 6.0.16, which is the 16th revision of the libstdc++.so.6
version, which corresponds to the GLIBCXX_3.4.16
symbol versions.
Or do you mean the release it comes from? It's part of GCC so it's the same version as GCC, so unless you've screwed up your system by installing unmatched versions of g++
and libstdc++.so
you can get that from:
$ g++ -dumpversion
4.6.3
Or, on most distros, you can just ask the package manager. On my Fedora host that's
$ rpm -q libstdc++
libstdc++-4.6.3-2.fc16.x86_64
libstdc++-4.6.3-2.fc16.i686
As other answers have said, you can map releases to library versions by checking the ABI docs
To keep beginner attitude you can explain that all the command line is automaticaly splite in a array fo String (the String[]
).
For static
you have to explain, that it not a field like another : it is unique in the JVM even if you have thousand instances of the class
So main
is static, because it is the only way to find it (linked in its own class) in a jar
.
... after you look at coding, and your job begin ...
A litte late answer.
If you want to use a grid like this, you should have a look at Bootstrap, It's relatively easy to install, and it gives you exactly what you are looking for, all wrapped in nice and simple html/css + it works easily for making websites responsive.
This is often misunderstood so let me clear it up.
Static typing is where the type is bound to the variable. Types are checked at compile time.
Dynamic typing is where the type is bound to the value. Types are checked at run time.
So in Java for example:
String s = "abcd";
s
will "forever" be a String
. During its life it may point to different String
s (since s
is a reference in Java). It may have a null
value but it will never refer to an Integer
or a List
. That's static typing.
In PHP:
$s = "abcd"; // $s is a string
$s = 123; // $s is now an integer
$s = array(1, 2, 3); // $s is now an array
$s = new DOMDocument; // $s is an instance of the DOMDocument class
That's dynamic typing.
(Edit alert!)
Strong typing is a phrase with no widely agreed upon meaning. Most programmers who use this term to mean something other than static typing use it to imply that there is a type discipline that is enforced by the compiler. For example, CLU has a strong type system that does not allow client code to create a value of abstract type except by using the constructors provided by the type. C has a somewhat strong type system, but it can be "subverted" to a degree because a program can always cast a value of one pointer type to a value of another pointer type. So for example, in C you can take a value returned by malloc()
and cheerfully cast it to FILE*
, and the compiler won't try to stop you—or even warn you that you are doing anything dodgy.
(The original answer said something about a value "not changing type at run time". I have known many language designers and compiler writers and have not known one that talked about values changing type at run time, except possibly some very advanced research in type systems, where this is known as the "strong update problem".)
Weak typing implies that the compiler does not enforce a typing discpline, or perhaps that enforcement can easily be subverted.
The original of this answer conflated weak typing with implicit conversion (sometimes also called "implicit promotion"). For example, in Java:
String s = "abc" + 123; // "abc123";
This is code is an example of implicit promotion: 123 is implicitly converted to a string before being concatenated with "abc"
. It can be argued the Java compiler rewrites that code as:
String s = "abc" + new Integer(123).toString();
Consider a classic PHP "starts with" problem:
if (strpos('abcdef', 'abc') == false) {
// not found
}
The error here is that strpos()
returns the index of the match, being 0. 0 is coerced into boolean false
and thus the condition is actually true. The solution is to use ===
instead of ==
to avoid implicit conversion.
This example illustrates how a combination of implicit conversion and dynamic typing can lead programmers astray.
Compare that to Ruby:
val = "abc" + 123
which is a runtime error because in Ruby the object 123 is not implicitly converted just because it happens to be passed to a +
method. In Ruby the programmer must make the conversion explicit:
val = "abc" + 123.to_s
Comparing PHP and Ruby is a good illustration here. Both are dynamically typed languages but PHP has lots of implicit conversions and Ruby (perhaps surprisingly if you're unfamiliar with it) doesn't.
The point here is that the static/dynamic axis is independent of the strong/weak axis. People confuse them probably in part because strong vs weak typing is not only less clearly defined, there is no real consensus on exactly what is meant by strong and weak. For this reason strong/weak typing is far more of a shade of grey rather than black or white.
So to answer your question: another way to look at this that's mostly correct is to say that static typing is compile-time type safety and strong typing is runtime type safety.
The reason for this is that variables in a statically typed language have a type that must be declared and can be checked at compile time. A strongly-typed language has values that have a type at run time, and it's difficult for the programmer to subvert the type system without a dynamic check.
But it's important to understand that a language can be Static/Strong, Static/Weak, Dynamic/Strong or Dynamic/Weak.
For below detail steps and working example, you can visit https://loiane.com/2017/08/how-to-add-bootstrap-to-an-angular-cli-project/
Very details steps with proper explanation.
Steps: Installing Bootstrap from NPM
Next, we need to install Bootstrap. Change the directory to the project we created (cd angular-bootstrap-example) and execute the following command:
For Bootstrap 3:
npm install bootstrap --save
For Bootstrap 4 (currently in beta):
npm install bootstrap@next --save
OR Alternative: Local Bootstrap CSS As an alternative, you can also download the Bootstrap CSS and add it locally to your project. I donwloaded Bootstrap from the website and created a folder styles (same level as styles.css):
Note: Don’t place your local CSS files under assets folder. When we do the production build with Angular CLI, the CSS files declared in the .angular-cli.json will be minified and all styles will be bundled into a single styles.css. The assets folder is copied to the dist folder during the build process (the CSS code will be duplicated). Only place your local CSS files under assets in case you are importing them directly in the index.html.
Importing the CSS 1.We have two options to import the CSS from Bootstrap that was installed from NPM:
strong text1: Configure .angular-cli.json:
"styles": [
"../node_modules/bootstrap/dist/css/bootstrap.min.css",
"styles.scss"
]
2: Import directly in src/style.css or src/style.scss:
@import '~bootstrap/dist/css/bootstrap.min.css';
I personally prefer to import all my styles in src/style.css since it’s been declared in .angular-cli.json already.
3.1 Alternative: Local Bootstrap CSS If you added the Bootstrap CSS file locally, just import it in .angular-cli.json
"styles": [
"styles/bootstrap-3.3.7-dist/css/bootstrap.min.css",
"styles.scss"
],
or src/style.css
@import './styles/bootstrap-3.3.7-dist/css/bootstrap.min.css';
4: Bootstrap JavaScript Components with ngx-bootstrap (Option 1) In case you don’t need to use Bootstrap JavaScript components (that require JQuery), this is all the setup you need. But if you need to use modals, accordion, datepicker, tooltips or any other component, how can we use these components without installing jQuery?
There is an Angular wrapper library for Bootstrap called ngx-bootstrap that we can also install from NPM:
npm install ngx-bootstrap --save
Noteng2-bootstrap and ngx-bootstrap are the same package. ng2-bootstrap was renamed to ngx-bootstrap after #itsJustAngular.
In case you want to install Bootstrap and ngx-bootstrap at the same time when you create your Angular CLI project:
npm install bootstrap ngx-bootstrap --save
4.1: Adding the required Bootstrap modules in app.module.ts
Go through the ngx-bootstrap and add the modules needed in your app.module.ts. For example, suppose we want to use the Dropdown, Tooltip and Modal components:
import { BsDropdownModule } from 'ngx-bootstrap/dropdown';
import { TooltipModule } from 'ngx-bootstrap/tooltip';
import { ModalModule } from 'ngx-bootstrap/modal';
@NgModule({
imports: [
BrowserModule,
BsDropdownModule.forRoot(),
TooltipModule.forRoot(),
ModalModule.forRoot()
],
// ...
})
export class AppBootstrapModule {}
Because we call the .forRoot() method for each module (due the ngx-bootstrap module providers), the functionalities will be available in all components and modules of your project (global scope).
As an alternative, if you would like to organize the ngx-bootstrap in a different module (just for organization purposes in case you need to import many bs modules and don’t want to clutter your app.module), you can create a module app-bootstrap.module.ts, import the Bootstrap modules (using forRoot()) and also declare them in the exports section (so they become available to other modules as well).
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BsDropdownModule } from 'ngx-bootstrap/dropdown';
import { TooltipModule } from 'ngx-bootstrap/tooltip';
import { ModalModule } from 'ngx-bootstrap/modal';
@NgModule({
imports: [
CommonModule,
BsDropdownModule.forRoot(),
TooltipModule.forRoot(),
ModalModule.forRoot()
],
exports: [BsDropdownModule, TooltipModule, ModalModule]
})
export class AppBootstrapModule {}
At last, don’t forget to import your bootstrap module in you app.module.ts.
import { AppBootstrapModule } from './app-bootstrap/app-bootstrap.module';
@NgModule({
imports: [BrowserModule, AppBootstrapModule],
// ...
})
export class AppModule {}
ngx-bootstrap works with Bootstrap 3 and 4. And I also made some tests and most of the functionalities also work with Bootstrap 2.x (yes, I still have some legacy code to maintain).
Hope this help someone!
This link answer your question: http://wiki.netbeans.org/FaqI18nProjectEncoding
You can change the sources encoding or runtime encoding.
You don't need to use display:inline
to achieve this:
.inline {
border: 1px solid red;
margin:10px;
float:left;/*Add float left*/
margin :10px;
}
You can use float-left
.
Using float:left is best way to place multiple div elements in one line. Why? Because inline-block does have some problem when is viewed in IE older versions.
Microsoft now recommends using an IHttpClientFactory
instead of directly using HttpClient
:
https://docs.microsoft.com/en-us/aspnet/core/fundamentals/http-requests?view=aspnetcore-5.0
Example Mock with request that returns expected result:
private LoginController GetLoginController()
{
var expected = "Hello world";
var mockFactory = new Mock<IHttpClientFactory>();
var mockMessageHandler = new Mock<HttpMessageHandler>();
mockMessageHandler.Protected()
.Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
.ReturnsAsync(new HttpResponseMessage
{
StatusCode = HttpStatusCode.OK,
Content = new StringContent(expected)
});
var httpClient = new HttpClient(mockMessageHandler.Object);
mockFactory.Setup(_ => _.CreateClient(It.IsAny<string>())).Returns(httpClient);
var logger = Mock.Of<ILogger<LoginController>>();
var controller = new LoginController(logger, mockFactory.Object);
return controller;
}
Source:
EasyDict
library (doc):EasyDict allows to access dict values as attributes (works recursively). A Javascript-like properties dot notation for python dicts.
USEAGE
>>> from easydict import EasyDict as edict >>> d = edict({'foo':3, 'bar':{'x':1, 'y':2}}) >>> d.foo 3 >>> d.bar.x 1 >>> d = edict(foo=3) >>> d.foo 3
[INSTALLATION]:
pip install easydict
An even better idea is to use the requests_toolbelt library, which can dump out both requests and responses as strings for you to print to the console. It handles all the tricky cases with files and encodings which the above solution does not handle well.
It's as easy as this:
import requests
from requests_toolbelt.utils import dump
resp = requests.get('https://httpbin.org/redirect/5')
data = dump.dump_all(resp)
print(data.decode('utf-8'))
Source: https://toolbelt.readthedocs.org/en/latest/dumputils.html
You can simply install it by typing:
pip install requests_toolbelt
With pure javascript:
this === document.activeElement // where 'this' is a dom object
or with jquery's :focus
pseudo selector.
$(this).is(':focus');
I was trying to set up MediaWiki on my windows 7 pc and got this error.
My solution was to "create a global FastCGI handler mapping for php".
import platform
platform.architecture()
From the Python docs:
Queries the given executable (defaults to the Python interpreter binary) for various architecture information.
Returns a tuple (bits, linkage) which contain information about the bit architecture and the linkage format used for the executable. Both values are returned as strings.
Simple and readable snippet, using lodash.
You need to put the key in quotes only when calling sortBy. It doesn't have to be in quotes in the data itself.
_.sortBy(myObj, "key")
Also, your second parameter to map is wrong. It should be a function, but using pluck is easier.
_.map( _.sortBy(myObj, "key") , "value");
/etc/init.d/mysql stop
chown -R mysql:mysql /var/lib/mysql
mysql_install_db
/etc/init.d/mysql start
All this rescued my MySQL server!
From RFC 6750, Section 1.2:
Bearer Token
A security token with the property that any party in possession of the token (a "bearer") can use the token in any way that any other party in possession of it can. Using a bearer token does not require a bearer to prove possession of cryptographic key material (proof-of-possession).
The Bearer Token or Refresh token is created for you by the Authentication server. When a user authenticates your application (client) the authentication server then goes and generates for your a Bearer Token (refresh token) which you can then use to get an access token.
The Bearer Token is normally some kind of cryptic value created by the authentication server, it isn't random it is created based upon the user giving you access and the client your application getting access.
See also: Mozilla MDN Header Information.
Not 100% what you were looking for, but kind of an inside-out way of doing it:
SQL> CREATE TABLE mytable (id NUMBER, status VARCHAR2(50));
Table created.
SQL> INSERT INTO mytable VALUES (1,'Finished except pouring water on witch');
1 row created.
SQL> INSERT INTO mytable VALUES (2,'Finished except clicking ruby-slipper heels');
1 row created.
SQL> INSERT INTO mytable VALUES (3,'You shall (not?) pass');
1 row created.
SQL> INSERT INTO mytable VALUES (4,'Done');
1 row created.
SQL> INSERT INTO mytable VALUES (5,'Done with it.');
1 row created.
SQL> INSERT INTO mytable VALUES (6,'In Progress');
1 row created.
SQL> INSERT INTO mytable VALUES (7,'In progress, OK?');
1 row created.
SQL> INSERT INTO mytable VALUES (8,'In Progress Check Back In Three Days'' Time');
1 row created.
SQL> SELECT *
2 FROM mytable m
3 WHERE +1 NOT IN (INSTR(m.status,'Done')
4 , INSTR(m.status,'Finished except')
5 , INSTR(m.status,'In Progress'));
ID STATUS
---------- --------------------------------------------------
3 You shall (not?) pass
7 In progress, OK?
SQL>
Alternatively, you can use maven-assembly-plugin, as shown in the below example:
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<mainClass>com.package.MainClass</mainClass>
</manifest>
</archive>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
In this example all the dependency jars as specified in section will be automatically included in your single jar. Note that jar-with-dependencies should be literally put as, not to be replaced with the jar file names you want to include.
export CLASSPATH=/home/appnetix/LOG4J_HOME/log4j-1.2.16.jar
or, if you already have some classpath set
export CLASSPATH=$CLASSPATH:/home/appnetix/LOG4J_HOME/log4j-1.2.16.jar
and, if also you want to include current directory
export CLASSPATH=$CLASSPATH:/home/appnetix/LOG4J_HOME/log4j-1.2.16.jar:.
for what it's worth I'm using node.js 0.6.7 on OSX and I couldn't get 'Authorization':auth to work with our proxy, it needed to be set to 'Proxy-Authorization':auth my test code is:
var http = require("http");
var auth = 'Basic ' + new Buffer("username:password").toString('base64');
var options = {
host: 'proxyserver',
port: 80,
method:"GET",
path: 'http://www.google.com',
headers:{
"Proxy-Authorization": auth,
Host: "www.google.com"
}
};
http.get(options, function(res) {
console.log(res);
res.pipe(process.stdout);
});
If you have deleted multiple files locally but not committed, you can force checkout
$ git checkout -f HEAD
The "responsible" answer would be for me to suggest building a ViewModel for the dialog and use two-way databinding on the TextBox so that the ViewModel had some "ResponseText" property or what not. This is easy enough to do but probably overkill.
The pragmatic answer would be to just give your text box an x:Name so that it becomes a member and expose the text as a property in your code behind class like so:
<!-- Incredibly simplified XAML -->
<Window x:Class="MyDialog">
<StackPanel>
<TextBlock Text="Enter some text" />
<TextBox x:Name="ResponseTextBox" />
<Button Content="OK" Click="OKButton_Click" />
</StackPanel>
</Window>
Then in your code behind...
partial class MyDialog : Window {
public MyDialog() {
InitializeComponent();
}
public string ResponseText {
get { return ResponseTextBox.Text; }
set { ResponseTextBox.Text = value; }
}
private void OKButton_Click(object sender, System.Windows.RoutedEventArgs e)
{
DialogResult = true;
}
}
Then to use it...
var dialog = new MyDialog();
if (dialog.ShowDialog() == true) {
MessageBox.Show("You said: " + dialog.ResponseText);
}
Update using NuGet Package Manager
Console in your Visual Studio
Update-Package -reinstall Microsoft.AspNet.Mvc
When I needed to do an ajax call with all the form fields, I had problems with the :input selector returning all checkboxes whether or not they were checked. I added a new selector to just get the submit-able form elements:
$.extend($.expr[':'],{
submitable: function(a){
if($(a).is(':checkbox:not(:checked)'))
{
return false;
}
else if($(a).is(':input'))
{
return true;
}
else
{
return false;
}
}
});
usage:
$('#form_id :submitable');
I've not tested it with multiple select boxes yet though but It works for getting all the form fields in the way a standard submit would.
I used this when customising the product options on an OpenCart site to include checkboxes and text fields as well as the standard select box type.
To build on the previous answer if you add -f
you can tail the logs.
kubectl logs -f deployment/app
You need to install Python's header files (python-dev package in debian/ubuntu) to compile lxml. As well as libxml2, libxslt, libxml2-dev, and libxslt-dev:
apt-get install python-dev libxml2 libxml2-dev libxslt-dev
JavaScript is a client-side scripting language, which means all of the code is executed on the web user's machine. The POST variables, on the other hand, go to the server and reside there. Browsers do not provide those variables to the JavaScript environment, nor should any developer expect them to magically be there.
Since the browser disallows JavaScript from accessing POST data, it's pretty much impossible to read the POST variables without an outside actor like PHP echoing the POST values into a script variable or an extension/addon that captures the POST values in transit. The GET variables are available via a workaround because they're in the URL which can be parsed by the client machine.
Call clearAnimation()
on whichever View
you called startAnimation()
.
List.ForEach() is considered to be more functional.
List.ForEach()
says what you want done. foreach(item in list)
also says exactly how you want it done. This leaves List.ForEach
free to change the implementation of the how part in the future. For example, a hypothetical future version of .Net might always run List.ForEach
in parallel, under the assumption that at this point everyone has a number of cpu cores that are generally sitting idle.
On the other hand, foreach (item in list)
gives you a little more control over the loop. For example, you know that the items will be iterated in some kind of sequential order, and you could easily break in the middle if an item meets some condition.
Some more recent remarks on this issue are available here:
You can use InkWell to do that:
A rectangular area of a Material that responds to touch.
Below example demonstrate how to use InkWell
. Notice: you don't need StatefulWidget
to do that. I used it to change the state of the count.
Example:
import 'package:flutter/material.dart';
class SettingPage extends StatefulWidget {
@override
_SettingPageState createState() => new _SettingPageState();
}
class _SettingPageState extends State<SettingPage> {
int _count = 0;
@override
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(
child: new InkWell(// this is the one you are looking for..........
onTap: () => setState(() => _count++),
child: new Container(
//width: 50.0,
//height: 50.0,
padding: const EdgeInsets.all(20.0),//I used some padding without fixed width and height
decoration: new BoxDecoration(
shape: BoxShape.circle,// You can use like this way or like the below line
//borderRadius: new BorderRadius.circular(30.0),
color: Colors.green,
),
child: new Text(_count.toString(), style: new TextStyle(color: Colors.white, fontSize: 50.0)),// You can add a Icon instead of text also, like below.
//child: new Icon(Icons.arrow_forward, size: 50.0, color: Colors.black38)),
),//............
),
),
);
}
}
If you want to get benefit of splashColor
, highlightColor
, wrap InkWell
widget using a Material
widget with material type circle. And then remove decoration
in Container
widget.
Outcome:
Never alter the container you're looping on, because iterators on that container are not going to be informed of your alterations and, as you've noticed, that's quite likely to produce a very different loop and/or an incorrect one. In normal cases, looping on a copy of the container helps, but in your case it's clear that you don't want that, as the container will be empty after 50 legs of the loop and if you then try popping again you'll get an exception.
What's anything BUT clear is, what behavior are you trying to achieve, if any?! Maybe you can express your desires with a while
...?
i = 0
while i < len(some_list):
print i,
print some_list.pop(0),
print some_list.pop(0)
The problem here is that the "on" is applied to all elements that exists AT THE TIME. When you create an element dynamically, you need to run the on again:
$('form').on('submit',doFormStuff);
createNewForm();
// re-attach to all forms
$('form').off('submit').on('submit',doFormStuff);
Since forms usually have names or IDs, you can just attach to the new form as well. If I'm creating a lot of dynamic stuff, I'll include a setup or bind function:
function bindItems(){
$('form').off('submit').on('submit',doFormStuff);
$('button').off('click').on('click',doButtonStuff);
}
So then whenever you create something (buttons usually in my case), I just call bindItems to update everything on the page.
createNewButton();
bindItems();
I don't like using 'body' or document elements because with tabs and modals they tend to hang around and do things you don't expect. I always try to be as specific as possible unless its a simple 1 page project.
The easiest way to concat a static text string to a selected value is to use element.
<a>
<xsl:attribute name="href">
<xsl:value-of select="/*/properties/property[@name='report']/@value" />
<xsl:text>staticIconExample.png</xsl:text>
</xsl:attribute>
</a>
@Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(this).inflate(R.menu.folderview_options, menu);
return (super.onCreateOptionsMenu(menu));
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.locationListRefreshLocations) {
Cursor temp = helper.getEmployee(active_employeeId);
String[] matches = new String[1];
if (temp.moveToFirst()) {
matches[0] = helper.getEmployerID(temp);
}
temp.close();
startRosterReceiveBackgroundTask(matches);
} else if (item.getItemId()==R.id.locationListPrefs) {
startActivity(new Intent(this, PreferencesUnlockScreen.class));
return true;
}
return super.onOptionsItemSelected(item);
}
Your application icon shows in the taskbar. The icon on the topleft (window) is the form-icon. Go to your form and fill the property "icon" with the same icon; problem solved. You don't need to put the icon in the outputfolder (that's just for setups).
Rails 4 + Scope + Arel
class Creature < ActiveRecord::Base
scope :is_good_pet, -> {
where(
arel_table[:is_cat].eq(true)
.or(arel_table[:is_dog].eq(true))
.or(arel_table[:eats_children].eq(false))
)
}
end
I tried chaining named scopes with .or and no luck, but this worked for finding anything with those booleans set. Generates SQL like
SELECT 'CREATURES'.* FROM 'CREATURES' WHERE ((('CREATURES'.'is_cat' = 1 OR 'CREATURES'.'is_dog' = 1) OR 'CREATURES'.'eats_children' = 0))
Please note that the problem is not white
color. It is because it is being transparent.
When an element is made transparent, all of its child element's opacity; alpha filter in IE 6 7 etc, is changed to the new value.
So you cannot say that it is white!
You can place an element above it, and change that element's transparency to 1
while changing the image's transparency to .2
or what so ever you want to.
A simpler solution nowadays would be to use your shape as a background and then programmatically change its color via:
view.background.setColorFilter(Color.parseColor("#343434"), PorterDuff.Mode.SRC_ATOP)
See PorterDuff.Mode for the available options.
UPDATE (API 29):
The above method is deprecated since API 29 and replaced by the following:
view.background.colorFilter = BlendModeColorFilter(Color.parseColor("#343434"), BlendMode.SRC_ATOP)
See BlendMode for the available options.
$('#table tr').slice(1).remove();
I remember coming across that 'slice' is faster than all other approaches, so just putting it here.
You can try accessing the NavigationBars Right Button item and set its selector property...heres a reference UIBarButtonItem reference, another thing if this doenst work that will def work is, set the right button item of the nav bar to a custom UIBarButtonItem that you create and set its selector...hope this helps
You'll need to use the HTML()
or display()
functions from IPython's display module:
from IPython.display import display, HTML
# Assuming that dataframes df1 and df2 are already defined:
print "Dataframe 1:"
display(df1)
print "Dataframe 2:"
display(HTML(df2.to_html()))
Note that if you just print df1.to_html()
you'll get the raw, unrendered HTML.
You can also import from IPython.core.display
with the same effect
D = {}
is a dictionary not set.
>>> d = {}
>>> type(d)
<type 'dict'>
Use D = set()
:
>>> d = set()
>>> type(d)
<type 'set'>
>>> d.update({1})
>>> d.add(2)
>>> d.update([3,3,3])
>>> d
set([1, 2, 3])
Probably because it's trying to execute "export" as an external command, and it's a shell internal.
First, try omitting the quotes from 12 and 24. Worth a shot.
Second, it's better to do this in CSS. See also http://www.w3schools.com/css/css_font.asp . Here is an inline style for a table tag:
<table style='font-family:"Courier New", Courier, monospace; font-size:80%' ...>...</table>
Better still, use an external style sheet or a style tag near the top of your HTML document. See also http://www.w3schools.com/css/css_howto.asp .
You declared the constructor blowfish as this:
Blowfish(BlowfishAlgorithm algorithm);
So this line cannot exist (without further initialization later):
Blowfish _blowfish;
since you passed no parameter. It does not understand how to handle a parameter-less declaration of object "BlowFish" - you need to create another constructor for that.
This because in.nextInt() only receive a int number, doesn't receive a new line. So you input 3 and press "Enter", the end of line is read by in.nextline().
Here is my code:
int nnames;
String names[];
System.out.print("How many names are you going to save: ");
Scanner in = new Scanner(System.in);
nnames = in.nextInt();
in.nextLine();
names = new String[nnames];
for (int i = 0; i < names.length; i++){
System.out.print("Type a name: ");
names[i] = in.nextLine();
}
Many answers refer to IDE's like Eclipse. However, the question relates to native development with Notepad++.
The core reason of the named error is a mismatch of the used Java Runtime Environment and used classes respectively libraries. The goal of the following descriptions is to compile without any additional installation.
1)
Check the definition in the PATH
variable. If there is defined:
C:\Program Files (x86)\Common Files\Oracle\Java\javapath
and/or
C:\ProgramData\Oracle\Java\javapath
These paths link to java/javac with a fixed java version. You can check this versions in this folder with javac -version
. Result can be:
java version "1.8.0_231"
This means, Java version 8 is in use.
Replace this entries with %JAVA_HOME%\bin
.
If the JDK's was installed manually, check whether JAVA_HOME
is set in the environment. If not, add it, here e.g. with:
JAVA_HOME="C:\Program Files\Java\jdk1.7.0_80"
2)
I have build the project on command-line with gradle. In build.gradle
was defined:
android {
buildToolsVersion "24.0.1"
dependencies {
compile 'com.android.support:design:23.0.1'
compile 'com.android.support:support-v4:23.0.1'
...
}
...
}
The used build-tools
dx-files are newer then other components. Therefore a modification is required:
buildToolsVersion "23.0.1"
Check up the date ISO standard; kind of like this:
yyyy.MM.ddThh:mm
It becomes 2008.11.20T22:18
.
It will start as soon as the page loads. You can keep it under some events like button click
$("#btn").click(function() {
var val= $('input[type="radio"]:checked').val();
});
Response.Redirect()
will send you to a new page, update the address bar and add it to the Browser History. On your browser you can click back.
Server.Transfer()
does not change the address bar. You cannot hit back.
I use Server.Transfer()
when I don't want the user to see where I am going. Sometimes on a "loading" type page.
Otherwise I'll always use Response.Redirect()
.
Including C file into another file is legal, but not advisable thing to do, unless you know exactly why are you doing this and what are you trying to achieve.
I'm almost sure that if you will post here the reason that behind your question the community will find you another more appropriate way to achieve you goal (please note the "almost", since it is possible that this is the solution given the context).
By the way i missed the second part of the question. If C file is included to another file and in the same time included to the project you probably will end up with duplicate symbol problem why linking the objects, i.e same function will be defined twice (unless they all static).
It's been correctly pointed out above that finding a given word in a sentence is not the same as finding the charsequence, and can be done as follows if you don't want to mess around with regular expressions.
boolean checkWordExistence(String word, String sentence) {
if (sentence.contains(word)) {
int start = sentence.indexOf(word);
int end = start + word.length();
boolean valid_left = ((start == 0) || (sentence.charAt(start - 1) == ' '));
boolean valid_right = ((end == sentence.length()) || (sentence.charAt(end) == ' '));
return valid_left && valid_right;
}
return false;
}
Output:
checkWordExistence("the", "the earth is our planet"); true
checkWordExistence("ear", "the earth is our planet"); false
checkWordExistence("earth", "the earth is our planet"); true
P.S Make sure you have filtered out any commas or full stops beforehand.
The benefit of a generator expression is that it uses less memory since it doesn't build the whole list at once. Generator expressions are best used when the list is an intermediary, such as summing the results, or creating a dict out of the results.
For example:
sum(x*2 for x in xrange(256))
dict( (k, some_func(k)) for k in some_list_of_keys )
The advantage there is that the list isn't completely generated, and thus little memory is used (and should also be faster)
You should, though, use list comprehensions when the desired final product is a list. You are not going to save any memeory using generator expressions, since you want the generated list. You also get the benefit of being able to use any of the list functions like sorted or reversed.
For example:
reversed( [x*2 for x in xrange(256)] )
You can catch it like any other exception:
try {
foo();
}
catch (const std::bad_alloc&) {
return -1;
}
Quite what you can usefully do from this point is up to you, but it's definitely feasible technically.
In general you cannot, and should not try, to respond to this error. bad_alloc
indicates that a resource cannot be allocated because not enough memory is available. In most scenarios your program cannot hope to cope with that, and terminating soon is the only meaningful behaviour.
Worse, modern operating systems often over-allocate: on such systems, malloc
and new
can return a valid pointer even if there is not enough free memory left – std::bad_alloc
will never be thrown, or is at least not a reliable sign of memory exhaustion. Instead, attempts to access the allocated memory will then result in a segmentation fault, which is not catchable (you can handle the segmentation fault signal, but you cannot resume the program afterwards).
The only thing you could do when catching std::bad_alloc
is to perhaps log the error, and try to ensure a safe program termination by freeing outstanding resources (but this is done automatically in the normal course of stack unwinding after the error gets thrown if the program uses RAII appropriately).
In certain cases, the program may attempt to free some memory and try again, or use secondary memory (= disk) instead of RAM but these opportunities only exist in very specific scenarios with strict conditions:
It’s exceedingly rare that applications have control over point 1 — userspace applications never do, it’s a system-wide setting that requires root permissions to change.1
OK, so let’s assume you’ve fixed point 1. What you can now do is for instance use a LRU cache for some of your data (probably some particularly large business objects that can be regenerated or reloaded on demand). Next, you need to put the actual logic that may fail into a function that supports retry — in other words, if it gets aborted, you can just relaunch it:
lru_cache<widget> widget_cache;
double perform_operation(int widget_id) {
std::optional<widget> maybe_widget = widget_cache.find_by_id(widget_id);
if (not maybe_widget) {
maybe_widget = widget_cache.store(widget_id, load_widget_from_disk(widget_id));
}
return maybe_widget->frobnicate();
}
…
for (int num_attempts = 0; num_attempts < MAX_NUM_ATTEMPTS; ++num_attempts) {
try {
return perform_operation(widget_id);
} catch (std::bad_alloc const&) {
if (widget_cache.empty()) throw; // memory error elsewhere.
widget_cache.remove_oldest();
}
}
// Handle too many failed attempts here.
But even here, using std::set_new_handler
instead of handling std::bad_alloc
provides the same benefit and would be much simpler.
1 If you’re creating an application that does control point 1, and you’re reading this answer, please shoot me an email, I’m genuinely curious about your circumstances.
new
in c++?The usual notion is that if new
operator cannot allocate dynamic memory of the requested size, then it should throw an exception of type std::bad_alloc
.
However, something more happens even before a bad_alloc
exception is thrown:
C++03 Section 3.7.4.1.3: says
An allocation function that fails to allocate storage can invoke the currently installed new_handler(18.4.2.2), if any. [Note: A program-supplied allocation function can obtain the address of the currently installed new_handler using the set_new_handler function (18.4.2.3).] If an allocation function declared with an empty exception-specification (15.4), throw(), fails to allocate storage, it shall return a null pointer. Any other allocation function that fails to allocate storage shall only indicate failure by throw-ing an exception of class std::bad_alloc (18.4.2.1) or a class derived from std::bad_alloc.
Consider the following code sample:
#include <iostream>
#include <cstdlib>
// function to call if operator new can't allocate enough memory or error arises
void outOfMemHandler()
{
std::cerr << "Unable to satisfy request for memory\n";
std::abort();
}
int main()
{
//set the new_handler
std::set_new_handler(outOfMemHandler);
//Request huge memory size, that will cause ::operator new to fail
int *pBigDataArray = new int[100000000L];
return 0;
}
In the above example, operator new
(most likely) will be unable to allocate space for 100,000,000 integers, and the function outOfMemHandler()
will be called, and the program will abort after issuing an error message.
As seen here the default behavior of new
operator when unable to fulfill a memory request, is to call the new-handler
function repeatedly until it can find enough memory or there is no more new handlers. In the above example, unless we call std::abort()
, outOfMemHandler()
would be called repeatedly. Therefore, the handler should either ensure that the next allocation succeeds, or register another handler, or register no handler, or not return (i.e. terminate the program). If there is no new handler and the allocation fails, the operator will throw an exception.
new_handler
and set_new_handler
?new_handler
is a typedef for a pointer to a function that takes and returns nothing, and set_new_handler
is a function that takes and returns a new_handler
.
Something like:
typedef void (*new_handler)();
new_handler set_new_handler(new_handler p) throw();
set_new_handler's parameter is a pointer to the function operator new
should call if it can't allocate the requested memory. Its return value is a pointer to the previously registered handler function, or null if there was no previous handler.
Given the behavior of new
a well designed user program should handle out of memory conditions by providing a proper new_handler
which does one of the following:
Make more memory available: This may allow the next memory allocation attempt inside operator new's loop to succeed. One way to implement this is to allocate a large block of memory at program start-up, then release it for use in the program the first time the new-handler is invoked.
Install a different new-handler: If the current new-handler can't make any more memory available, and of there is another new-handler that can, then the current new-handler can install the other new-handler in its place (by calling set_new_handler
). The next time operator new calls the new-handler function, it will get the one most recently installed.
(A variation on this theme is for a new-handler to modify its own behavior, so the next time it's invoked, it does something different. One way to achieve this is to have the new-handler modify static, namespace-specific, or global data that affects the new-handler's behavior.)
Uninstall the new-handler: This is done by passing a null pointer to set_new_handler
. With no new-handler installed, operator new
will throw an exception ((convertible to) std::bad_alloc
) when memory allocation is unsuccessful.
Throw an exception convertible to std::bad_alloc
. Such exceptions are not be caught by operator new
, but will propagate to the site originating the request for memory.
Not return: By calling abort
or exit
.
This solution is generic when reading json streams and need to get only some fields while fields not mapped correctly in your Domain Classes can be ignored:
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
A detailed solution would be to use a tool such as jsonschema2pojo to autogenerate the required Domain Classes such as Student from the Schema of the json Response. You can do the latter by any online json to schema converter.
Try with "update tablet set (row='value' where id=0001'), (row='value2' where id=0002'), ...
Deactivating Breakpoints caused the new script to load for me.
loop to the last element of the linked list which have next pointer to null then modify the next pointer to point to a new node which has the data=object and next pointer = null
Similar to Julien's answer above, I had success with the following:
fig, ax = plt.subplots(figsize=(10,4))
for key, grp in df.groupby(['ticker']):
ax.plot(grp['Date'], grp['adj_close'], label=key)
ax.legend()
plt.show()
This solution might be more relevant if you want more control in matlab.
Solution inspired by: https://stackoverflow.com/a/52526454/10521959
With some of the answers here for disabling Google Chrome automatic updates, I've come up with a solution that uses specific group policy settings and also a PowerShell startup script to rename the GoogleUpdate.exe, disable the correlated services, and disable the correlated Task Scheduler tasks.
I'm posting as an answer in case someone else needs an all-in-one solution that can easily be expanded on (or toned down some) if needed and potentially save them some time.
## -- Rename the Google Update executable file
$Chrome = "${env:ProgramFiles(x86)}\Google\Update\GoogleUpdate.exe";
If(Test-Path($Chrome)){Rename-Item -Path $Chrome -NewName "Old_GoogleUpdate.exe.old" -Force};
$Chrome = "$env:ProgramFiles\Google\Update\GoogleUpdate.exe";
If(Test-Path($Chrome)){Rename-Item -Path $Chrome -NewName "Old_GoogleUpdate.exe.old" -Force};
## -- Stop and disable the Google Update services that run to update Chrome
$GUpdateServices = (Get-Service | ?{$_.DisplayName -match "Google Update Service"}).Name;
$GUpdateServices | % {
$status = (Get-Service -Name $_).Status;
If($status -ne "Stopped"){Stop-Service $_ -Force};
$sType = (Get-Service -Name $_).StartType;
If($sType -ne "Disabled"){Set-Service $_ -StartupType Disabled};
};
## -- Disable Chrome Update Scheduled Tasks
$GUdateTasks = (Get-ScheduledTask -TaskPath "\" -TaskName "*GoogleUpdateTask*");
$GUdateTasks | % {If($_.State -ne "Disabled"){Disable-ScheduledTask -TaskName $_.TaskName}};
Be sure the Software Restriction policy blocks EXE file types at a minimum for these specific folder locations but the defaults should work fine if you leave as-is.
Set Chrome Browser policies on managed PCs
The compilation of a C++ program involves three steps:
Preprocessing: the preprocessor takes a C++ source code file and deals with the #include
s, #define
s and other preprocessor directives. The output of this step is a "pure" C++ file without pre-processor directives.
Compilation: the compiler takes the pre-processor's output and produces an object file from it.
Linking: the linker takes the object files produced by the compiler and produces either a library or an executable file.
The preprocessor handles the preprocessor directives, like #include
and #define
. It is agnostic of the syntax of C++, which is why it must be used with care.
It works on one C++ source file at a time by replacing #include
directives with the content of the respective files (which is usually just declarations), doing replacement of macros (#define
), and selecting different portions of text depending of #if
, #ifdef
and #ifndef
directives.
The preprocessor works on a stream of preprocessing tokens. Macro substitution is defined as replacing tokens with other tokens (the operator ##
enables merging two tokens when it makes sense).
After all this, the preprocessor produces a single output that is a stream of tokens resulting from the transformations described above. It also adds some special markers that tell the compiler where each line came from so that it can use those to produce sensible error messages.
Some errors can be produced at this stage with clever use of the #if
and #error
directives.
The compilation step is performed on each output of the preprocessor. The compiler parses the pure C++ source code (now without any preprocessor directives) and converts it into assembly code. Then invokes underlying back-end(assembler in toolchain) that assembles that code into machine code producing actual binary file in some format(ELF, COFF, a.out, ...). This object file contains the compiled code (in binary form) of the symbols defined in the input. Symbols in object files are referred to by name.
Object files can refer to symbols that are not defined. This is the case when you use a declaration, and don't provide a definition for it. The compiler doesn't mind this, and will happily produce the object file as long as the source code is well-formed.
Compilers usually let you stop compilation at this point. This is very useful because with it you can compile each source code file separately. The advantage this provides is that you don't need to recompile everything if you only change a single file.
The produced object files can be put in special archives called static libraries, for easier reusing later on.
It's at this stage that "regular" compiler errors, like syntax errors or failed overload resolution errors, are reported.
The linker is what produces the final compilation output from the object files the compiler produced. This output can be either a shared (or dynamic) library (and while the name is similar, they haven't got much in common with static libraries mentioned earlier) or an executable.
It links all the object files by replacing the references to undefined symbols with the correct addresses. Each of these symbols can be defined in other object files or in libraries. If they are defined in libraries other than the standard library, you need to tell the linker about them.
At this stage the most common errors are missing definitions or duplicate definitions. The former means that either the definitions don't exist (i.e. they are not written), or that the object files or libraries where they reside were not given to the linker. The latter is obvious: the same symbol was defined in two different object files or libraries.
Additionally to Bruno's answer I ended up registering the same port for localhost. Otherwise VS2015 was giving me Access Denied error on server start.
netsh http add urlacl url=http://localhost:{port}/ user=everyone
May be it's because I have binding for localhost in aplicationhost.config also.
If it helps anyone, I was having an issue where I wanted to treat an object as another type with a similar interface. I attempted the following:
Didn't pass linting
const x = new Obj(a as b);
The linter was complaining that a
was missing properties that existed on b
. In other words, a
had some properties and methods of b
, but not all. To work around this, I followed VS Code's suggestion:
Passed linting and testing
const x = new Obj(a as unknown as b);
Note that if your code attempts to call one of the properties that exists on type b
that is not implemented on type a
, you should realize a runtime fault.
If animating opacity
is not an option, you can also animate background-size
.
For example, I used this CSS to set a backgound-image
with a delay.
.before {
background-size: 0;
}
.after {
transition: background 0.1s step-end;
background-image: $path-to-image;
background-size: 20px 20px;
}
You could also try editing adb_usb.ini file, located at /home/username/.android/. This file contains id vendor list of devices you want to connect. You just add your device's id vendor in new line (it's one id per line). Then restart adb server and replug your device.
It worked for me on Ubuntu 12.10.
Or it could be that Skype is running on the same port (it does by default).
Disable Skype or configure Skype to use another port
Ok, The Windows 10 BatchFile is done works just like I had hoped. First press the windows key and R. Type mmc and Enter. In File Add SnapIn>Got to a specific Website and add it to the list. Press OK in the tab, and on the left side console root menu double click your site. Once it opens Add it to favourites. That should place it in C:\Users\user\AppData\Roaming\Microsoft\StartMenu\Programs\Windows Administrative Tools. I made a shortcut of this to a folder on the desktop. Right click the Shortcut and view the properties. In the Shortcut tab of the Properties click advanced and check the Run as Administrator. The Start in Location is also on the Shortcuts Tab you can add that to your batch file if you need. The Batch I made is as follows
@echo off
title Manage SiteEnviro
color 0a
:Clock
cls
echo Date:%date% Time:%time%
pause
cls
c:\WINDOWS\System32\netstat
c:\WINDOWS\System32\netstat -an
goto Greeting
:Greeting
cls
echo Open ShellSite
pause
cls
goto Manage SiteEnviro
:Manage SiteEnviro
"C:\Users\user\AppData\Roaming\Microsoft\Start Menu\Programs\Administrative Tools\YourCustomSavedMMC.msc"
You need to make a shortcut when you save this as a bat file and in the properties>shortcuts>advanced enable administrator access, can also set a keybind there and change the icon if you like. I probably did not need :Clock. The netstat commands can change to setting a hosted network or anything you want including nothing. Can Canscade websites in 1 mmc console and have more than 1 favourite added into the batch file.
Use a non-consuming regular expression.
The typical (i.e. Perl/Java) notation is:
(?=
expr)
This means "match expr but after that continue matching at the original match-point."
You can do as many of these as you want, and this will be an "and." Example:
(?=match this expression)(?=match this too)(?=oh, and this)
You can even add capture groups inside the non-consuming expressions if you need to save some of the data therein.
The /g
modifier is used to perform a global match (find all matches rather than stopping after the first)
You can use \d
for digit, as it is shorter than [0-9]
.
JavaScript:
var s = "04.07.2012";
echo(s.replace(/\d/g, "X"));
Output:
XX.XX.XXXX
If you really want to prune your history of .gitignore
d files, first save .gitignore
outside the repo, e.g. as /tmp/.gitignore
, then run
git filter-branch --force --index-filter \
"git ls-files -i -X /tmp/.gitignore | xargs -r git rm --cached --ignore-unmatch -rf" \
--prune-empty --tag-name-filter cat -- --all
Notes:
git filter-branch --index-filter
runs in the .git
directory I think, i.e. if you want to use a relative path you have to prepend one more ../
first. And apparently you cannot use ../.gitignore
, the actual .gitignore
file, that yields a "fatal: cannot use ../.gitignore as an exclude file" for some reason (maybe during a git filter-branch --index-filter
the working directory is (considered) empty?)git ls-files -iX <(git show $(git hash-object -w .gitignore))
instead to avoid copying .gitignore
somewhere else, but that alone already returns an empty string (whereas cat <(git show $(git hash-object -w .gitignore))
indeed prints .gitignore
's contents as expected), so I cannot use <(git show $GITIGNORE_HASH)
in git filter-branch
....gitignore
-clean a specific branch, replace --all
in the last line with its name. The --tag-name-filter cat
might not work properly then, i.e. you'll probably not be able to directly transfer a single branch's tags properly'Common Table Expression' feature is not available in MySQL, so you have to go to make a view or temporary table to solve, here I have used a temporary table.
The stored procedure mentioned here will solve your need. If I want to get all my team members and their associated members, this stored procedure will help:
----------------------------------
user_id | team_id
----------------------------------
admin | NULL
ramu | admin
suresh | admin
kumar | ramu
mahesh | ramu
randiv | suresh
-----------------------------------
Code:
DROP PROCEDURE `user_hier`//
CREATE DEFINER=`root`@`localhost` PROCEDURE `user_hier`(in team_id varchar(50))
BEGIN
declare count int;
declare tmp_team_id varchar(50);
CREATE TEMPORARY TABLE res_hier(user_id varchar(50),team_id varchar(50))engine=memory;
CREATE TEMPORARY TABLE tmp_hier(user_id varchar(50),team_id varchar(50))engine=memory;
set tmp_team_id = team_id;
SELECT COUNT(*) INTO count FROM user_table WHERE user_table.team_id=tmp_team_id;
WHILE count>0 DO
insert into res_hier select user_table.user_id,user_table.team_id from user_table where user_table.team_id=tmp_team_id;
insert into tmp_hier select user_table.user_id,user_table.team_id from user_table where user_table.team_id=tmp_team_id;
select user_id into tmp_team_id from tmp_hier limit 0,1;
select count(*) into count from tmp_hier;
delete from tmp_hier where user_id=tmp_team_id;
end while;
select * from res_hier;
drop temporary table if exists res_hier;
drop temporary table if exists tmp_hier;
end
This can be called using:
mysql>call user_hier ('admin')//
In Swift5 ans Xcode 10
Add two textfields with Save and Cancel actions and read TextFields text data
func alertWithTF() {
//Step : 1
let alert = UIAlertController(title: "Great Title", message: "Please input something", preferredStyle: UIAlertController.Style.alert )
//Step : 2
let save = UIAlertAction(title: "Save", style: .default) { (alertAction) in
let textField = alert.textFields![0] as UITextField
let textField2 = alert.textFields![1] as UITextField
if textField.text != "" {
//Read TextFields text data
print(textField.text!)
print("TF 1 : \(textField.text!)")
} else {
print("TF 1 is Empty...")
}
if textField2.text != "" {
print(textField2.text!)
print("TF 2 : \(textField2.text!)")
} else {
print("TF 2 is Empty...")
}
}
//Step : 3
//For first TF
alert.addTextField { (textField) in
textField.placeholder = "Enter your first name"
textField.textColor = .red
}
//For second TF
alert.addTextField { (textField) in
textField.placeholder = "Enter your last name"
textField.textColor = .blue
}
//Step : 4
alert.addAction(save)
//Cancel action
let cancel = UIAlertAction(title: "Cancel", style: .default) { (alertAction) in }
alert.addAction(cancel)
//OR single line action
//alert.addAction(UIAlertAction(title: "Cancel", style: .default) { (alertAction) in })
self.present(alert, animated:true, completion: nil)
}
For more explanation https://medium.com/@chan.henryk/alert-controller-with-text-field-in-swift-3-bda7ac06026c
You can use sub query way of codeigniter to do this for this purpose you will have to hack codeigniter. like this
Go to system/database/DB_active_rec.php
Remove public or protected keyword from these functions
public function _compile_select($select_override = FALSE)
public function _reset_select()
Now subquery writing in available And now here is your query with active record
$this->db->select('trans_id');
$this->db->from('myTable');
$this->db->where('code','B');
$subQuery = $this->db->_compile_select();
$this->db->_reset_select();
// And now your main query
$this->db->select("*");
$this->db->where_in("$subQuery");
$this->db->where('code !=', 'B');
$this->db->get('myTable');
And the thing is done. Cheers!!!
Note : While using sub queries you must use
$this->db->from('myTable')
instead of
$this->db->get('myTable')
which runs the query.
Watch this too
How can I rewrite this SQL into CodeIgniter's Active Records?
Note : In Codeigntier 3 these functions are already public so you do not need to hack them.
You will have to assign both left
and right
property 0
value for margin: auto
to center the logo.
So in this case:
#logo {
background:red;
height:50px;
position:absolute;
width:50px;
left: 0;
right: 0;
margin: 0 auto;
}
You might also want to set position: relative
for #header
.
This works because, setting left
and right
to zero will horizontally stretch the absolutely positioned element. Now magic happens when margin
is set to auto
. margin
takes up all the extra space(equally on each side) leaving the content to its specified width
. This results in content becoming center aligned.
I think you're a little confused. PYTHONPATH sets the search path for importing python modules, not for executing them like you're trying.
PYTHONPATH Augment the default search path for module files. The format is the same as the shell’s PATH: one or more directory pathnames separated by os.pathsep (e.g. colons on Unix or semicolons on Windows). Non-existent directories are silently ignored.
In addition to normal directories, individual PYTHONPATH entries may refer to zipfiles containing pure Python modules (in either source or compiled form). Extension modules cannot be imported from zipfiles.
The default search path is installation dependent, but generally begins with prefix/lib/pythonversion (see PYTHONHOME above). It is always appended to PYTHONPATH.
An additional directory will be inserted in the search path in front of PYTHONPATH as described above under Interface options. The search path can be manipulated from within a Python program as the variable sys.path.
http://docs.python.org/2/using/cmdline.html#envvar-PYTHONPATH
What you're looking for is PATH.
export PATH=$PATH:/home/randy/lib/python
However, to run your python script as a program, you also need to set a shebang for Python in the first line. Something like this should work:
#!/usr/bin/env python
And give execution privileges to it:
chmod +x /home/randy/lib/python/gbmx.py
Then you should be able to simply run gmbx.py
from anywhere.
The suggestions to use ToTitleCase won't work for strings that are all upper case. So you are gonna have to call ToUpper on the first char and ToLower on the remaining characters.
try this:
ffmpeg -i "path to file" -f null /dev/null 2>&1 | grep 'frame=' | cut -f 2 -d ' '
There is a new cross plateform (java) and open source tool, that enable you to do that, just checkout https://bytecodeviewer.com
=========
EDIT: As of April 2017, there is a new open source tool developed by google, that is meant to do just what we have been looking for => https://github.com/google/android-classyshark
Taking a stab at this. Kind of hard to measure performance, though.
function palin(word) {
var i = 0,
len = word.length - 1,
max = word.length / 2 | 0;
while (i < max) {
if (word.charCodeAt(i) !== word.charCodeAt(len - i)) {
return false;
}
i += 1;
}
return true;
}
My thinking is to use charCodeAt()
instead charAt()
with the hope that allocating a Number
instead of a String
will have better perf because String
s are variable length and might be more complex to allocate. Also, only iterating halfway through (as noted by sai) because that's all that's required. Also, if the length is odd (ex: 'aba'
), the middle character is always ok.
Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.
Do you have this:
use Cartalyst\Sentry\Sentry;
In your code?
Ok, but if this line is working for you:
$user = $this->sentry->register(array( 'username' => e($data['username']), 'email' => e($data['email']), 'password' => e($data['password']) ));
So you already have it instantiated and you can surely do:
$adminGroup = $this->sentry->findGroupById(5);
The problem is that you do not have bzip2 installed. The tar program relies upon this external program to do compression. For installing bzip2, it depends on the system you are using. For example, with Ubuntu that would be on Ubuntu
sudo apt-get install bzip2
The GNU tar program does not know how to compress an existing file such as user-logs.tar (bzip2 does that). The tar program can use external compression programs gzip, bzip2, xz by opening a pipe to those programs, sending a tar archive via the pipe to the compression utility, which compresses the data which it reads from tar and writes the result to the filename which the tar program specifies.
Alternatively, the tar and compression utility could be the same program. BSD tar does its compression using lib archive (they're not really distinct except in name).
For %appdata% take a look to
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
This is equivalent to new Date().getTime()
in JavaScript :
Use the below statement to get the time in seconds.
SELECT cast(DATEDIFF(s, '1970-01-01 00:00:00.000', '2016-12-09 16:22:17.897' ) as bigint)
Use the below statement to get the time in milliseconds.
SELECT cast(DATEDIFF(s, '1970-01-01 00:00:00.000', '2016-12-09 16:22:17.897' ) as bigint) * 1000
Yes. In Ruby the not equal to operator is:
!=
You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.
Since you've labeled the question C++, you might be interested in using boost::asio, ACE, or some other cross-platform socket library for C++ or for C. Some other cross-platform libraries may be found in the answers to C++ sockets library for cross-platform and Cross platform Networking API.
Assuming that using a third party cross-platform sockets library is not an option for you...
The header <sys/socket.h> is defined in IEEE Std. 1003.1 (POSIX), but sadly Windows is non-compliant with the POSIX standard. The MinGW compiler is a port of GCC for compiling Windows applications, and therefore does not include these POSIX system headers. If you install GCC using Cygwin, then it will include these system headers to emulate a POSIX environment on Windows. Be aware, however, that if you use Cygwin for sockets that a.) you will need to put the cygwin DLL in a place where your application can read it and b.) Cygwin headers and Windows headers don't interact very well (so if you plan on including windows.h
, then you probably don't want to be including sys/socket.h
).
My personal recommendation would be to download a copy of VirtualBox, download a copy of Ubuntu, install Ubuntu into VirtualBox, and then do your coding and testing on Ubuntu. Alternatively, I am told that Microsoft sells a "UNIX subsystem" and that it is pre-installed on certain higher-end editions of Windows, although I have no idea how compliant this system is (and, if it is compliant, with which edition of the UNIX standard it is compliant). Winsockets are also an option, although they can behave in subtly different ways than their POSIX counterparts, even though the signatures may be similar.
a = [[] for index in range(1, n)]
Full outer join for two or more tables: First extract the column that you want to join on.
var DatesA = from A in db.T1 select A.Date;
var DatesB = from B in db.T2 select B.Date;
var DatesC = from C in db.T3 select C.Date;
var Dates = DatesA.Union(DatesB).Union(DatesC);
Then use left outer join between the extracted column and main tables.
var Full_Outer_Join =
(from A in Dates
join B in db.T1
on A equals B.Date into AB
from ab in AB.DefaultIfEmpty()
join C in db.T2
on A equals C.Date into ABC
from abc in ABC.DefaultIfEmpty()
join D in db.T3
on A equals D.Date into ABCD
from abcd in ABCD.DefaultIfEmpty()
select new { A, ab, abc, abcd })
.AsEnumerable();
Use the operator sizeof
, it will give you the size of a type expressed in byte. One byte is eight bits. See the following program:
#include <iostream>
int main(int,char**)
{
std::cout << "unsigned long long " << sizeof(unsigned long long) << "\n";
std::cout << "unsigned long long int " << sizeof(unsigned long long int) << "\n";
return 0;
}
you can try quoting it which will keep the link as text. see the code blocks section: https://get.slack.help/hc/en-us/articles/202288908-Format-your-messages#code-blocks
The issue is fixed by adding repository url under distributionManagement tab in main pom.xml.
Jenkin maven goal : clean deploy -U -Dmaven.test.skip=true
<distributionManagement>
<repository>
<id>releases</id>
<url>http://domain:port/content/repositories/releases</url>
</repository>
<snapshotRepository>
<id>snapshots</id>
<url>http://domain:port/content/repositories/snapshots</url>
</snapshotRepository>
</distributionManagement>
I had the same problem when using bootstrap-datewidget and i loaded jquery in the header instead of loading it at the end of the body and it worked.
To add to @Sam_D's answer, I had to do this to make it work:
this.setTitle("my title!");
((TextView)v.findViewById(R.id.title)).setText(this.getTitle());
TextView title = ((TextView)v.findViewById(R.id.title));
title.setEllipsize(TextUtils.TruncateAt.MARQUEE);
title.setMarqueeRepeatLimit(1);
// in order to start strolling, it has to be focusable and focused
title.setFocusable(true);
title.setSingleLine(true);
title.setFocusableInTouchMode(true);
title.requestFocus();
It seems like overkill - referencing v.findViewById(R.id.title)) twice - but that's the only way it would let me do it.
There are a few ways to go about this. One option would be to use inputfile.read()
instead of inputfile.readlines()
- you'd need to write separate code to strip the first four lines, but if you want the final output as a single string anyway, this might make the most sense.
A second, simpler option would be to rejoin the strings after striping the first four lines with my_text = ''.join(my_text)
. This is a little inefficient, but if speed isn't a major concern, the code will be simplest.
Finally, if you actually want the output as a list of strings instead of a single string, you can just modify your data parser to iterate over the list. That might looks something like this:
def data_parser(lines, dic):
for i, j in dic.iteritems():
for (k, line) in enumerate(lines):
lines[k] = line.replace(i, j)
return lines
For fellow Xamarians, the Xamarin.iOS/C# version of the answer would look like the following:
public override void DrawRect(CGRect area, UIViewPrintFormatter formatter)
{
CGContext currentContext = UIGraphics.GetCurrentContext();
currentContext.SaveState();
currentContext.SetShadow(new CGSize(-15, 20), 5);
base.DrawRect(area, formatter);
currentContext.RestoreState();
}
The main difference is that you acquire an instance of CGContext
on which you directly call the appropriate methods.
You can use filters available in swift to filter content from an array instead of using a predicate like in Objective-C.
An example in Swift 4.0 is as follows:
var stringArray = ["foundation","coredata","coregraphics"]
stringArray = stringArray.filter { $0.contains("core") }
In the above example, since each element in the array is a string you can use the contains
method to filter the array.
If the array contains custom objects, then the properties of that object can be used to filter the elements similarly.
The most effective way that I have found is to use setTimeout with time of 0 inside of the page/component constructor. This let's the jQuery run in the next execution cycle after Angular has finished loading all the child components. A few other component methods could be used but all I have tried work best when run inside a setTimeout.
export class HomePage {
constructor() {
setTimeout(() => {
// run jQuery stuff here
}, 0);
}
}
I agree with Shog9, though I might instead use:
<input type = "button" onClick="addItem(); return false;" value="Add Item" />
According to w3schools, the <button>
tag has different behavior on different browsers.
Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.
You've got:
//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]
Which translates into:
Get me all the elements that have an ID
that contains ctl00_btnAircraftMapCell
. Out of these elements, get any child elements that have a title
that contains Select Seat
.
What you actually want is:
//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]
Which translates into:
Get me all the anchor elements that have both: an id
that contains ctl00_btnAircraftMapCell
and a title
that contains Select Seat
.
For anyone finding this post through Google (as I did) here's the correct formula for cell F5 in the above example:
=SUMPRODUCT((MONTH(Sheet1!$A$1:$A$50)=MONTH(DATEVALUE(E5&" 1")))*(Sheet1!$A$1:$A$50<>""))
Formula assumes a list of dates in Sheet1!A1:A50 and a month name or abbr ("April" or "Apr") in cell E5.
Never use .onclick()
, or similar attributes from a userscript! (It's also poor practice in a regular web page).
The reason is that userscripts operate in a sandbox ("isolated world"), and onclick
operates in the target-page scope and cannot see any functions your script creates.
Always use addEventListener()
Doc (or an equivalent library function, like jQuery .on()).
So instead of code like:
something.outerHTML += '<input onclick="resetEmotes()" id="btnsave" ...>'
You would use:
something.outerHTML += '<input id="btnsave" ...>'
document.getElementById ("btnsave").addEventListener ("click", resetEmotes, false);
For the loop, you can't pass data to an event listener like that See the doc. Plus every time you change innerHTML
like that, you destroy the previous event listeners!
Without refactoring your code much, you can pass data with data attributes. So use code like this:
for (i = 0; i < EmoteURLLines.length; i++) {
if (checkIMG (EmoteURLLines[i])) {
localStorage.setItem ("nameEmotes", JSON.stringify (EmoteNameLines));
localStorage.setItem ("urlEmotes", JSON.stringify (EmoteURLLines));
localStorage.setItem ("usageEmotes", JSON.stringify (EmoteUsageLines));
if (i == 0) {
console.log (resetSlot ());
}
emoteTab[2].innerHTML += '<span style="cursor:pointer;" id="'
+ EmoteNameLines[i]
+ '" data-usage="' + EmoteUsageLines[i] + '">'
+ '<img src="' + EmoteURLLines[i] + '" /></span>'
;
} else {
alert ("The maximum emote (" + EmoteNameLines[i] + ") size is (36x36)");
}
}
//-- Only add events when innerHTML overwrites are done.
var targetSpans = emoteTab[2].querySelectorAll ("span[data-usage]");
for (var J in targetSpans) {
targetSpans[J].addEventListener ("click", appendEmote, false);
}
Where appendEmote is like:
function appendEmote (zEvent) {
//-- this and the parameter are special in event handlers. see the linked doc.
var emoteUsage = this.getAttribute ("data-usage");
shoutdata.value += emoteUsage;
}
.outerHTML
or .innerHTML
, you trash any event handlers on the affected nodes. If you use this method beware of that fact.Here is bitmap extension .convertToByteArray
wrote in Kotlin.
/**
* Convert bitmap to byte array using ByteBuffer.
*/
fun Bitmap.convertToByteArray(): ByteArray {
//minimum number of bytes that can be used to store this bitmap's pixels
val size = this.byteCount
//allocate new instances which will hold bitmap
val buffer = ByteBuffer.allocate(size)
val bytes = ByteArray(size)
//copy the bitmap's pixels into the specified buffer
this.copyPixelsToBuffer(buffer)
//rewinds buffer (buffer position is set to zero and the mark is discarded)
buffer.rewind()
//transfer bytes from buffer into the given destination array
buffer.get(bytes)
//return bitmap's pixels
return bytes
}
I adapted the answer by ChrisB. Like in his example a temporary combobox is made visible when a cell is clicked. Additionally:
Option Explicit_x000D_
_x000D_
Private Const DATA_RANGE = "A1:A16"_x000D_
Private Const DROPDOWN_RANGE = "F2:F10"_x000D_
Private Const HELP_COLUMN = "$G"_x000D_
_x000D_
_x000D_
Private Sub Worksheet_SelectionChange(ByVal target As Range)_x000D_
Dim xWs As Worksheet_x000D_
Set xWs = Application.ActiveSheet_x000D_
_x000D_
On Error Resume Next_x000D_
_x000D_
With Me.TempCombo_x000D_
.LinkedCell = vbNullString_x000D_
.Visible = False_x000D_
End With_x000D_
_x000D_
If target.Cells.count > 1 Then_x000D_
Exit Sub_x000D_
End If_x000D_
_x000D_
Dim isect As Range_x000D_
Set isect = Application.Intersect(target, Range(DROPDOWN_RANGE))_x000D_
If isect Is Nothing Then_x000D_
Exit Sub_x000D_
End If_x000D_
_x000D_
With Me.TempCombo_x000D_
.Visible = True_x000D_
.Left = target.Left - 1_x000D_
.Top = target.Top - 1_x000D_
.Width = target.Width + 5_x000D_
.Height = target.Height + 5_x000D_
.LinkedCell = target.Address_x000D_
_x000D_
End With_x000D_
_x000D_
Me.TempCombo.Activate_x000D_
Me.TempCombo.DropDown_x000D_
End Sub_x000D_
_x000D_
Private Sub TempCombo_Change()_x000D_
If Me.TempCombo.Visible = False Then_x000D_
Exit Sub_x000D_
End If_x000D_
_x000D_
Dim currentValue As String_x000D_
currentValue = Range(Me.TempCombo.LinkedCell).Value_x000D_
_x000D_
If Trim(currentValue & vbNullString) = vbNullString Then_x000D_
Me.TempCombo.ListFillRange = "=" & DATA_RANGE_x000D_
Else_x000D_
If Me.TempCombo.ListIndex = -1 Then_x000D_
Dim listCount As Integer_x000D_
listCount = write_matching_items(currentValue)_x000D_
Me.TempCombo.ListFillRange = "=" & HELP_COLUMN & "1:" & HELP_COLUMN & listCount_x000D_
Me.TempCombo.DropDown_x000D_
End If_x000D_
_x000D_
End If_x000D_
End Sub_x000D_
_x000D_
_x000D_
Private Function write_matching_items(currentValue As String) As Integer_x000D_
Dim xWs As Worksheet_x000D_
Set xWs = Application.ActiveSheet_x000D_
_x000D_
Dim cell As Range_x000D_
Dim c As Range_x000D_
Dim firstAddress As Variant_x000D_
Dim count As Integer_x000D_
count = 0_x000D_
xWs.Range(HELP_COLUMN & ":" & HELP_COLUMN).Delete_x000D_
With xWs.Range(DATA_RANGE)_x000D_
Set c = .Find(currentValue, LookIn:=xlValues)_x000D_
If Not c Is Nothing Then_x000D_
firstAddress = c.Address_x000D_
Do_x000D_
Set cell = xWs.Range(HELP_COLUMN & "$" & (count + 1))_x000D_
cell.Value = c.Value_x000D_
count = count + 1_x000D_
_x000D_
Set c = .FindNext(c)_x000D_
If c Is Nothing Then_x000D_
GoTo DoneFinding_x000D_
End If_x000D_
Loop While c.Address <> firstAddress_x000D_
End If_x000D_
DoneFinding:_x000D_
End With_x000D_
_x000D_
write_matching_items = count_x000D_
_x000D_
End Function_x000D_
_x000D_
Private Sub TempCombo_KeyDown( __x000D_
ByVal KeyCode As MSForms.ReturnInteger, __x000D_
ByVal Shift As Integer)_x000D_
_x000D_
Select Case KeyCode_x000D_
Case 9 ' Tab key_x000D_
Application.ActiveCell.Offset(0, 1).Activate_x000D_
Case 13 ' Pause key_x000D_
Application.ActiveCell.Offset(1, 0).Activate_x000D_
End Select_x000D_
End Sub
_x000D_
Notes:
2 - fmMatchEntryNone
. Don't forget to set ComboBox name to TempCombo
ComboBox.addItem
, but it turned out to be hard to repaint list box as user typescompileSdkVersion : The compileSdkVersion is the version of the API the app is compiled against. This means you can use Android API features included in that version of the API (as well as all previous versions, obviously). If you try and use API 16 features but set compileSdkVersion to 15, you will get a compilation error. If you set compileSdkVersion to 16 you can still run the app on a API 15 device.
minSdkVersion : The min sdk version is the minimum version of the Android operating system required to run your application.
targetSdkVersion : The target sdk version is the version your app is targeted to run on.
Are the Android samples not good enough? I've found the ApiDemos to be indispensable when learning a new aspect of Android, myself.
If you use Arch Linux (distributions like Manjaro
or Antegros
) simply type:
sudo pacman -S tk
And all will work perfectly!
It is commonly agreed that primary keys should be immutable (or as stable as possible since immutability can not be enforced in the DB). While there is nothing that will prevent you from updating a primary key (except integrity constraint), it may not be a good idea:
From a performance point of view:
Other considerations:
In conclusion, during design, it is generally safer to use a surrogate key in lieu of a natural primary key that is supposed not to change -- but may eventually need to be updated because of changed requirements or even data entry error.
If you absolutely have to update a primary key with children table, see this post by Tom Kyte for a solution.
I don't understand how can datenwolf`s index generation can be correct. But still I find his solution rather clear. This is what I get after some thinking:
inline void push_indices(vector<GLushort>& indices, int sectors, int r, int s) {
int curRow = r * sectors;
int nextRow = (r+1) * sectors;
indices.push_back(curRow + s);
indices.push_back(nextRow + s);
indices.push_back(nextRow + (s+1));
indices.push_back(curRow + s);
indices.push_back(nextRow + (s+1));
indices.push_back(curRow + (s+1));
}
void createSphere(vector<vec3>& vertices, vector<GLushort>& indices, vector<vec2>& texcoords,
float radius, unsigned int rings, unsigned int sectors)
{
float const R = 1./(float)(rings-1);
float const S = 1./(float)(sectors-1);
for(int r = 0; r < rings; ++r) {
for(int s = 0; s < sectors; ++s) {
float const y = sin( -M_PI_2 + M_PI * r * R );
float const x = cos(2*M_PI * s * S) * sin( M_PI * r * R );
float const z = sin(2*M_PI * s * S) * sin( M_PI * r * R );
texcoords.push_back(vec2(s*S, r*R));
vertices.push_back(vec3(x,y,z) * radius);
push_indices(indices, sectors, r, s);
}
}
}
Either hand divisions, or use the SimpleDateFormat API.
long start = System.currentTimeMillis();
// do your work...
long elapsed = System.currentTimeMillis() - start;
DateFormat df = new SimpleDateFormat("HH 'hours', mm 'mins,' ss 'seconds'");
df.setTimeZone(TimeZone.getTimeZone("GMT+0"));
System.out.println(df.format(new Date(elapsed)));
Edit by Bombe: It has been shown in the comments that this approach only works for smaller durations (i.e. less than a day).
Worth noting that the code you see is sent to the database as is, the queries are sent separately to prevent SQL injection. AFAIK The ? marks are placeholders that are replaced by the number params by the database, not by hibernate.
The easiest solution to this is to use rgba
as the color: border-color: rgba(0,0,0,0);
That is fully transparent border color.
For a more detailed answer on creating your own colormaps, I highly suggest visiting this page
If that answer is too much work, you can quickly make your own list of colors and pass them to the color
parameter. All the colormaps are in the cm
matplotlib module. Let's get a list of 30 RGB (plus alpha) color values from the reversed inferno colormap. To do so, first get the colormap and then pass it a sequence of values between 0 and 1. Here, we use np.linspace
to create 30 equally-spaced values between .4 and .8 that represent that portion of the colormap.
from matplotlib import cm
color = cm.inferno_r(np.linspace(.4, .8, 30))
color
array([[ 0.865006, 0.316822, 0.226055, 1. ],
[ 0.851384, 0.30226 , 0.239636, 1. ],
[ 0.832299, 0.283913, 0.257383, 1. ],
[ 0.817341, 0.270954, 0.27039 , 1. ],
[ 0.796607, 0.254728, 0.287264, 1. ],
[ 0.775059, 0.239667, 0.303526, 1. ],
[ 0.758422, 0.229097, 0.315266, 1. ],
[ 0.735683, 0.215906, 0.330245, 1. ],
.....
Then we can use this to plot, using the data from the original post:
import random
x = [{i: random.randint(1, 5)} for i in range(30)]
df = pd.DataFrame(x)
df.plot(kind='bar', stacked=True, color=color, legend=False, figsize=(12, 4))
just tested doing this and it seems to work in firefox & IE
<html>
<head>
<script type="text/javascript">
function alertFilename()
{
var thefile = document.getElementById('thefile');
alert(thefile.value);
}
</script>
</head>
<body>
<form>
<input type="file" id="thefile" onchange="alertFilename()" />
<input type="button" onclick="alertFilename()" value="alert" />
</form>
</body>
</html>
You can fill it from XAML or from .cs. There are few ways to fill controls with data. It would be best for You to read more about WPF technology, it allows to do many things in many ways, depending on Your needs. It's more important to choose method based on Your project needs. You can start here. It's an easy article about creating combobox, and filling it with some data.
The first parameter is the name of the script you want to run. From the second parameter onwards it is the the parameters that you want to pass from your command line. Below is a test script:
from sys import argv
script, first, second = argv
print "Script is ",script
print "first is ",first
print "second is ",second
And here is how you pass the input parameters : 'Path to your script','First Parameter','Second Parameter'
Lets say that the Path to your script is /home/my_folder/test.py , the output will be like :
Script is /home/my_folder/test.py
first is First Parameter
second is Second Parameter
Hope this helps as it took me sometime to figure out input parameters are comma separated.
This is what I did to get it to work.
I am using pythonbrew(which is using pip) with python 2.7.5 installed.
I first did what Zubair(above) said and ran this command:
sudo apt-get install libsqlite3-dev
Then I ran this command:
pip install pysqlite
This fixed the database problem and I got confirmation of this when I ran:
python manager.py syncdb
Use CSS3
.container {
-webkit-column-count: 2;
-moz-column-count: 2;
column-count: 2;
-webkit-column-gap: 20px;
-moz-column-gap: 20px;
column-gap: 20px;
}
Browser Support
-webkit-
)-moz-
)-webkit-
)-webkit-
)This can be simplified by completely skipping the where object and the $users declaration. All you need is:
Code
get-content c:\scripts\users.txt | get-aduser -properties * | select displayname, office | export-csv c:\path\to\your.csv
For those people using ASP.NET MVC 5, add this code in your BundleConfig.cs to enable the CDN for jquery:
bundles.UseCdn = true;
Bundle jqueryBundle = new ScriptBundle("~/bundles/jquery", "//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js").Include("~/Scripts/jquery-{version}.js");
jqueryBundle.CdnFallbackExpression = "window.jQuery";
bundles.Add(jqueryBundle);
To answer the original posters question.... to 'decrypt' the password, you have to do what a password cracker would do.
In other words, you'd run a program to read from a large list of potential passwords (a password dictionary) and you'd hash each one using bcrypt
and the salt and complexity from the password you're trying to decipher. If you're lucky you'll find a match, but if the password is a strong one then you likely won't find a match.
Bcrypt
has the added security characteristic of being a slow hash. If your password had been hashed with md5 (terrible choice) then you'd be able to check billions of passwords per second, but since it's hashed using bcrypt
you will be able to check far fewer per second.
The fact that bcrypt
is slow to hash and salted is what makes it a good choice for password storage even today. That being said I believe NIST
recommends the PBKDF2 for password hashing.
Like so
DECLARE @t INT=1
SELECT CASE
WHEN @t>0 THEN
CASE
WHEN @t=1 THEN 'one'
ELSE 'not one'
END
ELSE 'less than one'
END
EDIT: After looking more at the question, I think the best option is to create a function that calculates the value. That way, if you end up having multiple places where the calculation needs done, you only have one point to maintain the logic.
if(list.ElementAtOrDefault(2) != null)
{
// logic
}
ElementAtOrDefault() is part of the System.Linq
namespace.
Although you have a List, so you can use list.Count > 2
.
I tried use [disabled]="!editmode"
but it not work in my case.
This is my solution [disabled]="!editmode ? 'disabled': null"
, I share for whom concern.
<button [disabled]="!editmode ? 'disabled': null"
(click)='loadChart()'>
<div class="btn-primary">Load Chart</div>
</button>
Some time you can solve problem through MySQL Administrator wizard. In
Startup variables > Advanced >
and set Def. char Set:utf8
Maybe this config need restart MySQL.
No need for the long code for number input restriction just try this code.
It also accepts valid int & float both values.
onload =function(){ _x000D_
var ele = document.querySelectorAll('.number-only')[0];_x000D_
ele.onkeypress = function(e) {_x000D_
if(isNaN(this.value+""+String.fromCharCode(e.charCode)))_x000D_
return false;_x000D_
}_x000D_
ele.onpaste = function(e){_x000D_
e.preventDefault();_x000D_
}_x000D_
}
_x000D_
<p> Input box that accepts only valid int and float values.</p>_x000D_
<input class="number-only" type=text />
_x000D_
$(function(){_x000D_
_x000D_
$('.number-only').keypress(function(e) {_x000D_
if(isNaN(this.value+""+String.fromCharCode(e.charCode))) return false;_x000D_
})_x000D_
.on("cut copy paste",function(e){_x000D_
e.preventDefault();_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<p> Input box that accepts only valid int and float values.</p>_x000D_
<input class="number-only" type=text />
_x000D_
The above answers are for most common use case - validating input as a number.
But to allow few special cases like negative numbers & showing the invalid keystrokes to user before removing it, so below is the code snippet for such special use cases.
$(function(){_x000D_
_x000D_
$('.number-only').keyup(function(e) {_x000D_
if(this.value!='-')_x000D_
while(isNaN(this.value))_x000D_
this.value = this.value.split('').reverse().join('').replace(/[\D]/i,'')_x000D_
.split('').reverse().join('');_x000D_
})_x000D_
.on("cut copy paste",function(e){_x000D_
e.preventDefault();_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<p> Input box that accepts only valid int and float values.</p>_x000D_
<input class="number-only" type=text />
_x000D_
To resolve the conflicts, use Git stash to save away your uncommitted changes; then pull down the remote repository change set; then pop your local stash to reapply your uncommitted changes.
In Eclipse v4.5 (Mars) to stash changes (a relatively recent addition, wasn't in previous EGit) I do this: right-click on a top-level Eclipse project that's in Git control, pick Team, pick Stashes, pick Stash Changes; a dialog opens to request a stash commit message.
You must use the context menu on a top level project! If I right click on a directory or file within a Git-controlled project I don't get the appropriate context menu.
Here is my solution which is pretty easy:
Instead of encoding the url itself i encoded the parameters that I was passing because the parameter was user input and the user could input any unexpected string of special characters so this worked for me fine :)
String review="User input"; /*USER INPUT AS STRING THAT WILL BE PASSED AS PARAMTER TO URL*/
try {
review = URLEncoder.encode(review,"utf-8");
review = review.replace(" " , "+");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String URL = "www.test.com/test.php"+"?user_review="+review;
Try using this:
$(".move_to").on("click", function(e){
e.preventDefault();
$('#contactsForm').attr('action', "/test1").submit();
});
Moving the order in which you use .preventDefault()
might fix your issue. You also didn't use function(e)
so e.preventDefault();
wasn't working.
Here it is working: http://jsfiddle.net/TfTwe/1/ - first of all, click the 'Check action attribute.' link. You'll get an alert saying undefined
. Then click 'Set action attribute.' and click 'Check action attribute.' again. You'll see that the form's action attribute has been correctly set to /test1
.
A couple years late, but here is a solution that retrieves both inline styling and external styling:
function css(a) {
var sheets = document.styleSheets, o = {};
for (var i in sheets) {
var rules = sheets[i].rules || sheets[i].cssRules;
for (var r in rules) {
if (a.is(rules[r].selectorText)) {
o = $.extend(o, css2json(rules[r].style), css2json(a.attr('style')));
}
}
}
return o;
}
function css2json(css) {
var s = {};
if (!css) return s;
if (css instanceof CSSStyleDeclaration) {
for (var i in css) {
if ((css[i]).toLowerCase) {
s[(css[i]).toLowerCase()] = (css[css[i]]);
}
}
} else if (typeof css == "string") {
css = css.split("; ");
for (var i in css) {
var l = css[i].split(": ");
s[l[0].toLowerCase()] = (l[1]);
}
}
return s;
}
Pass a jQuery object into css()
and it will return an object, which you can then plug back into jQuery's $().css()
, ex:
var style = css($("#elementToGetAllCSS"));
$("#elementToPutStyleInto").css(style);
:)
public partial class MainForm : Form
{
Image img;
private void button1_Click(object sender, EventArgs e)
{
LoadImageAsynchronously("http://media1.santabanta.com/full5/Indian%20%20Celebrities(F)/Jacqueline%20Fernandez/jacqueline-fernandez-18a.jpg");
}
private void LoadImageAsynchronously(string url)
{
/*
This is a classic example of how make a synchronous code snippet work asynchronously.
A class implements a method synchronously like the WebClient's DownloadData(…) function for example
(1) First wrap the method call in an Anonymous delegate.
(2) Use BeginInvoke(…) and send the wrapped anonymous delegate object as the last parameter along with a callback function name as the first parameter.
(3) In the callback method retrieve the ar's AsyncState as a Type (typecast) of the anonymous delegate. Along with this object comes EndInvoke(…) as free Gift
(4) Use EndInvoke(…) to retrieve the synchronous call’s return value in our case it will be the WebClient's DownloadData(…)’s return value.
*/
try
{
Func<Image> load_image_Async = delegate()
{
WebClient wc = new WebClient();
Bitmap bmpLocal = new Bitmap(new MemoryStream(wc.DownloadData(url)));
wc.Dispose();
return bmpLocal;
};
Action<IAsyncResult> load_Image_call_back = delegate(IAsyncResult ar)
{
Func<Image> ss = (Func<Image>)ar.AsyncState;
Bitmap myBmp = (Bitmap)ss.EndInvoke(ar);
if (img != null) img.Dispose();
if (myBmp != null)
img = myBmp;
Invalidate();
//timer.Enabled = true;
};
//load_image_Async.BeginInvoke(callback_load_Image, load_image_Async);
load_image_Async.BeginInvoke(new AsyncCallback(load_Image_call_back), load_image_Async);
}
catch (Exception ex)
{
}
}
protected override void OnPaint(PaintEventArgs e)
{
if (img != null)
{
Graphics grfx = e.Graphics;
grfx.DrawImage(img,new Point(0,0));
}
}
I'd probably go with this (I know its not pure linq), keep a reference to the original list if you want to retain all items, and you should find the updated values are in there:
foreach (var mc in list.Where(x => x.Name == "height"))
mc.Value = 30;
Christian C. Salvadó's and zzzzBov's answer have both given wonderful answers, but just to add my own interpretation based on my having moved into heavy Node.js development from PHP/Zend Framework where singleton patterns were common.
The following, comment-documented code is based on the following requirements:
My code is very similar to zzzzBov's answer except I've added a prototype chain to the constructor and more comments that should help those coming from PHP or a similar language translate traditional OOP to JavaScript's prototypical nature. It may not be the "simplest" but I believe it is the most proper.
// Declare 'Singleton' as the returned value of a self-executing anonymous function
var Singleton = (function () {
"use strict";
// 'instance' and 'constructor' should not be available in a "public" scope
// here they are "private", thus available only within
// the scope of the self-executing anonymous function
var _instance=null;
var _constructor = function (name) {
this.name = name || 'default';
}
// Prototypes will be "public" methods available from the instance
_constructor.prototype.getName = function () {
return this.name;
}
// Using the module pattern, return a static object
// which essentially is a list of "public static" methods
return {
// Because getInstance is defined within the same scope
// it can access the "private" 'instance' and 'constructor' vars
getInstance:function (name) {
if (!_instance) {
console.log('creating'); // This should only happen once
_instance = new _constructor(name);
}
console.log('returning');
return _instance;
}
}
})(); // Self execute
// Ensure 'instance' and 'constructor' are unavailable
// outside the scope in which they were defined
// thus making them "private" and not "public"
console.log(typeof _instance); // undefined
console.log(typeof _constructor); // undefined
// Assign instance to two different variables
var a = Singleton.getInstance('first');
var b = Singleton.getInstance('second'); // passing a name here does nothing because the single instance was already instantiated
// Ensure 'a' and 'b' are truly equal
console.log(a === b); // true
console.log(a.getName()); // "first"
console.log(b.getName()); // Also returns "first" because it's the same instance as 'a'
Note that technically, the self-executing anonymous function is itself a singleton as demonstrated nicely in the code provided by Christian C. Salvadó. The only catch here is that it is not possible to modify the prototype chain of the constructor when the constructor itself is anonymous.
Keep in mind that to JavaScript, the concepts of “public” and “private” do not apply as they do in PHP or Java. But we have achieved the same effect by leveraging JavaScript’s rules of functional scope availability.
I worked on this issue for a few days. Installed all packages, modified web.config and still had the same problem. I finally removed
<assemblies>
<add assembly="Microsoft.ReportViewer.Common, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</assemblies>
from the web.config and it worked. No exactly sure why it didn't work with the tags in the web.config file. My guess there is a conflict with the GAC and the BIN folder.
Here is my web.config file:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<httpHandlers>
<add verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</httpHandlers>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=12.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
</handlers>
</system.webServer>
</configuration>
In my case because I assigned the post data to the header, this is how I get it:
protected void Page_Load(object sender, EventArgs e){
...
postValue = Request.Headers["Key"];
This is how I attached the value and key to the POST
:
var request = new NSMutableUrlRequest(url){
HttpMethod = "POST",
Headers = NSDictionary.FromObjectAndKey(FromObject(value), FromObject("key"))
};
webView.LoadRequest(request);